Introduction
1.1 · What YASDE is
YASDE (Yet Another Samsung Dex Emulator) is a Linux program with a single window that is an emulated desktop: the apps of an Android 14+ phone run as windows inside it. This manual describes how it is built, for a developer who must change the code. It documents the code as it is today; where the code and the older design documents disagree, the code wins and the difference is listed in 1.5 “Known deviations from the design documents”.
The product has two halves. On the PC a program written in C17 (built with Meson) talks to the phone over wireless ADB, decodes the video the phone sends, plays its audio, and draws the desktop with GTK4. On the phone a small Java component, started with app_process, creates virtual displays, encodes them to H.264, captures audio, injects input and answers questions about the phone. Nothing is installed on the phone and nothing needs root.
The project's site is https://yasde.nicfio.it/. Questions and reports: yasde@nicfio.it.
1.2 · Principles
Four rules shape every design choice in the code. They come from the project instructions and are enforced by review, not by the compiler.
| Principle | What it means in the code |
|---|---|
| Nothing installed on the phone | The component is a jar copied to /data/local/tmp/yasde-<8 hex digits>.jar at every start and deleted at the end. No APK, no package, no service registered with Android. |
| No root | The component runs as the shell user (uid 2000), exactly like any command typed in adb shell. It refuses connections from any other uid (Pari, see 6.4 “Who may talk to the component”). |
| Plain Android APIs only | Public APIs first. Hidden APIs are reached by reflection and gathered in one class per folder (Nascoste, NascosteVideo, NascosteAudio, NascostePannello ...), each with a check at start-up that names the ones missing on this phone. No vendor-specific code: a workaround is triggered by a measured symptom, never by the manufacturer's name. |
| Every change has its undo | Whatever the component changes on the phone (screen timeout, media volume, panel power, minimum refresh rate) registers its undo command with the guardian Custode before the change is made (6.5 “The guardian and the restore list”). |
1.3 · Requirements
What is needed to build and run YASDE, as declared by the meson.build files.
| Where | Requirement |
|---|---|
| PC, language and build | C17, warnings as errors, Meson; tests run under AddressSanitizer. Version 2.1.0 (meson.build at the root). |
| PC, libraries | OpenSSL (TLS 1.3, RSA, AES-GCM, HKDF, SPAKE2 arithmetic), FFmpeg (libavcodec, libavformat, libavutil, libswscale), Vulkan headers and loader (to detect hardware decoding), Opus, PipeWire (libpipewire-0.3), GTK 4.14 or newer for the shell, pthreads. |
| PC, hardware | A GPU with VA-API H.264 decoding (first choice) or Vulkan Video; the software decoder is the last resort. |
| Phone | Android 14 or newer, wireless debugging turned on and the PC paired with it (5.2 “Pairing with the six-digit code”). |
| Phone jar | Java source level 8 against android.jar (no lambdas, no method references), converted with d8 at --min-api 34 by telefono/costruisci.sh. |
1.4 · Conventions and names
Code, comments and internal documents are written in Italian, so identifiers in this manual are Italian too. The first time a recurring name appears its meaning is given in brackets; the table lists the ones you meet most.
| Name | Meaning | Where |
|---|---|---|
Custode | the guardian: the process that undoes the phone changes if the service dies | telefono/base |
Registro | the registry where the pieces of the component register themselves | telefono/contratto |
Pari | the peers: the check on who connects to the socket | telefono/base |
Smistatore | the dispatcher of command-channel messages | telefono/base |
Sessione | one video session (virtual display, encoder and app) | telefono/video |
Pannello | the physical panel (phone screen) manager | telefono/pannello |
TieniSveglio | “keep awake”: the wake lock | telefono/pannello |
collegamento | the link: the state machine that keeps one phone connected | src/collegamento |
componente | the component: PC side of the protocol | src/componente |
scoperta | discovery of phones with mDNS | src/scoperta |
abbinamento | pairing with the six-digit code | src/abbinamento |
dati | phone data: apps, state, notifications, search, clipboard | src/dati |
PhErrore | error record: a sentence in Italian saying what was being done | src/comune/errore.h |
Conventions of the C code: every public name starts with ph_ or Ph (the prefix is historical and was kept); functions return 0 or -1 (pointers return NULL on error) and fill a PhErrore; no function calls exit() for a failure that depends on the phone or the network. The full list of code conventions is in chapter 18.
1.5 · Known deviations from the design documents
The table lists the places where this manual states that the code does not do what the design documents say. Each one is detailed in the chapter named in the last column.
| Design document says | Code does | Chapter |
|---|---|---|
| The shell draws with Vulkan. | The shell draws with GTK4. Vulkan is used only to detect and drive hardware H.264 decoding. | see chapter 8 |
| Two guardians (connection and service). | One guardian, Custode | see chapter 6 |
| Audio and video are synchronised. | No synchronisation is active: video frames are shown as they arrive. ph_audio_tempo_telefono_us exists but nothing outside src/audio calls it. | see chapter 9 |
The protocol defines VIDEO_EVENTO kind 3 (size changed). | The phone code never sends it; sizes change only through the resize request and the new configuration packet. | see chapter 8 |
| Hardware decoding hands frames to the screen without copies. | Only with VA-API, the first automatic choice. Vulkan is the fallback where VA-API is missing: in that case ph_esporta copies the frame to memory (PH_ESPORTA_RIPIEGO). | see chapter 8 |
| Audio capture starts 5 s after the drawer mirror opens. | Audio starts 5 s after the first video stream of the session; there is no mirror at start-up (sv_audio.c). | see chapter 9 |
| The panel goes off again after the inactivity time chosen by the user. | Only the first input from the PC turns it off again; there is no inactivity timer on the PC. | see chapter 10 |
| The panel turns on when the last window closes. | Closing the last window does not turn the panel on while YASDE is connected. | see chapter 10 |
| The mouse is one finger. | True for the left button only. The right and middle buttons pressed on the content of an app window reach the phone as real mouse buttons (context menu, open in a new tab), as DeX does. | see chapter 10 |
| Minimum refresh rate set to 60 Hz when the panel goes off. | Set to the highest rate with the same resolution (capped by the user's peak rate) only if the measured rate is lower. | see chapter 10 |
Architecture
2.1 · The two halves
YASDE is one Linux process on the PC plus one short-lived Java process on the phone. They talk over a single ADB connection (TCP, TLS 1.3) opened by the PC; every logical channel of the protocol is an ADB channel multiplexed on it.
The PC side is divided into pieces, one folder each under src/, and the build (meson.build at the root, one meson.build per piece defining <piece>_dep) lets a piece be compiled alone with -Dpezzo=<name>: whatever a piece depends on is then replaced by a fake written inside its own folder. The phone side is one folder per piece under telefono/ compiled together into yasde.jar.
2.2 · Pieces and dependencies
Each PC piece depends only on the ones listed here. The shell is the only code that sees all of them, and it never uses a lower piece directly: it goes through the service layer described in chapter 11.
| Piece | Folder | Uses | What it provides | |
|---|---|---|---|---|
| Common | src/comune | - | PhBuffer | , PhErrore, PhFotogramma (the frame handed to the shell) |
| ADB client | src/adb | common, OpenSSL | RSA key and certificate, TLS connection, channels, shell v2 (4.1 “The ADB client: transport”) | |
| Discovery | src/scoperta | common | mDNS search for connect and pairing services (5.1 “Discovery with mDNS”) | |
| Pairing | src/abbinamento | adb (key), common | pairing with the six-digit code (5.2 “Pairing with the six-digit code”) | |
| Files | src/file | adb | copy and listing through sync: (4.6 “File transfer with sync”) | |
| Component | src/componente | adb, file | starts the service, command channel, video sessions, input, presence (6.1 “Starting the component on the phone”) | |
| Data | src/dati | component | apps, icons, state, notifications, search, clipboard | |
| Video | src/video | common, FFmpeg, Vulkan | H.264 decoding, export to PhFotogramma, PNG and MP4 capture (8.4 “Video: receiving and decoding”; the hardware path stage by stage: 8.5 “Hardware acceleration end to end”) | |
| Audio | src/audio | adb, Opus, PipeWire | decoding, jitter queue, playback, gain (9.3 “Audio: playback on the PC”) | |
| Link | src/collegamento | scoperta, adb, abbinamento, componente, dati, config | the state machine that keeps one phone connected (3.3 “Link states and timings”) | |
| Config | src/config | common | files in ~/.config/YASDE, language table, phone profile | |
| Windows, transfers, weather | src/finestre, src/trasferimenti, src/meteo | common, config, file, adb | see chapters 12, 13 and 15 | |
| Shell | src/shell | all of the above | GTK4 desktop; src/shell/ossatura wires the real services |
The phone side follows the same idea. telefono/contratto holds the shared interfaces (Registro, GestoreCanale, GestoreComandi, Guardiano); telefono/base holds the service; every other folder (video, audio, dati, archivio, appunti, pannello, controlli) registers itself through Registro and never names another folder: base and video talk only through Registro.
2.3 · Threads
The code is thread-based, with no event loop of its own on the PC side. The table lists the long-lived threads and who owns them.
| Thread | Owner | Job |
|---|---|---|
| ADB reader | ph_adb_collega | reads every ADB packet from the TLS socket and routes it to its channel; one per connection |
| Link thread | ph_col_avvia | search, connect, monitor every 500 ms, drop, close; delivers every notice one at a time |
| Component: commands | ph_componente_avvia | reads the command channel and separates answers from events |
| Component: shell | ph_componente_avvia | reads and discards the log lines of the service process |
| Component: presence | ph_componente_avvia | sends PRESENZA when nothing has been sent for 5 minutes |
| Search, clipboard | src/dati | one thread per file search and one for the clipboard channel |
| Audio reader, PipeWire | src/audio | reads and decodes Opus; PipeWire calls the fill function from its own real-time thread |
Manager ph-gestore | src/shell/ossatura | builds the session when the link is up, tears it down on loss, starts audio after its delay |
| Worker pools | src/shell/ossatura | seven GThreadPools: 3 general workers, and one thread each for state, icons, writing, streams, input, install |
| Video reader | the shell surface | calls sv_flusso_leggi in a loop: receive, decode, export, one thread per window |
| GTK main thread | GTK | everything visible; never waits on the network |
The rules that keep this safe are in the contract headers and are checked first by review: a public function that uses an object must survive a close called from another thread at the same moment (a use counter that close waits for); no callback runs while holding a lock its receiver might want; no wait is unbounded unless the contract says so; no lock is held during an external command or a network write. The single known exception is the input channel lock, held during a write because ADB forbids two writers on one channel.
PhAdb, PhComponente, PhDati) are never used without a loan: 3.4 “Loans: using the session objects”.2.4 · Life of a click
This is the path of a user action, to fix the picture before the details. A click on a window of a phone app:
- GTK delivers the pointer event to the window surface; the shell turns it into a
PhSrvInputin the video's own coordinates and callssv_flusso_input. - If the stream is active and the video size matches, the phone panel is switched off if the phone is “in hand”, then the event is queued on the input pool.
ph_input_toccowrites aTOCCOmessage (type0x50) on theinputchannel, with the video size it was computed on.- On the phone,
Inputreads it, drops it if the size is stale, scales it to the virtual display and injects aMotionEventtouchscreen event on that display. - The app draws; the virtual display feeds the encoder; a H.264 packet travels the
video:<id>channel back; the reader thread decodes it with FFmpeg and hands the frame to GTK (as a DMA-BUF texture with VA-API; copied to memory first with the Vulkan via, used only where VA-API is missing).
Startup and session lifecycle
3.1 · Startup: from the AppImage to the window
The AppImage runs pacchetto/AppRun, a POSIX shell script that prepares the environment and then replaces itself (exec) with usr/bin/yasde. The program is src/shell/ossatura/main.c, which only calls ph_ossatura_esegui.
AppRuntakesAPPDIRfrom its own location (never from the environment, which could point to another package), puts the package libraries first inLD_LIBRARY_PATH, adds the package schemas toXDG_DATA_DIRS, and pointsGIO_MODULE_DIRto an empty folder so that no system GIO module of another GLib version is loaded.- The image-loader cache for gdk-pixbuf is generated from a template with the mount point of the package (
~/.cache/YASDE/yasde-pixbuf-<pid>.cache); files of dead processes (or older than a day) are removed. If the folder is not writable or the path has unsafe characters the program starts without these loaders (WebP does not open; PNG and JPEG stay). ph_ossatura_eseguifirst loads the preferences; an unreadable file is set aside and defaults are used.ph_lingua_inizializzaalways selects English: thelinguapreference is read and ignored.- If the user chose a fixed shell scale,
GDK_DPI_SCALEis set from it before GTK starts (GTK4 has no fractional widget scale; it is applied to fonts). - The
GtkApplicationhas the idit.yasde.YASDEand is unique per session. Instartup(primary instance only) SIGTERM and SIGINT are routed tog_application_quit, temporary files older than 3600 s are removed and orphan background images are cleaned. - In
activatethe services are built (ph_ossatura_servizi_veri: theyasde.jaris looked up next to the executable; the key path ischiave.pemin the config folder), then the shell and the window are created and the pieces installed. A second launch only presents the existing window.
3.2 · Connecting: from search to a live session
Everything between “no phone” and “connected” happens in tentativo and prova_candidato (src/collegamento/collegamento.c) on the link thread. The thread starts in CERCO (searching) as soon as ph_col_avvia returns.
- Last known address. From
telefoni.toml(the config piece): the phone expected, or the most recently seen one. It is tried first because the port of wireless debugging changes every time the option is turned on, but the address often still works. - Discovery.
ph_scoperta_cercafor 1500 ms; pairing services are ignored here. Known phones come first (heaviest weight: the most recently seen), then the others. If several are found and none is known, the first is taken and the notice says so (scelta_arbitraria). - ADB connection with
ph_adb_collega(8000 ms). If the phone does not recognise the key the outcome isT_NON_ABBINATO: if no candidate connects, the state becomesNON_ABBINATOand the link waits for the pairing code (5.2 “Pairing with the six-digit code”). - Serial number.
getprop ro.serialno; if empty orunknown,aid-<android_id>(fromsettings get secure android_id), and as a last resortmodello-<model>. After the first connection only the same serial is accepted: another phone at the same address is discarded. - Component start (6.1 “Starting the component on the phone”) with a 15000 ms limit for copy, launch,
PRONTOand greeting. - Data:
ph_dati_apriregisters on the events0x7e-0x7f(the link is the only one that does: there is one listener per component); then the locked state is read once. - Record.
telefoni.tomlis updated (serial, name, address ashost:portor[host]:portfor IPv6, last seen); a failure to save is never fatal. The session is published and the state becomesCOLLEGATO, orBLOCCATOif the screen is locked.
3.3 · Link states and timings
The link is a state machine with its own thread and no graphics. Notices are delivered one at a time from that thread, in order, and repeated notices are not sent twice.
| State | Meaning | Leaves when |
|---|---|---|
CERCO | searching, connecting | connected; or no candidate answers (waits pausa_cerca_ms and tries again); or the key is rejected |
COLLEGATO | ADB alive, component started, greeting done | the screen locks (BLOCCATO), or the connection or component dies (PERSO) |
BLOCCATO | connected but the phone screen is locked: the shell shows a veil | unlock (COLLEGATO), or drop (PERSO) |
PERSO | lost: retries by itself with growing waits | a retry succeeds; ph_col_riconnetti_ora skips the wait |
NON_ABBINATO | the phone does not know this PC's key | ph_col_abbina (pairing), or ph_col_riconnetti_ora to retry without pairing |
CHIUSO | close requested; everything released in order | final state |
| Option | Default | Used for |
|---|---|---|
durata_scoperta_ms | 1500 | one network search |
timeout_collega_ms | 8000 | ph_adb_collega (the whole TCP, STLS, TLS procedure) |
timeout_componente_ms | 15000 | ph_componente_avvia |
timeout_abbinamento_ms | 15000 | ph_abbinamento_esegui |
pausa_cerca_ms | 1000 | between two searches in CERCO |
riprova_iniziale_ms | 1000 | first wait in PERSO; doubles every time |
riprova_massimo_ms | 30000 | ceiling of that wait |
riprova_dopo_blocco_ms | 3000 | ceiling after a drop that happened from BLOCCATO: wireless debugging is reopened on unlock |
controllo_ms | 500 | period of the liveness and lock check |
attesa_prestiti_ms | 3000 | how long a drop waits for loans to be returned |
PhColOpzioni; 0 means default)While COLLEGATO or BLOCCATO the thread checks every controllo_ms that ph_adb_viva and ph_componente_vivo are still true and follows the lock flag, which comes from the 0x7e events and from the first state read. Some phones turn wireless debugging off when they lock: “locked, lost, unlocked, connected” then happens without any intervention.
3.4 · Loans: using the session objects
The link's sessions live only while the connection does. Whoever wants to use the ADB connection, the component or the data object takes a loan and gives it back; the link never destroys an object under the feet of a borrower.
ph_col_prestareturns a loan only inCOLLEGATOorBLOCCATO;ph_col_prestito_adb,ph_col_prestito_componenteandph_col_prestito_datiare valid untilph_col_restituisci.- On a drop (or on close) the link first stops granting loans, calls the
in_perditanotice (“about to lose the connection: give back”), then waits up toattesa_prestiti_msfor them. - If a loan is not returned in time the session becomes an orphan: its memory stays valid, calls fail quickly because the connection is dead, and the last to return destroys it in order (data, component, connection; up to about 2 s). Meanwhile the link goes on with a new session.
- Everything opened with the borrowed objects (channels from
ph_componente_canale, searches and clipboard ofdati) must be closed before the loan is returned. Video streams may be closed afterwards: the component closes them anyway, but they must still be passed toph_video_chiudi. - A loan must never be returned from inside a component or data callback (it could wait for that very callback): the same rule forbids calling
ph_col_chiudifrom a notice.
3.5 · Building the session on the shell side
When the link reports COLLEGATO or BLOCCATO, col_avviso (in src/shell/ossatura/servizi_veri.c) posts a message to the manager thread ph-gestore, which builds the shell-side session.
- Weather: the phone's serial is told to the weather service; the phone profile (window layout, desktop, preferences per phone) is loaded.
- Data (
sv_dati_sessione_nuova): the state is read; the listener for panel events0x6eis registered andPANNELLO_STATOis asked; if the panel is on and the phone is not “in hand” it is switched off, queued on the state pool because it can take seconds (10.4 “The phone panel: off when connected”); the clipboard channel is opened; the app list and the notifications are requested; the quick-controls state is read. - Transfers: the transfer queue gets the new session.
- Streams: every window already open (after a drop) is reopened (8.2 “Video: sessions and recovery”).
- Weather position: there is a phone now, so the position is the phone's.
- Audio is not started here: the first stream of the session schedules it
SV_AUDIO_RITARDO_MS(5000 ms) later, and a failed start is retried after 2, 4, 8 and 16 s (9.3 “Audio: playback on the PC”).
3.6 · Orderly close, drop and reconnection
There are two ways out: the user closes YASDE (orderly), or the connection or the service dies (drop). Both end with the phone as it was, the first by the component, the second by the guardian.
Orderly close. The window is hidden and destroyed (pieces stop listening), then ph_shell_libera closes the streams, then the services are freed: ph_col_chiudi raises in_perdita, the manager closes the session and returns the loan, and the component is closed. ph_componente_chiudi first forbids any new PRESENZA, sends CHIUDI and waits at most 2000 ms for the answer (the wait for the turn included), then joins its threads and closes the channels. The shell channel goes last: closing it is the safety net that stops the service. SIGTERM and SIGINT take the same path.
On the phone the Servizio answers OK and then: closes the command socket and the listening socket; runs the pieces' close actions on a separate thread for at most 3 s; asks the guardian to run the restore list (20 s limit per run); deletes its files; prints servizio terminato and exits.
Drop. If the connection dies (ph_adb_viva becomes false within about 10 s thanks to TCP keepalive and TCP_USER_TIMEOUT), or the service process ends, the link moves to PERSO, gives back the session as above and retries with waits of 1, 2, 4 ... up to 30 s. On the phone the service sees its command channel or stdin close and shuts down by itself; if it was killed (kill -9, or adbd restarted), the guardian reads end-of-file on its pipe and runs the restore list. The streams of the open windows become PERSO and are reopened by themselves when a new session exists; a running recording is stopped.
adbd kills the whole process group) leaves the jar and the restore script behind. The next service cleans them at start-up (6.6 “Cleaning up leftovers at start-up”).The ADB client
4.1 · The ADB client: transport
The ADB client is src/adb: a client for the Android Debug Bridge protocol written from scratch, with no ADB library and no use of the adb tool. It opens one TLS connection to the phone's wireless-debugging port and multiplexes any number of channels on it. It knows nothing about video, audio or files; its public header is src/adb/adb.h.
| File | Role |
|---|---|
adb.h | the contract: PhChiave, PhAdb, PhCanale, ph_shell_esegui |
chiave.c | RSA key file, self-signed certificate, public key in Android format |
connessione.c | TCP, STLS, TLS 1.3, reader thread, channels and flow control |
pacchetto.c, interno.h | the 24-byte packet header and its checksum |
shell.c | shell v2 commands |
finto_telefono.c | a fake phone used by tests |
src/adbThe concurrency model is binding: one reader thread per PhAdb reads every packet from the socket and routes it to its channel; writes on the socket are serialised by a mutex so that a packet is never split by another; every channel has its own incoming queue; ph_canale_leggi blocks (with a timeout) only the thread that reads that channel. On one channel one reader and one writer may work together, two readers or two writers may not. If the connection dies, every read and write in progress returns an error at once, no thread stays blocked, and ph_adb_viva becomes false.
4.2 · Connection and TLS handshake
The connection is opened by ph_adb_collega(host, port, key, timeout, not_paired, error). One deadline covers the whole procedure: TCP connect, STLS exchange, TLS handshake and the phone's greeting.
- TCP. A non-blocking socket tried on every address returned by
getaddrinfo. After connecting:TCP_NODELAY,SO_KEEPALIVEwith idle 5 s, interval 2 s, 3 probes, andTCP_USER_TIMEOUT10000 ms: a phone that leaves the Wi-Fi without closing is detected in about 10 s instead of hours.SIGPIPEis ignored for the whole process (once, only if nobody chose a behaviour), because OpenSSL writes withwrite(). - CNXN in clear. Version
0x01000001(checksum no longer verified: integrity is given by TLS), maximum data 1 MiB, bannerhost::features=shell_v2,cmd,delayed_ack;. The final semicolon is required: adbd reads the banner as a C++ string including the terminator, and without it the last feature would bedelayed_ackfollowed by a NUL byte and would not be recognised. - STLS. If the phone answers
AUTHthe PC is not paired (*non_abbinato = true); any other answer is an error. The PC answersSTLSand starts TLS. - TLS 1.3 only, with the PC certificate. The phone certificate is not verified (it is self-signed, as for the standard tool): what matters is that the phone recognises the PC, and it decides by the PC key. The handshake failing with a certificate alert, or the phone closing during or just after the handshake, is reported as “not paired”; any other error is a network error.
- Greeting. Inside TLS the phone sends its CNXN: its maximum data (capped at 1 MiB, and refused if below 256) and the banner (which contains the model).
delayed_ackis active only if both sides declared it.
The banner is available as ph_adb_presentazione. ph_adb_chiudi marks the connection closed, shuts the socket down to wake the reader, joins it and releases; the file descriptor and the SSL object stay until the last channel is closed, so that a channel finishing an operation never finds a recycled descriptor.
4.3 · The PC key and certificate
The key and the certificate live in chiave.c. The key file is chiave.pem in ~/.config/YASDE, an RSA 2048-bit private key in PKCS#8 PEM (the format of the standard tool's adbkey, so that in development an already paired phone can be reused).
| Item | Value |
|---|---|
| Creation | ph_chiave_carica_o_crea: if the file is missing the key is generated and saved with permissions 0600, creating the folder with 0700 |
| Certificate | X.509 v3, serial 1, subject and issuer CN=yasde, valid from one day ago for ten years, signed with SHA-256; used for TLS and for pairing |
| Public key for the phone | ph_chiave_pubblica_adb: Android's RSAPublicKey structure (length in words, n0inv, modulus, rr = (2^2048)^2 mod n, exponent; little endian; 524 bytes) in base64, followed by a space and user@host, NUL-terminated |
| OpenSSL API | only EVP and BN calls of OpenSSL 3; the deprecated low-level RSA functions are not used |
n0inv and rr are what adbd needs for Montgomery multiplication; this is why the key cannot be sent as a plain public key.4.4 · Channels and flow control
A channel is one ADB service opened on the connection: ph_canale_apri(adb, service, timeout, error). Services used by YASDE: shell,v2,raw:<command>, shell:<command>, sync: and localabstract:yasde.
| Function | Behaviour |
|---|---|
ph_canale_leggi | reads 1 to n bytes; returns the count, PH_CANALE_CHIUSO (0: the other side closed and the queue is empty), PH_CANALE_ERRORE (-1, error filled) or PH_CANALE_TEMPO (-2: timeout, not an error); a negative timeout waits without limit |
ph_canale_leggi_tutto | exactly n bytes or failure; closing before n bytes is an error |
ph_canale_scrivi | all n bytes, split in ADB packets, or failure |
ph_canale_chiudi | closes and frees; wakes a read in progress in another thread |
Flow control exists in two forms, chosen at connection time.
| Mode | Sending | Receiving |
|---|---|---|
delayed_ack (both sides declare it) | a window per channel: the phone's OKAY carries the number of bytes by which the window grows; the PC never sends beyond it, and several writes may be in flight | the PC grants the phone a 4 MiB window per channel (FINESTRA_RICEZIONE); each OKAY widens it by what the reader really consumed, sent after 1 MiB of consumed data (ACK_SOGLIA); a phone sending beyond its window violates the flow control and the connection drops |
| classic | after a WRTE the OKAY is awaited before the next WRTE on the same channel | the OKAY is sent when data is queued, but withheld while the queue exceeds twice the maximum packet (SOGLIA_CODA), and resumes when the reader has emptied it |
The effect is that a slow reader brakes the phone instead of filling the PC's memory. Waiting for an OKAY or writing to the socket has a hard limit of 30000 ms (ATTESA_SCRITTURA_MS): a phone that stops answering does not block a thread for ever. A late reply to an open that had timed out is answered with CLSE so that the service is closed on the phone.
ph_pacchetto_decodifica, which refuses a magic that is not the complement of the command and a length above PH_ADB_MAX_DATI (1 MiB); an OKAY with a malformed payload in delayed_ack mode drops the connection.4.5 · Shell commands
ph_shell_esegui(adb, command, out, err, &code, timeout, error) runs a command with the shell v2 protocol and waits for the end. It opens a channel with service shell,v2,raw:<command>, reads frames of one id byte plus a 32-bit little-endian length plus data, and closes the channel.
| Id | Meaning |
|---|---|
1 | stdout: appended to out (may be NULL) |
2 | stderr: appended to err (may be NULL) |
3 | exit code, one byte; ends the command |
It returns -1 if the command could not run or the time ran out; a non-zero exit code is not an error of the function. A frame longer than 16 MiB is refused. Read in slices of 4096 bytes. The component itself is started with the older shell: service because its output is a plain line stream (6.1 “Starting the component on the phone”).
4.6 · File transfer with sync
The copy of the component jar and every file transfer use the ADB sync: service, in src/file/file.c. Requests are four letters plus a 32-bit little-endian length (the protocol is documented in AOSP's SYNC.TXT; the code here is new). Each operation opens its own sync: channel, so several can run together from different threads.
| Operation | Request | Notes |
|---|---|---|
ph_file_invia | SEND + DATA blocks + DONE | PC to phone; creates or overwrites; keeps the local modification time; a partial remote file is removed on cancel or failure; mode 0100644 |
ph_file_ricevi | RECV, with a prior STA2 | phone to PC; writes <local>.parziale created exclusively, renames at the end without replacing an existing file, gives the phone's modification time; never overwrites a user file |
ph_file_elenca | LIS2 (entries DNT2) | folder listing without . and ..; sorted: folders first, then files, by name ignoring case; hidden names are included (the shell filters) |
ph_file_info | STA2 | information on a path |
| remove remote | shell:rm -f -- '<path>' | sync cannot delete; the path is quoted with '\'' for embedded quotes |
sync: operations| Constant | Value | Meaning |
|---|---|---|
BLOCCO_MAX | 65536 | largest DATA block (protocol limit) |
BLOCCHI_PER_SCRITTURA | 16 | blocks gathered in one write (cancellation is checked about every MiB) |
PH_FILE_ATTESA_MS | 30000 | silence after which the phone is declared stuck |
PH_FILE_FETTA_MS | 200 | read slice, so the cancel flag is checked often |
PERCORSO_MAX | 1024 | longest path in a sync request |
VOCI_MAX, NOMI_BYTE_MAX | 200000; 64 MiB | safety caps on entries and on the bytes of their names |
src/fileOutcomes are PhFileEsito: PH_FILE_RIUSCITO, PH_FILE_ERRORE, PH_FILE_ANNULLATO (the cancel flag became true), PH_FILE_NON_TROVATO, PH_FILE_NON_CONSENTITO (Android denies access) and PH_FILE_ESISTE (the destination or its .parziale already exists on the PC: nothing was touched). A FAIL from the phone is plain text and is classified by its words.
Discovery and pairing
5.1 · Discovery with mDNS
Discovery is src/scoperta: a multicast-DNS (DNS-SD) client written from scratch, with no Avahi and no library. It looks for the two services Android announces while Wireless debugging is on. It depends only on src/comune.
| Service | Gives | Exists |
|---|---|---|
_adb-tls-connect._tcp.local | the port to connect to (abbinamento = false) | while wireless debugging is on; the port changes every time it is turned on |
_adb-tls-pairing._tcp.local | the pairing port (abbinamento = true) | only while the phone shows the pairing-code screen |
API. ph_scoperta_cerca(duration_ms, found, max, error) asks on every active interface, collects answers for the given time and fills PhTelefonoTrovato (instance name such as adb-R5CT0000000-AbCdEf, address text, port, pairing flag), without duplicates. It returns the count; zero is not an error. ph_scoperta_leggi_risposta and ph_scoperta_domanda are the pure parts, testable without a network; a malformed or hostile packet must never read outside the buffer and returns 0.
- Sockets. IPv4 only for sending: one socket per interface that is up, running, not loopback and multicast-capable (at most 16, one per distinct address), bound to that interface with
IP_MULTICAST_IF, TTL 255, multicast loop off. Replies sent from a port other than 5353 come back unicast to that socket. - Listening. One extra socket on UDP 5353 joined to
224.0.0.251, shared with other programs (Avahi may already own the port). If the port is not available the search goes on with unicast replies only. - Questions. The first question has the QU bit (unicast answer wanted). Questions repeat at 0, 250, 1000, 2000, 3000, 4500, 6000 and 8000 ms from the start and then every 2 s, because a phone with Wi-Fi in power saving answers late. From the second question on, follow-up questions are added: SRV for an instance seen in a PTR without SRV, and A for an SRV target without an address.
- Filtering. A packet whose source is outside the subnet of every interface is discarded (multicast is not routed, so an outside sender is not a real neighbour). At most 64 packets are read per socket per turn, and the time limit is checked inside the loop.
- Combining. PTR, SRV and A/AAAA records may arrive in different packets and are joined only at the end; the list is recomputed from scratch at every turn so that a TTL 0 “goodbye” removes an entry already found. Name compression is followed for at most 16 pointers; the collection holds at most 64 SRV, 128 address and 64 PTR records.
The link asks for 1500 ms per search (3.3 “Link states and timings”). The hand tool src/scoperta/cerca.c searches for 5 seconds and prints a trace of every packet; it is how a silent phone is diagnosed.
5.2 · Pairing with the six-digit code
Pairing is src/abbinamento. ph_abbinamento_esegui(host, port, code, key, timeout_ms, error) makes the phone register the PC's public key. host and port are those of the pairing service, not of the connection. The code is the one the phone shows under Developer options, Wireless debugging, Pair device with pairing code.
- Transport. TCP with a deadline, then TLS 1.3 with the PC certificate; the phone certificate is not verified (the guarantee comes from the code). All reads and writes have a socket timeout equal to
timeout_ms(10000 if zero or negative).SIGPIPEis ignored, because pairing happens before any connection. - Binding to the connection. 64 bytes are exported from the TLS session with
SSL_export_keying_material(labeladb-labelincluding its terminating zero, no context). The SPAKE2 password is the code followed by these bytes, so a man in the middle cannot reuse the exchange on another connection. A code of 1 to 32 characters is accepted at this level. - SPAKE2. On edwards25519, in the variant used by Android (BoringSSL's, with its quirks reproduced on purpose: without them the phone refuses). The PC is
alicewith the nameadb pair client, the phone isbob(adb pair server); both names enter the final digest with their zero terminator (16 bytes each). The points M and N are fixed, generated from the seedsedwards25519 point generation seed (M)and(N), and a test regenerates them. The arithmetic uses OpenSSL BIGNUMs: correct but not constant time, which is accepted because the code is valid once, for a few seconds, on the home network. - Key. HKDF-SHA256 over the 64-byte SPAKE2 key with info
adb pairing_auth aes-128-gcm key(no terminating zero) gives a 16-byte AES key. - Information exchange. Each side sends one packet of 8192 bytes plus the 16-byte AES-GCM tag, with nonce counter 0 (8 bytes little endian plus four zeros). The PC's plaintext is the type byte 0 (ADB public key) followed by the key text of
ph_chiave_pubblica_adb; the rest is zeros. - Verification. A wrong code is detected only by the failure to decrypt the phone's packet (or by the phone closing): this is the single confirmation.
| Field | Size | Value |
|---|---|---|
| Version | 1 byte | 1 |
| Type | 1 byte | 0 = SPAKE2 message, 1 = information |
| Length | 4 bytes big endian | at most 2 * 8192; checked before reading |
| Body | length | 32 bytes (SPAKE2) or 8192 + 16 bytes (information) |
Secrets are wiped with OPENSSL_cleanse (password, shared key, AES key, plaintext). Failures return a specific sentence: phone silent on that port; phone closed the pairing (code expired or screen closed); wrong protocol version; unexpected or oversized answer; “wrong or expired code”.
5.3 · Pairing as seen by the link and the shell
From the user's side pairing is a state of the link, not a separate program. When ph_adb_collega reports that no candidate knows the PC key, the link enters NON_ABBINATO and the shell shows the connection window.
- The window asks for the six-digit code. The field accepts only digits, at most 6, even when pasted: spaces and other characters are filtered out and the buffer is wiped (
src/shell/connessione). - The shell registers the request before calling
ph_col_abbina(code)(orph_col_abbina_a(host, port, code)when an address is typed) and starts a timer. The outcome is not a return value: it arrives in a link notice whose fieldesito_abbinamentoisRIUSCITOorFALLITO, exactly once per accepted request. With no outcome inPH_SRV_ABB_LIMITE_S(60) seconds the request counts as expired. - The link thread looks for the pairing service for 1500 ms: the one at the address of the phone that answered “not paired”, otherwise the only one present; with more than one and no match, or none, the notice says to open the pairing-code screen on the phone and try again.
- It loads or creates the key and calls
ph_abbinamento_eseguiwith a 15000 ms limit. Success moves the state toCERCO(“pairing done: connecting”); failure stays inNON_ABBINATOwith a sentence of the link's own: user-facing messages never contain addresses or the library's text. - The code is wiped with
explicit_bzeroright after use and never reaches a log or a file. If a close arrives during pairing no notice concludes the request; onlyCHIUSOarrives.
ph_col_riconnetti_ora in NON_ABBINATO retries the connection without pairing; it is refused (-1) while a pairing is accepted or running.
The phone component
6.1 · Starting the component on the phone
The PC side of the phone component is src/componente. It copies the jar to the phone, launches the service, opens the protocol channels, greets the service and then offers the rest of the PC two things: requests answered with OK or ERRORE (and events that arrive at any time), and the video and input functions. It uses only adb.h and file.h and never decodes video: it hands packets to the layer above.
| File | Role |
|---|---|
componente.h | the contract: message codec, PhComponente, video and input functions, presence |
componente.c | start, close, command thread, requests, input |
video.c | video sessions: open, read packets, resize, key frame, pause, close |
messaggi.c, lettura.c | message writer and bounded reader; resumable reads |
interno.h | internal constants and the PhComponente structure |
src/componenteph_componente_avvia(adb, jar, event_fn, user, info, timeout_ms, error) does the following in order. timeout_ms (0 means 10000) applies to the launch, the wait for PRONTO, opening the channels and the greeting; afterwards a request has 15000 ms (PH_TIMEOUT_RICHIESTA_MS, because opening an app can take a while).
- Name.
/data/local/tmp/yasde-<8 hex digits>.jarwith the digits read from/dev/urandom. The name changes at every start so that the guardian of a service that has just died, which deletes its own jar, cannot delete the next one. - Copy with
ph_file_invia(4.6 “File transfer with sync”). The “jar copied” flag is set before the copy: if anything fails from here on, the jar is removed withrm -f(3000 ms limit, result ignored). - Launch with the legacy
shell:service:CLASSPATH=<jar> app_process / it.yasde.Servizio. The channel stays open for the whole life of the service; if it closes, the service ends. - Wait for PRONTO: the output is read line by line (lines of at most 160 characters are kept, a longer unterminated chunk beyond 4096 bytes is dropped); earlier log lines are discarded but the last one is remembered for the error message (“the service ended before PRONTO; last line: ...”).
- Channels. Each protocol channel is an ADB channel
localabstract:yasdefollowed by one ASCII line naming its type. The component openscomandiandinputitself; the rest of the PC opens others throughph_componente_canale(audio,cerca,appunti), which refuses the three names owned by the component (comandi,input,video:...) and any line longer than 60 characters. - Threads are started: command reader and shell-log reader; then
SALUTOis sent; then the presence thread. - Greeting.
SALUTOcarries the protocol version (1). The reply gives the version, the Android API level, the real screen size and density, and the model (PhTelefonoInfo). A different version is an error.
| Constant | Value | Meaning |
|---|---|---|
PH_PROTOCOLLO_VERSIONE | 1 | protocol version |
PH_MSG_MAX_CORPO | 1 MiB | largest message body; a larger declared length ends the command thread |
PH_VIDEO_MAX_PACCHETTO | 8 MiB | largest video packet |
PH_FETTA_MS | 50 | every blocking read is cut in slices of this size, so a close never waits long |
PH_TIMEOUT_PREDEFINITO_MS | 10000 | start-up default |
PH_TIMEOUT_RICHIESTA_MS | 15000 | one request |
PH_PRESENZA_INTERVALLO_S | 300 | idle time after which PRESENZA is sent |
Requests. The command channel serves one request at a time: ph_componente_richiedi_coda takes the turn (a flag, not a mutex, because the wait is timed and the death of the component wakes the queue), writes the message and waits for the OK or ERRORE delivered by the reader thread. An ERRORE becomes a PhErrore with the phone's sentence; the sentence tipo sconosciuto is turned into “the service on the phone does not know request 0x..”. If the phone does not answer within the limit the channel is no longer aligned (a late answer would be taken for the next one), so the component is declared dead. An answer with no request waiting is discarded.
Events (phone to PC, any time, even between a request and its answer) are told apart by type. Video events (0x48) go to the PhEvento given at start; others go to listeners registered with ph_componente_ascolta by type range (at most 8, a range overlapping another without being equal is an error, a NULL function removes). The listener table lock stays held during the call, so removing a listener waits for a call in progress; a listener must return fast and must not call request functions.
Presence. The thread thread_presenza sends PRESENZA when no request has started for presenza_ms (300 s). It uses the boot clock (CLOCK_BOOTTIME, which advances while the PC sleeps, so at wake-up the message goes at once) and waits in slices of at most 30 s. A failure writes one generic line on stderr and is retried at the next expiry. See 10.7 “Signs of life and PC absence”.
6.2 · The service process
The service runs Servizio.main in telefono/base/it/yasde/Servizio.java. Every thread catches everything, including Error, so a broken channel cannot bring the service down. The order of its start-up matters.
- Find the running jar from
CLASSPATH; it is accepted only if it is under/data/local/tmp/, ends in.jarand has no..(otherwise nothing will be deleted at the end). - Create the guardian object (not started).
- Take the socket: an abstract
LocalServerSocketnamedyasde. From here no other service of this name is alive. - Clean leftovers of dead sessions (6.6 “Cleaning up leftovers at start-up”), before starting the own guardian (its script could have the name of a dead one with the same pid).
- Start the guardian (6.5 “The guardian and the restore list”) and register it in
Registro; add a JVM shutdown hook (SIGHUP, SIGTERM) that runs the close withoutSystem.exit. - Check the hidden APIs (
Nascoste.verifica) and log the missing ones; then register the pieces (below). - Start the stdin guard thread: if the shell's stdin closes, the PC is gone and the service shuts down.
- Print
PRONTOand loop onaccept, one daemon thread namedcanaleper connection.
Pieces. Servizio calls by reflection the static method registra() of each class in PEZZI; a missing class is skipped with a log line.
| Class | Folder | Registers |
|---|---|---|
Video | telefono/video | channel video, commands 0x40-0x4f, close action |
Input | telefono/video | channel input |
Audio | telefono/audio | channel audio, close action |
Dati | telefono/dati | commands 0x70-0x73, 0x76-0x77, 0x7b-0x7d, 0x90-0x9f; events 0x7e, 0x7f; close action |
Archivio | telefono/archivio | commands 0x74, 0x75 |
Cerca | telefono/archivio | channel cerca |
Appunti | telefono/appunti | channel appunti, close action |
Pannello | telefono/pannello | commands 0x60-0x6f, signs of life, close action |
Controlli | telefono/controlli | commands 0x80-0x8f, close action (turns off the torch YASDE lit) |
Channels. Each connection is first checked for who is on the other end (6.4 “Who may talk to the component”), then a line of at most 64 characters is read with a 5 s socket timeout. comandi is served by the service itself and only one command channel may exist (a second is refused). Any other line is split at the first colon into prefix and argument and handed to Registro.canale; an unknown prefix closes the channel.
Command channel. A loop reads a message, calls Smistatore.tratta and writes OK or ERRORE under a lock shared with the events, so answers and events never interleave. An exception becomes ERRORE with its message (an exception with no message becomes “malformed request”: a Java class name is never sent). After a successful CHIUDI the loop ends and the service shuts down; if the channel closes for any reason the service shuts down as well.
6.3 · The registry and the dispatcher
Registro (in telefono/contratto) is the meeting point between the service and the pieces, so the two folders compile without each other. Everything in it is thread-safe.
| Method | Used by | Purpose |
|---|---|---|
registraCanale(prefix, handler) | pieces | serve the channel whose first line starts with the prefix (GestoreCanale.gestisci(socket, argument)) |
registraComandi(from, to, handler) | pieces | serve command types in a range (GestoreComandi.gestisci(type, body) returns the body of the OK) |
registraChiusura(runnable) | pieces | what to do at orderly close; run before the guardian restores; never run if the service is killed |
mandaEvento(type, body) | pieces | send an event to the PC; does nothing without an open command channel |
guardiano() | pieces | the guardian; can be null in isolated tests of one piece |
segnoDiVita(nowMs) | dispatcher | record a sign of life of the PC and notify listeners |
registraSegnoDiVita(runnable) | pieces | be notified at every sign of life, on the command thread: only wake a thread, no work |
RegistroSmistatore has no Android classes (the clock and the greeting come from outside) so it can be tested on a plain JVM. For every message, even unknown or malformed, it first records the sign of life, then dispatches: SALUTO to the greeting function; PRESENZA answers an empty OK (and refuses a non-empty body); CHIUDI answers an empty OK; anything else goes to the handler registered for its type, or fails with tipo sconosciuto.
6.4 · Who may talk to the component
The socket is abstract and in principle reachable by any process of the phone. Without a check any app could take the command channel before the PC, or open input and send touches. The PC always arrives through adbd, that is as the shell user.
Right after accept and before reading one byte, Servizio.connessione reads the peer's credentials from the kernel (not forgeable) and accepts only Pari.UID_SHELL (2000) and Pari.UID_ROOT (0, which is adbd on development phones). Any other uid (apps start at 10000) is closed at once. If the credentials cannot be read, the connection is refused. The refusal is logged as collegamento rifiutato (uid N non ammesso) at most once per second. The uid is not personal data and is what tells you what to change if some phone's adb shows a different user.
6.5 · The guardian and the restore list
The guardian is the class Custode (telefono/base/it/yasde/Custode.java), the implementation of the Guardiano interface. It makes sure the phone returns as it was even if the service dies abruptly. The design documents speak of two guardians (connection and service); the code has this single one.
- A separate process. The service starts
setsid sh -c <script>, a shell that is leader of its own session, so it dies neither with the service nor with the PC's shell. The service keeps the write end of a pipe open: its death, however it happens (evenkill -9), closes the pipe and the guardian reads end-of-file. - The list. The restore commands live in a file
/data/local/tmp/yasde-custode-<pid>.sh, rewritten atomically (temporary file,fsync, rename on the same file system) at everyimpostaortogli. The guardian runs it as a script. It starts withecho $$ > "$0.pid"(the id of the session, used to kill leftovers) and definestimeout 20if the phone has it. - One shell per entry, sorted by order (lowest first; equal orders keep insertion order), each in its own
sh -c '...'so a wrong command does not eat the next ones; each runs undertimeout 20when available. - The guardian's script reads one line from the pipe. If the line is not
fine(end-of-file: the service died) it runs the list. Then it deletes the list and its.tmpand.pid, deletes the jar only if it is still the same file seen at start (inode, size, date: the PC may already have copied a new one), and as a last act kills the processes still in its own session, including children of an expired restore adopted by init. - Orderly close:
ferma()runs the list itself (20 s limit; on expiry the session is killed withpgrep -s), then writesfineand closes the pipe; the guardian only deletes the files. If a restore does not finish in time,fineis not written and nothing is deleted: closing the pipe makes the guardian redo the list.
The contract (Guardiano): imposta(name, order, shellCommand) returns true only if the restore is really safe, that is the new list was written. If it returns false the caller must not make the change, because nobody would undo it. After the guardian has stopped, imposta executes the command at once (20 s) and returns false. togli(name) removes an entry whose change has already been undone; if the rewrite fails the disk list keeps the entry (one entry too many, conditional and harmless, is better than one too few).
Value-wins rule. A restore command changes a setting only if it still has the value YASDE wrote; if the user changed it meanwhile, it stays. Commands are self-contained shell lines: no environment variables of the service, no nested quotes.
| Entry | Order | Registered by | Restores |
|---|---|---|---|
audio-volume | 50 | Cattura | media volume back to the original, only if still at the maximum YASDE set (cmd media_session volume --stream 3) |
pannello-acceso | 400 | Pannello | panel on: CLASSPATH=<jar> app_process / it.yasde.Pannello accendi, which does nothing if Android is asleep |
pannello-frequenza | 410 | Pannello | min_refresh_rate back to the user's value, only if still ours |
pannello-timeout | 420 | Pannello | screen_off_timeout back to the user's value (or deleted if it did not exist), only if still the maximum |
trova-volume, trova-modo, trova-non-disturbare | 420-422 | Trova | unused: “find my phone” is not available in this version |
TieniSveglio) is not in the list for the same reason it is not needed: the system releases it when the process dies.6.6 · Cleaning up leftovers at start-up
If adbd restarts (wireless debugging switched off and on), init kills every process of its group, even those with setsid: service and guardian die together and the jar and the restore script stay on the phone. The next service cleans them. The rule is in Resti (pure, with no Android classes: the processes are read from a folder passed in, so it is tested on a JVM) and Custode.pulisciResti.
- Names recognised by exact form only:
yasde-custode-<pid>.shwith accessories.pid,.tmpand.tentativi, andyasde-<8 hex>.jar. - If there is nothing of ours apart from the current jar, the costly scan of the processes is skipped.
- Scan of the processes in
/proc: the pids of services and the paths under the folder cited by any process. If the own service is not among the processes read, the scan is not reliable and nothing is executed or deleted. - The plan. A script is dead if its pid is not a live service (the own pid always counts as dead: its guardian has not started) and no live process cites it. A jar is old if it is not the current one and no live process cites it. Orphan accessories whose script is gone are deleted.
- Run dead scripts first (their pending restores) with a total budget
4000ms, of which 1000 reserved to kill the session of an expired one; only files that are regular, not links and owned by shell or the service's own user are executed. A counter in.tentativi, written before running, stops retries: afterMAX_TENTATIVI(3) failed starts the script is no longer executed and stays on the phone with the user's restores inside. - Then delete the script and accessories, then the old jars; a jar cited by a script that is left behind stays, because the script's command (
app_process ... it.yasde.Pannello accendi) needs it.
This must finish before PRONTO, which the PC waits for only a short time, hence the budget. The PC side removes its own jar when start-up fails (6.1 “Starting the component on the phone”).
6.7 · What happens when the service dies
What happens depends on how the service ends.
| Cause | Service | Phone | PC |
|---|---|---|---|
| PC closes YASDE | gets CHIUDI, runs close actions and restores, deletes jar | as before | orderly |
| PC silent (no signs of life) | keeps running | after 30 minutes without signs of life the panel and the wake lock are released but service and sessions stay | 10.7 “Signs of life and PC absence” |
| Command channel or stdin closes | shuts down by itself, restores | as before | link goes to PERSO |
| SIGHUP, SIGTERM | shutdown hook: close without exit; the guardian is the net | as before | link goes to PERSO |
kill -9 of the service | gone | guardian reads end-of-file and runs the list, then removes files | link goes to PERSO, reconnects with a new jar |
| adbd restarted | service and guardian both gone | leftovers stay until the next start | reconnects; the new service cleans (6.6 “Cleaning up leftovers at start-up”) |
The protocol
7.1 · Channels
The protocol between the PC and the component is described in docs/protocollo.md, which is the contract between src/componente (PC, C) and telefono/ (phone, Java). Whoever finds it wrong or incomplete does not change it alone: the problem is reported to whoever coordinates. This chapter reorganises that document for reading; the version is 1 (PH_PROTOCOLLO_VERSIONE, Protocollo.VERSIONE).
All the channels are ADB channels of the service localabstract:yasde. Immediately after opening one, the PC writes a line of ASCII text ended by a newline that names the channel type. The service accepts lines of at most 64 characters (5 s to arrive).
| Line | Channel | How many | Direction |
|---|---|---|---|
comandi | requests and answers, events | one | both |
video:<id> | H.264 packets of the session | one per session | phone to PC |
input | mouse and keyboard events | one | PC to phone |
audio | Opus packets | one (a second is closed) | phone to PC |
cerca | search of files and folders | one per search | both |
appunti | shared clipboard | one | both |
An unknown type makes the service close the channel. The service runs as uid 2000 and, at the end (command channel closed, or shell closed), closes every session, runs the restores and deletes the jar.
7.2 · Message format
On comandi and input every message has the same shape. All numbers are big endian; a stringa is a 2-byte length followed by UTF-8 with no terminator.
| Field | Size | Notes |
|---|---|---|
| type | 1 byte | see the tables below |
| length | 4 bytes | body length only; at most 1 MiB (PH_MSG_MAX_CORPO, Protocollo.MAX_CORPO) |
| body | length bytes | depends on the type |
On comandi the PC sends one request at a time and waits for the answer, OK (possibly with a body) or ERRORE. Events (phone to PC) may arrive at any moment, even between a request and its answer, and are recognised by their type. Two channels have a different layout: video:<id> (8.4 “Video: receiving and decoding”) and audio (9.1 “Audio: capture and transport”). The clipboard messages carry the text as a 32-bit length plus UTF-8, not as a stringa.
| Writer | Reader |
|---|---|
ph_msg_inizia, ph_msg_u8, ph_msg_u16, ph_msg_i16, ph_msg_u32, ph_msg_stringa, ph_msg_finisci (writes the provisional length, then corrects it) | PhLettore with ph_leggi_u8..ph_leggi_u64 and ph_leggi_stringa: a cursor that never leaves the buffer; after a short body rotto stays true and reads return 0 |
Protocollo.scrivi, Protocollo.scriviStringa, Protocollo.corpoErrore | Protocollo.leggi: refuses a length above the maximum |
comandi counts as a sign of life (10.7 “Signs of life and PC absence”).7.3 · Message types
Types by range. Direction: PC→T is a request or command from the PC to the phone, T→PC is an answer or event.
| Type | Name | Direction | Body |
|---|---|---|---|
General (0x01–0x0f), on comandi | |||
0x01 | SALUTO | PC→T | u16 protocol version. Answer OK: u16 version, u16 API level, u16 width, u16 height, u16 dpi, stringa model. A different version is ERRORE |
0x02 | OK | T→PC | depends on the request; empty if not said |
0x03 | ERRORE | T→PC | stringa a sentence in Italian (shown to the user only after translation or kept to the log); unknown type: tipo sconosciuto |
0x04 | CHIUDI | PC→T | empty; the service answers OK and then restores everything and ends |
0x05 | PRESENZA | PC→T | empty; answer OK empty. “The PC is alive” |
Video (0x40–0x4f), on comandi | |||
0x40 | VIDEO_APRI | PC→T | u32 id, u16 width, u16 height, u16 dpi, u32 bits per second, u8 fps, stringa app package (empty = mirror of the real screen) |
0x41 | VIDEO_CHIUDI | PC→T | u32 id, u8 remove_task (1 = remove the app from recents) |
0x42 | VIDEO_RIDIMENSIONA | PC→T | u32 id, u16 width, u16 height, u16 dpi. Answer OK: u16 width, u16 height actually applied |
0x43 | VIDEO_CHIAVE | PC→T | u32 id: ask for a key frame now |
0x44 | VIDEO_PAUSA | PC→T | u32 id |
0x45 | VIDEO_RIPRENDI | PC→T | u32 id |
0x48 | VIDEO_EVENTO | T→PC event | u32 id, u8 what, u16 a, u16 b |
Input (0x50–0x55), on input, PC to phone only, no answer | |||
0x50 | TOCCO | PC→T | u32 id, u16 width, u16 height, u8 action (0 down, 1 move, 2 up, 3 cancel), u16 x, u16 y, u8 buttons (bit 0 left, 1 right, 2 middle; sent by the PC, not read by the phone in this version) |
0x51 | ROTELLA | PC→T | u32 id, u16 width, u16 height, u16 x, u16 y, i16 horizontal, i16 vertical (in 120ths of a notch) |
0x52 | TASTO | PC→T | u32 id, u8 action (0 down, 1 up), u32 Android key code (KeyEvent.KEYCODE_*), u32 modifier state (KeyEvent.META_*) |
0x53 | TESTO | PC→T | u32 id, stringa text to insert |
0x54 | INDIETRO | PC→T | u32 id: the Back key (down and up) |
0x55 | PIZZICO | PC→T | u32 id, u16 width, u16 height, u8 phase (0 start, 1 continue, 2 end, 3 cancel), u16 x, u16 y, i16 step (120ths of a notch, positive = zoom in, −1200..1200) |
Clipboard (0x58–0x5a), on appunti | |||
0x58 | APPUNTI_TESTO | T→PC | the text just copied on the phone |
0x59 | APPUNTI_IMPOSTA | PC→T | the text to put in the phone's clipboard |
0x5a | APPUNTI_INCOLLA | PC→T | u32 video session id, then the text; puts it in the clipboard and sends “paste” to the app of that session |
Panel (0x60–0x6f), on comandi | |||
0x60 | PANNELLO_IMPOSTA | PC→T | u8 0 = off, 1 = on |
0x61 | PANNELLO_STATO | PC→T | empty. Answer OK: u8 on, u8 in hand |
0x6e | PANNELLO_EVENTO | T→PC event | u8 on, u8 reason (1 user, 2 call, 3 call ended, 4 asked by PC, 5 restore at close, 6 PC absent 30 min) |
Phone data (0x70–0x7f), on comandi unless noted | |||
0x70 | APP_ELENCO | PC→T | empty. Answer: u16 count, then per app stringa package, stringa shown name, u8 flags (bit 0 system app, bit 1 portrait only) |
0x71 | APP_ICONA | PC→T | stringa package, u16 side in pixels (16–512). Answer: the bytes of a square PNG |
0x72 | STATO | PC→T | empty. Answer: u8 battery 0–100, u8 charging, u8 network (0 none, 1 Wi-Fi, 2 cellular), u8 signal 0–4, u8 screen locked |
0x73 | NOTIFICHE | PC→T | empty. Answer: u16 count, then per notification stringa key, package, title, text, u64 time (ms since 1970) |
0x74 | MINIATURA | PC→T | stringa file path, u16 maximum side (32–512). Answer: the bytes of a JPEG |
0x75 | MEMORIA | PC→T | empty. Answer: u64 total bytes, u64 free bytes of internal storage |
0x76 | MEMORIA_DETTAGLIO | PC→T | empty. Answer: u64 bytes of images, video, audio, apps (code and data, cache included); unreadable = 0xFFFFFFFFFFFFFFFF |
0x77 | CALENDARIO | PC→T | u8 maximum (1–16). Answer: u16 count, per event stringa title, u64 start, u64 end, u8 all-day |
0x78 | CERCA | PC→T | on cerca: stringa start folder, stringa text, u8 folders only, u16 maximum results |
0x79 | TROVATO | T→PC | on cerca: stringa full path, u8 is a folder |
0x7a | CERCA_FINE | T→PC | on cerca: u8 reason (0 finished, 1 maximum reached, 2 error) |
0x7b | CALENDARIO_INTERVALLO | PC→T | u64 from, u64 to (at most 62 days), u16 maximum (1–500). Answer: u8 truncated, stringa package of the default calendar app, then count and events as in CALENDARIO |
0x7c | SVEGLIA | PC→T | empty. Answer: u8 there is one, u64 time, stringa package that set it |
0x7d | BATTERIA | PC→T | empty. Answer: u8 level, u8 status, u8 power source bits, i16 temperature in tenths of °C (0x7fff unknown), u8 health, u16 millivolts, i32 minutes to full, i32 minutes of estimated autonomy (−1 unknown) |
0x7e | STATO_CAMBIATO | T→PC event | as the answer of STATO |
0x7f | NOTIFICHE_CAMBIATE | T→PC event | empty: the PC asks NOTIFICHE again |
Quick controls (0x80–0x8f), on comandi | |||
0x80 | CONTROLLI_STATO | PC→T | empty. Answer: u8 ringer (0 ring, 1 vibrate, 2 silent, 0xff n/a), u8 Do Not Disturb, u8 torch, u8 find in progress, u8 possible commands (bit 0 ringer, 1 DND, 2 torch, 3 find) |
0x81 | SUONERIA_IMPOSTA | PC→T | u8 mode |
0x82 | NON_DISTURBARE_IMPOSTA | PC→T | u8 0 off, 1 on (priority only) |
0x83 | TORCIA_IMPOSTA | PC→T | u8 0 off, 1 on |
0x84 | TROVA_AVVIA | PC→T | u16 maximum seconds; in this version always ERRORE without touching anything |
0x85 | TROVA_FERMA | PC→T | empty; in this version OK doing nothing |
0x8e | CONTROLLI_CAMBIATI | T→PC event | as the answer of CONTROLLI_STATO |
Approximate position (0x90–0x9f), on comandi | |||
0x90 | POSIZIONE | PC→T | u8 search allowed. Answer: u8 outcome (0 known, 1 location off, 2 permission denied, 3 none known), i32 latitude and i32 longitude in thousandths of a degree, always multiples of 5, u32 age in seconds (0xffffffff unknown), u8 provider (0 network, 1 gps, 2 fused, 3 passive), stringa place name, u8 search started. The body is exactly 17 + n bytes |
0x46-0x47 are reserved (freeing the encoder in long pauses: +0.07 s at resume; added only if a measurement asks). The sizes of video and audio packets are given in their chapters. Details of video, input, clipboard and panel are in chapters 8, 9 and 10; those of files, notifications and weather in chapters 11, 13 and 15.7.4 · Errors and malformed input
Every request that fails answers ERRORE with one sentence. The PC turns it into a PhErrore. The cases to know:
| Case | Result |
|---|---|
| Unknown type | ERRORE “tipo sconosciuto”. The PC maps it to “old service version” (ph_componente_richiesta) |
| Malformed body | ERRORE with the exception's message, or “malformed request” if it has none |
| Different protocol version | ERRORE on SALUTO |
| Body longer than 1 MiB | the PC ends the command thread and the component is dead; the phone's reader refuses it |
| Answer after the PC gave up | discarded by the PC; the PC already considers the component dead after a timeout |
| Event type not registered on the PC | ignored |
Unknown type on input | ignored: that channel has no answers, so there is no visible error |
PERSO and reconnects.Video
8.1 · Video on the phone: virtual displays and the encoder
Each window of a phone app is a video session. On the phone a session is a virtual display, an H.264 hardware encoder fed by it, and the app launched on that display. The code is in telefono/video: Video (commands and the channel), Sessione (one session), Codificatore (the encoder), ControlloSchermi (protected windows) and NascosteVideo (hidden APIs).
| Class | Role |
|---|---|
Video | registers commands 0x40-0x4f, the channel video and a close action; keeps the map id → session |
Sessione | virtual display, encoder, app launch, guard thread, pause, resize, close |
Codificatore | one MediaCodec H.264 encoder with its input surface and the thread that reads packets |
Inoltro | turns encoder output into protocol packets and keeps the configuration aside until a channel exists |
ControlloSchermi | one thread for all sessions: a window dump every second to detect protected screens |
AnalisiFinestre | pure parser of that dump |
LiberaTask | removes the tasks of a display and waits for it to empty |
Specchio | real screen size, to bring the input of a mirror session to the real display |
Input | Iniettore, Gesti, Pizzico: input injection (chapter 10) |
telefono/videoChecks on VIDEO_APRI. Width and height must be multiples of 8 between 64 and 2560; dpi between 40 and 1000; bit rate between 100000 and 200000000; the package, if present, must match [A-Za-z0-9_.]{1,255}; the id must be unused in this connection. An fps outside 1..120 becomes 60. Anything else answers ERRORE.
The session is created in Sessione.apri in this order: resolve the app, create the encoder, create the virtual display on the encoder's surface, launch the app. A failure at any step releases what was already made.
- Resolve the launcher activity with the
PackageManager(ACTION_MAIN+CATEGORY_LAUNCHER, restricted to the package; no implicit resolution). The class name must match a safe pattern and the package must be the one asked. - Encoder.
Codificatore.creatries, in order: every hardware H.264 encoder with SPS/PPS prepended to key frames, then every hardware encoder without, then Android's default encoder. The last error goes in the message. Format: surface input, the requested bit rate and frame rate, key frame interval 10 s, priority 0 (real time),KEY_REPEAT_PREVIOUS_FRAME_AFTER100000 µs (without it many encoders emit nothing on a still screen). - Virtual display.
DisplayManager.createVirtualDisplayis tried with sets of flags from the richest to the simplest and the first accepted wins. For an app, four sets: public + own-content-only + touch + destroy-with-content + trusted + own group + always unlocked; the same without always-unlocked; public + own-content-only + touch + destroy-with-content; and the last without public. For the mirror: mirror + public, mirror, mirror + own-content-only. The flags used are logged. - Launch with
am start-activity --display <id> -n <component> -f 0x18000000(new task + clear task), 10 s limit; output containingErroror “Activity not started” fails the open. - Guard. A thread checks every second that the app is still on the display; after it has been seen and then found missing twice in a row it sends the event
VIDEO_EVENTO 1(the app closed by itself; the session stays to be closed by the PC).
Event che cosa | Meaning | a, b |
|---|---|---|
1 | the app closed itself | 0, 0 |
2 | protected screen on or off (FLAG_SECURE) | a = 1 or 0 |
3 | the size changed on its own: defined by the protocol, never sent by this version of the phone code | a × b |
4 | encoder error: the session is dead | 0, 0 |
VIDEO_EVENTO kindsThe protected-screen state is computed once per second for all sessions at once by one dumpsys window analysis (each dump holds the WindowManager lock, so there must be only one); the event goes out only when the state changes.
8.2 · Video: sessions and recovery
A session starts on the shell side as a stream, SvFlusso in src/shell/ossatura/sv_flussi.c. It holds the PhVideoFlusso of the component, the decoder and the capture state. Opening, pause, resize and close run in order on the p_flussi pool; input on p_input; the reading thread is the one that calls sv_flusso_leggi.
- Request.
VIDEO_BIT_AL_SECONDOis 8000000 andVIDEO_FPSis 60. The size and density come from the window; with a density of 0 the session's own density is used, or 420 if unknown. For the mirror the size is the real screen's, scaled so that no side exceeds 1920 pixels, with sides rounded down to a multiple of 8 and at least 64 (ph_ossatura_misura_specchio). - Component.
ph_video_apriassigns the id (an increasing counter, never reused in the connection), sendsVIDEO_APRI, and onOKopens the channelvideo:<id>. If anything fails after the phone created the session,VIDEO_CHIUDIis sent (2000 ms) so that no virtual display is left on. The encoder starts producing when the channel opens; before that its packets are discarded and the configuration is kept aside. - Open job. It makes up to 3 rounds, repeated only when the session vanishes and a new one appears meanwhile; with no session the stream goes to
PERSOand waits. - Rule of use. Whoever calls
ph_video_*on a stream holds one use of the stream and of the session; whoever replaces or closes it removes the pointer first and waits for the uses to reach zero, so no call starts afterph_video_chiudiand no read runs while the stream closes.
| Stream state | Entered when | Leaves when |
|---|---|---|
PH_FL_APRENDO | session created or connection back | open succeeded (ATTIVO), no session (PERSO), refused (MORTO) |
PH_FL_ATTIVO | open succeeded; notice APERTO the first time, RIPRESO later | session lost (PERSO), encoder error (MORTO) |
PH_FL_PERSO | the link's session was lost | a new session exists: reopen by itself |
PH_FL_MORTO | the phone refused to open, or the encoder died (event 4) | never: it does not restart |
ph_fl_passo, src/shell/ossatura/logica.c)On a drop every stream becomes PERSO, its pinch and touch are cancelled, and a running recording is stopped with “connection lost”. On the new session sv_flussi_sessione_nuova reopens every stream; the pause the shell wanted and any resize asked while the stream was absent are reapplied.
8.3 · Pause, resize and density
Pause turns a minimised window into a stream that costs nothing. The phone detaches the encoder surface from the virtual display (VirtualDisplay.setSurface(null)), so the display, the app and the encoder stay alive but no frames are produced. Measured on the test phone: resume in 0.12–0.17 s, with the phone's compositor idle during the pause and the app still alive.
VIDEO_PAUSA: already paused isOKwith no effect; resize and key-frame requests in pause areERRORE; input does not error but has no effect (measured: with a detached surface Android does not deliver it to the app), so the PC sends none to a paused session and, before pausing, closes every touch and pinch in progress (up or cancel). Open gestures are also closed on the phone before the surface is detached, since afterwards the cancel would be lost.VIDEO_RIPRENDI: re-attaches the surface and asks for a key frame; if none arrives within about 250 ms (a still app: 12 checks of 20 ms) a redraw is forced by detaching and attaching the surface again. The first packet written after theOKis a key frame, preceded by a configuration if needed. Packets written before the pause and not yet read may still arrive after the resume.VIDEO_RIDIMENSIONA: the phone creates a new encoder, resizes the display and sets the new surface, then swaps; from then no packet with the old size is written (the filter drops packets of an encoder that is no longer the current one). The first packet with the new size is a configuration. To resize a paused stream the PC resumes it first.- Mirror. The shell never resizes the mirror: the request is ignored for sessions with an empty package. Resize requests received while paused or while the stream is absent are remembered (size and density) and applied by the resume or the reopen.
- Density. The density is part of the resize request, so a window can change the app's layout class without restarting it: this is the protocol side of the density rule described in chapter 12.
- Barrier. Pause and resize run on the streams pool and first wait (bounded) for the inputs queued before them to have been sent, so a touch is never overtaken by a pause or a resize.
8.4 · Video: receiving and decoding
The channel video:<id> carries phone-to-PC packets only. The PC never writes on it; if it closes it, the encoder stops (the session lives until VIDEO_CHIUDI). A second channel for the same session closes the first (shutdown of output and input).
| Field | Size | Notes |
|---|---|---|
| kind | 1 byte | 1 = CONFIGURAZIONE (SPS+PPS), 2 = FOTOGRAMMA; any other value breaks the stream |
| flags | 1 byte | bit 0 = key frame |
| width | 2 bytes | size of the video the packet belongs to |
| height | 2 bytes | |
| time | 8 bytes | microseconds, phone monotonic clock (presentationTimeUs) |
| length | 4 bytes | at most 8 MiB (PH_VIDEO_MAX_PACCHETTO) |
| data | length | H.264, Annex B (start codes 00 00 00 01) |
After the channel is opened the first packet is a configuration and the second a key frame. ph_video_leggi(stream, packet, timeout, error) returns 1 for a packet, 0 for end of stream, PH_CANALE_ERRORE or PH_CANALE_TEMPO. Reads are in 50 ms slices and are resumable (a slice that expires loses nothing). The data buffer grows in pieces of 256 KiB, so a false length does not allocate everything at once; a half packet at the end is a broken stream. The data pointer is valid until the next read.
Decoding is src/video/decodifica.c, on FFmpeg's libavcodec. The via is chosen when the decoder is created (ph_decodifica_crea).
| Via | When | Notes |
|---|---|---|
PH_VIA_VAAPI | automatic, first choice | FFmpeg VA-API hardware device; hands the frame to the shell without copies (DMA-BUF) |
PH_VIA_VULKAN | automatic, only if VA-API is missing or fails and any non-CPU Vulkan device offers VK_KHR_video_decode_h264 as shipped | detected without environment variables: a function the driver keeps off does not count; CPU-type Vulkan devices are ignored; the frame is copied to memory (PH_ESPORTA_RIPIEGO) |
PH_VIA_SOFTWARE | last resort, or when GTK refuses the DMA-BUF | slice threads, thread count automatic |
ph_decodifica_ordine_automatico, proved without a graphics card)The decoder is created with AV_CODEC_FLAG_LOW_DELAY and AV_CODEC_FLAG2_FAST (no frame held back for reordering). For the hardware vias extra_hw_frames is 6: the shell keeps some frames alive beyond the decoder's life (the one shown, the one waiting, one being delivered), and without extra surfaces the GPU's fixed pool would run out and decoding would stop. An explicit via fails if it is not available, with no silent fallback (this is for measuring); get_format records when FFmpeg dropped to software (at the first packet, or at the first packet after a new configuration, for example a resize), and ph_decodifica_dai then returns an error on any hardware via, the automatic one included (the check is on the via, not on whether it was explicit); the shell reacts by recreating the decoder as software, once (8.7 “When hardware decoding is not available”).
Feeding. A configuration packet is kept and prepended to the next frame (a configuration alone is not a frame). Packets are sent with the phone's time as pts and dts. A damaged packet is not fatal: the call fails and decoding continues from the next key frame; the reader then asks for a key frame, at most every 500 ms, because the picture stays broken until the next one (up to 10 s at the encoder's interval). The last configuration (at most 64 KiB) is stored and given to every new decoder, since an encoder that does not prepend headers would leave a new decoder without them.
To the shell without copies. ph_esporta (src/video/esporta.c) turns the AVFrame into a PhFotogramma, described in src/comune/fotogramma.h without FFmpeg or GTK types. The frame belongs to the receiver, which must call ph_fotogramma_rilascia exactly once, from any thread, when the picture is not needed (typically in the release function of the GdkTexture); until then file descriptors and data are valid.
| Via | Form | What happens |
|---|---|---|
PH_ESPORTA_DMABUF | PH_FOTO_DMABUF | VA-API frame mapped to DMA-BUF: fourcc and modifier from the DRM descriptor, planes, offsets and strides; GTK shows it as a texture without any copy |
PH_ESPORTA_MEMORIA | PH_FOTO_MEMORIA | frame already in memory (BGRA, RGBA, RGB24 with positive stride: not copied) or the needed YUV to RGB conversion only; format B8G8R8A8_PREMOLT normally |
PH_ESPORTA_RIPIEGO | PH_FOTO_MEMORIA | a GPU frame that could not be mapped (Vulkan, or VA-API refused) was copied to memory; the shell writes it in the decision log once per stream |
Colours: BT.709 or BT.601 according to what the frame declares (undeclared: BT.709 from 720 rows up, BT.601 below), limited range unless declared; full range maps to the PIENO variants; other matrices leave the choice to GTK. An offset or stride above 32 bits is an error. In the shell, sv_flusso_memoria can force the software decoder when GTK refuses the DMA-BUF, which is logged (flusso in memoria invece che DMA-BUF) and asks for a key frame.
8.5 · Hardware acceleration end to end
This section follows one video frame from the phone's encoder to the screen and says, at every stage, who does the work (GPU or CPU) and where the data is copied. It comes from the sources; what was measured, and where, is in 8.9 “Requirements and limits of hardware acceleration”.
| Stage | Code | Who works | What is copied |
|---|---|---|---|
| 1. Encode | telefono/video/it/yasde/Codificatore.java | the phone's H.264 encoder, hardware if one is found | the virtual display renders into the encoder's input surface: no copy made by YASDE code |
| 2. Transport | src/componente/video.c, src/adb | CPU (TLS, ADB) | each packet is read into the stream buffer (up to 8 MiB, grown in 256 KiB pieces); the decoder receives a copy of it with the stored configuration in front |
| 3. Decode | src/video/decodifica.c | GPU with VA-API or Vulkan; CPU with the software via | hardware: nothing, the picture stays in GPU memory (AV_PIX_FMT_VAAPI or AV_PIX_FMT_VULKAN); software: the picture is written in system memory |
| 4. Export | src/video/esporta.c | see the table of paths below | DMA-BUF: nothing; memory form: for a GPU frame a GPU-to-CPU download, then a CPU colour conversion into a new buffer |
| 5. Texture | src/shell/superficie/superficie.c | GTK, on the GTK thread | DMA-BUF: the file descriptors are handed to GTK; memory: the buffer is wrapped in a GBytes without a copy, and GTK uploads it to the GPU by itself |
| 6. Draw | GtkGraphicsOffload and the renderer GTK has chosen | GPU, with the GL or Vulkan renderer GTK chooses | what GTK does internally with a DMA-BUF (colour conversion, a direct hand-off to the screen) is up to GTK and not controlled by YASDE (see below) |
1. Encoding on the phone. Codificatore.crea lists the encoders of MediaCodecList(REGULAR_CODECS) that are encoders, are not aliases, report isHardwareAccelerated() and not isSoftwareOnly(), and support video/avc, and tries them in the list's order: first each with prepend-sps-pps-to-idr-frames set to 1, then each without it, and last Android's default encoder for the type (createEncoderByType), which the code does not check to be hardware: it may be a software encoder. The format asks for surface input, the bit rate and frame rate of the request (the shell asks for 8000000 and 60), a key frame every 10 s, priority 0 and repeat-previous-frame after 100000 µs. Profile, level and bit-rate mode are not set: the encoder's own defaults apply. If no encoder can be configured the open fails with codificatore H.264 non configurabile and the last error, the phone answers ERRORE to VIDEO_APRI, and the stream goes to PH_FL_MORTO with the notice “This app's video has stopped”. The name of the chosen encoder is printed only by the test class ProvaVideo: in a normal run it is not logged, and the service's log lines are read by the PC and thrown away.
3. Decoding. prova_via (src/video/decodifica.c) uses FFmpeg's h264 decoder with AV_CODEC_FLAG_LOW_DELAY and AV_CODEC_FLAG2_FAST. For a hardware via it opens the device with av_hwdevice_ctx_create(type, NULL, NULL, 0) (type AV_HWDEVICE_TYPE_VAAPI or AV_HWDEVICE_TYPE_VULKAN: the code names no device, FFmpeg picks the default one), gives it to the codec context as hw_device_ctx, installs get_format that accepts only the via's own pixel format (AV_PIX_FMT_VAAPI or AV_PIX_FMT_VULKAN), and sets extra_hw_frames to 6 (reason in 8.4 “Video: receiving and decoding”). The hardware decoders are the FFmpeg hwaccels h264_vaapi and h264_vulkan compiled into the packaged FFmpeg (pacchetto/dentro.sh). The software via uses slice threading with an automatic thread count. A configuration packet is kept and put in front of the next frame.
4. Export. ph_esporta takes the AVFrame (it becomes the function's in every case) and returns one of three forms. Their conditions, in the order the code tests them:
| Condition | Form | Steps | Copies per frame |
|---|---|---|---|
the frame is not in GPU memory (no hw_frames_ctx) | PH_ESPORTA_MEMORIA | BGRA, RGBA or RGB24 with a positive stride are wrapped as they are; any other format (the normal case, YUV from the software decoder) is converted by libswscale (SWS_BICUBIC | SWS_ACCURATE_RND) into a new BGRA buffer, with the matrix and range of the frame | 0 if already RGB, otherwise 1 conversion on the CPU |
VA-API frame and av_hwframe_map to AV_PIX_FMT_DRM_PRIME succeeds | PH_ESPORTA_DMABUF | the DRM descriptor gives the file descriptors, offsets, strides, modifier and fourcc; the mapped frame keeps the picture alive until GTK releases the texture | 0 |
| a GPU frame that is not VA-API (Vulkan), or whose mapping was refused | PH_ESPORTA_RIPIEGO | av_hwframe_transfer_data brings the picture to system memory, then the same conversion as above | 1 download GPU to CPU plus 1 CPU conversion |
ph_esportaIn PH_ESPORTA_DMABUF the fourcc is the layer's format when there is one layer, or NV12 or P010 (from the frame's software format) for multi-layer descriptors; at most 4 planes; all planes must have the same modifier or the export fails; sizes up to 16384. In the PH_ESPORTA_RIPIEGO case the shell writes one decision line per stream (8.8 “Checking which path is in use”).
5. The texture (texture_da, 11.7 “The video surface”). For a memory frame: gdk_memory_texture_new with the format GDK_MEMORY_B8G8R8A8_PREMULTIPLIED, R8G8B8A8 or R8G8B8. For a DMA-BUF: GdkDmabufTextureBuilder with the fourcc, modifier, planes, offsets and strides of the frame. Before the first DMA-BUF the surface asks GTK for its list of importable formats (gdk_display_get_dmabuf_formats); if the pair fourcc and modifier is not in it, it logs a line and tries anyway. If the builder returns no texture (its error is discarded) the frame is dropped and counted as a refusal, which has consequences described in 8.7 “When hardware decoding is not available”. For a DMA-BUF texture only (memory textures are already BGRA, with the matrix applied by libswscale in the export), the colour state is given only if the program was compiled against GTK 4.16 or newer: BT.709 or BT.601 (CICP primaries, transfer and matrix 1/1/1 or 6/6/6) with narrow or full range, from what the frame declares or the height rule; for any other matrix, or if GTK does not build the colour state (one log line), GTK decides.
6. Drawing. The picture is a GtkPicture-like widget (PhImmagine) inside a GtkGraphicsOffload with offload enabled (and, from GTK 4.16, a black background). The widget appends a plain texture node because GTK 4.18 does not offload a scaled-texture node. The program never sets the renderer: GTK chooses it, and the AppRun script does not touch GSK_RENDERER. Only the development scripts set it (strumenti/app-sul-tablet.sh defaults to vulkan and sets GDK_DEBUG=offload; strumenti/foto-demo.sh uses cairo).
| Path | Decoder | Export form | Copies per frame | Who draws |
|---|---|---|---|---|
| VA-API (first choice) | GPU, VA-API | PH_ESPORTA_DMABUF | none: DMA-BUF handed to GTK | GTK's renderer, chosen by GTK (on the GPU with the GL or Vulkan renderer); what GTK does internally, YUV conversion included, is not controlled by YASDE |
| VA-API, mapping refused | GPU, VA-API | PH_ESPORTA_RIPIEGO | 1 download, 1 CPU conversion, then GTK's upload | GTK's renderer, chosen by GTK, with a memory texture |
| Vulkan Video (only if offered as shipped and VA-API did not open) | GPU, Vulkan | PH_ESPORTA_RIPIEGO | 1 download, 1 CPU conversion, then GTK's upload | GTK's renderer, chosen by GTK, with a memory texture |
| Software (nothing else opened) | CPU, libavcodec | PH_ESPORTA_MEMORIA | 1 CPU conversion, then GTK's upload | GTK's renderer, chosen by GTK, with a memory texture |
| Software after a DMA-BUF refusal | CPU, libavcodec | PH_ESPORTA_MEMORIA | 1 CPU conversion, then GTK's upload | GTK's renderer, chosen by GTK, with a memory texture |
The “then GTK's upload” part is GTK's own work with a memory texture and is not visible in the code of YASDE; the table counts only what the code of the project does.
8.6 · How the decoding path is chosen and when it falls back
The automatic order and the checks are in src/video/decodifica.c. The order is the pure function ph_decodifica_ordine_automatico(vulkan_di_fabbrica, sequence): VA-API first; Vulkan second only if vulkan_di_fabbrica is true; software always last. It is proved without a graphics card by src/video/prova/prova_ordine_via.c. ph_decodifica_crea(PH_VIA_AUTOMATICA) tries each in order with prova_via and takes the first that opens; only the last attempt fills the error text, so the reasons why VA-API or Vulkan did not open are lost. Reason for VA-API first: it hands the frame to the shell without copies, and the Vulkan via copies it (the choice of the project's owner, “route A”).
What ph_decodifica_vulkan_di_fabbrica looks at. It creates a Vulkan instance (API 1.3, no layers, no extensions), lists the physical devices, skips every device of type CPU, and returns true if any other device lists the extension VK_KHR_video_decode_h264. It reads no environment variable, so a function the driver keeps switched off does not count. It does not look at queue families or video capabilities. If the instance cannot be created it returns false. It runs every time an automatic decoder is created.
What makes a hardware via fail to open. Only two checks exist: av_hwdevice_ctx_create returning an error (the error text reads “via vaapi: accelerazione non disponibile: avcodec_open2 returning an error. Why FFmpeg refuses (no render device, no driver, a library not found) is not distinguished by the code, and the text of those errors is lost; the program reports only the outcome (8.7 “When hardware decoding is not available”).
The one thing the code does not turn into a failure. The hardware format is accepted only if FFmpeg offers it in get_format. If the device opened but the GPU cannot decode this stream (for example an unsupported profile), the callback sets ripiego_software and lets FFmpeg take its default, which is its own software decoding. This is the third case below.
Device lost in mid-session. There is no code for it. FFmpeg errors come back from ph_decodifica_dai or ph_decodifica_prendi as -1; the reader asks for a key frame at most every 500 ms and nothing else happens: the decoder object is replaced only when the stream is reopened (new session after a drop), when GTK refuses the DMA-BUF, or when a hardware decoder drops to software at its first packet or after a new configuration, which also recreates the decoder (8.7 “When hardware decoding is not available”); a device lost later is none of these. What the picture does then depends on FFmpeg and the driver and has not been tried.
Going back to hardware. A new decoder repeats the whole automatic order, hardware attempts included, so hardware is tried again whenever a stream is opened or reopened after a drop, never in the middle of a stream.
8.7 · When hardware decoding is not available
What the user sees: in all three cases a decision line is written on standard error and, at most once per link session, a toast appears on screen (8.8 “Checking which path is in use”). All three go through via_verifica (src/shell/ossatura/sv_flussi.c), which asks ph_decodifica_via for the via the decoder REALLY uses (ph_via_reale: the chosen via, or software if FFmpeg dropped to software) after the decoder is created and after every packet given to it. It writes one line per stream and per change of via. When the via is software the cause in the line comes from three facts, tested in this order: the stream's memory preference is set and the decoder is the software one (memoria and dec_software) means GTK refused the DMA-BUF; else a decoder that was born with a hardware via (dec_nato_hw) means the hardware via cannot sustain the stream; else no hardware via was available.
The toast. When the via becomes software, via_verifica calls ph_servizi_pubblica_decodifica_software (any thread), which delivers PH_SRV_EV_DECODIFICA on the GTK thread; src/shell/sistema/sistema.c shows it with ph_sistema_toast_info_lungo, title Decodifica video hardware non disponibile (“Hardware video decoding unavailable”) and body Il video usa il processore: le app sono meno fluide. Installa i driver video VA-API o Vulkan. (“Video uses the CPU: apps are less smooth. Install VA-API or Vulkan video drivers.”). It stays 9 s (DURATA_INFO_LUNGO_MS in toast.c); the other information toasts stay 3.2 s, notification toasts 5.2 s. It is sent at most ONCE per link session (sv->decod_sw_sess holds the last session that got it): not per frame, not per window, not at every re-creation of the decoder, and if a stream goes back to hardware and falls again in the same session it is not repeated. A new session after a drop can show it again. Proved by src/shell/ossatura/prova_decodifica_avviso.c; a screenshot is docs/sources/img/decoding-warning.png.
Case 1: no hardware via opens
- Trigger. In the automatic order VA-API and, if offered, Vulkan both fail the two checks above (missing decoding drivers, a virtual machine, a card with neither VA-API nor Vulkan Video, or a missing device).
- Steps.
ph_decodifica_creareaches the software via,prova_viaopens theh264decoder with slice threads and an automatic thread count, and the decoder is created normally. Right after,via_verificasees software with no via logged yet for the stream. - Log.
[decisione] hh:mm:ss.mmm decodifica col processore - causa: nessuna via hardware disponibile: prestazioni ridotte(“decoding with the processor - cause: no hardware via available: reduced performance”): the decoder was not born with a hardware via and GTK has refused nothing. The toast follows. The failed hardware attempts themselves write nothing (only the last attempt fills the error text). Only if even the software decoder cannot be created:decodifica non disponibile - il decodificatore non si e' creato(“decoding not available - the decoder was not created”), once per change of state, and on recoverydecodifica di nuovo disponibile - il decodificatore si e' creato(“decoding available again”). - Cost. The H.264 decoding is done by the CPU, then each frame goes through a YUV to BGRA conversion on the CPU (
PH_ESPORTA_MEMORIA) and GTK's upload. No figure for software decoding is recorded anywhere in the project: not measured. The toolmisura_decodificacan measure it on a given machine. - Back to hardware. At the next decoder creation (stream opened or reopened), when the automatic order runs again; if hardware opens then, the line
decodifica video - causa: via vaapi (scheda grafica)is written (the via changed).
Case 2: the GPU decodes but GTK refuses the DMA-BUF
- Trigger. The surface cannot build a DMA-BUF texture:
gdk_dmabuf_texture_builder_buildreturns NULL for a frame of DMA-BUF form (the error is discarded). - Steps. (1) That frame is dropped and counted in the statistics as discarded and as a DMA-BUF refusal. (2)
ph_srv_flusso_preferisci_memoriareachessv_flusso_memoria, which sets the atomic flagmemoriaof that stream; it is called on every refusal, not once. (3) At the next readleggi_unosees the flag withdec_softwarestill false and callsdecodificatore_nuovo(sv, sf, vf, true): this is where thesoftwareparameter comes from. It is not a preference, a command-line option or an environment variable: it is the flag of the stream, set only by a refusal of GTK. (4) The old decoder is freed, a software decoder is created, the stored configuration is given to it, a key frame is requested from the phone withph_video_chiave, andvia_verificaruns. - Log. From the surface, once per surface:
[decisione] hh:mm:ss.mmm flusso in memoria invece che DMA-BUF - causa: GTK ha rifiutato il DMA-BUF (fourcc NV12, modificatore 0x0)(“stream in memory instead of DMA-BUF - cause: GTK refused the DMA-BUF (fourcc, modifier)”; the values are those of the refused frame). From the stream, at the switch: the same first words with the causeGTK ha rifiutato il DMA-BUF: decodifica software(“GTK refused the DMA-BUF: software decoding”), thendecodifica col processore - causa: GTK ha rifiutato il DMA-BUF: prestazioni ridotte(“decoding with the processor - cause: GTK refused the DMA-BUF: reduced performance”), and the toast. Before the first DMA-BUF the surface may also have writtenDMA-BUF provato comunque - causa: GTK non elenca fourcc … modificatore … tra i formati importabili(“DMA-BUF tried anyway - cause: GTK does not list fourcc … modifier … among the importable formats”). - Cost. As case 1, plus the frames lost until the key frame arrives. Not measured.
- Back to hardware. Never inside the stream: the flag is never cleared, and it survives a reopening after a drop (the new decoder is created software again). A new window is a new stream and tries the DMA-BUF again.
Case 3: FFmpeg drops to software inside the hardware decoder
- Trigger. The device opened, but when the stream starts FFmpeg's
get_formatlist does not contain the via's hardware format (the GPU cannot decode this stream), soscegli_formatosetsripiego_softwareand returns FFmpeg's default format. This is found at the first packet, not at creation. - Steps. At creation
via_verificastill sees the hardware via and writesdecodifica video - causa: via vaapi (scheda grafica);dec_nato_hwis set.ph_decodifica_daithen sends the first packet; the fall-back flag turnsph_decodifica_viainto software (ph_via_reale), andph_decodifica_daiitself returns -1 for this packet.via_verificais called right after it even when it fails: it writes the processor line, raises the toast, and, because the decoder was born hardware, recreates it ONCE asPH_VIA_SOFTWARE, gives it the stored configuration, requests ONE key frame from the phone and tellsleggi_unoto drop the packet in hand. From then on there are no more errors at every packet and no key-frame requests every 500 ms. Frames are exported as memory frames. That this works on a GPU that cannot decode a stream is read from the code and was not run. - Log.
[decisione] hh:mm:ss.mmm decodifica col processore - causa: la via hardware non regge il flusso: prestazioni ridotte(“decoding with the processor - cause: the hardware via cannot sustain the stream: reduced performance”), after thevia vaapiline, and the toast. Noflusso in memoria invece che DMA-BUFline: that one is written only when GTK really refused. - Cost. CPU decoding as above, plus the lost time of the failed first packets and one key frame. Not measured.
- Back to hardware. At the next decoder creation, as in case 1.
8.8 · Checking which path is in use
Everything the program says about video paths goes to standard error (the terminal that started the AppImage), plus the toast described above. There is no log file.
Decision lines have the form [decisione] hh:mm:ss.mmm <what> - causa: <cause> (ph_shell_decisione, src/shell/comune/consegna.c).
| Line (what - cause) | Meaning | Where |
|---|---|---|
decodifica video - via vaapi (scheda grafica) or via vulkan (scheda grafica) | “video decoding - via vaapi (graphics card)”: the via the decoder really uses, one line per stream and per change of via | sv_flussi.c, via_verifica |
decodifica col processore - nessuna via hardware disponibile: prestazioni ridotte | case 1: no hardware via opened | sv_flussi.c, via_verifica |
decodifica col processore - GTK ha rifiutato il DMA-BUF: prestazioni ridotte | case 2 | sv_flussi.c, via_verifica |
decodifica col processore - la via hardware non regge il flusso: prestazioni ridotte | case 3 | sv_flussi.c, via_verifica |
flusso in memoria invece che DMA-BUF - fotogramma della scheda grafica non mappabile, copiato in memoria | “stream in memory instead of DMA-BUF - GPU frame that cannot be mapped, copied to memory”: PH_ESPORTA_RIPIEGO, that is the Vulkan via, or VA-API with a refused mapping; once per stream | sv_flussi.c, esporta |
flusso in memoria invece che DMA-BUF - GTK ha rifiutato il DMA-BUF (fourcc %s, modificatore 0x%llx) | GTK refused a DMA-BUF texture; once per surface | superficie.c, mostra |
flusso in memoria invece che DMA-BUF - GTK ha rifiutato il DMA-BUF: decodifica software | the stream switched to the software decoder (case 2) | sv_flussi.c, decodificatore_nuovo |
DMA-BUF provato comunque - GTK non elenca fourcc %s modificatore 0x%llx tra i formati importabili | “DMA-BUF tried anyway”; may precede a refusal | superficie.c, texture_da |
spazio dei colori lasciato a GTK - GTK non ha costruito lo spazio dei colori %d: %s | “colour space left to GTK”: the colour state could not be built | superficie.c, stato_colore |
fotogramma scartato - esportazione non riuscita | “frame discarded - export failed”, once; then fotogrammi scartati - %u in tutto prima di questo when exports work again | sv_flussi.c, esporta |
decodifica non disponibile - il decodificatore non si e' creato | no decoder at all, not even software | sv_flussi.c, decodificatore_nuovo |
Statistics. With the environment variable PH_SUPERFICIE_STAT=1 (a value starting with “1”, read when each surface is created) every surface writes every 5 s, from its reading thread: superficie N: ricevuti X (R/s), mostrati Y (R/s), scartati Z, rifiuti DMA-BUF W (“surface N: received, shown, discarded, DMA-BUF refusals”; N counts surfaces from 1 in creation order). Received and shown are the frames read and the textures put on screen with their rates since the last line; refusals above 0 mean GTK is refusing the DMA-BUF (src/shell/superficie/superficie.c).
What the lines tell. The first line of a stream names the via really in use: vaapi means the copy-free path unless a flusso in memoria invece che DMA-BUF line follows (mapping refused, or GTK refused); vulkan always means the copying path (PH_ESPORTA_RIPIEGO). The “processor” lines say the decoding is software and why. Because the line is written when the decoder is created and after each packet, a fall-back found at the first packet or after a new configuration (case 3) shows as a vaapi line followed by a processor line.
Which via a machine gets. The program itself now says it, in the first decision line of each stream. The measuring tools also print it, because they call ph_decodifica_via: finestra-prova and prototipo-gtk write decodifica: via vaapi (or vulkan, software) on standard error; misura-flussi prints the via of each stream; misura_decodifica prints it with the pixel format and the decoding time. With --via automatica (the default) they use the same order as the program. GTK's own offload messages are available with GDK_DEBUG=offload, which the development scripts set.
Forcing a path. The program has no switch for it: no preference, option or variable chooses the decoding via, and the order cannot be changed. The option exists only in the tools, as --via automatica|vaapi|vulkan|software (misura-flussi also accepts nessuna; misura_decodifica takes the via as its second argument), and an explicit via fails if it is not available. The project plan speaks of a switch for measuring the two vias: it is this one, in the tools.
| Tool | What it measures |
|---|---|
strumenti/misura-flussi.c | opens one session per app on a real phone and measures, for each stream, the frames that arrive, the bandwidth, their regularity (intervals), and with decoding the via, the decoding errors and the mean decoding time; answers how many encoders in parallel the phone supports |
strumenti/prototipo-gtk.c | a GTK4 prototype, not the shell: composes several streams in windows, with the no-copy DMA-BUF path by default and --copia for the memory path; --giostra moves and resizes the windows by itself. It measured whether GTK composes several streams without copies and without stutter |
src/video/misura_decodifica.c | decodes a raw H.264 file with the chosen via and prints frames, size, pixel format, mean and worst decoding time and frames per second |
strumenti/finestra-prova.c | a bare window (SDL3) that copies frames from the GPU to memory and measures click-to-image latency; not the final path |
8.9 · Requirements and limits of hardware acceleration
Libraries from the system. The AppImage includes a minimal FFmpeg (pacchetto/dentro.sh: decoder h264, parser, PNG encoder, MP4 muxer, --enable-hwaccel=h264_vaapi and --enable-hwaccel=h264_vulkan, with libva, libdrm and Vulkan), but the following stay with the system and are required: libva.so.2 and libva-drm.so.2 (without them the program does not start: they are needed by FFmpeg), libvulkan.so.1 (the loader: without it the program does not start) and libdrm.so.2. For hardware decoding the machine also needs a VA-API driver for the GPU (Vulkan Video: a Vulkan driver that offers VK_KHR_video_decode_h264). Source: pacchetto/LEGGIMI.md and the file SYSTEM-REQUIREMENTS.txt that the build writes.
What was measured, and where. From the project plan: on one machine with an Intel GPU (GTK 4.18.6), where Vulkan decoding is switched off by the driver as shipped, GTK4 drawing through Vulkan with the images passed from the decoder without copying gave 59 frames per second with 3 windows and regular intervals; the default renderer (GL) gave 54 even with 5 windows; with the images copied, 27 frames per second with 3 windows. Those are measurements of the prototype strumenti/prototipo-gtk.c on recorded video, not of the final program. Not yet measured: five really active apps from a real phone, and HiDPI. The same machine is where the choice of route A was made (VA-API where Vulkan Video is off).
Direct hand-off to the screen (offload). On that machine GTK never printed “Attaching … GdkDmabufTexture” with GDK_DEBUG=offload, even with forced offload and with both renderers, not in the surface demo and not in the prototype: the direct hand-off is not active. The textures are DMA-BUF (no refusals), so the video reaches the GPU without a copy in memory and only the last step is missing. Rounded corners and clipping of the real windows would prevent it anyway. Open point.
What was run, and what was not. The program has run live with video (1440p, two screens, a test of 23 Nov 2026, recorded in the project plan), but which decoding via it used was not recorded then. Not proved on real hardware: the Vulkan via, and the three software cases; the software cases also have no recorded measurement.
Known limit. With only Vulkan (VA-API absent) every frame is copied to memory (PH_ESPORTA_RIPIEGO): the copy-free path exists only with VA-API. The automatic order puts VA-API first for that reason.
frequenza fotogrammi ridotta); that is a separate mechanism, described with the surface.8.10 · Screenshots and recordings
Screenshots and recordings use the decoded frames and the received packets, in src/video/cattura_png.c, src/video/cattura_mp4.c and src/video/cattura_nome.c; the header src/video/cattura.h exposes no FFmpeg type.
Screenshot. The reader thread serves pending screenshots before ph_esporta consumes the frame (same thread as the decoder: capture reads, never modifies). sv_flusso_screenshot queues the request, gives it 2 s, and asks for a key frame because a still screen sends nothing. GPU frames are brought to memory with av_hwframe_transfer_data, then libswscale converts any YUV 8 or 10 bit format (width and height 1 to 16384). Two destinations: a PNG file (ph_cattura_screenshot) and a PNG in memory for the clipboard (ph_cattura_png_memoria). No file is ever overwritten: creation is atomic with O_EXCL and a taken name becomes (2), (3) up to 999; a partial file is deleted on error.
Names. <app> + date + time + extension, as <app> YYYY-MM-DD HH.MM.SS.png (local time). The app part removes / \ : * ? " < > | and control characters (replaced by _), is cut to 80 bytes without splitting a UTF-8 character, loses spaces and dots at its ends, and if nothing is left it is YASDE.
Recording. The H.264 is written as received, with no re-encoding, into a fragmented MP4 (empty_moov, default_base_moof, frag_custom): the writer closes a fragment at every key frame or about every second. Why: the file is playable even if the process dies (at most the last second is lost); a classic MP4 without the final moov is unreadable. SPS and PPS go in the track description; the samples lose them, and start codes become lengths. The file is opened with O_EXCL.
| Rule | Detail |
|---|---|
| Start | nothing is written until the first key frame (an IDR NAL with a configuration already received or in the same packet); earlier packets are dropped |
| Size change | after the first key frame the size must stay the same; a change is an error and the recording is finished by the caller |
| Configuration change | an SPS/PPS different from the one in use is an error and the frame does not enter |
| Time | the first key frame is time 0; a time not greater than the previous one is corrected (the previous frame keeps its duration); a forward jump is taken as true up to 30 minutes; the counters tempi_corretti count them |
| Write error | the file is brought back to the last good point and closed; later calls return -1; the file stays playable |
| Audio track | supported by the library (Opus, 48 kHz stereo, pre-skip 312 samples) but not used: the shell opens recordings with no audio, so YASDE recordings are video only |
In the shell every packet, configurations included, goes to the recording before decoding. If the writer fails the recording is stopped with a message; a drop of the connection stops it too.
Audio
9.1 · Audio: capture and transport
The phone captures everything it plays and sends it as Opus; the PC plays it. On the phone the code is telefono/audio: Audio (the channel), Cattura (one capture), Volume (media volume) and NascosteAudio (the hidden audio-policy APIs).
- Opening the channel starts the capture, closing it stops it. One audio channel at a time: a second one waits up to 2000 ms for the first to finish closing and is then refused (closed). If the service is closing, no capture starts.
- Loopback rule.
NascosteAudioregisters anAudioPolicywith a mixing rule that matches by usage: unknown, media, alarm, notification, notification event, accessibility, navigation guidance, sonification, game and assistant. While the rule is active the phone stays silent and the sounds come out of the PC; when it is removed the phone plays again by itself. The recorder is built by hand (NascosteAudio.creaRegistratore) with a context that presents itself ascom.android.shell: the library helper creates it without a context, so the package would beandroidand the system refuses uid 2000. - Format.
AudioRecord48 kHz stereo 16 bit, read in blocks of 960 frames (20 ms), encoded with aMediaCodecOpus encoder at 128 kbit/s. - Time. The time of each packet is the number of samples captured so far divided by 48000, not the clock, and a lost PCM block is added to it, so a gap always shows as a jump of 20 ms or more.
- Queue. Packets wait in a queue of 250 (5 s) toward the PC; beyond it the oldest is dropped and the jump is visible in the time.
| Field | Size | Notes |
|---|---|---|
| time | 8 bytes | microseconds: samples captured so far / 48000 (not the clock) |
| length | 2 bytes | at most 4000 on the PC side; more means a broken channel |
| data | length | one Opus packet |
9.2 · Media volume on the phone
The media volume must be at the maximum during capture: with volume 0 some apps do not start their audio. The change follows the rule that governs every change to the phone: the undo is registered first, the change is verified, the user's value wins.
- Read the current volume and the maximum (
cmd media_session volume --stream 3 --get, parsed fromvolume is N in range [a..b]). - If it is already at the maximum, do nothing. Otherwise register the entry
audio-volume(order 50) withGuardiano.imposta. If it returns false, or there is no guardian, the volume is not touched and the capture goes on. - Set the maximum and re-read it: a different value is an error and the volume is restored.
- At close: read the volume; only if it is still the maximum YASDE set, put the original back (retried once if the re-read does not match) and remove the guardian entry after the check succeeded. Otherwise it is left and logged as changed by the user. A failed check leaves the entry for the guardian.
The volume the user moves in the shell is a gain applied on the PC and does not touch the phone's volume. All commands run with a real timeout: the output is read on a separate thread so a blocked command cannot block the caller.
9.3 · Audio: playback on the PC
On the PC the audio piece is src/audio. The public header is audio.h; the parts are tested alone, without an audio device. Audio has no hardware acceleration on the PC: the Opus packets are decoded by libopus on the CPU; on the phone the Opus encoder is the one Android returns for createEncoderByType, and the code does not say whether it is hardware or software.
| File | Role |
|---|---|
pacchetti.c | reads packets from the channel (resumable reads: a timeout in the middle of a packet keeps the state) |
decodifica.c | Opus 48 kHz stereo to float, with concealment of missing packets |
flusso.c | decode plus detection of lost and late packets |
coda.c | queue with adaptive margin and lag recovery |
uscita_pipewire.c | the PipeWire output behind a small interface (PhUscita); tests use a fake one |
audio.c | the player that puts the parts together |
suona.c | a hand tool that plays a channel |
src/audioLife. ph_audio_crea(channel, notice, ctx, error) takes the channel (it closes it even if creation fails), with volume 100 and not muted. ph_audio_avvia opens the PipeWire output (application name YASDE, 48 kHz stereo float, requested node latency 1024/48000, 3 s to start) and starts the reading thread; once only. ph_audio_ferma stops reading and output; ph_audio_distruggi also closes the channel and frees. The notice PhAudioAvviso is called once, from the reading thread or PipeWire's, when the stream ends (PH_AUDIO_FINITO: the phone closed it) or breaks (PH_AUDIO_ERRORE); it is not called when the stop was requested, and it must not call stop or destroy.
Packets in. Each packet is decoded; a jump in the time field larger than 10 ms (half a packet; less is noise) means lost packets and up to 10 of them (200 ms) are concealed with the decoder's own concealment, no more sound is invented beyond that; a packet that arrives out of order or twice is dropped and counted; 25 late packets in a row mean the phone restarted its time and the stream is re-synchronised; 100 undecodable packets in a row make the flow unrecoverable.
The queue. Between the arriving packet and the sample leaving there is a margin that absorbs network delay. It is computed from the data: for each packet the lateness (arrival time minus the time field; the two clocks are not comparable but their difference is) is measured against the most punctual of the last 10 s; the maximum lateness in that window plus a fixed 40 ms is the ideal margin. It rises at once and falls by 8 ms per second. Constants: capacity 2 s; initial target 60 ms; limits 40 and 600 ms.
- Every half second the queue checks how much audio is really there. If it is well above the margin (more than 40 ms) it plays slightly faster, if well below slightly slower, rereading samples with linear interpolation by at most 2%: it is heard neither as a click nor as a pitch change. It stops when within 8 ms of the margin.
- A huge excess (after a stall and a burst) beyond 250 ms is cut at once to 40 ms, with a 5 ms (240 frames) cross-fade.
- An empty queue during playback is an underrun: the sound is faded out, the queue goes back to “filling” and restarts only with the full margin. After a hole the margin climbs again by 20 ms.
- A stall is ignored for the estimate for at most 5 s: beyond that it is the clock that changed.
ph_audio_statistiche reports received, lost, late, invalid packets, underruns, discarded frames, the margin and the target, and PipeWire diagnostics (device delay, buffered and queued frames).
9.4 · Gain, start-up and synchronisation
Gain. ph_audio_volume(percent) (0–100, clamped) and ph_audio_muto set a gain applied on the PC to the samples, with a cubic curve (v/100)^3 like the sliders of PipeWire and PulseAudio: 0 is silence, 100 is gain 1. A ramp of 10 ms avoids clicks. Muting does not stop reading: packets are received and decoded all the time, only the gain drops. The volume is persisted by the caller (the config piece, in the phone profile), not here. The default of the shell slider is 100%.
When audio starts. sv_audio_programma (src/shell/ossatura/sv_audio.c) schedules the start SV_AUDIO_RITARDO_MS = 5000 ms after the first video stream of the session opens; the manager thread ph-gestore does the actual open. Opening goes through ph_componente_canale(c, "audio"). If the open fails or the stream ends, a new attempt is scheduled after 2, 4, 8 and 16 s (SV_AUDIO_TENTATIVI = 4 per session); decisions go to the decision log. On session teardown the audio is destroyed and the counters reset.
Synchronisation. The audio clock is exposed: ph_audio_tempo_telefono_us gives the phone time (the time field) of the sample leaving the speakers now, estimated with the latency PipeWire declares (delay plus buffered plus queued frames), or -1 if unknown. The two phone clocks (video presentation time and audio sample count) are not comparable with each other. As the code stands, no caller in the shell uses this function: video frames are shown as they arrive and there is no active audio-video synchronisation yet. The piece to measure is listed among the open points.
cattura.h says the same for recordings, and the shell would have to do the conversion.Input, clipboard and the phone's panel
10.1 · Input injection
A window of a phone app sends the user's mouse and keyboard to the phone as input events. The PC side is ph_input_* in src/componente/componente.c and the stream code in src/shell/ossatura/sv_flussi.c; the phone side is telefono/video: Input (the channel), Iniettore (the injection), Gesti (what a touch or pinch means) and Pizzico (the pinch geometry).
On the PC. sv_flusso_input accepts an event only if the stream is active and not paused and, for touch and wheel, the video size it was computed on equals the stream's current size (the phone would discard it anyway). It then switches the panel off again if the phone is “in hand” (10.4 “The phone panel: off when connected”). Mouse moves and wheel events are dropped when more than CODA_INPUT_MAX (512) jobs are waiting in the input pool, so a phone that cannot keep up does not accumulate movements; the closing phases of a gesture always pass. The window code (src/shell/finestra-app/finestra_app.c) feeds it from one drag gesture on the windows container that accepts every button; gesto_inizia_pulsante maps the GDK button with ph_fa_pulsante_tocco to the bit of pulsanti (left 1, right 2, middle 4; back, forward and others start nothing). The left button keeps everything it had: title bar and corner start a window move or resize, content sends a touch. Right and middle count only on the content of an app window (the same discards as the left: pause, lost-connection veil and buttons inside it, black bands around the image, a size that changed); on the title bar, the corner handle, the window buttons or outside the windows nothing happens, not even a change of the active window. TOCCO down and moves carry the bit of the button that started the gesture (tocco_pulsanti), up and cancel carry 0; the field travels unchanged through ph_superficie_tocco, ph_srv_flusso_tocco and sv_flusso_input to the message. One button at a time: pressing a different button while a gesture is open makes GTK reset the controller (gtk_gesture_single_handle_event), so the toolkit sends a cancel and the gesture in progress is cancelled (the touch is cancelled on the phone; a window move or resize is cancelled); the second button starts nothing. gesto_inizia_pulsante also refuses a press while a gesture is open, as a defence. Every way of losing the gesture (cancel by the toolkit, window closed, pause, pinch starting, window minimised) sends a cancel for the touch that is down, so no down is left without its up or cancel. Text that is plain ASCII goes as TESTO; text with other characters goes through the clipboard as a paste (APPUNTI_INCOLLA, 10.3 “The shared clipboard”). The send writes on the input channel under a lock held during the write: the known exception to the rule of no lock during a network write, because ADB forbids two writers on one channel.
On the phone. Input reads the channel without a buffer and puts each message in a bounded queue of 256 closures; when the queue is full the reader waits, so no event is lost. One thread executes them. Each event carries the session id and, for touch, wheel and pinch, the video size used for the coordinates; if it differs from the session's current size the event is discarded (specification 4.5). A touch-down during a pause, resize or other transition is dropped. At the end of the channel (PC gone or error) every open gesture of every session is cancelled: no finger stays down.
| Message | Injected as |
|---|---|
TOCCO | a MotionEvent on the session's display: down, move, up or cancel. The left button is a finger (source touchscreen). If the pulsanti field has the right or the middle button when the gesture starts (the right wins if both), the whole gesture is a real mouse: source mouse, tool type mouse, ACTION_DOWN with BUTTON_SECONDARY or BUTTON_TERTIARY followed by ACTION_BUTTON_PRESS, moves with the button held, then ACTION_BUTTON_RELEASE and up (or cancel) with no button; setActionButton is hidden, so it is called by reflection and, if missing, the two BUTTON events are skipped. The button is decided at the press and remembered until the release; unknown bits are ignored. A cancelled mouse gesture (another session pressing, pause, resize, end of channel) sends only ACTION_CANCEL with no button and no ACTION_BUTTON_RELEASE (a release would count as a mouse-up and open the link). For the mirror the coordinates are scaled to the real screen |
ROTELLA | ACTION_SCROLL with source mouse; AXIS_HSCROLL and AXIS_VSCROLL are the 120ths divided by 120 |
TASTO | a KeyEvent with the code and meta state given, from the virtual keyboard map, on the session's display |
TESTO | each character mapped by the virtual keyboard map to key events; a character the map cannot produce is skipped and logged as a code point |
INDIETRO | Back down then up |
PIZZICO | see the next section |
Every injected event carries the id of the session's virtual display (schermoInput: 0, the real screen, for the mirror).
10.2 · The pinch gesture
Ctrl + wheel is a zoom. The PC sends the gesture as steps and the phone makes two fingers: this lets the apps' gesture detectors see a continuous movement. The shell turns the wheel into ph_input_pizzico calls; the argument checks (phase unknown, x or y outside the video, zero size) fail with -1 without sending anything and the step is clamped to −1200..1200.
| Rule | Value |
|---|---|
| Fingers | on a horizontal line through the centre (x, y), symmetric |
| Initial distance | 25% of the shorter side of the virtual display |
| Per 120 of step | the distance is multiplied by 1.25 (−120 divides it); steps of the gesture are summed |
| Distance limits | between 5% and 90% of the shorter side |
| Near an edge | the centre moves inward just enough that both fingers stay inside [0, w−1] × [0, h−1]; the gesture goes on from there with the same shift |
| Long steps | a step beyond ±30 is split into several ACTION_MOVE (at most 30 per move, one every 8 ms) |
| Phases | start puts both fingers down (and applies its step); continue moves; end lifts both (ACTION_POINTER_UP then ACTION_UP); cancel sends ACTION_CANCEL. Continue or end without an open start is discarded; a new start closes the open gesture first |
| Always closed | after 400 ms with no step the phone ends the gesture by itself; session close, pause and size change cancel it |
| With a touch in progress | the last arrival wins: a pinch start cancels the touch finger first; a touch down closes an open pinch (cancel); a touch move or up whose finger is no longer down is discarded |
| Paused | the pinch is discarded and an open one is cancelled |
Pizzico, Gesti)On the PC side the stream records the last pinch centre so that a pause, resize or close sends a PH_PIZZICO_ANNULLA and no finger stays down; what counts is what the phone really received, updated after each successful send, so a lost “up” is still cancelled and a cancel is not sent for a down that never left. An old jar answers an unknown type as it does for any unknown input type, with no visible error.
10.3 · The shared clipboard
Text copied on the phone is copied on the PC and the reverse. Only text: images and files are ignored. The phone side is telefono/appunti (Appunti, Regole, NascosteAppunti), the PC side is src/dati/appunti.c, on the channel appunti.
| Type | Name | Direction | Body |
|---|---|---|---|
0x58 | APPUNTI_TESTO | T→PC | the text just copied on the phone |
0x59 | APPUNTI_IMPOSTA | PC→T | the text to put in the phone clipboard |
0x5a | APPUNTI_INCOLLA | PC→T | u32 session id, then the text; clipboard plus “paste” to the app of that session |
u32 length plus UTF-8, not a 16-bit stringa)Never passed (in either direction, silently):
- copies marked sensitive (
ClipDescription.EXTRA_IS_SENSITIVE); - texts above 200000 bytes (
MAX_TESTO, alsoPH_DATI_APPUNTI_MAXon the PC): the message is ignored; - copies that come from a password manager or an authenticator: the criterion is the list of known packages in
Regole(a name stands for itself and its sub-packages). The Google password manager copies from Play Services, so it cannot be filtered by package and only the standard sensitive flag applies; - non-text content.
No echo. The phone sends APPUNTI_TESTO when its clipboard changes but not for what it has just received from the PC: an echo is the copy YASDE itself put (label yasde, source com.android.shell when the system tells it) with the same text as the last one from the PC. A real copy on the phone with the same text has another label and passes. The system notifies twice for one copy; the same timestamp and text count once, and an uncertain source is re-evaluated at the next notice. When the channel closes the phone's clipboard stays as it is.
On the PC a thread reads messages for the whole session (150 ms slices); a text is cleaned by ph_dati_pulisci (invalid UTF-8 becomes U+FFFD, NUL bytes are removed, and the length inside the message must match the bytes present) and handed to the notice; it is discarded if the cleaning grew it above the limit. When the reader ends by itself the notice is called once with a NULL text. APPUNTI_INCOLLA serves the text the virtual keyboard cannot produce (accents, emoji): afterwards the phone's clipboard keeps that text.
10.4 · The phone panel: off when connected
While the apps are used from the PC the phone panel (its real screen) stays off, while the phone stays awake and unlocked; when the user takes the phone in hand the panel turns on again. The code is telefono/pannello (Pannello, TieniSveglio, AssenzaPc, InputFisico, Frequenze, ImpostazioniPannello, NascostePannello) and, on the PC, src/shell/ossatura/sv_dati.c.
| Type | Name | Body |
|---|---|---|
0x60 | PANNELLO_IMPOSTA | u8 0 = off, 1 = on (any other value is an error) |
0x61 | PANNELLO_STATO | empty; answer u8 on, u8 in hand |
0x6e | PANNELLO_EVENTO | event: u8 on, u8 reason |
| Reason | Name in code | Meaning | In hand on the PC |
|---|---|---|---|
1 | MOTIVO_UTENTE | the user touched the real screen or a physical key, unlocked or woke the phone | yes |
2 | MOTIVO_CHIAMATA | incoming or ongoing call | yes |
3 | MOTIVO_FINE_CHIAMATA | call ended | yes |
4 | MOTIVO_PC | asked by the PC | no |
5 | MOTIVO_CHIUSURA | restore at close | no |
6 | MOTIVO_ASSENTE | PC absent for 30 minutes | yes: the panel stays on until the first PC input turns it off |
ph_ossatura_pannello_da_evento)How off works. PANNELLO_IMPOSTA 0 acts only on the compositor (SurfaceControl.setDisplayPowerMode, a hidden API): Android still believes the screen is on, so the apps on the virtual displays go on running and receiving input. It is refused with ERRORE during a call, when the phone is locked or its screen is off, and when the guardian is missing.
- Open the listener on the physical devices (
InputFisico:getevent -plonce, devices chosen by capability, touchscreen withABS_MT_POSITION_XandINPUT_PROP_DIRECT, keys by common physical keys; the shell may read/dev/inputbecause it is in the groupinput). Without it the panel is not turned off. Injected events never reach/dev/input, so they cannot count as the user touching the phone. - Register the restore entries first, then change: the screen timeout (
pannello-timeout, order 420) if it is not already the maximum, then the panel (pannello-acceso, order 400). If any registration returns false nothing is changed; if the later step fails, the earlier ones are undone as far as they can. - Raise the screen timeout to the maximum
2147483647ms (screen_off_timeoutthroughcmd settings, verified by re-reading): without it the apps on virtual displays stop receiving input. It stays at the maximum even during the “in hand” periods, and is restored (only if still ours) when the PC asks to turn on or at close. - Turn the panel off, send the event (reason 4), then measure the refresh rate.
It comes back by itself, and the event goes out, when the user touches the real screen or presses a physical key, unlocks the phone, or a call arrives or is in progress. From then the phone is “in hand” and stays on until the PC sends PANNELLO_IMPOSTA 0 again. If the turn-on fails, the reason is remembered and the control loop retries it every second, before anything else. If Android is asleep the panel is not forced (the system turned it off; the user wakes it).
The control loop. One thread, every 1000 ms (PERIODO_MS), reads the call state, whether the screen is interactive and whether the phone is locked, each in its own try so one failing read does not stop the others, then evaluates the PC absence, then the wake-lock guard, then reports changes: a call starting turns the panel on (or marks the phone in hand), the end of a call is reported, a lock or sleep with the panel off turns it on, and an unlock or wake with the panel on is reported as reason 1. It starts at the first sign of life, and an exception in a round never kills it.
The PC decides when to turn the panel off; the phone only obeys and reports. The code is in sv_dati.c.
- At connection (decision of 24 Nov 2026): as soon as the session is up, if the panel is on and the phone is not in hand, YASDE turns it off, once, queued on the state pool because it can last seconds. If the phone refuses (locked, in a call) it is not retried; at unlock or at the end of the call the “in hand” rule takes over. If the phone is already in hand at connection the panel is not turned off. Reading the state again after a refusal is not covered by a test.
- First input from the PC with the phone in hand and the panel on:
sv_pannello_spegni_se_in_manoqueues one turn-off (one at a time). After a refused turn-off it waits 2 s before trying again. - The popup switch “physical panel” calls
sv_pannellodirectly. - Closing the last window does not turn the panel on while YASDE is connected (decision of 23 Nov 2026, in place of the specification). The panel comes on only for the user (unlock on the phone, the popup switch), a call, the end of a call, and YASDE closing or dropping (restore on the phone side).
- Turned off or on by the PC means not in hand. State changes from
0x6eevents are published as the phone state; every state read is requested after the listener is registered. - There is no timer on the PC that turns the panel off again after the user's inactivity. The design documents say there is; the code does not (1.5 “Known deviations from the design documents”).
10.5 · Refresh rate while the panel is off
Turning the panel off makes the phone's compositor drop to a lower rate. A measured case (120 Hz test phone): the compositor went from 120 to 60 Hz with the panel off and the video fell from about 87 to 57 frames per second; with the remedy it climbed back to about 80. The remedy is a workaround started by the measured symptom on any phone, never by the manufacturer's name; it is isolated in one place and documented.
- After every turn-off the active compositor rate is measured and written in the log with the display's maximum.
- The wanted rate is the highest among the modes with the same resolution as the active one (
Frequenze.massimaStessaRisoluzione), capped by the user'speak_refresh_rateif it is numeric and greater than 0 (Frequenze.voluta). - If the active rate is below the wanted one,
min_refresh_rateis set to the wanted rate, with the restore (pannello-frequenza, order 410) registered before and applied only if the value is still ours; at turn-on it is put back. If the user already has a minimum equal or higher nothing changes.
10.6 · Keeping the phone awake
A wake lock keeps the phone awake and therefore protected from locking through inactivity for as long as YASDE is connected and alive. It is in TieniSveglio, with the Android part behind the Presa interface so the logic is tested on a plain JVM. The lock is taken from the first message of the command channel (the greeting), not at service start.
Why a wake lock and not the screen timeout: the wake lock belongs to the process, so if the service dies (even with kill -9) the system releases it and the phone goes back to turning off and locking on its own times. No setting stays changed and nothing needs the guardian.
| Condition (all must hold) | Detail |
|---|---|
| Channel greeted | the PC has sent SALUTO |
| Phone not locked | the lock would keep the lock screen lit for ever after a lock with the power key: it is released while locked and taken again at unlock; an unreadable state counts as locked |
| PC alive | last sign of life younger than 30 minutes (Registro.PC_ASSENTE_MS); exactly 30 minutes is already too much; a sign newer than now is an incoherent clock and counts as no |
Every doubt goes to the safe side: release. The wanted state itself expires: if aggiorna does not arrive within SCADENZA_STATO_MS (30 s, measured with its own monotonic clock) the thread treats it as “do not hold”. 30 s and not 5 because the control round and the PC's commands work under the same lock as the panel and run cmd settings with 10 s limits (up to 20 s); with 5 s a phone under load would drop the lock and fall asleep mid-session. The caller of aggiorna never waits: it only writes the wanted state; a separate thread takes and releases, outside every lock, retrying every 5 s on failure.
The lock is taken without ON_AFTER_RELEASE (the safe choice): when it is released and the user has not touched the phone for longer than their own timeout, Android does not restart the countdown from zero, it turns the screen off and locks at once.
10.7 · Signs of life and PC absence
The phone must not stay in a state “owned by YASDE” when the PC has vanished without closing. Rule: any message the phone receives from the PC on the command channel (the greeting included) is a sign of life. The service notes the time (monotonic clock, SystemClock.elapsedRealtime) before dispatching it (Smistatore.tratta → Registro.segnoDiVita).
| Constant | Value | Where |
|---|---|---|
PRESENZA_INTERVALLO | 300 s (PH_PRESENZA_INTERVALLO_S) | PC: sends PRESENZA when nothing has been sent on the command channel for 5 minutes; it is needed only when there is no other traffic |
PC_ASSENTE | 1800 s (Registro.PC_ASSENTE_MS, PH_PC_ASSENTE_S) | phone: six missed PRESENZA in a row |
| Control round | 1000 ms | phone: absence check and wake-lock guard |
On absence (AssenzaPc, exactly PC_ASSENTE_MS, a clock going back counts as expired) the steps are, in order: turn the panel on if YASDE had turned it off; restore the minimum refresh rate; put the user's screen timeout back (only if still ours); then send PANNELLO_EVENTO (on, reason 6). A step that fails or throws stops there and is retried at the next round, without skipping the order and without sending the event early. The wake lock is not a step: the guard releases it with the same limit. It does not close the service or the sessions. It is the safest state: the phone is exactly as every day and Android turns it off and locks it with the user's times.
On return (the first sign of life after the absence): the wake lock is taken again if the phone is not locked, and the screen timeout is raised again (the restore registered before); the panel STAYS ON until the PC sends PANNELLO_IMPOSTA 0, exactly as if the phone were in hand (reason 6 counts as in hand on the PC). A failed return is retried at the next round.
If the wake-up of a sleeping PC delays a PRESENZA, the boot clock makes the next one go out at once; a late message does not trip the 30 minutes because the window is six times the interval. The case “phone restarted by the user and the PC still running” needs no rule: the link loses the connection and starts again.
The shell
11.1 · Overview and pieces
The shell is everything the user sees: the single GTK 4 window, the desktop inside it, and the windows of the phone's apps drawn as inner windows. It lives entirely under src/shell/. GTK appears nowhere else in the project, and the shell never touches the phone, the audio or the disk directly: it goes through one narrow door, the services (11.4 “The services and their backends”).
Two Italian words recur in the code. ossatura is the skeleton: the piece that owns the program, the main window and the real services. pezzo (piece) is the unit of work: one piece is one folder, with its own meson.build, its own tests and, in the shell, its own style sheet and translation file.
| Piece (test name) | Folder | What it does |
|---|---|---|
shell-ossatura | src/shell/ossatura/ | The GtkApplication it.yasde.YASDE, the main window, the real services, the lock and connection veil, the PC/phone clipboard link, the ordered shutdown |
shell-superficie | src/shell/superficie/ | The widget that shows one video stream without copies (DMA-BUF) or from memory |
shell-finestra-app | src/shell/finestra-app/ | The inner windows of the apps: title bar, buttons, input translation, pause, screenshot and recording, Compatibility |
shell-barra | src/shell/barra/ | The bar at the bottom (48 px) |
shell-launcher | src/shell/launcher/ | The app launcher with search |
shell-desktop | src/shell/desktop/ | Wallpaper, icons, widgets, menus and the two dialogs |
shell-trasferimento | src/shell/trasferimento/ | Send and receive panels, folder navigator, APK confirmation |
shell-sistema | src/shell/sistema/ | Notifications, toasts, phone status, volume |
shell-connessione | src/shell/connessione/ | First connection and pairing screen |
shell-finto | src/shell/finto/ + src/shell/comune/ | The fake backend, and the common piece (delivery, context, services wrapper, style) |
strumenti/prova.sh takes11.2 · Layers, popups and piece handlers
The root of the shell (ph_shell_radice) is a stack of layers (PhShellStrato in src/shell/shell.h). Inside a layer the last child added is on top. For absolute positions (windows, icons, context menus) a piece uses ph_shell_libero_nuovo(), a container that lets clicks through wherever it has no child.
Each piece offers a single entry point, ph_<piece>_installa(PhShell *), declared in src/shell/pezzi.h. It is called once, from the GTK thread, after ph_shell_nuova: it builds the widgets, adds them to the layers, loads the piece's CSS, registers the handlers it serves and starts listening to the services. ph_ossatura_installa_pezzi (in src/shell/ossatura/ossatura.c) installs only the pieces present in the build (the header generated at configuration time, with one flag per piece).
Pieces serve each other through PhShell handlers, never by including each other's headers: windows (open an app, list the windows, bar click, mirror), desktop (icons), notices (ph_shell_avviso), launcher, transfer, system (the three bar buttons and the hidden-notification set) and pinned apps. Events travel the other way with ph_shell_ascolta: PH_SHELL_EV_FINESTRE, PH_SHELL_EV_POPUP, PH_SHELL_EV_HOST, PH_SHELL_EV_AREA, PH_SHELL_EV_DESKTOP, PH_SHELL_EV_NASCOSTE, PH_SHELL_EV_FISSATE.
Popups follow one rule: only one is open at a time (PhShellPopup). Opening one closes the open one; a transparent veil under the popups, bar included, turns the first click outside into a close that does not reach what is below. Escape closes the open popup; with none open it goes to the active inner window, which translates it to the phone's Back when the preference esc_indietro is on (the default). F11 toggles full screen and never reaches the phone.
11.3 · Threads and delivery to the GTK thread
The shell is one GTK thread plus worker threads. The rule is written at the top of src/shell/servizi.h and in src/shell/CONTRATTI.md, and every piece obeys it.
- One GTK thread. All widgets,
PhShelland everyph_srv_*call live there. - The GTK thread never blocks: no network, no large file reads, no joins of threads that may hang. Requests to the phone start on backend threads and return with a callback.
- The only road from another thread to the GTK thread is
ph_shell_consegna(fn, dati, libera). It is always asynchronous, even when called from the GTK thread (the function runs in a later iteration of the main loop, never inside the call), it keeps the order of deliveries from one thread, and it frees the data afterwards. Scatteredg_idle_addorg_main_context_invokecalls are forbidden in pieces. - Every callback and every event arrives on the GTK thread. A
GCancellablecancelled from the GTK thread guarantees that the callback will not arrive any more, even if the result is already queued. - Snapshots. State (connection, phone, apps, notifications, transfers, volume) is read with calls that return the last snapshot. A returned pointer is valid until the GTK thread returns to the main loop; anything needed later is copied.
- Video: one reader thread per stream, owned by the surface, calls
ph_srv_flusso_leggi(reception and decoding happen there). Textures are built on the GTK thread.
Pool (in struct Sv) | Threads | Work |
|---|---|---|
p_lavori | 3 | Folder listings, searches, thumbnails, file reads |
p_stato | 1 | Apps, notifications, panel (in order) |
p_icone | 1 | App icons, one at a time |
p_scrittura | 1 | Saving profile and preferences (in order) |
p_flussi | 1 | Opening, pausing, resizing and closing video streams |
p_input | 1 | Input toward the phone (in order) |
p_installa | 1 | APK installation and uninstallation, one at a time |
src/shell/ossatura/servizi_veri.c, src/shell/ossatura/sv_interno.h)Besides the pools the real services run a manager thread (ph-gestore): it is the only one that takes a borrowed session from the connection (chapter 3); pool threads only "use" the session through a counter, and the manager waits for the counter before it hands the session back.
11.4 · The services and their backends
Every piece reaches the phone, the audio, the transfers and the persistence only through PhServizi (src/shell/servizi.h). Two implementations stand behind it: the real one, written by the skeleton on top of the lower pieces, and the fake one (11.9 “The fake backend”), so any piece can be run and photographed without a phone.
The common piece (src/shell/comune/servizi.c) wraps a backend table (PhServiziBackend in src/shell/servizi_backend.h) and enforces the thread rules for both: events on the GTK thread, snapshots, the icon cache, cancellation, deferred saving of the profile and the life of video streams. App icons (ph_srv_icona, GTK thread only): if the package has a row in the Kora table (tabella.txt, lines <package> <kora-name>) and the file <kora-name>.png loads, that texture is returned and the phone is not asked at all (a PNG of another size is accepted, up to 1024 px a side and 2 MiB: whoever shows it scales it); otherwise the phone's icon, or none yet (the request starts by itself and PH_SRV_EV_ICONA arrives), and the initials square if it never comes. The folder is the one in the environment variable YASDE_ICONE_KORA if set and not empty, else $APPDIR/usr/share/yasde/icone-kora (inside the AppImage), else none. The table is read once, at first use (at most 256 KiB and 2000 lines; malformed lines are skipped; package up to 127 characters, name up to 95 and valid; a package twice: the first wins); each PNG is loaded at first use and kept; a PNG that fails to load is not tried again. Missing or damaged files mean the phone's icon, with no error on screen; only a missing or unreadable table writes one decision line in the log. An app that changes its icon on the phone keeps showing the Kora one. A backend call is answered with exactly one final ph_servizi_lavoro_* call per job (searches: zero or more ph_servizi_lavoro_trovati and one ph_servizi_lavoro_cerca_fine). After the final call the job is not touched again.
Event (PhSrvEvento) | Meaning |
|---|---|
PH_SRV_EV_COLLEGAMENTO | Connection state, including the lock |
PH_SRV_EV_TELEFONO | Battery, network, physical panel |
PH_SRV_EV_APP, PH_SRV_EV_ICONA | App list; an icon arrived (argument: package) |
PH_SRV_EV_NOTIFICHE | Notifications changed |
PH_SRV_EV_TRASFERIMENTI | Transfer queue changed |
PH_SRV_EV_VOLUME, PH_SRV_EV_APPUNTI | Volume; text arrived from the phone's clipboard |
PH_SRV_EV_PROFILO | The profile of another phone was loaded: re-read it |
PH_SRV_EV_CONTROLLI, PH_SRV_EV_METEO | Quick switches; weather forecast |
Strings given to the services are copied before the call returns. Strings coming from the phone are already safe to show (valid UTF-8, no control characters); the raw percorso and nome fields only serve to navigate and request, and only the _schermo versions are displayed. Structures of the contracts are always initialized by field name, never by position, because contracts grow by adding fields at the end.
11.5 · The skeleton
The skeleton is src/shell/ossatura/. main.c only calls ph_ossatura_esegui.
- Before any thread: preferences (
ph_cfg_preferenze_carica; result -1 means defaults and never save), language (ph_lingua_inizializza), and the font scale: withscala_automaticaoff, the value is applied throughGDK_DPI_SCALEbeforegtk_init, because GTK 4 has no fractional widget scale. - Single instance: the application id is
it.yasde.YASDE; a second launch brings the existing window to the front (activate) and opens no second connection. - At startup (main instance only): handlers for
SIGTERMandSIGINTthat callg_application_quit, removal of stale temporary files (ph_cfg_pulisci_temporanei(3600)) and of old wallpaper images (ph_cfg_pulisci_sfondi). - On activation: real services (
ph_ossatura_servizi_veri),ph_shell_nuova, the host window (ph_finestra_nuova), the pieces, and the clipboard link (ph_appunti_installa). - The host window is a resizable
GtkApplicationWindowtitled YASDE with a header bar that carries the full-screen button, default size 980×584, minimum 640×420, with the shell root as its content. F11 is caught on the window before any inner window sees it. In full screen a 6 px strip at the top (PH_STRATO_TITOLO_HOST) expands to a title row on hover. - Host visibility:
ph_host_visibile_da_statoreads the toplevel state: minimized or suspended means not visible. The skeleton tells the shell withph_shell_imposta_hostand every video stream goes to pause.
What covers the shell is decided by ph_ossatura_vista (in src/shell/ossatura/logica.c): the first-connection screen wins when ph_shell_connessione_da_mostrare says so, otherwise the veil, otherwise nothing. Never both.
| Connection state | Shown | Content |
|---|---|---|
PH_SRV_NON_ABBINATO | Connection screen, always | Pairing code (11.6 “The pieces of the shell”) |
PH_SRV_CERCO, PH_SRV_PERSO | Connection screen only if no phone was ever connected in this run; otherwise the veil | Veil: title and the connection's own reason; Reconnect now when the connection is lost |
PH_SRV_BLOCCATO | Veil | Lock icon, Phone locked and a fixed sentence |
PH_SRV_COLLEGATO, PH_SRV_CHIUSO | Nothing | — |
A phone whose screen was turned off by the system or by the power button (schermo_spento) gets the lock veil too, and its streams stop.
Ordered shutdown (ph_ossatura_chiudi, used by the program and by demo-ossatura so the demo tests the real sequence): (1) the window is hidden and destroyed; (2) ph_shell_libera destroys the root itself, so the destroy handlers of the pieces run once, with PhShell and the services still alive, and streams are closed; (3) only then ph_servizi_libera closes the connection, and the guardians restore the phone. After each step the pending main-loop work is drained. A second defence, the registry of live objects in src/shell/comune/ascoltatori.c, makes ph_srv_smetti and ph_shell_smetti harmless after release. The rule for pieces: in the root's destroy stop listening with all the *_smetti functions and keep your own reference to the widgets as long as listeners exist.
11.6 · The pieces of the shell
Short descriptions of the pieces; the real behavior is in each folder's code and in its COMPITO.md.
| Piece | Behavior verified in the code |
|---|---|
| Bar | 48 px at the bottom. Left to right: launcher button, separator, one entry per open inner window (icon or initials placeholder, indicator under it: active, open, minimized), then the system area: send, receive, volume, phone status, notifications (the last three are created by the system piece and only placed here). Clicking an entry calls ph_shell_clic_barra. A right click opens the bar menu (PH_POPUP_MENU_BARRA): close the app, pin or unpin. Pinned apps are per phone, at most PH_CFG_MAX_FISSATE (16) and stay on the bar when closed. The clock opens the calendar popup. |
| Launcher | Grid of the phone's apps with a search field (a case-insensitive match; Enter opens the first result). The panel is centered horizontally, 60% of the area wide (at least 480, at most 960 px; if the area is narrower than 528 px it stays 24 px from the edges), its top at 6% of the height (at least 24 px) and its height that of the content, up to 76% of the height above the bar; the search field stays at the top and the grid scrolls vertically. Icons are 60 px, columns 112 px wide (as many as fit the inner width), 28 px between rows; a click outside the panel closes it (the shell's popup veil). The measures are in PH_LAUNCHER_* and ph_launcher_misure (src/shell/launcher/logica.h), applied by misure_aggiorna in launcher.c; this replaces the measures of the specification. Known limit: when the window is resized with the launcher open, the old measures hold for one frame. Click opens, drag starts a drag to the desktop (the launcher closes when the drag starts), right click offers open and add to or remove from the desktop, plus pin. |
| Desktop | Wallpaper (solid, gradient or an image taken from the phone and saved in the cache), icon grid with cells of 92×96 starting at 16,16, and widgets. The catalog in src/shell/desktop/widget.c has Clock, Calendar, Phone status, Recent notifications, Phone storage, Weather, Month calendar, Next alarm, Battery in detail, Quick switches, Frequent apps and Recent transfers. Find-my-phone is compiled out (PH_DSK_TROVA_OFFERTO is 0), and the types note and riproduzione exist in the profile format but are not in the catalog. |
| Inner window | Title bar of 50 px with Back on the left, then the name, and on the right the REC marker (just before screenshot), screenshot, record, more (⋮), minimize, maximize, close, as round buttons of 30 px that show only their symbol until the pointer passes over them (Close turns coral); in very narrow windows (such as the minimum, 288 px; the room for the name is the width minus 270 px) the name has no room and is not shown. Light frame, corner radius 24 px (0 when maximized or snapped, with no shadow and no border); border and highlight line are drawn by a child (ph-finestra-app-filo) drawn over the whole frame without moving the other children, so the children stay where finestre.h puts them. A window that is not active keeps the same fill, with name and symbols dimmed and a lighter shadow. Glass. GTK has no backdrop filter, so behind the title bar only (50 px) the frame, in its own snapshot, redraws what lies under the window, blurred (Gaussian, deviation 26 px) and more saturated (1.6): the widgets drawn before it, that is the desktop layer and the windows below. Each is taken through a GtkWidgetPaintable, which reuses the drawing already made and signals when it changes; for the other windows the paintables of their children are used, not the frame's, so blurs are not nested. On top comes the CSS background of the title, a white veil at 58% (42% when the window is not active). The rest of the window is covered by the opaque content and is not blurred. The mode is decided when the frame is realized, by the one rule of the whole shell (ph_shell_vetro_decidi, see Glass surfaces below); if it is off, or the frame is not inside the shell's root, the frame keeps its almost opaque fill (94%) and the title bar is plain. The automatic tests of this glass are shell-finestra-app-vetro and shell-finestra-app-vetro-menu. Colours, radius and shadows are the --ph-vetro-* variables of src/shell/ossatura/base.css, used by finestra-app.css; resize handle of 18 px; shortcuts Ctrl+R rotate, Ctrl+W close app, Ctrl+Shift+C copy screenshot. Rules for geometry and density live in src/finestre/ (chapter 12). |
| Video surface | See the next section. |
| System | Notification panel (hiding applies only inside the shell; an updated notification becomes visible again), toasts (5.2 s for a phone notification, 3.2 s for an information notice), a desktop notice through GNotification when the host window is not visible, the phone popup with the mirror switch and the physical panel switch, and the volume popup. |
| Transfer | Send and receive panels with queues, the folder navigator and the APK confirmation (chapter 13). |
| Connection | Card over the default gradient: instructions and a search spinner when no phone was ever paired; a code field and a pair button when the phone does not know the PC, an expander for typing an address and port by hand, and a Search again button. The code is read at click, passed to ph_srv_abbina, and the field is emptied after every attempt. Pairing code, addresses, ports and serial numbers never reach disk or logs. |
11.7 · The video surface
Each video stream is shown by one GtkPicture inside a GtkGraphicsOffload with a black background (src/shell/superficie/superficie.c). The surface owns its PhSrvFlusso, opens it, and runs one reader thread that loops on ph_srv_flusso_leggi with a 100 ms timeout.
- Hand-over. The reader keeps at most one frame waiting: a new frame replaces the old one and releases it, and at most one
ph_shell_consegnais in flight. Frames are dropped, never resolution (ph_sup_scambio_metti). - Without copies. A
PH_FOTO_DMABUFframe becomes aGdkDmabufTextureBuildertexture (fd, offsets, strides, modifier; for YUV formats the color state fromPhFotoColore, BT.709 or BT.601, limited or full range). APH_FOTO_MEMORIAframe becomesgdk_memory_texture_newover aGBytesthat wraps the data. Frames are checked first (sizes 1 to 8192, 1 toPH_FOTO_PIANI_MAXplanes, valid descriptors): an invalid one is released and discarded. - Fallbacks are recorded. If GTK refuses a DMA-BUF, the stream goes to memory and a line is written with
ph_shell_decisione:[decisione] HH:MM:SS.mmm <what> - causa: <cause>on stderr, never with personal data. - Under load. The surface of the foreground window never gives up by itself; the others show one frame in two, then one in four, until the queue is empty (
ph_superficie_primo_piano). Resolution is never lowered. - States shown by the surface itself: the protected-screen message, and, when the connection is lost, the last image blurred with Reconnect now and Close.
- Closing:
ph_srv_flusso_interrompi, wait for the reader thread (at most the read timeout), thenph_srv_flusso_chiudion the GTK thread; idempotent, and no callback arrives afterwards. - Counters: with the environment variable
PH_SUPERFICIE_STATset to 1, one line every 5 s on stderr per stream.
11.8 · Style, resources and accessibility
Each piece has its CSS file, compiled into the executable as a GResource at /it/yasde/shell/<piece>.css and loaded by the piece's own _installa with ph_shell_stile_carica. The base style, src/shell/ossatura/base.css (compiled by the common piece as base.css), is loaded by ph_shell_nuova and holds the --ph-* color variables and the shared classes (ph-pannello, ph-dialogo, ph-menu, ph-tb, ph-riga, ph-pbtn, ph-ghost, ph-accento, ph-pillola, ph-campo, …).
- A piece uses only classes prefixed
ph-<piece>-. It is GTK CSS, not web CSS: nogap,max-widthorposition; sizes come frommin-width, margins or code. - No
GtkStyleContextper widget and no inline CSS, except computed colors (the user's wallpaper color, placeholder colors). - Icons are the mockup's SVG paths drawn in the text color (
ph_shell_icona_nuova,PhShellIcona), with round line caps and joins unless the fieldspigoli_viviis true (butt caps and mitered joins,GSK_LINE_CAP_BUTT/GSK_LINE_JOIN_MITER); it is true only for the seven title symbols of the inner windows, which followdocs/DESIGN_FINESTRE.mdand not the mockup (checked byprova_comune.c); missing app icons become a colored square with initials (ph_shell_segnaposto_nuovo). - Every piece's logic test loads its CSS (
ph_shell_stile_controlla) and fails on any syntax error. - The look is glass, not the mockup's dark colours: the mockup stays the reference for the layout only. Bar, launcher, panels, menus, dialogs and widgets are glass surfaces (next point); the host window and system dialogs follow the system theme.
- Glass surfaces. A piece registers a widget with
ph_shell_vetro_registra(sh, w, radius, type)(src/shell/shell.h, section “Vetro”; implementation insrc/shell/comune/vetro.c). The shell gives it the CSS classph-vetro-chiaro(light) orph-vetro-scuro(dark); the classes inbase.cssgive the veil, the edge (light: border and long shadow; dark: a thin light line on top) and the text colours. When the graphics card draws, the graphics card draws, the layered root draws behind it, inside its rounded rectangle (the same radius as its CSS), what lies in the layers below it, blurred and more saturated throughGtkWidgetPaintable(light: deviation 26 px, saturation 1.6; dark: 20 px, 1.4). The rule is one for the whole shell (ph_shell_vetro_per_renderer): blur only withGskGLRenderer,GskNglRendererorGskVulkanRenderer; the environment variableYASDE_SFOCATURA(0 or 1) overrides it (ph_shell_vetro_decidi). When blur is on the root has the classph-vetro-attivo; without a graphics card the surfaces have an almost opaque fill, never a translucent veil without blur. Blurs are never nested: a registered surface is drawn whole in the snapshot of whoever is above it (without its own blur, with its veil, border and shadow), while a widget that draws its own blur (the frame of an inner window, marked withph_shell_vetro_proprio) is drawn from its children. Known limits (the first and the last are written in the code, the connection card one follows from the mechanism): behind a surface only what lies in the layers below it is seen, not what lies under it in the same layer (an icon under a desktop widget stays sharp; behind the connection card the blur is covered by the screen's own background); the CSS opacity of a surface does not apply to its blur. - Which surfaces are glass. Dark: the bar. Light: the launcher and its menu, the system popups, the notice (toast), the transfer panels, the desktop widgets, the menus and dialogs of the desktop, the calendar and the menu of the bar, the ⋮ menu of the inner window, the connection card. Not glass: the lock veil, the “Drop to send” frame (it stays a dark veil), the icons and names on the desktop, the PC window.
- Theme. Inside a light surface the
--ph-*variables change value: text#10202E,#2F4558,#3A4D5F(three levels), accent#1F7A8C(only as a background), and new variables for text that must stay readable on light:--ph-accento-testo(accent as text),--ph-errore,--ph-avviso, plus focus, field text, ghost border and progress track; the nearest surface wins, so a dark one inside a light one restores the dark values. The full list is inbase.cssand insrc/shell/CONTRATTI.md, section 6. Rule for the pieces: no hand-written content colour in their CSS, only--ph-*variables; a colour that is data (an icon, a category) stays with a same-line commentcolore-dato: reason, and every piece's test checks it withsrc/shell/prova_css.h. A piece never sets background, border or shadow on a registered widget. - Glass tests.
shell-comune-vetro(the registry and the rule),shell-finestra-app-vetroandshell-finestra-app-vetro-menu(the title bar and the ⋮ menu),shell-desktop-vetro(widgets, menu, dialogs), and each piece's own tests check that its surfaces carry the right class. - Cost of the blur. Measured on 24 Nov 2026 on the development tablet, fake phone, four video windows at 60 frames/s, Vulkan renderer; median / 95th percentile of the draw time: without blur 5.1 / 7.2 ms; blur on the windows only 7.1 / 10.0 ms; with the launcher open above the windows 8.5 / 12.8 ms. No frame lost; CPU time of the program about +50%.
- Readability limit. With the 58% veil over a very dark or very bright wallpaper the secondary levels of text lose contrast (only the main text stays full), and the dark bar over a white background turns grey.
- Accessibility: everything clickable is a real control reachable with Tab, with a visible focus ring; labels go through
ph_shell_etichetta,ph_shell_espansoandph_shell_premuto.
The renderer is not forced by the program: GTK chooses it. The development scripts that open demos on the tablet export GSK_RENDERER=vulkan unless the variable is already set.
11.9 · The fake backend
The fake backend (src/shell/finto/, finto means fake) is a simulated phone in memory, used by every demo and by the piece tests. Nothing is written to disk and no real file is sent.
- It simulates the connection (searching, then connected after 300 ms; lock, drop and return on command), a list of apps with generated icons, notifications, battery, a folder tree with thumbnails, transfers that advance every 300 ms, synthetic video streams at 60 frames per second (in memory, or in DMA-BUF with the
dmabufoption), volume, clipboard, profile and preferences, APK installation, screenshot (a real PNG) and simulated recording, and the data of the new widgets. - It also simulates a first connection:
PhFintoIniziocan start the phone as connected, as not paired (fake codes: 123456 is right, 000000 means the code screen is not open on the phone, anything else is wrong) or as searching. - Every command received (input, panel, …) is written on stderr with the prefix
finto:. - Each piece has a demo,
demo-<piece>, built by itsmeson.build.strumenti/demo-sul-tablet.shopens it on the test tablet;strumenti/foto-demo.shopens it on an invisible screen and saves PNG photographs, which is how a piece's look is compared with the mockup (16.1 “Tests of the PC pieces”). demo-ossaturais the whole shell with the pieces present, over the fake backend.
Windows and density
12.1 · The window rules
The rules of the inner windows are pure logic in src/finestre/: no graphics, no phone, no internal clock (the time arrives as a parameter, in milliseconds, non-decreasing), one thread. The shell piece src/shell/finestra-app/ only draws what these rules decide and feeds them events. The header src/finestre/finestre.h is the contract; the tests are in src/finestre/prova_finestre.c.
Coordinates are the shell's logical units (physical pixels divided by the shell scale), with the origin at the top-left corner of the usable area, which is the root minus the 48 px bar (PH_FIN_BARRA_H). Pointers are double, rectangles are integers. Return values follow the project convention: 0 or -1 with a PhErrore; a pointer or id of 0 is an error. At most PH_FIN_MAX (64) windows are open at once.
| Constant | Value | Meaning |
|---|---|---|
PH_FIN_TITOLO_H | 50 | Window title bar |
PH_FIN_CROM_H | 70 | Title bar plus technical foot (PH_FIN_PIE_H, 20 px); taken from the content only when the foot is on, otherwise only the 50 px of the title |
PH_FIN_PULS | 30 | Round title buttons, centred vertically in the title bar |
PH_FIN_PULS_DIST, PH_FIN_PULS_MARG_DX, PH_FIN_PULS_MARG_SX | 4, 14, 22 | Gap between two buttons; margin from the right edge to the right-hand group; margin from the left edge to Back |
PH_FIN_ANGOLO | 18 | Resize handle, bottom right |
PH_FIN_MIN_W × PH_FIN_MIN_H | 288 × 180 | Minimum size when resizing (288 = 22 + 7 buttons of 30 + 6 gaps of 4 + 14, plus 18 px: the seven buttons fit without overlapping, the app name has no room) |
PH_FIN_VISIBILE_MIN | 96 | Pixels of a window that must stay inside the area horizontally |
PH_FIN_AGG_LATO, PH_FIN_AGG_ALTO | 14, 10 | Snap distance from the side edges and from the top |
PH_FIN_ASSESTA_MS | 300 | Settle time without size changes before the phone is asked |
PH_FIN_DENS_PASSO | 20 | Step of the automatic effective density, in dpi |
PH_FIN_FLUSSO_MIN, PH_FIN_FLUSSO_TETTO | 64, 2560 | Smallest side and default cap of the stream |
PH_FIN_DENSITA_RIF | 160 | Reference dpi of a shell at scale 1 |
PH_FIN_DENSITA_MIN – PH_FIN_DENSITA_MAX | 50 – 2000 | Accepted densities |
PH_FIN_MARGINE_AREA | 16 | Margin left per side when a default size must shrink to fit |
src/finestre/finestre.h12.2 · Order, snapping and gestures
Order, snapping and the gestures follow the mockup unless a comment in the header says SCELTA (choice).
- Opening (
ph_fin_apri): if the app already has a window it is restored, brought to the front and made active (no new window). Otherwise a cascade places it at x = 70 + n·40, y = 30 + n·30 with n the number of open windows (the mirror excluded) modulo 6, then brings it inside the area. The mirror opens at x = 640, y = 20 with no cascade. With the preferenceriapri_dove_eri(reopen where you were) on, position and size come from the remembered rectangle of the app. - Depth. Windows are kept in depth order, minimized ones included (
ph_fin_ordine). Closing leaves no window active; minimizing an active window leaves none active either. - Dragging (title bar): the window follows the pointer. At the bottom it may go past the area until only the title bar is visible (
yis limited to the area height minus the title height); at the top never, so the title stays grabbable; horizontally at least 96 px stay visible. A click without movement neither detaches nor snaps. - Snapping (resizable windows only): pointer within 14 px of the left or right edge gives the left or right half, within 10 px of the top gives maximize;
ph_fin_gesto_anteprimareturns the rectangle for the preview. A snapped window follows the area; on the first movement of a drag it detaches and recovers its previous size, keeping the pointer at the same horizontal proportion of the title. - Resizing (corner handle): size = original + displacement, at least 288×180, at most up to the right edge and the bar. No request goes to the phone during the gesture.
- Maximize / restore: toggles, and restore returns to the arrangement before (also from snapped). Rotate (Ctrl+R) swaps the width and height of the content, within the area.
- Minimize is a separate flag from the arrangement: restoring returns to what it was. A minimized window's stream is paused (
ph_fa_pausa_voluta): the shell also pauses every stream when the host window is not visible, and before pausing any open touch is closed. - Bar click (
ph_fin_clic_barra): in front goes minimized, minimized goes restored, otherwise it comes to the front. - When the area shrinks (host window, full screen, scale:
ph_fin_imposta_host): each normal window remembers the size it was given by the user (the one at opening, or the last resize, rotation or return to resizable) and its effective size is that one, reduced only as much as needed to fit; so a window shrunk by a small area grows back when the area grows. A window that was fully inside is brought fully inside; one the user had pushed out is moved only as much as keeps the title bar and 96 px visible. - Registration in progress (
ph_fin_imposta_registrazione): resizing, unsnapping, maximize, snap and rotate are refused and nothing is asked of the phone until it ends (moving is still allowed), because the size of a recording cannot change.
12.3 · Input translation
A window's input goes to the phone in the video's own coordinates. ph_fin_trova finds the topmost non-minimized window under a point and returns its zone: PH_FIN_ZONA_TITOLO, PH_FIN_ZONA_PULSANTE (with the button), PH_FIN_ZONA_CONTENUTO, PH_FIN_ZONA_ANGOLO or none.
- For the content the point is converted to the video:
vx = x · video_w / drawn width, always inside0 ≤ vx < video_wand truncated by the injector. The phone also receivesvideo_wandvideo_h, and drops the event if they no longer match its display. - At rest the image keeps the video's proportions, with bands at the sides when the area has other proportions. The shell therefore applies the same formula to the image rectangle (
ph_fa_traduci_immaginewithph_superficie_rettangolo_immagine): a point in a band is not input; a touch already begun is clamped into the image, because a touch that started in a window stays its own until release. - In automatic density the image is drawn 1:1 in the top-left corner of the content (
PhFinInfo.utile_w×utile_hphysical pixels, multiples of 8); the margin to the right and below (up to 7 physical pixels) is filled with the window background and a point in it is content withvalidofalse. The origin must also fall on a whole physical pixel (ph_fa_origine_pixel_intero). - Wheel: one notch is 120; a touchpad sends fractions that are accumulated without losing the remainder (
ph_fa_passi_rotella). The conversion from GTK's direction to Android's is done once, by the caller. - Ctrl + wheel is zoom. The window turns it into a simulated pinch at the pointer position (a protocol message with steps in 120ths; chapter 10). The normal wheel is not sent in that case. The gesture opens at the first step, sends one step per event, and ends
PH_FA_PIZZICO_FINE_MS(250 ms) after the last step, when Ctrl is released, when the pointer leaves, on focus loss, and before any touch. The phone always closes the gesture (by itself after 400 ms without steps). Touchpad pinch gestures (GtkGestureZoom) are also translated (a ratio of 1.25 per 120 steps), and a touchscreen pinch cancels the first finger's touch when the zoom starts; during a window move or resize zoom is refused. - Reserved keys (
ph_fa_tasto_riservato): Ctrl+R, Ctrl+W, Ctrl+Shift+C and F11 never go to the phone. Printable characters without Ctrl and Alt are sent as text (so capitals, accents and foreign layouts arrive right); everything else is an Android key code (ph_fa_tasto_android).
12.4 · The density rule
Every app window follows one rule, like Samsung DeX: the stream is the content of the window in physical pixels (1:1), and the density is 160 times the shell scale, so one dp is about one logical pixel of the shell. The rule is in misura_di_ex in src/finestre/finestre.c and is explained in the header comment of finestre.h.
- Stream. Under the cap the stream is exactly the usable content (multiples of 8, minimum 64). Above the cap
PH_FIN_FLUSSO_TETTO(2560 per side; the larger side decides, both sides are scaled by the same factor) the pixels are reduced in proportion, never the density:flusso = content · density_app / 160is only the old fixed-density rule. - Density.
ceil20(max(50, 160 · k))with k the shell scale (or less when above the cap), never above the phone's own density. Steps of 20 dpi (PH_FIN_DENS_PASSO). Nothing depends on a threshold:PhFinInfo.tablet(the short side of the content is at leastPH_FIN_TABLET_LATO= 600 logical px) is information only and changes no calculation. - Minimum width. An app never sees fewer points of width than the phone's screen has (
Wt, for example 384 for 1080 px at 450 dpi). With f = min(1, w / Wt), under Wt the density is the integerfloor(flux_w · 160 / Wt)(rounded down, so the points seen, truncated as Android does, stay at least Wt): 384 gives 160 dpi, 288 gives 120, 240 gives 100.PhFinInfo.fattoreandpunti_w,punti_hreport it. - Fixed density. If the profile has
densita_appgreater than 0 the user's value is used, fixed (ph_fa_densita_automaticais false andph_fin_imposta_densita_automatica(false)): the flux iscontent · density / 160and pixels shrink above the cap. The profile accepts 72–960 dpi or 0. - The default size of a phone-shaped window and of the mirror is the phone's screen in points (
px · 160 / density: 1080×2340 at 450 dpi is 384×832, one point is one logical pixel), always portrait for phone-shaped and generic windows, reduced in proportion to fit the area (margin 16 per side, content never narrower than min(288, area)) and snapped to multiples of 8 physical pixels. Without the phone's screen the fallbacks arePH_FIN_TEL_W×PH_FIN_TEL_H(296 × 490) for phone-shaped windows and the mirror, andPH_FIN_GENERICA_W×PH_FIN_GENERICA_H(384 × 442) for generic windows. - When the phone is asked.
ph_fin_avanzaruns on every frame (a tick callback) and returns the windows whose stream size or density has been unchanged for 300 ms and differs from the last request: the shell sends it as a resize with density (ph_superficie_ridimensiona_densita). During the gesture, minimized, or while recording, nothing is asked.
12.5 · Apps that cannot be resized
An app that cannot be resized stays as it is: the phone says so (PhSrvApp.solo_verticale: the launch activity declares a portrait orientation and is not resizable), and its window keeps a phone shape.
- No resize from the edges (
puo_ridimensionarefalse), no maximize (puo_ingrandire), no snapping (puo_agganciare); the commands show as disabled, and calling the function anyway returns -1 without changing anything. It can still be moved, minimized, restored and closed. Rotate is refused too. - The information may arrive after the window opens (
ph_fin_imposta_solo_verticale): an enlarged, snapped or wide window then returns to the phone shape in the same place; the stream changes size once, with the request at settled movement. On a minimized window the shape changes at once and the request leaves 300 ms after restore; while recording, the shape changes but nothing goes to the phone until the end. - The window sizes are recomputed (reduced in proportion) when the area shrinks, never stretched.
12.6 · Compatibility
Some apps draw themselves small, gathered in a corner, because they use the density of the phone's real screen while the window, the activity and the process see that of the virtual screen. The user decides, per app, with the Compatibility switch.
- Where: the ⋮ menu of the window (
PH_POPUP_ALTRI_COMANDI), after Rotate and before Close app, as a check item with a smaller grey line under it (For apps that look too small). Disabled during a recording and absent in the mirror. - State: per package, in the phone's profile (the
[[compatibilita]]list, at mostPH_CFG_MAX_COMPAT= 128), written only when the user changes the switch. The next time the app opens it is already on. - Effect (
ph_fin_imposta_compatibilita): the window uses the fixed-density rule with the phone's real density D, whatever the global rule says. With f = min(1, w / Wt) the stream is(w / f, h / f) · D / 160in multiples of 8, minimum 64. Above the cap the pixels are reduced in proportion and the density stays D (the app sees fewer points, and the surface enlarges the image): the density is never lowered, since the difference of density is what shrinks these apps. The image is not 1:1: the GPU scales it, and that is expected. A 384×832-point window at 450 dpi asks for about 1080×2340, the phone's screen. - On change: the window stays open, the new size and density are asked with a resize (the next
ph_fin_avanzaanswers at once, without the settle wait). No session is reopened. It was confirmed live that the app adapts immediately. - Refused (-1, nothing changes): the mirror, an unknown id, and a recording in progress.
12.7 · The mirror window
The mirror is the window that shows the phone's real screen (the app with an empty package, key phone in finestre.h). It is opened from the phone status popup with Show the phone screen and closed from the same switch.
- Fixed shape: like a non-resizable app it cannot be resized, maximized or snapped (even if created with
solo_verticalefalse). Its proportion is that of the phone's screen as it is, landscape included.ph_fin_misura_flussoreturns an error for it andph_fin_avanzanever names it: the size of the stream is decided by the phone. - Stream size:
ph_ossatura_misura_specchiotakes the phone's screen to multiples of 8 inside 64 to 1920 per side without deforming it (cap of 1920); the window first asks withSPECCHIO_FLUSSO_W×SPECCHIO_FLUSSO_H= 288 × 512 as a placeholder that the backend ignores for the mirror. - No density: density is 0 and the Compatibility entry is absent. If the phone rotates while the mirror is open, the window stays as it is and the image appears with bands.
- Closing: the mirror closes without touching the recents list; closing an app window removes the app from the recents (
togli_task).
12.8 · What is remembered
What is saved, and where.
| What | Where | Written by |
|---|---|---|
Remembered rectangle per app ([[finestra]], at most 64) | Phone profile | Windows piece, through ph_fa_ricordi_a_profilo; the mirror is never saved |
Fixed density ([app] densita) | Phone profile | Read by the windows piece; 0 means the automatic rule |
| Compatibility list | Phone profile | Windows piece, only on user change |
Opening counts ([[apertura]]) | Phone profile | Windows piece: one count per new window of an app, not for the mirror, a raise or a restore |
esc_indietro, riapri_dove_eri | Preferences | Read only; the program has no interface that changes preferences |
finestre.h are at most PH_FIN_APP_MAX (48) bytes, shorter than a package name. The shell keeps a table package ↔ short key (a1, a2, …; phone for the mirror) in PhFaChiavi, and converts in both directions, also for the remembered rectangles.src/finestre/finestre.h (point 1 of the deviations) still says a dragged window stays above the bar; the code (src/finestre/finestre.c) lets it go down until only the title bar is visible.Files and transfers
13.1 · The file layer
Files move over the ADB connection with the sync: service (chapter 4). Three pieces share the work, from the bottom up: src/file/ (copy and listing, no queue), src/trasferimenti/ (the queue and the APK installer, no graphics) and src/shell/trasferimento/ (panels, navigator, drag and drop). The shell reaches them only through ph_srv_tr_* and ph_srv_apk_installa of the services.
Function (src/file/file.h) | Behavior |
|---|---|
ph_file_invia | PC to phone. The remote file is created or replaced (choosing a free name is the caller's job); the local modification time is kept; if cancelled or failed midway the partial file on the phone is removed. |
ph_file_ricevi | Phone to PC. Writes <local>.parziale created exclusively (if it exists: PH_FILE_ESISTE, nothing touched) and renames at the end; never replaces a user's file, except an empty regular file the caller placed as a name reservation. The file gets the phone's modification time. Cancelled or failed: the partial file is deleted. |
ph_file_elenca | A folder of the phone without . and .., sorted folders first, then files, by name ignoring case. Hidden files are included; whoever displays filters them. |
ph_file_info | One path of the phone. |
Results are PhFileEsito: PH_FILE_RIUSCITO, PH_FILE_ERRORE, PH_FILE_ANNULLATO, PH_FILE_NON_TROVATO, PH_FILE_NON_CONSENTITO (Android denies access) and PH_FILE_ESISTE. Every operation opens its own sync: channel, so several can run at once from different threads. A transfer that sees no data for PH_FILE_ATTESA_MS (30 s) fails; reads proceed in slices of PH_FILE_FETTA_MS (200 ms) so that cancellation is noticed quickly.
13.2 · The transfer queue
The queue (src/trasferimenti/trasferimenti.h) has one worker thread and does one transfer at a time, in order. Its functions may be called from any thread; only ph_tr_chiudi must be called once, with no other thread using the queue.
- Adding (
ph_tr_accoda): does not block and does not talk to the phone. Send: the origin is a regular file of the PC and the destination folder is any absolute path on the phone (/sdcardmeans/storage/emulated/0; the phone creates the folder if missing). Receive: the origin is a file of the phone and the PC folder must exist. For N dropped files the call is made N times. - States (
PhTrStato): waiting, in progress, completed, failed (the error is the sentence to show), cancelled. Ids start at 1, grow and are never reused. - Free name rule (never overwrite): if
folder/nameexists,name (1).ext,name (2).ext… until one is free. The extension is from the last dot, only if the dot is not the first character, at least one and at most 8 visible characters follow; so.bashrcandMakefilehave none. A compression extension after.tarmakes a double extension (a.tar.gzbecomesa (1).tar.gz). The number goes before the extension; a name over 255 bytes is shortened before the number without splitting a UTF-8 character. - On the PC the name is reserved at start with an exclusive creation (
O_EXCL) of an empty file that the received file replaces. A name is free only if both the destination and<dest>.parzialeare (so a name has at most 255 − 9 bytes); if one appears in the meantimeph_file_ricevianswersPH_FILE_ESISTEand the queue retries with the next number, up to 20 times. On the phone the comparison ignores case, and two entries never choose the same destination even if neither has started; every entry shows a provisional name that at start can only go up in number. - Cancel (
ph_tr_annulla,ph_tr_annulla_tutto): a waiting entry becomes cancelled at once and will not start; one in progress stops copying, the partial file disappears, and it becomes cancelled when the copy stops (if the copy had already finished it may be completed instead: look at the final state). - Notices (
PhTrAvviso): always from the worker thread, at every state change and, while copying, at most about 10 per second per entry; the final state of every entry always arrives. What the caller does (add, cancel a waiting entry, empty) generates no notice. A notice with a null entry means the queue stopped. - Lost connection: the entry in progress fails with its sentence, the others stay waiting, and the queue stops (
ph_tr_coda_fermatrue before the notice). It stays stopped until the caller callsph_tr_riprendiorph_tr_svuota. In the real services, a new session resumes the waiting entries and records it withph_shell_decisione(sv_tr_sessione_nuovainsrc/shell/ossatura/sv_tr.c). - Media scanner: after a sent file (not after a received one) the phone is told that a new file exists with a fixed command built by
ph_tr_comando_scanner: the path is percent-encoded, then put between single quotes, so no character of a name can leave the quotes. - Shutdown:
ph_tr_chiudicancels the transfer in progress (the partial file disappears), drops the remaining entries, and after it returns the connection can be closed.
13.3 · The panels
The shell piece (src/shell/trasferimento/) has two panels, send and receive, opened by the bar buttons (ph_shell_trasferimento_apri). A dot on a bar button shows that a queue of that direction has work.
- Send. A drop zone, a button to choose files from the PC, and the destination folder on the phone with a change button. A
GtkDropTargetofGDK_TYPE_FILE_LISTon the root accepts files dropped anywhere in the window (thePH_STRATO_RILASCIOlayer shows the drop box); non-local files are skipped, and folders and unreadable files are not sent, with a notice. - Receive. The phone's folder listing with multiple selection that stays when changing folder, a search of files and folders, and the destination folder on the PC.
- Destinations. Send folder: the profile's
cartella_invio, otherwise/storage/emulated/0/Download. Receive folder: the first valid of the profile'scartella_ricezione, the preferencecartella_ricevuti, the user's Download folder, the home folder, and finally/. The last chosen folder is saved in the profile. - Queue rows. At most
PH_TRF_ELENCO_MAX(12) rows per direction: in progress first, then waiting in queue order, then the latest finished; if the active ones do not fit, a line says how many more are waiting. Each row has a progress bar, a cross to cancel that entry and a button that cancels the whole queue of that direction. Rows update in place so scrolling and focus stay. - After a transfer only a notice appears; no panel opens.
- Recent transfers widget (desktop): the last completed ones of the session, kept in memory by the common piece; filenames are never written to disk or logs.
13.4 · The folder navigator
One navigator (PhNav in src/shell/trasferimento/navigatore.c) serves three lists.
Mode (PhNavModo) | What it is |
|---|---|
PH_NAV_TEL_CARTELLE | Folder chooser of the phone inside the send panel: Up, a typeable path, a folder search, the list of subfolders, New folder, Use this folder |
PH_NAV_TEL_FILE | Receive list: Up, path, search of files and folders, multiple selection kept across folders |
PH_NAV_PC_CARTELLE | Folder chooser of the PC: like the first, without search; the path is shown and also typeable; read with GIO, asynchronously |
- Paths.
ph_trf_normalizzacleans what the user types: spaces trimmed, a leading/added,/sdcard(any case) becomes the internal storage,//and/.removed,..resolved and never above/, trailing slashes removed. It rejects invalid UTF-8, control characters, and paths longer thanPH_TRF_PERCORSO_MAX(4096). For the PC,~is the home folder and relative paths start from the shown folder; a missing folder falls back to home. - Pages. A list shows
PH_TRF_PAGINA(200) entries and then a button with how many more; hidden entries (name starting with a dot, or any hidden part of a search result's path) are filtered. - Texts.
ph_trf_testo_sicuromakes names displayable: valid UTF-8, control and invisible direction characters replaced, a length limit with an ellipsis. Sizes are shown as B, KB, MB, GB with one decimal from 1 MiB (ph_trf_dimensione), computed in floating point, rounded to tenths and printed from an integer count of tenths, so the decimal separator follows the language of the app, never the language of the PC. - Lifecycle. The navigator is reference counted because GIO requests always return, even after it is closed; the owner frees it with
ph_nav_distruggi, which cancels everything. A cancelled services request never calls back. - The phone's folders are read by the real services with
ph_file_elencaon thep_lavoripool; searches are run on the phone's own search channel and can be cancelled. Creating a folder uses a shell command built byph_ossatura_comando_mkdirwith the path in single quotes (a quote inside becomes'\'').
13.5 · Installing and uninstalling APKs
A dropped .apk is not sent as a file. The shell asks for confirmation (ph_trf_apk_chiedi in src/shell/trasferimento/apk.c, a non-blocking GtkAlertDialog with Cancel and Install the app), then installs it with ph_srv_apk_installa, which runs ph_inst_installa from src/trasferimenti/installa.c on the p_installa pool (one at a time). The install row appears at the top of the send list, with progress and a cross.
- Recognition (
ph_inst_riconosci): an APK is a file whose name ends in.apk(any case) and whose content is a zip with anAndroidManifest.xmlentry in the central directory. Only the tail and the central directory are read (at most 32 MiB); zip64 files count as not APK. Every length read from the file is checked. - Steps (
ph_inst_installa): APK check, copy withph_file_inviato/data/local/tmp/yasde-apk-<8 hex digits>.apk(a random name from/dev/urandom, new at every call),pm install -r, cleanup of the temporary file. Limits:pm install120 s,pm uninstall30 s, cleanup 5 s. - The temporary file is always deleted after the copy was attempted: on success, refusal, error, cancel or lost connection. If the deletion cannot be confirmed,
temporaneo_rimastois true and the message says it will be removed at the next connection. - Cleanup at connection (
ph_inst_pulisci): the real services of the skeleton call it whenever they get a new session (src/shell/ossatura/servizi_veri.c), before any install:rm -f /data/local/tmp/yasde-apk-*.apk(a fixed line). It cannot match the component's own files, which are jars andyasde-custode-*. - Refusals in plain words.
ph_inst_analizzais a pure function that turns the output ofpminto aPhInstRisultato: outcome, aPhInstMotivo(already installed, different signature, older version, no space, invalid APK, old Android, wrong architecture, blocked, verification, test-only, cancelled on the phone, system app, not installed, too old target, split missing, other), theINSTALL_FAILED_*code and a translated sentence with no PC path.pmexits with 0 even when it refuses, so the exit code does not count, andSuccessmust be a whole line: an unrecognized answer is an error, never a success by chance. - The install is complete only if the outcome is
PH_INST_RIUSCITO; the one exception is apmthat does not answer in time (error, and the message says it is unknown whether it was installed). - Uninstall (
ph_inst_disinstalla) runspm uninstall <package>afterph_inst_nome_pacchetto_valido(1 to 255 characters of letters, digits,_and., first a letter: the only check that lets a name into a command line). It removes the app's data too, and the confirmation the shell shows must say so. Ifpmrefuses a system app the message says it.
13.6 · Temporary files
What can be left behind, and who removes it.
| Where | What | Who cleans it |
|---|---|---|
Phone, /data/local/tmp | yasde-apk-<hex>.apk | Always right after the copy; otherwise ph_inst_pulisci at the next connection |
| PC, next to the destination | <name>.parziale (receive in progress) | Removed on cancel or failure; never overwrites a user's file |
| PC, destination | An empty reserved file | Replaced by the received file; removed if the transfer does not start, when it is still the same file (same device and inode) |
| PC, configuration and cache folders | .name.XXXXXX temporaries of a safe write | ph_cfg_pulisci_temporanei(3600) at startup removes those older than an hour |
| PC, cache | sfondo-<n>.png wallpaper images that are named by no profile | ph_cfg_pulisci_sfondi at startup (see 14.1 “Files and folders on the PC”) |
Configuration and language
14.1 · Files and folders on the PC
The piece src/config/ is pure logic: no graphics, no phone. It holds the folders, the file formats, the safe writing and the language tables. On the PC's disk YASDE writes only in two folders, following XDG, and never anything on the phone.
| Folder | Content |
|---|---|
~/.config/YASDE/ (or $XDG_CONFIG_HOME/YASDE) | preferenze.toml (preferences), telefoni.toml (known phones), telefono-<serial>.toml (one profile per phone), profilo-<serial>.toml (measurements per phone; not written by the program today, see 14.4 “The measurements file”), chiave.pem (the PC's ADB key) |
~/.cache/YASDE/ (or $XDG_CACHE_HOME/YASDE) | Wallpaper images sfondo-<n>.png and, from the AppImage launcher, the image loader file (chapter 17) |
- An XDG variable that is empty or holds a non-absolute path is ignored, as XDG itself says. Folders are created with mode 0700; if the folder exists it must belong to the user (otherwise writing is refused), and if it is the user's but writable by group or others those permissions are removed.
- Safe writing (
ph_cfg_scrivi_file): a temporary file in the same folder (mode 0600, created exclusively),fsync,renameonto the final name,fsyncof the folder. An interruption leaves either the old file or the new one. A killed program may leave a.name.XXXXXXtemporary; startup removes those older than an hour (ph_cfg_pulisci_temporanei, a value under 60 s counts as 60). - Known limits. If a configuration file is a symbolic link, the rename replaces it with a regular file (the target is untouched). With two instances at once the last write wins, never a half-written file. A configuration file larger than
PH_CFG_MAX_FILE(1 MiB) is an error. - The serial number is hostile data (it comes from the phone): in a file name it enters only cleaned (
ph_cfg_seriale_pulito):[A-Za-z0-9_-]kept, every other byte becomes_, at most 63 characters, and if anything was changed or cut a dash and an 8-digit FNV-1a hash of the original are appended, soAB:CDandAB.CDnever share a file. Insidetelefoni.tomlit stays as it is, because there it is a value and never a path.
14.2 · The file formats and their keys
The format is a subset of TOML written from scratch (src/config/toml.c, toml.h): tables [name], repeated tables [[name]] for lists, quoted strings (valid UTF-8 on one line), 64-bit integers, finite decimals, booleans, and comments with #. Not supported: arrays, inline tables, multi-line strings, dates, hexadecimal integers. Limits: file PH_TOML_MAX_FILE 4 MiB, line 8192 bytes, 1024 tables, 2048 entries per table.
| Table.key | Type and range | Default |
|---|---|---|
preferenze.toml | ||
[generale] lingua | auto | it | en: read and ignored (the app is English only) | auto |
[generale] esc_indietro | true or false: Esc means Back on the phone | true |
[generale] avvisi | true or false: pop-up notices | true |
[generale] cartella_ricevuti | path; the starting receive folder, the phone's own receive folder wins when it exists | empty |
[generale] widget_nascosti | true or false: hide all widgets | false |
[generale] riapri_dove_eri | true or false: reopen windows where they were | false |
[shell] scala_automatica | true or false: shell scale from the system | true |
[shell] scala | 0.5 to 4.0, used when the automatic scale is off | 1.0 |
telefoni.toml: one [[telefono]] per phone | ||
seriale, nome, indirizzo, visto | serial (required, no duplicates), model name, last address as host:port (IPv6 as [host]:port), last time seen in Unix seconds | — |
telefono-<serial>.toml: the profile of one phone | ||
[sfondo] tipo | solido | sfumato | immagine | sfumato |
[sfondo] colore_solido | color #RRGGBB | #1f2430 |
[sfondo] colore_da, colore_a | gradient colors | #0e2638, #1a625f |
[sfondo] direzione | diagonale (135°) | verticale (180°) | orizzontale (90°) | diagonale-inversa (45°) | diagonale |
[sfondo] immagine | a file name in the cache (valid name: no /, not starting with a dot, only [A-Za-z0-9._-], 1 to 127) | empty |
[sfondo] adattamento | riempi | adatta | allunga | centra | riempi |
[[icona]] app, colonna, riga | desktop icon: package, 0 to 255 each; one icon per app, at most PH_CFG_MAX_ICONE (256) | — |
[[widget]] tipo | orologio, stato, notifiche, memoria, calendario, note, meteo, riproduzione, calendario-mese, sveglia, batteria, interruttori, trova, app-frequenti, trasferimenti; an unknown type drops the entry; at most PH_CFG_MAX_WIDGET (32) | — |
[[widget]] destra, alto | pixels from the right and top edge, 0 to 16384 | 16 |
[[widget]] dimensione | piccolo | medio | grande | medio |
[[widget]] stile, opzione | graphic variant 0 to 15; style-dependent value 0 to 255 | 0, 0 |
[audio] volume | 0 to 100 (the mute is not saved) | 100 |
[cartelle] invio, ricezione | last send folder (on the phone) and receive folder (on the PC), empty if none | empty |
[app] densita | 0 (the phone's own) or 72 to 960 dpi: a fixed density chosen by the user | 0 |
[[fissata]] app | pinned apps of the bar, in order, no duplicates, at most PH_CFG_MAX_FISSATE (16) | none |
[[apertura]] app, volte, ultima | opening counts for Frequent apps: package, 1 to PH_CFG_MAX_VOLTE, last time in Unix seconds; at most 64 (the least used goes first) | none |
[meteo] nome, dettaglio, lat_centesimi, lon_centesimi | the city chosen by hand: name, detail (region, country), degrees × 100 as integers (−9000..9000, −18000..18000); the section is written only if a city is chosen | none |
[[compatibilita]] app | apps with the Compatibility switch on, at most PH_CFG_MAX_COMPAT (128) | none |
[[finestra]] app, x, y, larghezza, altezza | remembered window rectangle (one per app, at most 64); x and y −32768..32767, sizes 1..16384 | none |
Defaults of a new phone. With no file (or a file set aside) the desktop has three medium widgets, Clock, Phone status and Recent notifications, at 16 px from the right edge and 16, 120 and 240 px from the top. A valid file always has the last word: without any [[widget]] there are no widgets.
14.3 · Tolerant reading and set-aside files
A damaged file must never crash the program or destroy data.
- Syntax error (unclosed quote, huge number, null byte, invalid UTF-8, line too long, a text that is not UTF-8 in the file…): the load function returns -1 with a message
riga N: …(the message text is in Italian, like all internal messages) and the structure holds the defaults, never half a structure. - Unknown tables and keys are ignored and not rewritten at the next save. A value of the wrong type, out of range, too long or with an unknown name returns that one field to its default, without an error; a list entry with invalid required fields (or a duplicate) is dropped.
- Missing file: defaults, return 0 (first run).
- Unreadable file: the
*_caricafunctions rename it to<name>.illeggibile(then.illeggibile.1….9; with all taken the oldest is replaced), return the defaults and return 1; the next save therefore destroys nothing. Results: 0 read or missing, 1 set aside, -1 a real error (path, permissions, failed rename). After -1 nothing must be saved, because the file was neither read nor set aside; the skeleton then uses defaults and never saves the preferences. - The
*_da_testofunctions do not touch the disk and return -1 with the line. - Wallpaper cleanup (
ph_cfg_pulisci_sfondi, once at startup, before threads): reads everytelefono-*.tomland removes from the cache the files named exactlysfondo-<1-10 digits>.pngthat are named by no profile. If even one profile cannot be read nothing is deleted (-2); only regular files of the user are touched, never folders or symlinks; a file modified less than 10 minutes ago stays (a choice in progress). Whoever saves a wallpaper writes the image and saves the profile that names it immediately after. - The city of the weather widget is the one position datum allowed on disk, because the user chose it by hand. A name that is empty or too long, a detail that is too long, or coordinates out of range mean no city, without failing the load.
14.4 · The measurements file
A second per-phone file, profilo-<serial>.toml, is handled by src/config/profilo.c (profilo.h): what was measured or observed on a phone, for choosing values next time and for a published table of tested phones. It never holds the serial number or an address; the model is the commercial name (Build.MODEL) and never the name the user gave the device.
| Table.key | Content |
|---|---|
[profilo] versione, modello, api | format version (PH_PROF_VERSIONE = 1), model, API level |
[encoder] scelto, ripiego, repeat_previous_frame_after_ignorato | the encoder chosen, the fallback used if any, whether forced redraw is needed |
[misure] max_flussi | streams in parallel without degradation, 1 to 64 |
[[sintomo]], [[workaround]] | nome ([A-Za-z0-9_.-], 1 to 31), nota (at most 128, never goes into the table), data |
A key that is absent means "not measured": no value is invented. A file of a future version (versione greater than the program's) is not touched and not renamed: load returns -1 with an empty profile, and the program must not save. Model and encoder strings accept only [A-Za-z0-9 ._+()/,-] (no colon, so no web addresses are formed).
src/config/ calls ph_profilo_*: the module and its tests exist, but the file is not yet written or read by the program.14.5 · Language and the English tables
User-visible text in the code is written in Italian, in ph_t("…") calls, and the English comes from tables compiled into the executable. Since 24 November 2026 the app is English only: ph_lingua_inizializza always sets English, whatever the preference in the file and whatever the PC's environment (an old it or auto is read and ignored).
- The functions (
src/config/lingua.h):ph_t(translation in the active language, never NULL, the pointer lives as long as the program; the Italian text itself when there is no translation or the language is Italian),PH_T_(a marker for a literal placed in a table: it translates nothing),ph_tv(translates a marked text later; not checked by the scan, only forPH_T_texts),ph_lingua_componi(placeholders),ph_lingua_traduzione_en(for the test). - The argument of
ph_tis always a literal (or adjacent literals).ph_t(variable)is an error of the test. - Placeholders are written
{name}([A-Za-z_][A-Za-z0-9_]*), not printf: a translation can reorder the words. A literal brace is{{or}}, and%means nothing.ph_lingua_componi(buf, size, ph_t("…"), "name", value, (const char *)NULL)substitutes them (at most 16 pairs); the model is never a printf format; a NULL value is a caller error (empty string, return(size_t)-1); a result that does not fit is cut on a UTF-8 character boundary. - The tables.
data/en/*.txt: one line per text,"italian" = "english", a subset of TOML. Files:comune.txt,config.txt,collegamento.txt,installa.txt, andshell-<piece>.txtfor most shell pieces (there is none for the launcher or the fake backend;shell-comune.txtholds all the mockup's texts). The texts of the phone (app names, notifications, error sentences of the component) arrive ready and are not translated. - The generator (
src/config/genera_traduzioni.c) runs at build time under Meson, reads the files and writes a C source with the table sorted bystrcmpon the Italian text. A duplicate text (between files or inside one), an empty translation, different placeholders between the two languages, or a syntax error stops the build with the file and line. The list of files is read at configuration: a new file needsmeson setup --reconfigure. A duplicate key between two files stops the build of everything. - The test (
lingua,src/config/prova_lingua.c) scans everysrc/source forph_t("…")andPH_T_("…")calls (skipping comments, strings and characters, joining adjacent literals) and fails if a text has no English translation, if the placeholders differ, or if an argument is not a literal. Comments of.cand.hfiles are scanned too, so an example call in a comment must not be written. - The test proves itself: the generator tests run with deliberately wrong files (
src/config/finti/) and must fail (should_fail), and succeed with a good one, so the failures depend on the content.lingua_funzionitests the functions with a fake table (src/config/tabella_finta.c). - A text without a translation makes the
linguatest oftuttofail even if its piece is not yet approved, because the scan reads all ofsrc/: the string and its translation are added together.
Weather
15.1 · What goes out and when
The PC side of the Weather widget is the only place where the YASDE program on the PC opens a connection to the Internet; everything else on the PC stays on the local network with the phone. (The phone itself may use a network service when its own geocoder names a place, see below.) The piece is src/meteo/ (contract meteo.h), and the rules below are written in its header and in src/shell/CONTRATTI.md.
- When. Only while at least one Weather widget is on the desktop (
ph_srv_meteo_osserva). With no such widget no connection is started at all, not even for the place search. There is no separate consent dialog: adding the widget is the choice. - Whom.
api.open-meteo.comfor forecasts andgeocoding-api.open-meteo.comfor the search of a place written by the user. Both are served over HTTPS on port 443. - What leaves the PC. The latitude and longitude of the phone rounded to 0.005° (about 500 m), or those of the city the user chose by hand, or the text the user typed in the place search together with
language=en(the language of the shell), plus the fixed parameters of the request. No identifier, no cookie, a genericUser-Agent:YASDE/2.1. The servers see the PC's IP address, as with any connection. - Where the rounding happens. On the phone, before anything else: the precise position never leaves the phone. The place name is produced by Android's geocoder on the phone, from the already rounded coordinates; the geocoder may itself use a network service of the phone. On the wire and in
PhDatiPosizioneandph_meteo_chiedicoordinates are in thousandths of a degree, always multiples of 5; the city chosen by hand stays in hundredths inPhMeteoLuogoand in the profile, and is passed toph_meteo_chiedimultiplied by 10. The shell never receives the phone's coordinates: only the forecast and, if the phone knows it, the place name. - Nothing on disk, nothing in logs. The phone's position and place name never go to disk or to any log, on the phone or on the PC, not even in error messages. The one exception on disk is the city chosen by hand (name, detail and coordinates rounded to 2 decimals in the profile), because it is the user's own choice; not even that, nor the searched text, goes into a log. An error says only its kind (service not responding, invalid answer, invalid certificate).
- Credit. The line Weather data by Open-Meteo.com with a link to
https://open-meteo.com/is always visible in the widget, in every size and style. Under the place search list, always: Places from GeoNames, via Open-Meteo.com linking tohttps://www.geonames.org/. The data are under CC BY 4.0; the service is used under Open-Meteo's non-commercial terms.
15.2 · From the widget to the forecast
The chain is: widget, ph_srv_meteo_osserva, the real backend (src/shell/ossatura/sv_meteo.c), which asks the phone for the position (ph_dati_posizione, message 0x90) and then calls ph_meteo_chiedi; the answer is published with ph_servizi_pubblica_meteo and ph_servizi_pubblica_meteo_fonte and reaches the widget as PH_SRV_EV_METEO.
- Rhythm. The backend asks again about every 5 minutes while the widget is there; the piece answers from its cache when a valid answer for the same position is younger than
PH_METEO_INTERVALLO_S(30 minutes), so in practice the network is used at most once every 30 minutes per position. The cache lives in memory only and holds the last 4 positions. - After a failure a new connection for the same position is not started before 5 minutes, then 15, then 30; meanwhile the caller gets the previous error at once, with no connection. A success resets the count. Every started connection counts as an attempt, even if interrupted. Between the start of any two connections at least
PH_METEO_AVVII_MIN_MS(5000 ms) pass. No bursts. - The piece does not retry by itself: whoever uses it calls
ph_meteo_chiediagain, and the rules above decide whether a connection is needed. - Position from the phone. The phone answers at once (tens of milliseconds) and never waits for a new position or for its geocoder inside the request. If it starts a background search (
ricerca_avviata), the backend asks once more after about 15 s without a new permission. The permission to start such a search is given at most once every 6 hours (sv_prova_meteo_permesso_s). - Outcomes of the position: known, turned off (The phone's location is turned off.), denied (YASDE is not allowed to use the phone's location.), unknown (The phone does not know its location yet.). Without a connected phone and without a chosen city the widget says No phone connected: without a location there is no forecast..
- The city written by hand (menu of the widget, Location…): a dialog with a text field, a Search button and the results list, and None to remove the choice. The search starts only with the button or Enter, never at each key. One city per profile (per phone). Precedence: the phone's position always wins; the chosen city is used only when the phone gives no position (off, denied, none known, phone not connected).
ph_srv_meteo_fontesays where the data come from. - Place name in the widget: from the phone's geocoder when the position is the phone's, from the chosen result when the city is manual. The title is Weather — {localita}, or just Weather without a name.
- Unavailable service: the widget says Weather forecast not available right now. with the time of the last data if there is one.
- Styles. The widget has six drawings (now, hours, week, compact, today, curve; the code names are
PH_DSK_METEO_*), chosen from its menu and remembered in the profile.
15.3 · The weather piece
The piece is written from scratch on top of OpenSSL (already a dependency for ADB): no new library.
| Part | File | Behavior |
|---|---|---|
| HTTPS | src/meteo/tls.c | TCP socket, SNI (SSL_set_tlsext_host_name), SSL_set1_host with SSL_VERIFY_PEER: chain and host name verified, an invalid certificate is an error and never ignored. Name resolution with getaddrinfo_a (cancellable, with a deadline), non-blocking connect with poll. |
| Certificate authorities | src/meteo/tls.c | The system's: OpenSSL default paths and, if they are not enough, the first existing of /etc/ssl/certs/ca-certificates.crt, /etc/pki/tls/certs/ca-bundle.crt, /etc/ssl/ca-bundle.pem |
| HTTP/1.1 | src/meteo/http.c | GET <path> HTTP/1.1, Host, User-Agent: YASDE/2.1, Accept: application/json, Connection: close. The status line must be 200; headers up to 16 KiB; the body with Content-Length or Transfer-Encoding: chunked (chunks checked; both together is refused as ambiguous). No redirects, no compression, no connection reuse. |
| JSON | src/meteo/analisi.c | ph_meteo_analizza: a streaming reader with limited depth (16), checked lengths, numbers read independent of the system language. It takes only utc_offset_seconds, current, hourly and daily; a missing, null or wrong-typed field means "not known", not an error; hours from now on, at most PH_METEO_ORE_MAX (48); days at most PH_METEO_GIORNI_MAX (7). |
| Request path | src/meteo/meteo.c | ph_meteo_percorso: coordinates in thousandths, limits ±90000 and ±180000 and multiples of 5 (otherwise -1), written with three decimals and always the dot (never printf with a float, so the system language cannot change it): 41895 becomes 41.895, -5 becomes -0.005. Fixed parameters: current, hourly, daily fields, timezone=auto, timeformat=unixtime, forecast_days=7. |
| Place search | src/meteo/meteo.c | ph_meteo_cerca: GET /v1/search?name=&count=&language=&format=json, at most PH_METEO_LUOGHI_MAX (10) results, text of at most PH_METEO_RICERCA_TESTO_MAX (64) bytes, answer at most PH_METEO_RICERCA_RISPOSTA_MAX (64 KiB), 2 s between searches, at most 10 searches per 10 minutes, the same failed search not before 30 s. Results are rounded to hundredths. |
- Limits. Whole request
PH_METEO_LIMITE_S(15 s), answer at mostPH_METEO_RISPOSTA_MAX(512 KiB). Cancel stops the request within 1 s. No lock is held during network work. - Network data is hostile. The analyzer never reads or writes outside its buffers.
- Callbacks. The result function is called from the piece's own thread; inside it only
ph_meteo_chiedimay be called.ph_meteo_chiudicalled inside is refused (nothing happens). Afterph_meteo_annullareturns no callback arrives any more.
15.4 · How it is tested
Tests run without Internet (src/meteo/prova/, strumenti/prova.sh meteo):
- Pure parts: the request path (including with an Italian locale active: the decimal point must stay), the analysis of a saved answer with fake values, missing fields,
null, wrong types, arrays of different lengths, truncated or too deeply nested or huge JSON, absurd numbers. - A fake local server (a thread listening on 127.0.0.1, TLS with a test certificate generated in the test and a test authority passed to the piece only in test mode) answers with a length, chunked, slowly (deadline), too large, status 500, and a certificate with the wrong name (must be refused).
src/meteo/prova/tls_finto.cis the fake TLS side. - Cache and frequency with a fake internal clock; cancel and close during a slow request (AddressSanitizer clean, no callback after return). The thread-sanitizer variant is built separately, because the two sanitizers do not mix.
- The real backend's weather side is tested over fake lower pieces:
src/shell/ossatura/prova_meteo_veri.c. - The TLS handshake to the real server was tried by hand from the AppImage (handshake and certificate check without sending anything); no real forecast request has been tried yet.
Testing
16.1 · Tests of the PC pieces
Tests live with the code. One piece is one folder and has its own meson.build, which defines <piece>_dep and its test(...) entries; the tests of a piece are in its folder (prova_*.c, or a prova/ subfolder). What a piece depends on is replaced in its tests by a fake written in its own folder, so with -Dpezzo=<name> the other pieces are not even built.
- Build flags. C17, warnings as errors (
warning_level=3,werror=truein the rootmeson.build), tests compiled with AddressSanitizer and UndefinedBehaviorSanitizer (-Db_sanitize=address,undefined). - Thread sanitizer. It cannot be mixed with AddressSanitizer, so the pieces whose correctness is about threads rebuild their sources in a second variant with
b_sanitize=thread(-fsanitize=thread): ADB, the component, data, transfers, the connection (collegamento-finto-tsan) and weather, each in its ownmeson.build. - Fakes. There are several, each for a different layer:
src/adb/finto_telefono.c(a fake ADB daemon in C),prove/telefono_finto/telefono_finto.py(a fake ADB daemon in Python with TLS, channels,shell,v2andsync:; it simulates neither pairing, norexec:, nor compression),src/componente/prova/finto.c(a fake component),src/dati/prova/finto.c,src/audio/prova/finto_canale.c,src/file/finto_canale.c,src/trasferimenti/prova/finto.cand the fake TLS side of the weather piece. - Fake lower pieces for the real services.
src/shell/ossatura/finti_sotto.creplaces connection, data, component and the rest, with fakes that "sleep like the network": the tests check that no call blocks the GTK thread, that borrowed sessions are given back, and that closing with requests in flight is clean. - Rules the tests must obey (from
CLAUDE.md): a test must fail if the code it proves is removed (verify it); never sleep to "give time" to another thread, wait for a signal with a deadline; every new error branch has its test; an intermittent failure is never ignored nor worked around by widening a tolerance: it is captured and explained.
16.2 · Running the tests
All builds and tests run on a build server, inside the build container, never on the machine where the sources are edited and never with large files in /tmp. The one entry point is strumenti/prova.sh <piece>. The script packs the tree, sends it over SSH to the server, runs the container under a per-piece lock (two agents asking for the same piece queue up instead of deleting each other's work), writes the whole log on the server, prints the last 25 lines, and the last line is always uscita N (N is the exit code). If a run fails, the log and the test details are kept with the time in the name, so an intermittent failure is not lost on the next run.
| Command | What it builds and runs |
|---|---|
prova.sh adb|file|scoperta|abbinamento|componente|video|audio|dati|finestre|config|trasferimenti|collegamento|meteo | One C piece with its tests, with AddressSanitizer and UBSan |
prova.sh shell-<piece> | One shell piece (shell-finto, shell-ossatura, shell-superficie, shell-finestra-app, shell-barra, shell-launcher, shell-desktop, shell-trasferimento, shell-sistema, shell-connessione): runs only the shell suite, then rebuilds the same piece with -O3 and no checks (the warnings that optimization shows, and the demos for the tablet) |
prova.sh tutto | All pieces that are finished and approved (pezzi_pronti and shell_pronti in the root meson.build), with every test. Only when the work is complete: the others compile your tree |
prova.sh veloce | Everything together, optimized (-Dbuildtype=release), without memory checks and without tests: for speed measurements and for the executables to try on the tablet. A C piece is finished only if this also passes, because optimization shows warnings that the test build does not |
prova.sh telefono, prova.sh telefono-<piece> | The phone component's jar (all pieces or one), with the JVM tests of each folder |
strumenti/prova.sh$ strumenti/prova.sh config
$ strumenti/prova.sh shell-desktop
$ strumenti/prova.sh veloceInside the container strumenti/dentro.sh does the work. For the shell it also starts a virtual screen, gtk4-broadwayd on display :5, waiting up to 10 s for its socket instead of pausing at random. The default container image has it; with an image that lacks it the tests that need a screen end with exit code 77 and are reported as skipped. The image recipe is strumenti/Containerfile (a Debian base with the build tools, Vulkan, FFmpeg and VA-API headers, SDL3, Opus, PipeWire, GTK 4, an Italian locale to prove that numbers are read and written the same under any system language, and the broadway tools).
16.3 · Shell tests, demos and photographs
Every shell piece has a logic test without a screen (prova_<piece>.c, with leak checking) and a screen test: the piece's demo run with --prova 2000 under the virtual screen with G_DEBUG=fatal-criticals. Logic is kept apart from the widgets (pure functions in the piece's own folder, for example src/shell/superficie/logica.c) precisely so it can be tested without a screen. Logic tests ignore the leaks of third-party libraries listed in src/shell/soppressioni-lsan.txt; screen tests turn leak detection off because GTK leaves reachable memory at the end.
- Demos.
demo-<piece>runs one piece over the fake phone;demo-ossaturaruns the whole shell. On the tablet:strumenti/demo-sul-tablet.sh <piece>takes the optimized demo from the server (options--misura WxH,--dmabuf,--senza-comandi); in the demo, F5 locks or unlocks, F6 drops the connection for 5 s, F7 sends a notification, F8 closes the last app. - Photographs.
strumenti/foto-demo.sh <piece>opens the demo on an invisible screen of the tablet (a headless compositor, so the user's screen is not disturbed) and saves PNG photographs to compare with the mockup: sizes, colors, order, texts. The demo's own output is also read, and must hold no GTK critical warning. - Other tools in
strumenti/:yasde-prova.c(a command line client for the lower pieces),finestra-prova.c(a bare window for an app, SDL3),misura-flussi.c(several video streams in parallel),prototipo-gtk.c(the GTK prototype that measured the frame path),app-sul-tablet.sh,finestra-sul-tablet.sh. They are built only withpezzo=tuttoand are not part of the program. - Scope of
tutto: it builds all pieces inpezzi_prontiplus the shell pieces inshell_pronti, so a piece still being written cannot break the build of the others; the coordinator adds a piece to those lists when it is approved.
16.4 · Tests of the phone component
The component's Java code is tested in two ways.
- On the container's JVM, without Android (run by
telefono/costruisci.shfor every piece that has aprove.sh): the piece's test classes are kept as.java.txtfiles and copied to a temporary folder at test time, so they never enter the jar. For exampletelefono/base/prove.shrunsProvaProtocollo,ProvaSmistatore,ProvaPariandProvaResti. - The build compiles the contract and the pieces' sources at Java source level 8 (
-source 8 -target 8, so no lambdas or method references: anonymous classes) againstandroid.jarof the SDK (platform 35), with-Xlint:all -Werror, and converts with D8 totelefono/yasde.jar(--min-api 34). The pieces arebase,video,audio,dati,archivio,appunti,pannello,controllipluscontratto(always present). - On the real phone: each piece has Python scripts in its
prove/folder (for exampletelefono/base/prove/prova_telefono.py) that push the jar through the phone's ADB and drive it. Those use the standardadbtool already paired with the phone.
16.5 · Rules for tests on the real phone
There is one test phone, so real-phone tests run one at a time. The rules come from CLAUDE.md and exist because earlier reviews found the opposite.
- The turn. Before touching the phone take the turn with a directory created in the user's cache (
mkdirfails if it exists: wait and retry every 20 to 30 s). Remove it withrmdironly if your ownmkdirsucceeded in this very run (script variable "my turn" and atraporfinallythat removes only one's own). If themkdirfails or times out, the script exits: never go on without the turn, never remove someone else's. - Do not wake or reconnect. Never wake, unlock or reconnect the phone: if it is not awake and connected, stop and report it.
- Touch only what you created. Note the pids of the processes launched and the names of the files written, and clean up only those (never "the first
it.yasdefound", never a wildcard on the guardian's scripts). Before touching anything, read-only: if the phone already runs a component or has a guardian file (another test, or the real program), exit. - Settings. No setting changed without a restore; the starting values are saved and compared line by line at the end. No volume or user setting written "to prepare" the test. Nothing is started on the real screen. No audible sound without the user's explicit consent.
- Every
adbcommand has a deadline; the cleanup runs in afinally. No serial number or address in any file: fake values (for exampleR5CT0000000) in examples. - The component restores the phone in every case: a thread that dies for an unexpected
Throwablemust leave the phone as it was, and a failed action that would leave an abnormal state (screen off, volume changed) is retried, not abandoned (chapter 6).
16.6 · What is not covered
The tests prove logic, formats, protocol, concurrency and the fake phones. Several things are only proven live or not at all, and the manual says so rather than imply otherwise.
- Tried live on 24 November 2026 with the AppImage, on one machine and one phone: pairing from an empty installation, the panel turning off by itself at connection, the bar volume starting at 100%, and the Compatibility switch (the hot change is enough). Never tried live at the time of writing: every English sentence on screen, the weather (a real forecast request: only the TLS handshake was tried by hand), the pairing screen's hints when the phone does not announce itself.
- Screen tests run on a virtual broadway screen: they prove that the widgets build and respond, not how they look on a real display, with the Vulkan renderer, or under fractional scales (125%, 150%), which have still to be tried.
- The AppImage was checked for its contents, legal texts and dependencies by the build script, and its startup with the interface was tried live on one distribution with one phone. Its use on another distribution or glibc, and the parts that trial did not touch (MP4 recording and PNG capture with the bundled libraries, Vulkan decoding), were not verified (chapter 17).
- Direct scan-out of video frames (offload) is not confirmed on the one machine where it was looked for (21.1 “The known problems at a glance”).
- One phone, one Android. Behavior on other makers' phones and Android versions beyond the one tested is not covered.
Building and packaging
17.1 · Meson and the project options
The PC side is built with Meson. The root meson.build declares the project yasde version 2.1.0 in C with the default options c_std=c17, warning_level=3, werror=true and buildtype=debugoptimized, adds -D_GNU_SOURCE, and then includes the pieces.
Option (meson_options.txt) | Type, default | Meaning |
|---|---|---|
pezzo | string, tutto | Builds one piece (for example adb, config, shell-desktop) or everything. With one piece the others do not exist and its tests use fakes. |
- Pieces. The list in the root file:
adb,file,scoperta,abbinamento,componente,video,audio,dati,finestre,config,trasferimenti,collegamento,meteo. Each lives insrc/<piece>/, has its ownmeson.buildand defines<piece>_dep(a dependency with its static library). Common code (src/comune/:PhErrore, buffers, the neutral frame descriptor) is always built. - With
pezzo=tuttoonly the pieces listed inpezzi_pronti(and the shell pieces inshell_pronti) enter: a piece still being written cannot break the whole build; the coordinator adds a piece to the list when it is approved. A shell piece namedshell-<piece>builds withconfigandfinestre(pure logic already approved), and the skeleton with all the pieces below. - The shell (
src/shell/meson.build) needs GTK 4 at least 4.14 (gtk4), builds the common piece and the fake backend always, and the shell pieces present. The skeleton's real services are built only if all the lower pieces are there (the flagPH_OSSATURA_SERVIZI_VERI). The program is the executableyasdebuilt fromsrc/shell/ossatura/main.c. A header generated at configuration time holds one flag per piece. - Libraries. OpenSSL 3 (ADB TLS and weather), FFmpeg's
libavcodec,libavutil,libavformat,libswscaleand Vulkan (thevideopiece: decoding, PNG and MP4 capture), Opus and PipeWire (audio), GTK 4 (the shell), gdk-pixbuf (the desktop piece, wallpaper decoding), and threads. FFmpeg stays closed insidesrc/video/and GTK insidesrc/shell/. - Resources. Each shell piece compiles its CSS with
glib-compile-resources(--manual-register, source files such asbarra.gresource.xml) as/it/yasde/shell/<piece>.css; the generated string is long, so resources are compiled apart with-Wno-overlength-strings. Translations and CSS are inside the executable: the program reads no data file at run time. - Translations. A generator built first (
genera_traduzioni) turns thedata/en/*.txtfiles into a C source at build time (chapter 14). - Phone component. Not in Meson:
telefono/costruisci.shcompiles the Java withjavacand D8 intotelefono/yasde.jar(chapter 16). The AppImage carries the jar next to the executable, which looks for it in its own folder.
17.2 · The build container
Builds do not run on the machine where the sources are edited. They run on a build server, inside a build container, started by strumenti/prova.sh (chapter 16), which copies the sources there. The container's recipe is strumenti/Containerfile: a Debian 13 image with the compilers (GCC and Clang), Meson, Ninja, pkg-config, Valgrind, GDB, the JDK, OpenSSL, Vulkan with its validation layers and compiler for shaders, FFmpeg's development libraries, VA-API and DRM, SDL3, Opus, PipeWire, GTK 4 and the broadway virtual screen, and an Italian locale. The Android SDK (platform 35, build-tools 35.0.0) is mounted read-only into the container; a container is new for every run.
- A build server path and the container's name are development equipment and are not part of the program; nothing in the executable or the package depends on them.
- Builds go in
build-<piece>folders next to the sources on the server:build-<piece>-veloceis the optimized variant of a shell piece (the demos for the tablet),build-veloceis the optimized whole. - Big files never go in
/tmp.
17.3 · The AppImage
The program ships as one file, YASDE-2.1-x86_64.AppImage (Linux x86_64), plus a source archive, YASDE-2.1-sorgenti.tar, published on the same release page. The scripts are pacchetto/costruisci.sh (starts on the development machine and sends the work to the build server over SSH, to run in the build container) and pacchetto/dentro.sh (runs inside; mounted read-only: the optimized program from prova.sh veloce and the jar from prova.sh telefono). The log ends with uscita N, and the script exits with the same N. A lock prevents two builds at once; a cache of downloaded sources and of the already built FFmpeg survives between runs, the rest is redone from zero. The script checks its folder variables (PACCHETTO_LAVORO, PACCHETTO_VELOCE, PACCHETTO_TELEFONO, PACCHETTO_LOG) against a strict pattern before touching the server, and refuses ones that contain .. or overlap.
- The launcher (
pacchetto/AppRun) always uses its own folder (an inheritedAPPDIRis ignored), puts the package's libraries first inLD_LIBRARY_PATH, the package's GSettings schemas first inXDG_DATA_DIRS, pointsGIO_MODULE_DIRto an empty folder (no system GIO modules, which are tied to another GLib), and thenexecsusr/bin/yasde. - Image loaders. The loaders cache template has a placeholder path;
AppRunresolves it at every start into${XDG_CACHE_HOME:-$HOME/.cache}/YASDE/yasde-pixbuf-<pid>.cache, the only file the package writes on the PC, in a folder the specification allows. If the package path contains\,",&,|or a newline, or the folder is not writable, it gives up with a warning and webp does not open (png and jpeg are inside the library). Files of past runs are removed at start: those whose pid is dead and those older than 24 hours. - No integration. No
.desktopfile is installed on the PC; the one inside the package serves onlyappimagetooland declaresX-AppImage-Integrate=false. - Public documents in the package are only in English (
README.txt,SOURCE-OFFER.txt,LIST.txt,SYSTEM-REQUIREMENTS.txt,open-meteo.txt,type2-runtime/NOTE.txt), with the line that the project is not affiliated with Samsung. - Size. About 20 MB for the AppImage and about 45 MB for the AppDir; the source archive is about 315 MB.
17.4 · Downloaded tools
Everything downloaded is fetched into the build server's work area (never into the repository), only over HTTPS, with a fixed version and a checksum verified before use.
| Item | Version | How it is verified |
|---|---|---|
appimagetool | 1.9.1 | SHA-256 as declared by the release |
AppImage runtime (type2-runtime) | 20251108 | SHA-256 as declared by the release; the tag's source tarball has the checksum seen at the first download (if it changes, the script stops) |
| FFmpeg | 7.1.5 | Tarball from ffmpeg.org; the fixed checksum was compared with the signed Debian sources index (Checksums-Sha256) |
| libtiff, cairo | Debian trixie sources | apt-get source (apt checks against the signed index) plus the orig checksum fixed in the script; if a version is gone from the current archive, a dated snapshot is used (inside the run only) |
libfuse 3.15.0 and squashfuse 0.5.2 | — | Versions and sums are those the runtime's own script verifies; the script rechecks them in that file |
The sources of every included Debian library are saved in the source archive (with a SHA256SUMS file), together with those of libtiff and cairo and the FFmpeg tarball.
17.5 · Legal texts and the checks that fail the build
The package must contain nothing that forces the combined work under GPL terms, and offer the sources of what it contains. The build script fails when any of the following is not true.
- FFmpeg is rebuilt, LGPL 2.1 or later:
--disable-gpl --disable-nonfree --disable-everything --disable-autodetect --disable-programs, shared, with only what the code uses: the H.264 decoder and parser with VA-API and Vulkan (software fallback is the decoder itself), the PNG encoder, the MP4 muxer (the container goes to an I/O context written by the program, so no protocols), and swscale. The script checks for "LGPL version 2.1 or later" in the configure output and in the library, and that every soname the executable asks for exists. - libtiff and cairo are rebuilt from Debian's sources, with Debian's security patches, because the distribution's builds pull in
libjbigandliblzo2(GPL-2+ without exception). libtiff without jbig, lerc, lzma, zstd, webp and deflate; cairo without lzo. The sonames stay the same (libtiff.so.6,libcairo.so.2and its siblings); cairo is replaced entirely, so the process has one version. The script fails if these libraries are not resolved from the versions built here, iflibjbig,liblzo2orlibLercend up in the package, or appear among the NEEDED entries of any file in it. - GPL check. The script fails if an included package has a
copyrightfile that cites a GPL (not LGPL), or is not machine-readable, and is not in the list of reasoned exceptions insidedentro.sh(21 cases at the time of writing: dual terms, or GPL only on parts not distributed, each with its reason). The check is mechanical (the machine-readable header lines of those files) plus those hand-written exceptions. - Source offer.
SOURCE-OFFER.txt(in the package's documentation folder) states that the sources are published next to the AppImage, in the source archive, and lists exact versions and origins. The archive must be published together with the AppImage. - Legal texts inside. Each library's
copyright; the texts of common legal texts that those files cite (from the distribution's common texts folder) incommon-texts/(the script fails if one is missing); for FFmpeg, libtiff and cairo the texts from their sources. - The AppImage runtime (MIT, statically linked to libfuse3 LGPL-2.1 and squashfuse BSD-2): the sources of the tag, libfuse and squashfuse are in the archive; legal texts and notes are in
type2-runtime/in the package documentation folder. For zstd, zlib, mimalloc and musl embedded in the runtime the notices are reproduced; the exact versions cannot be derived, which is irrelevant for terms that ask only for the notice. - Kora icons (GPL-3, separate files). The step
pacchetto/icone-kora.sh(called bydentro.shbefore the final texts, and again asverificaat the end of the checks; it can also run alone) fetches the Kora theme bybikass(github.com/bikass/kora) at a fixed commit (ff8ee3ce…, 19 Nov 2026) into a copy outside the repository, reused only if it is at that commit and unmodified; a failed download stops the build, never a package without icons. Only the icons named indata/icone-kora.txt(104 rows,<Android package> <icon name>) are converted to 128×128 PNG with a transparent background (rsvg-convert, not part of the package) intousr/share/yasde/icone-kora/, with an exact copy of the table astabella.txtand the SVG sources insorgenti/(real files, no links). A malformed row, an empty table, a name missing from the theme or a link leaving the theme stops the build, with the same limits as the program. In the package's documentation folder (usr/share/doc/licenses/) go the GPL-3 text of the theme and a credits file (commit, what was done, third-party marks), cited inLIST.txt,README.txtandSOURCE-OFFER.txt. The final check verifies the files: table, a PNG and an SVG for each name, PNG size, GPL-3 text and credits. Nothing of Kora is in the repository. YASDE itself is under the MIT License with the Commons Clause condition (fileLICENSEof the repository); the GPL-3 applies only to these separate files. - Weather.
open-meteo.txt(in the same documentation folder) carries the credits and terms of Open-Meteo and GeoNames data (CC BY 4.0). No certificate authority is included in the package: the program looks for the host system's (chapter 15), and the script proves, with the package'slibcrypto, that the same sequence loads the authorities of the container. - Naming. The project name is YASDE. The script fails if a forbidden project name appears, in any capitalization, in file names, in our texts, in the strings of the executable or of the jar, with no exception,
AppRunincluded. The script first proves the check itself: a phrase with the forbidden name in any capitalization must trigger it. - Dependencies. Every NEEDED of every file in the package is either included or in the list of what is left to the system;
lddreports no "not found". Required: glibc 2.38 or newer, PipeWire, libva, Vulkan and libdrm, X11 and Wayland client libraries, fontconfig, and the kernel's FUSE withfusermount3orfusermount(or--appimage-extract-and-run; the runtime has libfuse3 linked statically). Withoutlibpipewire-0.3.so.0,libva.so.2andlibva-drm.so.2orlibvulkan.so.1the program does not start. The script writes intoSYSTEM-REQUIREMENTS.txtonly the NEEDED libraries not included and the highest symbol versions required. - Self tests.
AppRun --helpmust answer, also withLD_BIND_NOW=1; png, jpeg and webp are saved and re-read with the bundled loaders, and the same test must fail without the webp loader (otherwise it proves nothing); certificate loading is proved as above.
17.6 · What the build does not prove
libz and libzstd with every Mesa driver loaded in the same process, and that libtiff and cairo behave correctly (only that their sonames resolve and that --help answers). The weather TLS connection to the real server was tried once by hand from the AppImage.Packages the script installs when missing, for that run only: file (required by appimagetool), the webp pixbuf loader, and when rebuilding nasm and cmake. They belong in the container image.
Conventions
18.1 · Principles of the project
The project's rules come from CLAUDE.md and from the contracts (src/*/*.h, docs/protocollo.md, src/shell/CONTRATTI.md). They were born from reviews, and a reviewer checks them first.
- Everything is new code. No third-party code is copied; Android's source is read as documentation only.
- PC side: C, Meson, Vulkan. Phone side: minimal Java launched with
app_process; only pure Android APIs, no dependency on a maker. - Nothing installed on the phone, no root. Every change made to the phone has its restore.
- Only what the specification and the mockup say. No features beyond them.
- A piece is one folder, one agent. Whoever writes a piece touches only its folder. Contract headers,
docs/protocollo.md,telefono/contratto/, the rootmeson.buildandstrumenti/are not modified by a piece: a wrong or incomplete contract is reported and the rest goes on. - No personal data in the repository (it is public): no serial numbers, addresses, network names or person names in files; fake values in tests (for example
R5CT0000000). - Language: names, comments, messages and documents are Italian in the code; the manuals and the public documents in the package are English (18.6 “Code language and user language”).
18.2 · C and the common code
The source is C17, compiled with warnings as errors, and tests run with AddressSanitizer and UndefinedBehaviorSanitizer (chapter 16). A piece is finished only if strumenti/prova.sh veloce (everything together with -O3) also passes, because optimization shows warnings the test build does not.
- Names. Public functions are prefixed
ph_and the piece (ph_fin_*for windows,ph_cfg_*for configuration,ph_tr_*for the queue,ph_srv_*for the shell's services). Types arePh…and constantsPH_…. Shell classes are prefixedph-<piece>-. - Errors. Every return value is checked. A function that can fail takes a
PhErrore *(which may be NULL; it holds a sentence of up to 256 bytes saying what the function was doing) (ph_errorewrites it,ph_errore_contestoprepends a context). The return convention is the same across the project:int0 for success and -1 for an error; a pointer is NULL on error. No function callsexitorabortfor an error that depends on the phone or the network. - Hostile data. Nothing that comes from the phone or the network may make the program read or write outside a buffer. Indexes into arrays that arrive through the services are checked against the length given; no fixed-size buffer is filled without a limit (
g_strlcpy,snprintf). Text shown is already safe (valid UTF-8, no control characters). - Contracts grow at the end. Structures of the contracts (handlers, requests, data) are always initialized by field name (
{.io = x, .apri_app = f}), never by position, because adding a field at the end would make a positional initializer an error (missing-field-initializers) for everyone. - Includes. No piece includes the internal header of another piece. GTK appears only under
src/shell/, FFmpeg only insrc/video/. The shell's pieces include none ofcollegamento.h,dati.h,componente.h,decodifica.h,audio.h,trasferimenti.h,file.h,adb.h; only the skeleton does, inside the real services. - Comments explain why, in Italian. Contracts say what a callback may call and what a function touched when it returns an error (usually nothing).
- No commits by pieces. Whoever writes a piece does not run
git commit
18.3 · Rules born from reviews
Defects found in earlier reviews, written so as not to be repeated. Each is checked by the reviewer.
| Rule | What it means in the code |
|---|---|
| Closing in parallel | Every public function that uses an object must tolerate the object's …_chiudi called by another thread at the same moment: either it finishes first, or it returns an error; never use of freed memory. A "is it closed?" check made and then dropped (lock released) does not protect: a use counter that the close waits for is needed. |
| Callbacks | After a …_chiudi returns, no callback is running and none will arrive. Never call a callback while holding a lock that the receiver may want to take. The contract says what a callback may call (for example inside the queue's notice, ph_tr_chiudi is forbidden). |
| Waits | No wait without a limit, except where the contract says so. No lock held during an external command, a network write or a pause. |
| Failing midway | If an operation of several steps fails midway, what was already done is undone; when a function returns an error, the contract says what was touched (normally nothing). |
| Phone | The restore is registered BEFORE the change and removed only AFTER the change was really undone; if Guardiano.imposta returns false the change is not made. A failed action that would leave the phone in an abnormal state (screen off, volume changed) is retried, not abandoned. A thread that dies of an unexpected Throwable must leave the phone as it was. |
| Tests | A test fails if the code it proves is removed (verified); no sleeping to give another thread time (wait for a signal with a deadline); every new error branch has a test; an intermittent failure is captured and explained, never ignored or hidden by a wider tolerance. |
| Real phone tests | The turn: rmdir only if the own mkdir succeeded in this run; if it fails the script exits. Never wake, unlock or reconnect the phone. A test touches only what it created, never a wildcard, and checks beforehand, read-only, that no component or guardian file of another run is there. |
| Whole builds | tutto and veloce run only when the work is finished, never with files half written: the others compile your tree. Never rm in data/ or in folders that are not yours. |
| Reports | Say what you did NOT verify. Never call clean what you did not see pass. |
CLAUDE.md18.4 · Rules of the shell
Rules specific to the GTK shell (src/shell/CONTRATTI.md), in addition to the above.
- One GTK thread; it never blocks; the only way from another thread is
ph_shell_consegna(11.3 “Threads and delivery to the GTK thread”).g_idle_addand similar are not scattered around the pieces. - Whoever hands a pointer to a widget to another thread keeps a
g_object_refuntil delivery. Whoever sends a lot (frames) coalesces: at most one delivery in flight per stream, the last datum wins. - Pieces free their things when the root is destroyed, with all the
*_smettifunctions, and keep their own reference to the widgets as long as listeners exist (11.5 “The skeleton”). - Every automatic decision of the program (pause, reduced rate, resumed stream, fallback from DMA-BUF to memory) is written with
ph_shell_decisionewith its cause and the number that caused it; never personal data. Things the user asks for are not automatic decisions. - No
GtkStyleContextper widget and no inline CSS (except computed colors); GTK CSS has nogap,max-widthorposition. - Everything clickable is a real control reachable with Tab.
- Privacy in logs and disk: no serial numbers, addresses, network names or person names; nothing about calendar event titles, file names, phone location, pairing code. The pairing code, addresses and ports are never written, not even in an error message.
18.5 · Rules of the phone side
The Java side follows rules of its own (chapter 6): source level 8 (no lambdas or method references: anonymous classes), pure Android APIs, hidden ones only by reflection and gathered in one class per folder with a startup self-check that says which are missing; every channel runs on its own thread and catches everything (even Error), so a broken channel does not take down the service; every change to the phone registers its restore command in the guardian (Custode), a separate shell process that executes it if the service dies suddenly, and that deletes the jar; restore commands are self-contained shell lines with no environment variables of the service and no nested quotes; the user's value wins, and a setting is restored only if it still has the value YASDE put there.
18.6 · Code language and user language
Two languages live in the code and they never mix.
| Language | Where | Examples |
|---|---|---|
| Italian | Identifiers, comments, internal messages (PhErrore sentences, stderr lines), file names, folders, configuration keys, protocol names, documents in the repository (CLAUDE.md, PIANO.md, CONTRATTI.md, COMPITO.md) | ph_fin_apri, telefoni.toml, [[fissata]], PH_SRV_NON_ABBINATO |
| English | Everything the user can read: interface texts (through data/en/), the public documents in the package, the two manuals | the window titles, buttons, notices; README.txt, SOURCE-OFFER.txt |
- Texts for the user are written in Italian in
ph_t("…")and translated by a table (chapter 14); the program always runs in English. The Italian text is the key: a text without translation fails the build's test, so none can reach the user in Italian. - Because the code is Italian, the manuals keep identifiers as they are and explain Italian words the first time (for example
ossatura, the skeleton). The check of the manuals rejects Italian sentences in running text, outside code and preformatted blocks. - Texts of the phone (app names, notifications, error sentences of the component) arrive ready, in the phone's language, and are not translated.
Extending YASDE
19.1 · Before you start
Four common extensions, with the files each one touches. The examples follow the path of an existing feature: the Next alarm widget (message 0x7c, SVEGLIA, the Italian word for alarm clock) goes through every layer. Its type 0x7c is taken: the whole range 0x70–0x7f is fully assigned, so a new message of the same kind needs a free number, for example one of 0x91–0x9f (already registered to Dati) or 0x86–0x8d (the Controlli range). Contract files (docs/protocollo.md, src/*/*.h, telefono/contratto/, src/shell/servizi.h, src/shell/servizi_backend.h, the root meson.build) are changed by whoever coordinates the project, not by the piece's author (chapter 18): in a team, a piece's author reports what is missing.
19.2 · Adding a protocol message on both sides
Take a request that returns data, like the existing SVEGLIA (0x7c) or BATTERIA (0x7d), which you can read as models; a new one takes a free number such as 0x91. The message types are in ranges, one per area, and each range is served by one phone class.
| Range | Area | Phone class (folder) |
|---|---|---|
| 0x01–0x0f | Generic: hello, OK, error, close, presence | Servizio (telefono/base/) |
| 0x40–0x4f | Video | Video (telefono/video/) |
| 0x50–0x5f | Input (and clipboard 0x58–0x5a) | Input, Appunti |
| 0x60–0x6f | Physical panel | Pannello (telefono/pannello/) |
| 0x70–0x7f | Phone data (0x74–0x75 in telefono/archivio/) | Dati (telefono/dati/), Archivio |
| 0x80–0x8f | Quick switches | Controlli (telefono/controlli/) |
| 0x90–0x9f | Approximate position | Dati |
docs/protocollo.md- Specify it in
docs/protocollo.md: the type number inside the right range (§2), the direction, the request body and the OK body. Numbers are big endian, a string is a 2-byte length plus UTF-8, a message is a type byte, a 4-byte length (at most 1 MiB) and the body. Say what the phone touches, and its restore if it changes anything (the guardian rule). - Phone side. Add the constant and the
casein the class that owns the range (telefono/dati/it/yasde/Dati.java: the existingSVEGLIA = 0x7cis the model), the encoding of the OK body in the helper class (CampiDati.java) and the reading of the data in the class of hidden or platform calls (NascosteDati.java). If the number is outside the ranges already registered withRegistro.registraComandi, register the new range in the class'sregistramethod. A thrown exception becomes anERROREwith its message. Source level is 8: no lambdas. - A new phone class (a new area) goes in a new folder under
telefono/with aprove.sh, and its name is added to the arrayPEZZIintelefono/base/it/yasde/Servizio.java, which registers each class by reflection at startup; also add it to the default list intelefono/costruisci.sh. - PC side, the piece (
src/dati/): addPH_DT_<NAME>to the enum insrc/dati/interno.h, the API and its structure insrc/dati/dati.h, and the function insrc/dati/nuovi.cbuilt onph_dati_chiedi. Read the answer with the bounds-checked reader, accept only a body of exactly the expected length, and return -1 with a fixed message otherwise: the body is hostile data. Add a free function for any allocated field. - Tests on both sides. PC: the fake component (
src/dati/prova/finto.c) answers the new type, andsrc/dati/prova/prova_dati.cproves the good answer and every refusal. Phone: a JVM test class (a.java.txtfile in the piece's test folder) and, for the real phone, a script intelefono/dati/prove/(chapter 16). Verify that each test fails if the code is removed. - The services (if the shell needs it):
ph_srv_tel_<name>and its callback type insrc/shell/servizi.h, the entrytel_<name>inPhServiziBackend(servizi_backend.h), the wrapper that makes a job insrc/shell/comune/servizi.c, the function the backend calls to deliver the result,ph_servizi_lavoro_<name>(declared inservizi_backend.h, defined inservizi.c, called for the alarm bysv_extra.c), the real implementation in the skeleton (sv_tel_svegliainsrc/shell/ossatura/sv_extra.c, registered in the table inservizi_veri.cand declared insv_interno.h), and the fake one insrc/shell/finto/finto.c(and a command in its small window if the state must change). - Document the change in the manual chapter that describes it, and in
src/shell/CONTRATTI.mdif it changes a rule.
19.3 · Adding a widget
A widget is drawn by the desktop piece (src/shell/desktop/) and shares the look of the others: same card, three sizes, translucent background.
- The type in the profile. Add a value at the end of
PhCfgWidgetTipoinsrc/config/config.h(values saved before stay valid) and its name in theNOMI_WIDGETtable insrc/config/config.c, in the same position. Extend the config tests (reading, writing, the unknown-type rule). - The catalog. Add an entry to
PH_DSK_CATALOGOinsrc/shell/desktop/widget.c: the type, the name and the description, both insidePH_T_. A widget that is not offered yet is left out with a compile-time switch, asPH_DSK_TROVA_OFFERTOdoes for the find-my-phone widget. - The drawing and data. Add a table of type
PhDskWxVt(src/shell/desktop/interno.h) in awx_*.cfile (start, stop, update, how often to ask) and map the type to it inph_dsk_wx_vtinsrc/shell/desktop/wx.c. Ask the phone only while the widget is on the desktop, usingph_dsk_wx_puo_chiedere(for example the next alarm every 5 minutes, the battery every minute, the calendar every 15 minutes), and never put titles, file names or other personal data on disk or in logs. - The texts. Every new text is in
ph_torPH_T_, and its translation is added todata/en/shell-desktop.txtin the same change, after checking withgrepthat the key does not exist in any file ofdata/en/(a duplicate key between two files stops the build). - The CSS in
src/shell/desktop/desktop.css, classesph-desktop-*. The fake: givesrc/shell/finto/the new data and, insrc/shell/desktop/demo_hook.c, the commands to show the empty, error and "not available" states. - Tests. Pure logic in
logica_wx.candsrc/shell/desktop/prova_desktop.c; photograph the demo (strumenti/foto-demo.sh) and compare it with the mockup.
19.4 · Adding an interface entry with its translation
An interface entry is any new text: a label, a hint, a message. The program is English only, so each Italian key in the code needs its English value, or the build's test fails.
- Write the text in the code with the Italian literal in
ph_t("…")(orPH_T_("…")for a literal placed in a table, translated later withph_tv). The argument is always a literal. Placeholders are{name}, composed withph_lingua_componi, never with printf. - Add the line
"italian" = "english"to the piece's filedata/en/shell-<piece>.txt(create it for a new piece: the list of files is read at configuration, so runmeson setup --reconfigure). Same placeholders in both. Check withgrepfor an existing key: the shell's mockup texts are all already indata/en/shell-comune.txtand must be reused as they are. - Run
strumenti/prova.sh <piece>and thelinguatest: it fails on a missing translation, different placeholders or a non-literal argument. Phone texts are not translated and are not written in the table. - Accessibility: the label goes through
ph_shell_etichettawith the text and the hint. Do not write exampleph_tcalls in comments, because the scan reads comments too.
19.5 · Adding a piece
A new piece is one folder, and one agent.
- Create
src/<piece>/with ameson.buildthat defines<piece>_dep(a dependency with its static library) and itstest(...)entries, plus the header that is the piece's contract. - Add the name to the list
pezziin the rootmeson.buildand, only when the reviewer approves it, topezzi_pronti. (A shell piece is added to theshell_pezzilist insrc/shell/meson.buildand toshell_prontiin the root; its entry point is declared insrc/shell/pezzi.hand called byph_ossatura_installa_pezzi, with a flag in the header generated at configuration time.) - In its tests replace what the piece depends on with a fake in its own folder, so
-Dpezzo=<piece>builds without the others. - Write the tests: logic without screen, every error branch, and for threads the concurrency tests (chapter 16). Close in parallel, callbacks, waits and midway failures follow the rules in 18.3 “Rules born from reviews”.
- Run
strumenti/prova.sh <piece>and, when it is finished,strumenti/prova.sh veloce. - Add the piece to the source map of the manual (chapter 20) and to the glossary if it brings new terms; the generator stops if a source file is missing from the map.
Source map
20.1 · The folders
The folders of the project, one piece per folder.
yasde/ ├── meson.build # root build file ├── meson_options.txt # the pezzo option ├── CLAUDE.md # project rules (Italian) ├── PIANO.md # work plan (Italian) ├── data/en/ # English translation tables ├── docs/ # protocol and the manuals' sources │ └── sources/ # build.py, style, script, technical/ and user/ chapters ├── mockup/ # the interface mockup ├── pacchetto/ # AppImage packaging ├── prove/telefono_finto/ # the fake ADB daemon in Python ├── src/ │ ├── comune/ # errors, buffers, neutral frame │ ├── adb/ # ADB client │ ├── scoperta/ # mDNS discovery │ ├── abbinamento/ # pairing with the code │ ├── collegamento/ # connection state machine │ ├── componente/ # PC side of the phone component │ ├── dati/ # phone data, search, clipboard │ ├── file/ # copy and listing │ ├── trasferimenti/ # queue and APK installer │ ├── video/ # decoding, capture │ ├── audio/ # Opus and PipeWire │ ├── finestre/ # window rules │ ├── config/ # folders, files, language │ ├── meteo/ # forecasts │ └── shell/ # GTK 4 interface │ ├── comune/ ossatura/ finto/ # common piece, skeleton, fake backend │ └── superficie/ finestra-app/ barra/ launcher/ desktop/ sistema/ trasferimento/ connessione/ ├── strumenti/ # build and demo tools └── telefono/ # the Java component and its tests ├── contratto/ base/ video/ audio/ dati/ archivio/ appunti/ pannello/ controlli/ └── costruisci.sh
20.2 · The project's files
Every source file with its line count, recounted each time the manual is generated. The map covers the C sources and headers under src/, the Java, shell and Python files of the phone component, the scripts and C tools of strumenti/ and pacchetto/, the root meson.build and the manual generator. If a file is missing from the map, or the map lists one that no longer exists, generation stops. The per-piece meson.build files, the COMPITO.md task files, CSS, resource and translation files are not counted.
| File | Lines | Role |
|---|---|---|
| Root and generator | ||
meson.build | 45 | Root build file: project options, the list of pieces, the pieces ready for «tutto» |
| Manuals | ||
docs/sources/build.py | 727 | Generates the two manuals: functions for text, tables and SVG figures, numbering, source map counting, checks |
| Common code | ||
src/comune/buffer.c | 51 | Growing byte buffer |
src/comune/buffer.h | 24 | Contract of the buffer |
src/comune/errore.c | 33 | PhErrore: writing and prefixing messages |
src/comune/errore.h | 22 | Error convention of the whole project |
src/comune/fotogramma.h | 82 | The neutral video frame (DMA-BUF or memory), pure C |
src/comune/prova_comune.c | 28 | Tests of the common code |
| ADB client | ||
src/adb/adb.h | 106 | Contract: connection, channels, shell, flow control |
src/adb/chiave.c | 268 | The PC's RSA key, self-signed certificate for TLS, ADB public key format |
src/adb/connessione.c | 1,152 | ADB connection: TCP, CNXN/STLS, TLS 1.3, reader thread, channels, flow control |
src/adb/interno.h | 49 | Internal: protocol packets |
src/adb/pacchetto.c | 60 | Packet header reading and writing |
src/adb/shell.c | 93 | The shell,v2 service: packets, output, exit code |
src/adb/finto_telefono.c | 644 | Fake ADB daemon on localhost for tests |
src/adb/finto_telefono.h | 68 | Contract of the fake daemon |
src/adb/prova_canali.c | 695 | Tests: channels, flow control, delayed acknowledgement |
src/adb/prova_chiave.c | 118 | Tests: key and certificate |
src/adb/prova_pacchetti.c | 70 | Tests: packet format |
src/adb/prova_velocita.c | 80 | Throughput measurement |
src/adb/prova_vera.c | 134 | Check against a real phone |
| Discovery and pairing | ||
src/scoperta/scoperta.h | 42 | Contract of the mDNS (DNS-SD) discovery, written from scratch |
src/scoperta/scoperta.c | 674 | mDNS queries and answers |
src/scoperta/scoperta_interno.h | 62 | Internal parts for tests |
src/scoperta/cerca.c | 29 | Hand tool: lists the phones found in 5 s |
src/scoperta/prova_scoperta.c | 446 | Tests of the discovery |
| Pairing | ||
src/abbinamento/abbinamento.h | 16 | Contract: pairing with the six-digit code |
src/abbinamento/abbinamento.c | 323 | Pairing sequence: TLS, SPAKE2, key exchange |
src/abbinamento/spake2.h | 40 | SPAKE2 on edwards25519, Android's variant |
src/abbinamento/spake2.c | 450 | SPAKE2 implementation |
src/abbinamento/prova_spake2.c | 73 | Tests of SPAKE2 |
| Connection | ||
src/collegamento/collegamento.h | 281 | Contract: states, borrowed sessions, concurrency rules |
src/collegamento/collegamento.c | 1,171 | State machine with its own thread: search, connect, component, guardian, retry |
src/collegamento/prova/finto.c | 672 | Fake lower pieces for the connection tests |
src/collegamento/prova/finto.h | 100 | Contract of those fakes |
src/collegamento/prova/lingua.c | 67 | Fake language functions for the tests |
src/collegamento/prova/prova_collegamento.c | 1,578 | Tests of the state machine, with the thread-sanitizer variant |
| Files | ||
src/file/file.h | 69 | Contract: copy and listing with sync: |
src/file/file.c | 908 | Send, receive, list, stat |
src/file/finto_canale.c | 476 | Fake channel for tests |
src/file/finto_canale.h | 44 | Contract of the fake channel |
src/file/prova_file.c | 714 | Tests of the file layer |
src/file/prova_vera.c | 123 | Check against a real phone |
| Transfers and installation | ||
src/trasferimenti/trasferimenti.h | 200 | Contract of the queue and the free-name rule |
src/trasferimenti/trasferimenti.c | 971 | The transfer queue and its worker thread |
src/trasferimenti/installa.h | 145 | Contract of install and uninstall |
src/trasferimenti/installa.c | 558 | APK recognition, copy, pm, cleanup, analysis of pm output |
src/trasferimenti/prova/finto.c | 354 | Fake lower pieces for the queue tests |
src/trasferimenti/prova/finto.h | 49 | Contract of the fake |
src/trasferimenti/prova/finto_installa.c | 192 | Fake phone for the install tests |
src/trasferimenti/prova/finto_installa.h | 34 | Contract of that fake |
src/trasferimenti/prova/prova_installa.c | 599 | Tests of install and uninstall |
src/trasferimenti/prova/prova_trasferimenti.c | 1,384 | Tests of the queue |
| The component, PC side | ||
src/componente/componente.h | 213 | Contract: start of the service, command channel, video sessions, input |
src/componente/componente.c | 873 | Startup, command channel, events, heartbeat |
src/componente/interno.h | 125 | Internal details |
src/componente/lettura.c | 23 | Resumable reading from a channel |
src/componente/messaggi.c | 117 | Pure part of the protocol: writing and reading messages |
src/componente/video.c | 417 | Video sessions: open, read H.264 packets, resize, keyframe, close |
src/componente/prova/finto.c | 983 | Fake component (a phone-side simulator in C) |
src/componente/prova/finto.h | 84 | Contract of the fake |
src/componente/prova/prova_componente.c | 1,662 | Tests of the component |
src/componente/prova/prova_messaggi.c | 198 | Tests of the message format |
| Phone data | ||
src/dati/dati.h | 393 | Contract: apps, icons, state, notifications, storage, calendar, alarm, battery, switches, position, search, clipboard |
src/dati/interno.h | 127 | Internal: message types |
src/dati/richieste.c | 690 | Requests 0x70–0x75 and events 0x7e–0x7f |
src/dati/nuovi.c | 489 | Month calendar, alarm, battery, quick switches, position |
src/dati/cerca.c | 239 | File search on the cerca channel |
src/dati/appunti.c | 208 | Shared clipboard channel |
src/dati/canale.c | 91 | Message reading from a channel, safe against a hostile phone |
src/dati/utf8.c | 127 | Cleaning of strings that come from the phone |
src/dati/prova/finto.c | 530 | Fake component for the data tests |
src/dati/prova/finto.h | 58 | Contract of the fake |
src/dati/prova/prova_dati.c | 2,683 | Tests of the data layer |
| Video | ||
src/video/decodifica.h | 65 | Contract of H.264 decoding (FFmpeg, hardware accelerated) |
src/video/decodifica.c | 256 | Decoder with VA-API or Vulkan and a software fallback |
src/video/esporta.h | 53 | Contract: decoded frame to the neutral frame |
src/video/esporta.c | 252 | DMA-BUF export without copies, or memory |
src/video/esporta_interno.h | 17 | Internal parts of the export |
src/video/colore.c | 34 | Color choices and checks on shared planes |
src/video/colore_interno.h | 17 | Internal color parts |
src/video/cattura.h | 175 | Contract: screenshot (PNG) and recording (MP4) |
src/video/cattura_interno.h | 26 | Internal parts of capture |
src/video/cattura_nome.c | 132 | File names of captures, created without overwriting |
src/video/cattura_png.c | 214 | Frame to RGB to PNG |
src/video/cattura_mp4.c | 831 | Fragmented MP4 recording without recoding |
src/video/misura_decodifica.c | 120 | Measurement tool for decoding |
src/video/prova/aiuti.h | 164 | Test helpers |
src/video/prova/prova_cattura_mp4.c | 309 | Tests of MP4 recording |
src/video/prova/prova_cattura_ostili.c | 675 | Tests with hostile input for capture |
src/video/prova/prova_cattura_png.c | 340 | Tests of PNG capture |
src/video/prova/prova_esporta.c | 290 | Tests of the frame export |
src/video/prova/prova_ordine_via.c | 33 | Tests of the automatic order of the decoding vias |
| Audio | ||
src/audio/audio.h | 89 | Contract: receive Opus packets, decode and play with PipeWire |
src/audio/audio.c | 241 | The player: channel reading, decoding, queue, output |
src/audio/pacchetti.c | 58 | Reading of audio packets (time, length, data) |
src/audio/decodifica.c | 62 | Opus decoding, 48 kHz stereo |
src/audio/flusso.c | 110 | Packet to queue: decoding and gap recognition |
src/audio/coda.c | 544 | Decoded audio queue with an adaptive margin |
src/audio/uscita_pipewire.c | 194 | PipeWire playback stream |
src/audio/suona.c | 201 | Hand tool: plays a stream or a 440 Hz tone |
src/audio/interno.h | 132 | Internal parts |
src/audio/prova/aiuti.h | 96 | Test helpers |
src/audio/prova/finto_canale.c | 126 | Fake audio channel |
src/audio/prova/finto_canale.h | 23 | Contract of the fake |
src/audio/prova/prova_audio.c | 311 | Tests of the player |
src/audio/prova/prova_coda.c | 422 | Tests of the queue |
src/audio/prova/prova_decodifica.c | 152 | Tests of decoding |
src/audio/prova/prova_pacchetti.c | 130 | Tests of packet reading |
| Window rules | ||
src/finestre/finestre.h | 506 | Contract: order, snapping, gestures, stream size, density, input translation |
src/finestre/finestre.c | 1,359 | The rules (pure logic) |
src/finestre/prova_finestre.c | 2,693 | Tests of the rules |
| Configuration and language | ||
src/config/config.h | 437 | Contract: folders, files, preferences, phone profile |
src/config/config.c | 891 | Reading and writing of the three configuration files, cleanup |
src/config/config_interno.h | 30 | Internal parts |
src/config/percorsi.c | 368 | XDG folders, safe write |
src/config/toml.h | 83 | Contract of the TOML subset |
src/config/toml.c | 668 | Reader and writer of the TOML subset |
src/config/profilo.h | 135 | Contract of the measurements file |
src/config/profilo.c | 439 | Reading and writing of the measurements file |
src/config/lingua.h | 85 | Contract: ph_t and placeholders |
src/config/lingua.c | 77 | Active language and lookup |
src/config/lingua_testo.c | 178 | Placeholder composition and comparison |
src/config/lingua_tabella.h | 18 | Shape of the generated table |
src/config/genera_traduzioni.c | 155 | Build-time generator of the English table |
src/config/tabella_finta.c | 10 | Fake table for the language tests |
src/config/prova_config.c | 1,895 | Tests of configuration |
src/config/prova_lingua.c | 314 | Scan of every ph_t call in the sources |
src/config/prova_lingua_funzioni.c | 189 | Tests of the language functions |
src/config/prova_profilo.c | 417 | Tests of the measurements file |
| Weather | ||
src/meteo/meteo.h | 244 | Contract: forecasts, place search, rules of privacy and frequency |
src/meteo/meteo.c | 733 | Requests, cache, frequency rules, request paths |
src/meteo/analisi.c | 802 | JSON reader for the forecast and the place search |
src/meteo/http.c | 349 | Minimal HTTP/1.1 client |
src/meteo/tls.c | 560 | HTTPS with OpenSSL: name resolution, connection, certificate check |
src/meteo/tls.h | 57 | Contract of the TLS layer |
src/meteo/interno.h | 46 | Internal parts |
src/meteo/prova/prova_meteo.c | 2,446 | Tests of the weather piece |
src/meteo/prova/prova_tls.c | 741 | Tests of TLS |
src/meteo/prova/tls_finto.c | 227 | Fake TLS server for tests |
src/meteo/prova/tls_finto.h | 25 | Contract of the fake server |
| Shell contracts | ||
src/shell/servizi.h | 808 | THE contract: the only door to the phone, audio, transfers, persistence |
src/shell/servizi_backend.h | 310 | How to write a backend of the services |
src/shell/shell.h | 409 | The shell context: delivery, layers, popups, handlers, style, icons, glass surfaces |
src/shell/superficie.h | 146 | Contract of the video surface widget |
src/shell/prova_css.h | 385 | Common detector of hand-written colours in the pieces' CSS, used by their tests |
src/shell/pezzi.h | 23 | Entry points of the pieces |
src/shell/fotogramma.h | 7 | Includes the neutral frame |
| Shell: common piece | ||
src/shell/comune/consegna.c | 88 | Delivery to the GTK thread, monotonic clock, decision log |
src/shell/comune/shell.c | 719 | The shell context: layers, popups, handlers |
src/shell/comune/servizi.c | 2,619 | Wrapper of a backend: events, snapshots, jobs, cancel |
src/shell/comune/stile.c | 299 | Loading and checking of CSS, icons |
src/shell/comune/vetro.c | 393 | Glass surfaces: registry, blur behind them |
src/shell/comune/prova_vetro.c | 794 | Tests of the glass |
src/shell/comune/ascoltatori.c | 101 | Listener lists and the registry of live objects |
src/shell/comune/interno.h | 71 | Internal parts |
src/shell/comune/prova_comune.c | 467 | Tests of the common piece |
| Shell: skeleton | ||
src/shell/ossatura/main.c | 7 | The program's main |
src/shell/ossatura/ossatura.c | 212 | Application, startup, ordered shutdown |
src/shell/ossatura/ossatura.h | 57 | Internal parts |
src/shell/ossatura/finestra.c | 240 | The host window, full screen, host state |
src/shell/ossatura/velo.c | 169 | Lock and connection veil |
src/shell/ossatura/appunti.c | 112 | PC and phone clipboard link |
src/shell/ossatura/logica.c | 291 | Pure logic: veil content, what covers the shell, host visibility, stream state machine |
src/shell/ossatura/logica.h | 122 | Contract of that logic |
src/shell/ossatura/servizi_veri.c | 646 | Core of the real services: connection, manager thread, pools, profile, shutdown |
src/shell/ossatura/sv_interno.h | 350 | Internal model of the real services |
src/shell/ossatura/sv_dati.c | 344 | Phone data, state, panel |
src/shell/ossatura/sv_extra.c | 701 | Calendar, alarm, battery, switches, position |
src/shell/ossatura/sv_file.c | 544 | Folder listing, search, folders, thumbnails, reading |
src/shell/ossatura/sv_flussi.c | 1,529 | Video streams: open, pause, resize, input, screenshot, recording |
src/shell/ossatura/sv_audio.c | 174 | Audio and volume |
src/shell/ossatura/sv_tr.c | 183 | The transfer queue's session life |
src/shell/ossatura/sv_abbina.c | 174 | Pairing from the shell |
src/shell/ossatura/sv_meteo.c | 776 | Weather observation and place search |
src/shell/ossatura/demo.c | 465 | Demo of the whole shell over the fake backend |
src/shell/ossatura/finti_sotto.c | 1,217 | Fake lower pieces that sleep like the network |
src/shell/ossatura/finti_sotto.h | 106 | Contract of those fakes |
src/shell/ossatura/prova_ossatura.c | 328 | Tests of the skeleton's logic |
src/shell/ossatura/prova_servizi_veri.c | 1,140 | Tests of the real services over fakes |
src/shell/ossatura/prova_meteo_veri.c | 685 | Tests of the real weather side |
src/shell/ossatura/prova_decodifica_avviso.c | 319 | Tests of the on-screen warning about CPU video decoding |
| Shell: video surface | ||
src/shell/superficie/superficie.c | 1,057 | The widget: reader thread, textures, blur, protected screen |
src/shell/superficie/logica.c | 417 | Frame swap, rhythm, format maps, exact rectangle |
src/shell/superficie/logica.h | 225 | Contract of that logic |
src/shell/superficie/demo.c | 316 | Demo with three surfaces |
src/shell/superficie/prova_superficie.c | 625 | Tests of the surface's logic |
| Shell: inner windows | ||
src/shell/finestra-app/finestra_app.c | 2,928 | Inner windows: title bar, buttons, input, pause, capture, Compatibility |
src/shell/finestra-app/logica.c | 449 | Keys, short names, pinch state machine, translation of points |
src/shell/finestra-app/logica.h | 211 | Contract of that logic |
src/shell/finestra-app/finestra_app_demo.h | 83 | Demo hooks |
src/shell/finestra-app/demo.c | 1,354 | Demo of the windows |
src/shell/finestra-app/prova_finestra_app.c | 1,085 | Tests of the windows' logic |
| Shell: bar | ||
src/shell/barra/barra.c | 1,088 | The bar widget |
src/shell/barra/logica.c | 230 | Pure logic of the bar |
src/shell/barra/logica.h | 93 | Contract of that logic |
src/shell/barra/demo.c | 502 | Demo of the bar |
src/shell/barra/prova_barra.c | 299 | Tests of the bar's logic |
| Shell: launcher | ||
src/shell/launcher/launcher.c | 919 | The launcher widget |
src/shell/launcher/launcher_interno.h | 56 | Internal parts |
src/shell/launcher/logica.c | 110 | Search filter |
src/shell/launcher/logica.h | 66 | Contract of that logic |
src/shell/launcher/demo.c | 265 | Demo of the launcher |
src/shell/launcher/prova_demo.c | 299 | Helper of the demo test |
src/shell/launcher/prova_demo.h | 17 | Contract of that helper |
src/shell/launcher/prova_launcher.c | 263 | Tests of the launcher's logic |
| Shell: desktop | ||
src/shell/desktop/desktop.c | 794 | The desktop: layers, menus, drag and drop |
src/shell/desktop/sfondo.c | 129 | Wallpaper drawing and loading |
src/shell/desktop/immagine.c | 199 | Wallpaper image decoding and reduction |
src/shell/desktop/icone.c | 523 | Icon grid |
src/shell/desktop/dialoghi.c | 1,109 | The wallpaper and widget dialogs |
src/shell/desktop/widget.c | 833 | Widget catalog and cards |
src/shell/desktop/wx.c | 128 | Table of the newer widget types |
src/shell/desktop/wx_calendario.c | 469 | Month calendar widget |
src/shell/desktop/wx_controlli.c | 371 | Quick switches widget |
src/shell/desktop/wx_elenchi.c | 232 | Frequent apps and recent transfers widgets |
src/shell/desktop/wx_meteo.c | 441 | Weather widget |
src/shell/desktop/wx_telefono.c | 188 | Alarm and battery widgets |
src/shell/desktop/orologio.c | 298 | Clock widget |
src/shell/desktop/meteo_disegno.c | 470 | Weather icons and drawings |
src/shell/desktop/meteo_luogo.c | 312 | Place search dialog of the weather |
src/shell/desktop/logica.c | 1,024 | Pure logic of the desktop |
src/shell/desktop/logica.h | 309 | Contract of that logic |
src/shell/desktop/logica_wx.c | 777 | Pure logic of the newer widgets |
src/shell/desktop/logica_wx.h | 142 | Contract of that logic |
src/shell/desktop/logica_meteo.c | 420 | Pure logic of the weather widget |
src/shell/desktop/logica_meteo.h | 91 | Contract of that logic |
src/shell/desktop/interno.h | 277 | Internal parts |
src/shell/desktop/demo.c | 284 | Demo of the desktop |
src/shell/desktop/demo_hook.c | 1,128 | Demo commands for the widgets |
src/shell/desktop/prova_desktop.c | 1,694 | Tests of the desktop's logic |
| Shell: system area | ||
src/shell/sistema/sistema.c | 188 | Installation of the system piece |
src/shell/sistema/notifiche.c | 391 | Notification panel |
src/shell/sistema/toast.c | 166 | Toasts and desktop notices |
src/shell/sistema/telefono.c | 256 | Phone status popup |
src/shell/sistema/volume.c | 171 | Volume popup |
src/shell/sistema/pulsanti.c | 213 | The three bar buttons |
src/shell/sistema/logica.c | 438 | Pure logic of the system piece |
src/shell/sistema/logica.h | 129 | Contract of that logic |
src/shell/sistema/interno.h | 111 | Internal parts |
src/shell/sistema/demo.c | 143 | Demo of the system piece |
src/shell/sistema/prova_sistema.c | 458 | Tests of the system piece's logic |
| Shell: transfer | ||
src/shell/trasferimento/trasferimento.c | 862 | The send and receive panels, drop target |
src/shell/trasferimento/navigatore.c | 1,247 | Folder and file navigator |
src/shell/trasferimento/navigatore.h | 64 | Contract of the navigator |
src/shell/trasferimento/elenco.c | 301 | Queue rows |
src/shell/trasferimento/elenco.h | 32 | Contract of the rows |
src/shell/trasferimento/percorsi.c | 448 | Pure logic: paths, free names, sizes, pages, completed transfers |
src/shell/trasferimento/percorsi.h | 104 | Contract of that logic |
src/shell/trasferimento/apk.c | 48 | APK installation confirmation |
src/shell/trasferimento/apk.h | 17 | Contract of the confirmation |
src/shell/trasferimento/interno.h | 58 | Internal parts |
src/shell/trasferimento/demo.c | 105 | Demo of the transfer piece |
src/shell/trasferimento/prova.c | 186 | Test helper |
src/shell/trasferimento/prova.h | 12 | Contract of that helper |
src/shell/trasferimento/prova_trasferimento.c | 462 | Tests of the transfer piece's logic |
| Shell: first connection | ||
src/shell/connessione/connessione.c | 485 | The first connection and pairing screen |
src/shell/connessione/connessione.h | 25 | Contract of the screen |
src/shell/connessione/logica_connessione.c | 242 | Pure logic: what to show in each state |
src/shell/connessione/logica_connessione.h | 100 | Contract of that logic |
src/shell/connessione/demo.c | 466 | Demo of the screen |
src/shell/connessione/prova_connessione.c | 262 | Tests of the screen's logic |
| Shell: fake backend | ||
src/shell/finto/finto.c | 2,552 | The fake phone: connection, apps, notifications, folders, transfers, widgets |
src/shell/finto/finto.h | 204 | Contract of the fake and of the demo program |
src/shell/finto/interno.h | 105 | Internal parts |
src/shell/finto/comandi.c | 355 | The small window of fake-phone commands |
src/shell/finto/flusso_finto.c | 900 | Synthetic video streams |
src/shell/finto/superficie_finta.c | 495 | Fake surface for tests |
src/shell/finto/demo_finto.c | 128 | Demo of the fake backend |
src/shell/finto/prova_finto.c | 2,033 | Tests of the fake backend |
| Packaging | ||
pacchetto/AppRun | 64 | AppImage launcher: libraries, schemas, loaders |
pacchetto/costruisci.sh | 53 | Runs the packaging on the build server |
pacchetto/icone-kora.sh | 218 | Packaging step: Kora icons as PNG, sources, GPL-3 text and credits |
pacchetto/dentro.sh | 722 | Packaging inside the container: tools, FFmpeg, libtiff, cairo, checks, AppImage |
pacchetto/yasde.desktop | 9 | Desktop entry used only by appimagetool |
pacchetto/prova_pixbuf.c | 43 | Packaging test: image loaders |
pacchetto/prova_tls.c | 45 | Packaging test: certificate authorities with the package's OpenSSL |
pacchetto/prova_tls_rete.c | 41 | Packaging test: TLS handshake over the network |
| Development tools | ||
strumenti/prova.sh | 28 | Builds and tests a piece on the build server |
strumenti/dentro.sh | 77 | The same, inside the container |
strumenti/Containerfile | 17 | Recipe of the build container |
strumenti/prepara-server.sh | 37 | Sets up an empty build server: container image and Android SDK |
strumenti/sdk.sh | 14 | Downloads the Android SDK; run by prepara-server.sh |
strumenti/meson.build | 29 | Builds the tools below |
strumenti/yasde-prova.c | 496 | Command line client for the lower pieces |
strumenti/finestra-prova.c | 524 | Bare window for one app (SDL3) |
strumenti/misura-flussi.c | 849 | Measures several video streams in parallel |
strumenti/prototipo-gtk.c | 1,195 | GTK prototype that measured the frame path |
strumenti/demo-sul-tablet.sh | 36 | Opens a piece's demo on the tablet |
strumenti/foto-demo.sh | 52 | Opens a demo on an invisible screen and photographs it |
strumenti/app-sul-tablet.sh | 47 | Opens the real program on the tablet |
strumenti/finestra-sul-tablet.sh | 23 | Opens the bare window on the tablet |
| Phone: build | ||
telefono/costruisci.sh | 23 | Compiles the component's jar and runs the JVM tests |
| Phone: contract | ||
telefono/contratto/it/yasde/Registro.java | 155 | Meeting point between the service and the pieces |
telefono/contratto/it/yasde/GestoreCanale.java | 9 | Handler of a channel |
telefono/contratto/it/yasde/GestoreComandi.java | 9 | Handler of a range of commands |
telefono/contratto/it/yasde/Guardiano.java | 15 | The restore guardian's interface |
| Phone: base | ||
telefono/base/it/yasde/Servizio.java | 411 | The service: app_process entry, socket, channel dispatch |
telefono/base/it/yasde/Protocollo.java | 105 | Message types and reading/writing |
telefono/base/it/yasde/Smistatore.java | 46 | Dispatch of the command channel |
telefono/base/it/yasde/Custode.java | 384 | The guardian: a separate shell process that restores the phone |
telefono/base/it/yasde/Resti.java | 137 | Leftovers of old sessions: finding and removing |
telefono/base/it/yasde/Pari.java | 29 | Who may connect to the service socket |
telefono/base/it/yasde/Nascoste.java | 44 | Single point for hidden APIs and their startup check |
telefono/base/prove.sh | 12 | JVM tests |
telefono/base/prove/prova_telefono.py | 504 | Real-phone test |
| Phone: video and input | ||
telefono/video/it/yasde/Video.java | 193 | Video channel and commands 0x40–0x4f |
telefono/video/it/yasde/Sessione.java | 594 | A session: virtual screen, encoder, the app on it |
telefono/video/it/yasde/Codificatore.java | 241 | Hardware H.264 encoder and its reader thread |
telefono/video/it/yasde/Inoltro.java | 43 | Rules of what leaves on the video channel |
telefono/video/it/yasde/Input.java | 214 | Input channel |
telefono/video/it/yasde/Iniettore.java | 295 | Builds and injects input events |
telefono/video/it/yasde/Gesti.java | 203 | State of gestures in progress |
telefono/video/it/yasde/Pizzico.java | 176 | Geometry and state machine of the pinch |
telefono/video/it/yasde/Specchio.java | 19 | Real screen measures for the mirror |
telefono/video/it/yasde/ControlloSchermi.java | 82 | Protected-screen watch |
telefono/video/it/yasde/AnalisiFinestre.java | 86 | Reads the window dump for protected windows |
telefono/video/it/yasde/LiberaTask.java | 34 | Close with task removal |
telefono/video/it/yasde/Barriera.java | 32 | Barrier on an execution queue |
telefono/video/it/yasde/Binario.java | 16 | Protocol string reading |
telefono/video/it/yasde/NascosteVideo.java | 315 | Hidden APIs of video and input |
telefono/video/it/yasde/ProvaVideo.java | 99 | Isolated test of a session |
telefono/video/prove.sh | 34 | JVM tests |
telefono/video/prove/prova_gesti.py | 153 | Real-phone test: gestures |
telefono/video/prove/prova_mouse.py | 131 | Real-phone test: right and middle mouse buttons |
telefono/video/prove/prova_pausa.py | 78 | Real-phone test: pause |
telefono/video/prove/prova_pausa_prod.py | 205 | Real-phone test: pause in production |
telefono/video/prove/prova_rotella.py | 96 | Real-phone test: wheel |
telefono/video/prove/prova_schermi.py | 112 | Real-phone test: screens |
telefono/video/prove/prova_video.py | 583 | Real-phone test: video |
telefono/video/prove/prova_zoom.py | 135 | Real-phone test: zoom |
| Phone: audio | ||
telefono/audio/it/yasde/Audio.java | 193 | Audio channel |
telefono/audio/it/yasde/Cattura.java | 313 | One capture: loopback, Opus |
telefono/audio/it/yasde/NascosteAudio.java | 317 | Hidden APIs of audio |
telefono/audio/it/yasde/Volume.java | 89 | Media volume through a shell command |
telefono/audio/prove.sh | 14 | JVM tests |
telefono/audio/prove/prova_audio.py | 536 | Real-phone test |
telefono/audio/prove/bin_a_ogg.py | 114 | Converts captured audio packets to Ogg Opus |
| Phone: data | ||
telefono/dati/it/yasde/Dati.java | 218 | Commands 0x70–0x7d, 0x90 and events |
telefono/dati/it/yasde/CampiDati.java | 420 | Pure part: fields, encoding, limits |
telefono/dati/it/yasde/NascosteDati.java | 1,010 | What the data layer asks Android |
telefono/dati/it/yasde/AnalisiBatteria.java | 41 | Parses dumpsys battery |
telefono/dati/it/yasde/AnalisiNotifiche.java | 273 | Parses notifications from the dump |
telefono/dati/it/yasde/LetturaUnica.java | 75 | A blocking read on its own thread with a deadline |
telefono/dati/it/yasde/LogicaPosizione.java | 308 | Pure part of the position: recency, rounding to 0.005° |
telefono/dati/prove.sh | 9 | JVM tests |
telefono/dati/prove/prova_dati.py | 332 | Real-phone test |
telefono/dati/prove/prova_posizione.py | 152 | Real-phone test: position |
telefono/dati/prove/prova_widget.py | 108 | Real-phone test: widget data |
telefono/dati/prove/prova_widget2.py | 161 | Real-phone test: newer widget data |
telefono/dati/prove/conta_verticali.py | 95 | Counts portrait-only apps |
telefono/dati/prove/sonda_riproduzione.sh | 17 | Probe: playback information |
telefono/dati/prove/sonda_widget.sh | 17 | Probe: widget data |
| Phone: archive, clipboard | ||
telefono/archivio/it/yasde/Archivio.java | 210 | Thumbnails and storage |
telefono/archivio/it/yasde/Cerca.java | 171 | Search channel |
telefono/archivio/it/yasde/Percorrenza.java | 143 | Breadth-first walk of a folder |
telefono/archivio/it/yasde/ConfrontoNomi.java | 34 | Name comparison for search |
telefono/archivio/it/yasde/BinarioArchivio.java | 46 | Protocol reading for this piece |
telefono/archivio/prove.sh | 9 | JVM tests |
telefono/archivio/prove/prova_archivio.py | 275 | Real-phone test |
telefono/appunti/it/yasde/Appunti.java | 290 | Clipboard channel |
telefono/appunti/it/yasde/Regole.java | 201 | Pure part: message format, never-pass rules, echo suppression |
telefono/appunti/it/yasde/NascosteAppunti.java | 297 | Hidden APIs of the clipboard |
telefono/appunti/prove.sh | 17 | JVM tests |
telefono/appunti/prove/prova_appunti.py | 486 | Real-phone test |
| Phone: panel and switches | ||
telefono/pannello/it/yasde/Pannello.java | 825 | Physical panel commands |
telefono/pannello/it/yasde/TieniSveglio.java | 250 | Keeps the phone awake while the PC is alive |
telefono/pannello/it/yasde/AssenzaPc.java | 141 | Rule of the PC's absence |
telefono/pannello/it/yasde/InputFisico.java | 187 | Notices a touch or key on the real screen |
telefono/pannello/it/yasde/EventiEvdev.java | 34 | Reads kernel input events |
telefono/pannello/it/yasde/Frequenze.java | 31 | Rate chosen with the panel off |
telefono/pannello/it/yasde/ImpostazioniPannello.java | 66 | System settings through a shell command |
telefono/pannello/it/yasde/ShellPannello.java | 54 | Shell commands with a real deadline |
telefono/pannello/it/yasde/NascostePannello.java | 514 | Hidden APIs of the panel |
telefono/pannello/prove.sh | 27 | JVM tests |
telefono/pannello/prove/prova_pannello.py | 648 | Real-phone test |
telefono/pannello/prove/prova_sveglio.py | 491 | Real-phone test: staying awake |
telefono/controlli/it/yasde/Controlli.java | 470 | Quick switches and find-my-phone commands 0x80–0x8f |
telefono/controlli/it/yasde/Trova.java | 389 | Find my phone (switched off) |
telefono/controlli/it/yasde/Telefono.java | 72 | What the switches ask of the phone |
telefono/controlli/it/yasde/TelefonoAndroid.java | 360 | The real phone for the switches |
telefono/controlli/it/yasde/ComandiShell.java | 68 | Restore lines for the guardian |
telefono/controlli/it/yasde/ShellControlli.java | 54 | Shell commands with a deadline |
telefono/controlli/it/yasde/AnalisiNonDisturbare.java | 93 | Parses the Do Not Disturb state |
telefono/controlli/it/yasde/NascosteControlli.java | 154 | The one hidden API of this piece |
telefono/controlli/prove.sh | 20 | JVM tests |
telefono/controlli/prove/prova_controlli.py | 579 | Real-phone test |
20.3 · The project in numbers
The same files, grouped by what they are.
| Part | Where | Lines | Contents |
|---|---|---|---|
| Shell, program | src/shell/ (not tests, demos, fake) | 36,105 | The GTK 4 interface |
| Shell, fake backend, demos and tests | src/shell/ | 22,986 | Fake phone, demos, logic and screen tests |
| PC pieces | src/*/ | 24,054 | ADB, discovery, pairing, connection, component, data, files, transfers, video, audio, windows, configuration, weather |
| PC piece tests and fakes | src/*/ | 26,968 | Tests and fakes of the pieces above |
| Phone component | telefono/*/it/ | 12,397 | Java source of the component |
| Phone tests and probes | telefono/ | 6,150 | Python and shell tests |
| Packaging | pacchetto/ | 1,195 | AppImage scripts and checks |
| Tools and build | root, strumenti/, telefono/costruisci.sh | 4,219 | Meson root, build scripts, development tools |
| Total | 134,074 |
Known problems
21.1 · The known problems at a glance
Only real problems, taken from the open points of the project plan and from the code. Each one says what is known, what is not, and where to look. None of them blocks the program.
| Problem | State | Where |
|---|---|---|
| Direct scan-out (offload) of the video not confirmed | Open: to understand before a release | src/shell/superficie/superficie.c |
| 1:1 image at a fractional scale (125%, 150%) | Function exists, not wired into the windows | src/shell/finestra-app/finestra_app.c |
| Blur behind the glass surfaces costs drawing time; off unless the renderer is GL, NGL or Vulkan | Known: with four video windows the median draw time goes from 5.1 to 7.1 ms with the blur on the windows only and to 8.5 ms with the launcher open above them (95th percentile 7.2 → 10.0 → 12.8 ms; measured once, CPU about +50%); with any other renderer (for example CPU drawing, GskCairoRenderer) the surfaces have an almost opaque fill. Readability: over a very dark or very bright wallpaper the secondary text on the 58% veil loses contrast | src/shell/comune/vetro.c, src/shell/finestra-app/finestra_app.c |
Relative XDG_CACHE_HOME in the AppImage launcher | Known, not blocking | pacchetto/AppRun |
| In-memory cache on some systems | Known: the wallpaper is lost at every reboot there | src/config/percorsi.c |
| Switched-off features: Find my phone, Quick notes, Now playing | Deliberate | src/shell/desktop/widget.c |
| Restores lost when the wireless debugging restarts | Open point, mitigated | telefono/base/ |
| Never tried live | A list of things proven only by tests | chapter 16 |
| Phone panel with no idle time; audio and video not in sync; Vulkan decoding copies frames | Open: to decide | Functions that are off |
| Documents that disagree with the code | A list | this chapter |
21.2 · Direct scan-out of the video
On one machine with an Intel GPU (GTK 4.18.6, a real screen, with GDK_DEBUG=offload, even with force-offload, with the Vulkan and the GL renderers) GTK never writes the line "Attaching … GdkDmabufTexture": the direct pass of the images to the screen does not appear active, neither in the surface demo nor in the prototype measured at the beginning (strumenti/prototipo-gtk.c: same result).
- The textures are DMA-BUF (zero refusals): the video reaches the graphics card without copies in memory; only the last step is missing.
- It does not depend on our widget tree (the prototype behaves the same). What is not known: whether it is the machine or the compositor, or a rule of GTK that does not say its reason.
- A hint for the real windows: rounded corners with clipping (
finestra-app.css,GTK_OVERFLOW_HIDDEN) would prevent it anyway. - Not urgent: the fluidity measured today is already reached without this step.
21.3 · The 1:1 image at fractional scales
Windows are sized so that the image is 1:1 with the physical pixels. At a fractional shell scale the widget's size is rounded to whole logical pixels (1000 physical pixels at 1.5 is 667 logical, which is 1000.5 physical), so the image is not exactly 1:1 and is resampled. Scales 1 and 2 are not affected.
- The surface has the answer:
ph_superficie_misura_esatta(src/shell/superficie/superficie.h) draws the image in a rectangle of non-integer size inside its allocation (ph_sup_rettangolo_esattoinsrc/shell/superficie/logica.c), andph_fa_origine_pixel_interocomputes an origin on a whole physical pixel. - Only the surface demo calls
ph_superficie_misura_esattatoday: the inner windows of the real program do not. The windows must also be tried on a small screen and at scales 125% and 150% before a release.
21.4 · Smaller issues
- Relative XDG. With
XDG_CACHE_HOMErelative, or a non-absoluteHOME,pacchetto/AppRunuses the value as it is; the program does not (it ignores a relative XDG variable, as the specification says), so the two may disagree on the cache folder. - Memory-backed cache. On the tablet used for tests
~/.cachelives in memory and is emptied at every reboot, so the wallpaper image saved there is lost each time (and a profile that names it then points to nothing;ph_cfg_pulisci_sfondionly removes files, it does not repair the profile). To evaluate. - The product name and trademarks. The name "Samsung DeX" belongs to Samsung; a non-affiliation line is present in the manuals and in the package. It is not a legal opinion.
- Pairing screen hint. When the phone does not announce itself on the network the screen stays at Looking for phones on the network… without saying what to check (in a live test the phone had to have its wireless debugging switched off and on). Hints after a few seconds without results were proposed, and the answer is awaited.
21.5 · Functions that are off
Some functions exist in the code and are off.
| Function | State | Detail |
|---|---|---|
| Find my phone | Not offered | The widget is not in the catalog (PH_DSK_TROVA_OFFERTO is 0); on the phone the command is switched off by a constant and touches nothing (message TROVA_AVVIA answers an error). Measured reasons: an audio track cannot be created from the shell process, and the switch to "ring" raises Android's saved ringer volume from 0 to 1 with no return. A future evolution, to take up with a test phone that is not the user's. |
| Quick notes | Not offered | The type note is in the profile format but not in the catalog (it was left for after the app worked). |
| Now playing, recent calls, network | Not made | Now playing needs a test with a real playback; the other two were to be evaluated for feasibility with pure Android, without root. |
| Audio in a window recording | Not wired | Recordings hold only video. src/video/cattura.h already accepts an Opus audio track, and the contract has the con_audio option, but the real services accept it and ignore it (src/shell/ossatura/sv_flussi.c): the step that brings the audio packets to the recording is missing. |
| Breaking away from FFmpeg | To evaluate | FFmpeg is confined to src/video/ precisely so it can be replaced later. |
| Idle time of the physical panel | Missing | The idle time foreseen by the specification (4.7) and by docs/protocollo.md §2.9 does not exist in the code: the panel is turned off again only at the first input from the PC with the phone "in hand". Either the function is missing or the protocol must be corrected: the user's decision. |
| Audio and video sync | Not active | ph_audio_tempo_telefono_us is not used by the shell: frames are shown as soon as they arrive. |
| Vulkan decoding copies frames | Open: to evaluate | The automatic order is VA-API first, then Vulkan: Vulkan decoding is used only where VA-API is missing or fails (for example a driver that offers only Vulkan Video), and there every frame is copied to memory (src/video/esporta.c, PH_ESPORTA_RIPIEGO): the copy-free path holds only with VA-API. It contradicts the architecture choice of never taking the copying path, and the measurements (27 frames per second with copies). To evaluate: export without copies also from Vulkan. On the machine tried VA-API is used, so it is not seen there. |
| Text size | Open | The size of texts in app windows (DeX uses 90%) is to be judged live. |
| Technical measurements file | Not connected | src/config/profilo.c has no caller outside its tests (chapter 14). |
| Decoder not replaced when the device is lost in mid-stream | To evaluate | A decoder born with a hardware via that FFmpeg drops to software (at the first packet, or after a new configuration such as a resize) is now recreated once as software (decision line and toast). A device lost in the middle of a session is not handled in the same way: it gives only decoding errors and key-frame requests every 500 ms, the decoder is not recreated and the via is not changed. Read from the code (src/video/decodifica.c, src/shell/ossatura/sv_flussi.c), never run. |
21.6 · Restores lost when the debugging restarts
When the wireless debugging is switched off and on, the phone's init system kills the whole process group, the service and its guardian, and nothing restores. A process of ours cannot survive that without root. Leftovers seen once after real sessions: jars and guardian scripts in /data/local/tmp, one with a volume restore never executed.
- Remedy in place: the next service's startup runs the pending restores and removes the leftovers (
telefono/base/it/yasde/Resti.java,telefono/base/it/yasde/Custode.java). The pending restore is run only if the setting still has the value YASDE put there. - Open points: a guardian script of an old session with the same pid as the new service, if it was not run at that startup, is overwritten (it should be renamed); and the PC is not told about a restore that was never executed (a contract to write).
- Open point: reduce what YASDE changes durably, preferring what Android undoes by itself when the process dies (the screen timeout at its maximum, and the maximum media volume, are to be measured). The PC also sends a presence message every 5 minutes, and after 30 minutes without a sign of life the phone stops keeping itself awake (chapter 6).
21.7 · Never tried live
What the project's own record says has not been seen working in the real program.
- Tried live on 24 November 2026 with the AppImage, on one machine and one phone: pairing from an empty installation, the panel turning off at connection, the bar volume at 100%, Compatibility. The AppImage with the interface was tried on one distribution; the others are not. Never tried live: every English sentence on screen (error sentences too), the pairing screen's three instruction lines, a wrong pairing code, a code pasted with spaces, authorization revoked from the phone, and wireless debugging switched off and on with the app open.
- The Compatibility switch was confirmed live with one app (Onecta by Daikin drawn at the right size in a phone-shaped window; the hot change is enough). The weather has not been tried live with a real forecast request.
- The AppImage on another distribution and with another glibc, and everything the build script cannot see (17.6 “What the build does not prove”).
- Behavior at fractional scales and on small screens (21.3 “The 1:1 image at fractional scales”).
- One phone only: other makers and Android versions are not covered.
21.8 · Documents that disagree with the code
Places where the written documents and the code do not agree. The code is right.
| Where | What it says | What the code does |
|---|---|---|
src/finestre/finestre.h, head comment, point 1 | A dragged window stays above the bar. | It may go down until only the title bar is visible (src/finestre/finestre.c). |
src/shell/CONTRATTI.md, decisions of 23 November | The bar has no pinned favorites. | Pinned apps exist: PhShellGestoreFissate in src/shell/shell.h, up to 16 per phone. |
meson_options.txt, the pezzo description | Lists pieces up to transfers. | The pieces are more (see the root meson.build). |
src/shell/finestra-app/COMPITO.md, opening sizes | 296×470 and 380×420 from the mockup. | The default is the phone's screen in points (12.4 “The density rule”). |
data/en/shell-trasferimento.txt, one key | "This version of YASDE cannot install apps on the phone yet." | Apps are installed (13.5 “Installing and uninstalling APKs”); the key is a leftover, not used by any ph_t call. |
docs/protocollo.md, VIDEO_APRI | Does not cite the limits. | telefono/video/it/yasde/Video.java imposes density 40 to 1000, bitrate and frame-rate limits. |
docs/protocollo.md, VIDEO_EVENTO | Event 3 exists. | The phone never sends it. |
telefono/pannello/it/yasde/Pannello.java, comment at line 32 | The wake lock starts at startup. | It starts from the greeting (SALUTO). |
src/adb/adb.h | Cites the adbkey format. | The file is chiave.pem. |
| The specification | Two guardians. | The code has one (Custode). |
pacchetto/LEGGIMI.md, line 169 | Cites libfuse.so.2. | The AppImage has libfuse3 inside and asks only for fusermount3 or fusermount. |
src/config/config.h, the example of widget types | Lists eight types. | The code accepts fifteen (14.2 “The file formats and their keys”). |
Glossary
22.1 · English terms
Terms used in the manual, in alphabetical order.
- AppImage
- The single-file package of YASDE (
YASDE-2.1-x86_64.AppImage) with the program, the phone component and the libraries. See 17.3 “The AppImage”. - AppRun
- The AppImage's launcher script: sets libraries, schemas and image loaders, then starts the program. See 17.3 “The AppImage”.
- Automatic density
- The rule that gives every app window a stream equal to its physical pixels and a density of 160 times the shell scale. See 12.4 “The density rule”.
- Backend
- A realization of the services: the real one in the skeleton, or the fake one. See 11.4 “The services and their backends”.
- Broadway
- GTK's virtual screen (
gtk4-broadwayd), used by the screen tests in the build container. See 16.2 “Running the tests”. - Compatibility
- The per-app window switch that gives the app the phone's real density. See 12.6 “Compatibility”.
- Component
- The Java code that runs on the phone, started with
app_process(chapter 6). - Contract
- A header or document that fixes how two pieces talk (for example
servizi.hor the protocol document). A piece does not change a contract by itself. See 18.1 “Principles of the project”. - Delivery
- Passing a function to the GTK thread with
ph_shell_consegna. See 11.3 “Threads and delivery to the GTK thread”. - Decoding path (via)
- The way an H.264 stream is decoded:
PH_VIA_VAAPI,PH_VIA_VULKANorPH_VIA_SOFTWARE. See 8.6 “How the decoding path is chosen and when it falls back”. - DMA-BUF
- A buffer shared with the graphics card, which lets a decoded frame reach the screen without a copy in memory. See 11.7 “The video surface”.
- DRM PRIME
- The FFmpeg pixel format
AV_PIX_FMT_DRM_PRIMEthat describes a frame as DMA-BUF file descriptors; a VA-API frame is mapped to it without copying. See 8.5 “Hardware acceleration end to end”. - Fake backend
- A simulated phone in memory used by demos and tests. See 11.9 “The fake backend”.
- Guardian
- The phone-side shell process that restores the phone's settings if the service dies (chapter 6).
- Host window
- The one real GTK window of the program, which contains the whole shell. See 11.5 “The skeleton”.
- Inner window
- The window of a phone app drawn inside the host window. See 12.1 “The window rules”.
- Layer
- One level of the shell's stack: desktop, windows, bar, panels, toasts, drop, veil, host title. See 11.2 “Layers, popups and piece handlers”.
- Modifier (DMA-BUF)
- A 64-bit code that tells how the planes of a DMA-BUF are laid out in memory (tiling, compression); it travels with the fourcc and the file descriptors from
ph_esportato GTK. See 8.5 “Hardware acceleration end to end”. - Mirror
- The inner window that shows the phone's real screen. See 12.7 “The mirror window”.
- Pairing
- Authorizing the PC on the phone with the six-digit code (chapter 5).
- Offload (scan-out)
- Handing a DMA-BUF texture straight to the display hardware instead of drawing it with the renderer, requested with
GtkGraphicsOffload; GTK decides, and it was not seen active on the one machine tried (an Intel GPU, GTK 4.18.6). See 8.9 “Requirements and limits of hardware acceleration”. - Piece
- One folder with its build file, its contract and its tests. See 16.1 “Tests of the PC pieces”.
- Popup
- A panel, menu or dialog of the shell; only one is open at a time. See 11.2 “Layers, popups and piece handlers”.
- Pool
- A group of worker threads of the real services with one role. See 11.3 “Threads and delivery to the GTK thread”.
- Profile
- The per-phone file
telefono-<serial>.toml(desktop, folders, pinned apps…). See 14.2 “The file formats and their keys”. - VA-API
- The Linux interface (libva) to the video decoding hardware of a GPU; the first choice of the decoding order, and the only one that gives the frame to the shell without copies. See 8.6 “How the decoding path is chosen and when it falls back”.
- Vulkan Video
- The Vulkan extension
VK_KHR_video_decode_h264for decoding on the GPU; the second choice, used only if offered as shipped, and it copies every frame to memory. See 8.6 “How the decoding path is chosen and when it falls back”. - Snapshot
- The last state received for something (connection, apps, notifications…), replaced only on the GTK thread. See 11.4 “The services and their backends”.
- Surface
- The widget that shows one video stream. See 11.7 “The video surface”.
- Veil
- The full-area cover for the lock and the lost connection. See 11.5 “The skeleton”.
- Widget (desktop)
- A card on the desktop (clock, weather…), drawn by the desktop piece (not a GTK widget). See 19.3 “Adding a widget”.
22.2 · Italian names in the code
The code is Italian: identifiers, files, configuration keys and comments keep Italian names, and the manual quotes them as they are. These are the recurring ones with their translation.
- abbinamento
- Pairing: the piece
src/abbinamento/and the code-based pairing. - avvisi
- Notices: pop-up messages; also the preference
avvisi. - barra
- The bar at the bottom of the host window (
src/shell/barra/). - cartella_invio, cartella_ricezione
- Send folder and receive folder, in the profile.
- cattura
- Capture: screenshot and recording (
src/video/cattura.h). - collegamento
- Connection: the state machine that keeps the relationship with one phone (
src/collegamento/). - componente
- The component on the phone, and its PC side (
src/componente/). - coda
- Queue (transfers; audio).
- consegna
- Delivery:
ph_shell_consegna. - custode
- Guardian: the phone-side restore process (
Custode). - dati
- Data:
src/dati/, the phone's apps, state, notifications, storage… - fissata
- Pinned: an app fixed on the bar (
[[fissata]]). - finestra, finestre
- Window, windows (
src/finestre/). - finto
- Fake (as in the fake backend,
src/shell/finto/). - flusso
- Stream: a video stream, or the stream size of a window.
- immagine
- Image.
- lingua
- Language.
- meteo
- Weather.
- ossatura
- Skeleton: the main window and program piece (
src/shell/ossatura/). - pannello
- Panel: the phone's physical screen panel (
telefono/pannello/). - pezzo
- Piece: the unit of work, and the build option
pezzo. - prova, prove
- Test, tests (
prova_*.c,strumenti/prova.sh). - ricezione
- Receive: phone to PC file transfer.
- scoperta
- Discovery: finding phones with mDNS (
src/scoperta/). - servizi
- Services: the shell's only door (
src/shell/servizi.h). - sfondo
- Wallpaper.
- sveglia
- Alarm clock.
- superficie
- Surface (the video surface).
- tutto
- All: the value of the build option
pezzothat builds every approved piece. - veloce
- Fast: the optimized whole build, without checks, for measurements.
- velo
- Veil.