From 9c710bedb9cd8083454b5e55f02c859f3a742ec6 Mon Sep 17 00:00:00 2001 From: Tamas Csikel Date: Mon, 2 Nov 2026 19:38:09 +0100 Subject: [PATCH] Fennec OS 0.3.2: one app at a time, Raspberry Pi shell packages - sf-core: only one app runs. Home, another app or a cast closes the app on screen (after the switch animation) instead of freezing it in the background. A frozen app that held a sound stream stalled PipeWire, so the next app could not play at all ("Failed to connect stream: No such entity" in Netflex after YouTube was sent home mid-video). The background limit and the low-memory watcher go with the freezing. - Raspberry Pi: image/pi (installer on Raspberry Pi OS), aarch64 shell packages (sf-shell--aarch64, arch in pkg.toml, sf-update installs only its own architecture), CI builds the aarch64 shell too. - sf-compositor: volume OSD, screencopy for remote view, blank cursor. - SDK v0.1.2. Co-Authored-By: Claude Opus 5.5 --- .gitea/workflows/packages.yml | 20 +- Cargo.lock | 25 +- Cargo.toml | 6 +- README.md | 48 ++- crates/sf-compositor/Cargo.toml | 2 + crates/sf-compositor/src/main.rs | 4 + crates/sf-compositor/src/osd.rs | 234 +++++++++++++ crates/sf-compositor/src/screencopy.rs | 323 ++++++++++++++++++ crates/sf-compositor/src/state.rs | 86 +++-- crates/sf-compositor/src/udev.rs | 35 +- crates/sf-compositor/src/winit.rs | 14 +- crates/sf-core/Cargo.toml | 2 +- crates/sf-core/src/apps.rs | 255 +++----------- crates/sf-core/src/main.rs | 4 +- crates/sf-ipc/src/message.rs | 7 +- crates/sf-launcher/src/core_client.rs | 2 +- crates/sf-launcher/src/devshot.rs | 5 + crates/sf-launcher/src/main.rs | 38 ++- crates/sf-update/src/appstore.rs | 21 +- crates/sf-update/src/arch.rs | 45 +++ crates/sf-update/src/main.rs | 1 + crates/sf-update/src/registry.rs | 49 ++- crates/sf-update/src/store.rs | 6 + docs/store.md | 3 + docs/updates.md | 6 + image/mkosi.extra/usr/bin/sf-launcher-start | 9 + image/mkosi.extra/usr/bin/sf-session | 10 +- .../usr/lib/smartfox/blank-cursor.py | 36 ++ image/mkosi.postinst.chroot | 35 +- image/pi/build.sh | 107 ++++++ image/pi/factory-store.toml | 12 + image/pi/install.sh | 163 +++++++++ tools/pkg/packages.sh | 35 +- 33 files changed, 1329 insertions(+), 319 deletions(-) create mode 100644 crates/sf-compositor/src/osd.rs create mode 100644 crates/sf-compositor/src/screencopy.rs create mode 100644 crates/sf-update/src/arch.rs create mode 100644 image/mkosi.extra/usr/lib/smartfox/blank-cursor.py create mode 100644 image/pi/build.sh create mode 100644 image/pi/factory-store.toml create mode 100644 image/pi/install.sh diff --git a/.gitea/workflows/packages.yml b/.gitea/workflows/packages.yml index 361d89f..b65516e 100644 --- a/.gitea/workflows/packages.yml +++ b/.gitea/workflows/packages.yml @@ -42,12 +42,24 @@ jobs: - name: Toolchain run: | export DEBIAN_FRONTEND=noninteractive + # arm64 libraries for the Raspberry Pi shell (SF_TARGET=aarch64-...): + # Ubuntu serves them from ports.ubuntu.com, the main mirror is amd64 only. + . /etc/os-release + dpkg --add-architecture arm64 + if [ -f /etc/apt/sources.list.d/ubuntu.sources ]; then + sed -i '/^Architectures:/d; /^Types:/a Architectures: amd64' /etc/apt/sources.list.d/ubuntu.sources + fi + [ -f /etc/apt/sources.list ] && sed -i 's/^deb \(http\)/deb [arch=amd64] \1/' /etc/apt/sources.list + printf 'Types: deb\nURIs: http://ports.ubuntu.com/ubuntu-ports/\nSuites: %s %s-updates %s-security\nComponents: main universe\nArchitectures: arm64\nSigned-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg\n' \ + "$VERSION_CODENAME" "$VERSION_CODENAME" "$VERSION_CODENAME" >/etc/apt/sources.list.d/arm64-ports.sources apt-get update -qq + libs="libfontconfig1-dev libfreetype-dev libxkbcommon-dev libdbus-1-dev libudev-dev + libinput-dev libgbm-dev libseat-dev libdrm-dev libegl-dev" apt-get install -y -qq --no-install-recommends build-essential pkg-config zstd \ - libfontconfig1-dev libfreetype-dev libxkbcommon-dev libdbus-1-dev libudev-dev \ - libinput-dev libgbm-dev libseat-dev libdrm-dev libegl-dev >/dev/null + gcc-aarch64-linux-gnu g++-aarch64-linux-gnu libc6-dev-arm64-cross \ + $libs $(for l in $libs; do printf '%s:arm64 ' "$l"; done) >/dev/null rm -rf /var/lib/apt/lists/* - curl -sSf https://sh.rustup.rs | sh -s -- -y -q --profile minimal --no-modify-path + curl -sSf https://sh.rustup.rs | sh -s -- -y -q --profile minimal --no-modify-path --target aarch64-unknown-linux-gnu /tmp/sf-build/cargo/bin/rustc --version - name: Build, sign, upload @@ -58,6 +70,8 @@ jobs: export PATH="/tmp/sf-build/cargo/bin:$PATH" cd /tmp/sf-build/src bash tools/pkg/packages.sh --upload + # The shell for the Raspberry Pi (sf-shell--aarch64; apps are the same). + SF_TARGET=aarch64-unknown-linux-gnu bash tools/pkg/packages.sh --upload shell - name: Clean up if: always() diff --git a/Cargo.lock b/Cargo.lock index f075bc2..b46ed61 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4734,8 +4734,8 @@ dependencies = [ [[package]] name = "sf-app" -version = "0.1.0" -source = "git+https://gitea.bluefox.support/fennec/sdk?tag=v0.1.0#f00e8c68479ec5271d06be5737d5c60a831c944e" +version = "0.1.2" +source = "git+https://gitea.bluefox.support/fennec/sdk?tag=v0.1.2#cb37d872ed7195e57268e0c3a1a76367039bf959" dependencies = [ "anyhow", "log", @@ -4745,8 +4745,9 @@ dependencies = [ [[package]] name = "sf-compositor" -version = "0.3.1" +version = "0.3.2" dependencies = [ + "ab_glyph", "anyhow", "sf-ipc", "smithay", @@ -4756,7 +4757,7 @@ dependencies = [ [[package]] name = "sf-core" -version = "0.3.1" +version = "0.3.2" dependencies = [ "anyhow", "env_logger", @@ -4771,7 +4772,7 @@ dependencies = [ [[package]] name = "sf-dial" -version = "0.3.1" +version = "0.3.2" dependencies = [ "anyhow", "log", @@ -4781,7 +4782,7 @@ dependencies = [ [[package]] name = "sf-ipc" -version = "0.3.1" +version = "0.3.2" dependencies = [ "anyhow", "log", @@ -4793,7 +4794,7 @@ dependencies = [ [[package]] name = "sf-launcher" -version = "0.3.1" +version = "0.3.2" dependencies = [ "anyhow", "chrono", @@ -4813,7 +4814,7 @@ dependencies = [ [[package]] name = "sf-miracast" -version = "0.3.1" +version = "0.3.2" dependencies = [ "anyhow", "env_logger", @@ -4825,7 +4826,7 @@ dependencies = [ [[package]] name = "sf-remote" -version = "0.3.1" +version = "0.3.2" dependencies = [ "anyhow", "bluer", @@ -4839,8 +4840,8 @@ dependencies = [ [[package]] name = "sf-ui" -version = "0.1.0" -source = "git+https://gitea.bluefox.support/fennec/sdk?tag=v0.1.0#f00e8c68479ec5271d06be5737d5c60a831c944e" +version = "0.1.2" +source = "git+https://gitea.bluefox.support/fennec/sdk?tag=v0.1.2#cb37d872ed7195e57268e0c3a1a76367039bf959" dependencies = [ "anyhow", "glow 0.16.0", @@ -4851,7 +4852,7 @@ dependencies = [ [[package]] name = "sf-update" -version = "0.3.1" +version = "0.3.2" dependencies = [ "anyhow", "base64 0.22.1", diff --git a/Cargo.toml b/Cargo.toml index b6251d9..b49349d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,7 +3,7 @@ resolver = "3" members = ["crates/sf-ipc", "crates/sf-launcher", "crates/sf-remote", "crates/sf-dial", "crates/sf-core", "crates/sf-update", "crates/sf-miracast", "crates/sf-compositor"] [workspace.package] -version = "0.3.1" +version = "0.3.2" edition = "2024" license = "MIT" @@ -11,8 +11,8 @@ license = "MIT" sf-ipc = { path = "crates/sf-ipc" } # The Fennec SDK (app contract, UI kit), by tag. Working on it next to the OS: # see "Fennec SDK" in README.md. -sf-app = { git = "https://gitea.bluefox.support/fennec/sdk", tag = "v0.1.0" } -sf-ui = { git = "https://gitea.bluefox.support/fennec/sdk", tag = "v0.1.0" } +sf-app = { git = "https://gitea.bluefox.support/fennec/sdk", tag = "v0.1.2" } +sf-ui = { git = "https://gitea.bluefox.support/fennec/sdk", tag = "v0.1.2" } sf-dial = { path = "crates/sf-dial" } serde = { version = "1", features = ["derive"] } serde_json = "1" diff --git a/README.md b/README.md index 1b83c33..1d582a0 100644 --- a/README.md +++ b/README.md @@ -7,7 +7,7 @@ A teljes terv: `C:\Users\csike\.claude\plans\szeretnek-egy-linux-alapra-resilien - [x] **1. fázis:** launcher prototípus (Slint + OpenGL Liquid Glass réteg) és manifest-alapú appok - [x] **1b. fázis:** Siri Remote: protokoll visszafejtve (`docs/siri-remote.md`), `sf-remote` driver (gombok, ismétlés, swipe → uinput) - [x] **2. fázis:** mkosi Debian image, telepítő ISO, csak olvasható rendszer + adatpartíció -- [x] **3. fázis:** `sf-core`: appok indítása systemd scope-ban, Home-ra fagyasztás, memóriafigyelés; Chromium web runtime +- [x] **3. fázis:** `sf-core`: appok indítása systemd scope-ban, egyszerre egy app; Chromium web runtime - [x] **4. fázis:** DIAL (YouTube cast telefonról), AirPlay (UxPlay); Miracast **kísérleti**, valódi telefonnal még nincs kipróbálva - [x] **5. fázis:** saját Smithay kompozitor (`sf-compositor`): app-váltás animációval, hangerő-OSD, `wlr-randr` támogatás @@ -140,6 +140,26 @@ Az eredmény: `image/out/smartfox-installer.iso`. Az üres partíciót az `sf-data-init.service` tölti fel a `/usr/share/factory/var` gyári tartalmával. +## Raspberry Pi (4 és 5) +A Fennec OS felrakható egy meglévő 64 bites Raspberry Pi OS-re (Debian trixie, arm64). A Pi megtartja a saját rendszerét, a hálózatát (NetworkManager) és az SSH-t; a képernyőt a Fennec OS veszi át. +```sh +sudo bash /mnt/g/source/smartfox/image/pi/build.sh # WSL Debianban, keresztfordítással +scp image/out/fennec-os-pi-*-aarch64.tar.gz pi: # a Pi-re +tar xf fennec-os-pi-*-aarch64.tar.gz && sudo fennec-os-pi/install.sh # a Pi-n, aztán reboot +``` +- A telepítő a hiányzó csomagokat apt-tal rakja fel. Létrehozza a `tv` felhasználót: ez automatikusan belép a tty1-en, és elindítja a TV-felületet. Az asztal (lightdm) nem indul. +- `--no-session`: csak telepít, a Pi az asztalra bootol tovább. `--uninstall`: vissza az asztalhoz, a `tv` és az adatai maradnak. `--purge`: azokat is törli. +- A frissítés ugyanúgy csomagokból megy, az `-aarch64` shell-csomagokkal (lásd `docs/updates.md`, Architektúrák). +- **Megjelenés:** a launcher és az SDK-s appok (pl. a Netflex) az első induláskor lemérik a GPU-t. Ahol az üveghatás nem fér bele egy képkockába, matt Material stílusra váltanak. A Pi 4-en ez a Material, ezzel navigálás közben 55–60 FPS. + - A mérés eredménye a `~/.cache/fennec-glass` fájlba kerül. + - Kézzel felülírható: `SMARTFOX_GLASS=full|light|flat|material` a `/var/lib/smartfox/session.env`-ben. + - Részletek: az SDK `docs/sf-ui.md` fájljában, „Megjelenés gyengébb GPU-n”. +- **Ami Pi-n nem megy:** + - Steam: csak x86-64. + - Netflex: amíg nincs ARM-csomagja. + - A Beállítások Wi-Fi része: iwd-t vár, a Pi-n NetworkManager van. + - A Távoli hibakeresés kapcsoló: az SSH-t itt a Pi saját beállítása kezeli. + ## Alapértelmezett belépés | Felhasználó | Jelszó | Megjegyzés | |---|---|---| @@ -241,9 +261,8 @@ Ha az ébresztés megbízhatatlan, a **Képernyő kikapcsolása** mód mindig m A TV-n az appokat az `sf-core` indítja, nem a launcher. A launcher csak kér a `$XDG_RUNTIME_DIR/smartfox-core.sock` socketen (JSON sorok, `crates/sf-ipc/src/message.rs`). Ha nincs `sf-core` (Windows, fejlesztés), a launcher maga indít. - **Indítás:** minden app saját systemd user scope-ban fut (`sf-app--.scope`), saját folyamatcsoportban. A web appok a közös Chromiumot kapják, appra szabott profillal (`~/.config/smartfox/profiles/`). -- **Home:** a kompozitor a launchert hozza elő, az app 0,6 mp múlva megfagy (`systemctl --user freeze`). Újra megnyitva azonnal folytatódik (`thaw`). -- **Memória:** legfeljebb 2 app vár a háttérben, a legrégebbi bezárul. Ha 400 MB alá esik a szabad memória, a legrégebbi háttérapp bezárul (értesítés jelenik meg). -- **cage alatt** (tartalék kompozitor) nem lehet ablakot váltani, ott Home bezárja az appot. +- **Egyszerre egy app:** Home, egy másik app indítása vagy egy tükrözés (AirPlay, Miracast) bezárja a képernyőn lévő appot. A kompozitor a launchert hozza elő, az app 0,6 mp múlva, a váltás animációja után zárul be (`systemctl --user stop`); ha addig újra megnyitod, megmarad. Háttérben nem vár app, így nem foglal memóriát, és nem tartja lefoglalva a hangkimenetet. +- **cage alatt** (tartalék kompozitor) nincs animáció, ott az app azonnal bezárul. - **Háttérszolgáltatások:** az `app.toml`-ban `service = true` (AirPlay, Miracast). Az `sf-core` folyamatosan futtatja és újraindítja őket. A csempe csak a Részletek lapot nyitja. ## Castolás @@ -256,8 +275,8 @@ A TV-n az appokat az `sf-core` indítja, nem a launcher. A launcher csak kér a **AirPlay:** iPhone, iPad vagy Mac Vezérlőközpont → Képernyőtükrözés → Fennec OS. - Az UxPlay mindig fut. -- Kapcsolódáskor a kompozitor előre hozza a képét, az előtérben lévő app megfagy, a launcher értesítést mutat. -- A tükrözés végén minden visszaáll arra, ami előtte látszott. +- Kapcsolódáskor a kompozitor előre hozza a képét, az előtérben lévő app bezárul, a launcher értesítést mutat. +- A tükrözés végén a launcher látszik. **Miracast (kísérleti):** Android → Képernyő tükrözése / Smart View → Fennec OS. - Wi-Fi Directet tudó kártya kell (pl. Intel AX200/AX210). Ilyen kártya nélkül az `sf-miracast` csak naplóz, és vár. @@ -269,7 +288,7 @@ A TV-n az appokat az `sf-core` indítja, nem a launcher. A launcher csak kér a ## Kompozitor (sf-compositor) A session az `sf-compositor`-t indítja a cage helyett (`sf-session`). Ha az nem indul, vagy 20 mp-en belül összeomlik, a session cage-gel indul. Cage kényszeríthető: `SMARTFOX_COMPOSITOR=cage` a `/etc/default/smartfox` vagy a `/var/lib/smartfox/session.env` fájlban. -- **Ablakok:** minden ablak teljes képernyős, egyszerre egy látszik: a launcher vagy az az app, amelyet az `sf-core` előre hozott. A többi app ablaka rejtve, lefagyva vár. +- **Ablakok:** minden ablak teljes képernyős, egyszerre egy látszik: a launcher vagy az az app, amelyet az `sf-core` előre hozott. Egyszerre csak egy app fut. - Melyik ablak melyik appé: a kliens folyamatcsoportja (az `sf-core` bejelenti: `register `), vagy a systemd scope neve. - **Váltás:** az app kicsiből nagyítva, áttűnve jelenik meg a launcher fölött, Home-ra ugyanígy tűnik el. - **Gombok:** @@ -281,6 +300,21 @@ A session az `sf-compositor`-t indítja a cage helyett (`sf-session`). Ha az nem - **Vezérlés:** `$XDG_RUNTIME_DIR/smartfox-wm.sock`, soronként egy parancs: `focus launcher`, `focus `, `register `, `status`. - **Fejlesztés:** Linux asztalon ablakban fut: `sf-compositor --winit -- `. WSL alatt a Slint X11-et választ, ezért ott a launcher nem a beágyazott kompozitorhoz csatlakozik. +### Távoli képernyő (VNC) +Fejlesztéshez: a TV képe VNC-n látszik, és billentyűzetről vezérelhető (nyilak, Enter, Esc, mint a távirányítóval). +```sh +echo 'SMARTFOX_REMOTE_VIEW=1' | sudo tee /var/lib/smartfox/session.env # a TV-n, aztán a felület újraindítása +ssh -N -L 5900:127.0.0.1:5900 # a gépeden +``` +A VNC-kliensben (pl. TigerVNC) a cím: `localhost:5900`. +- **Biztonság:** + - A `wayvnc` csak a TV-n belülről érhető el (`127.0.0.1`), kívülről SSH-alagúton át. + - A kompozitor a képernyőmásolást (`wlr-screencopy`) és a virtuális billentyűzetet csak akkor kínálja, ha a kapcsoló be van kapcsolva. Akkor is csak a `wayvnc`-nek és a `grim`-nek, ha a felhasználójuk ugyanaz, és nem sandboxban futnak. A store appok nem látják a képernyőt, és nem gépelhetnek. +- **Kijelző nélkül:** egy HDMI-kimenet kényszeríthető a kernel parancssorában: `video=HDMI-A-1:1920x1080@60D`. Raspberry Pi-n ez a `/boot/firmware/cmdline.txt`. +- **Raspberry Pi 4:** 1080p-n kb. 5 FPS. + - A `wayvnc` 0.10 H.264-kódolója a Pi 4-en összeomlik (`v4l2m2m: Failed to enqueue buffer`; labwc alatt is), ezért alapból ki van kapcsolva. + - Ahol működik, bekapcsolható: `SMARTFOX_VNC_ARGS=--gpu` a `session.env`-ben. + ## Licenc - A Slint a GPL-3.0 alatt van használva (beágyazott eszközre a royalty-free licenc nem vonatkozik). - Az Inter betűtípus OFL licencű (`crates/sf-launcher/ui/fonts/OFL-LICENSE.txt`). diff --git a/crates/sf-compositor/Cargo.toml b/crates/sf-compositor/Cargo.toml index 6e13d01..d18828c 100644 --- a/crates/sf-compositor/Cargo.toml +++ b/crates/sf-compositor/Cargo.toml @@ -12,6 +12,8 @@ tracing = "0.1" tracing-subscriber = { version = "0.3", features = ["env-filter"] } [target.'cfg(target_os = "linux")'.dependencies] +# Volume OSD text (osd.rs): pure Rust, the font comes from the system. +ab_glyph = "0.2" smithay = { version = "0.7", default-features = false, features = [ "backend_drm", "backend_gbm", diff --git a/crates/sf-compositor/src/main.rs b/crates/sf-compositor/src/main.rs index 598b921..831e1e6 100644 --- a/crates/sf-compositor/src/main.rs +++ b/crates/sf-compositor/src/main.rs @@ -16,8 +16,12 @@ #[cfg(target_os = "linux")] mod control; #[cfg(target_os = "linux")] +mod osd; +#[cfg(target_os = "linux")] mod output_mgmt; #[cfg(target_os = "linux")] +mod screencopy; +#[cfg(target_os = "linux")] mod state; #[cfg(target_os = "linux")] mod udev; diff --git a/crates/sf-compositor/src/osd.rs b/crates/sf-compositor/src/osd.rs new file mode 100644 index 0000000..a1c7b7f --- /dev/null +++ b/crates/sf-compositor/src/osd.rs @@ -0,0 +1,234 @@ +//! The volume OSD: a dark pill at the top of the screen with a speaker +//! icon, a level bar and the level as a number ("Némítva" when muted), in +//! the style of the launcher's status pill. +//! +//! Drawn on the CPU into a small image (anti-aliased shapes, text from the +//! system's Noto Sans), only when the level, the mute state or the output +//! size changes; the compositor shows it as one textured element. + +use ab_glyph::{Font, FontVec, PxScale, ScaleFont}; +use smithay::backend::allocator::Fourcc; +use smithay::backend::renderer::element::memory::MemoryRenderBuffer; +use smithay::utils::Transform; + +/// Size at 1080p (scaled with the output height). +const W: f32 = 460.0; +const H: f32 = 76.0; +const TOP: f32 = 48.0; +const PAD: f32 = 30.0; +const ICON: f32 = 34.0; +const TEXT_W: f32 = 112.0; +const TEXT_PX: f32 = 28.0; + +const FONTS: &[&str] = &[ + "/usr/share/fonts/truetype/noto/NotoSans-SemiBold.ttf", + "/usr/share/fonts/truetype/noto/NotoSans-Bold.ttf", + "/usr/share/fonts/truetype/noto/NotoSans-Regular.ttf", + "/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", +]; + +#[derive(Clone, Copy, PartialEq)] +struct Key { + percent: u32, + muted: bool, + out: (i32, i32), +} + +#[derive(Default)] +pub struct VolumeOsd { + font: Option, + font_tried: bool, + cached: Option<(Key, MemoryRenderBuffer, (i32, i32))>, +} + +impl VolumeOsd { + /// The OSD image for this level and output size, and where it goes + /// (top-left corner, physical px). + pub fn image(&mut self, level: f32, muted: bool, out: (i32, i32)) -> (&MemoryRenderBuffer, (i32, i32)) { + let key = Key { percent: (level.clamp(0.0, 1.0) * 100.0).round() as u32, muted, out }; + if self.cached.as_ref().is_none_or(|(k, _, _)| *k != key) { + if !self.font_tried { + self.font_tried = true; + self.font = FONTS.iter().find_map(|p| std::fs::read(p).ok().and_then(|d| FontVec::try_from_vec(d).ok())); + if self.font.is_none() { + tracing::warn!("volume OSD: no font found, showing the bar only"); + } + } + let k = (out.1 as f32 / 1080.0).max(0.5); + let (w, h) = ((W * k).round() as usize, (H * k).round() as usize); + let px = draw(w, h, k, key.percent, muted, self.font.as_ref()); + let buf = MemoryRenderBuffer::from_slice(&px, Fourcc::Argb8888, (w as i32, h as i32), 1, Transform::Normal, None); + let at = ((out.0 - w as i32) / 2, (TOP * k).round() as i32); + self.cached = Some((key, buf, at)); + } + let (_, buf, at) = self.cached.as_ref().unwrap(); + (buf, *at) + } +} + +/// Premultiplied RGBA, f32. +struct Canvas { + w: usize, + h: usize, + px: Vec<[f32; 4]>, +} + +impl Canvas { + fn over(&mut self, x: usize, y: usize, rgb: [f32; 3], a: f32) { + if x >= self.w || y >= self.h || a <= 0.0 { + return; + } + let d = &mut self.px[y * self.w + x]; + let a = a.min(1.0); + for i in 0..3 { + d[i] = rgb[i] * a + d[i] * (1.0 - a); + } + d[3] = a + d[3] * (1.0 - a); + } + + /// A shape given by its signed distance (px, negative inside), drawn + /// with a one-pixel anti-aliased edge, within the box x0..x1, y0..y1. + fn shape(&mut self, (x0, y0, x1, y1): (f32, f32, f32, f32), rgb: [f32; 3], a: f32, sd: impl Fn(f32, f32) -> f32) { + let (xa, ya) = (x0.floor().max(0.0) as usize, y0.floor().max(0.0) as usize); + let (xb, yb) = ((x1.ceil() as usize).min(self.w), (y1.ceil() as usize).min(self.h)); + for y in ya..yb { + for x in xa..xb { + let cov = (0.5 - sd(x as f32 + 0.5, y as f32 + 0.5)).clamp(0.0, 1.0); + self.over(x, y, rgb, a * cov); + } + } + } + + /// BGRA bytes, premultiplied (DRM ARGB8888, little endian). + fn bytes(&self) -> Vec { + let mut out = Vec::with_capacity(self.px.len() * 4); + for p in &self.px { + let c = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + out.extend_from_slice(&[c(p[2]), c(p[1]), c(p[0]), c(p[3])]); + } + out + } +} + +fn round_rect(px: f32, py: f32, (x, y, w, h): (f32, f32, f32, f32), r: f32) -> f32 { + let (hw, hh) = (w * 0.5, h * 0.5); + let (qx, qy) = ((px - x - hw).abs() - hw + r, (py - y - hh).abs() - hh + r); + qx.max(qy).min(0.0) + (qx.max(0.0).hypot(qy.max(0.0))) - r +} + +/// Distance to the segment a-b, minus half the stroke width. +fn capsule(px: f32, py: f32, (ax, ay): (f32, f32), (bx, by): (f32, f32), half: f32) -> f32 { + let (pax, pay, bax, bay) = (px - ax, py - ay, bx - ax, by - ay); + let t = ((pax * bax + pay * bay) / (bax * bax + bay * bay)).clamp(0.0, 1.0); + (pax - bax * t).hypot(pay - bay * t) - half +} + +const WHITE: [f32; 3] = [1.0, 1.0, 1.0]; + +fn draw(w: usize, h: usize, k: f32, percent: u32, muted: bool, font: Option<&FontVec>) -> Vec { + let mut c = Canvas { w, h, px: vec![[0.0; 4]; w * h] }; + let (wf, hf) = (w as f32, h as f32); + let all = (0.0, 0.0, wf, hf); + let pill = (0.5, 0.5, wf - 1.0, hf - 1.0); + let r = hf * 0.5 - 0.5; + + // Pill: dark, nearly opaque, with a faint light rim. + c.shape(all, [0.09, 0.09, 0.11], 0.92, |x, y| round_rect(x, y, pill, r)); + c.shape(all, WHITE, 0.14, |x, y| { + let d = round_rect(x, y, pill, r); + (d + 0.75 * k).abs() - 0.75 * k + }); + + // Speaker: a small box and a cone, then sound waves (or a cross when muted). + let s = ICON * k; + let (ix, iy) = (PAD * k, (hf - s) * 0.5); + let cy = iy + s * 0.5; + let ink = if muted { 0.55 } else { 1.0 }; + c.shape((ix, iy, ix + s * 0.3, iy + s), WHITE, ink, |x, y| round_rect(x, y, (ix, cy - s * 0.17, s * 0.24, s * 0.34), 1.5 * k)); + c.shape((ix, iy, ix + s * 0.62, iy + s), WHITE, ink, |x, y| { + // Cone: from the box (x = 0.20 s, half height 0.17 s) to x = 0.56 s (half height 0.42 s). + let (x0, x1, h0, h1) = (ix + s * 0.20, ix + s * 0.56, s * 0.17, s * 0.42); + let t = ((x - x0) / (x1 - x0)).clamp(0.0, 1.0); + let half = h0 + (h1 - h0) * t; + let dy = (y - cy).abs() - half; + let dx = (x0 - x).max(x - x1); + // Slanted edge: scale the vertical distance by the edge's slope. + let slope = ((h1 - h0) / (x1 - x0)).hypot(1.0); + dx.max(dy / slope) + }); + let ax = ix + s * 0.56; + if muted { + let (x0, x1, half) = (ax + s * 0.14, ax + s * 0.46, s * 0.16); + let st = 1.3 * k; + c.shape((ax, iy, ix + s * 1.2, iy + s), WHITE, 0.85, |x, y| { + capsule(x, y, (x0, cy - half), (x1, cy + half), st).min(capsule(x, y, (x0, cy + half), (x1, cy - half), st)) + }); + } else { + let waves = if percent == 0 { 0 } else if percent < 34 { 1 } else if percent < 67 { 2 } else { 3 }; + for i in 0..3 { + let rad = s * (0.18 + 0.17 * i as f32); + let a = if i < waves { 1.0 } else { 0.25 }; + let st = 1.4 * k; + c.shape((ax, iy - 2.0, ix + s * 1.3, iy + s + 2.0), WHITE, a, |x, y| { + let (dx, dy) = (x - (ax - s * 0.06), y - cy); + let ring = (dx.hypot(dy) - rad).abs() - st; + // Only the right-hand 90 degrees of the circle. + let cone = dy.abs() - dx * 0.9; + ring.max(cone) + }); + } + } + + // Level bar. + let bx0 = (PAD + ICON + 24.0) * k; + let bx1 = wf - (PAD + TEXT_W + 16.0) * k; + let bh = 8.0 * k; + let bar = (bx0, (hf - bh) * 0.5, bx1 - bx0, bh); + c.shape(all, WHITE, 0.22, |x, y| round_rect(x, y, bar, bh * 0.5)); + let level = percent as f32 / 100.0; + if level > 0.0 { + let fill = (bar.0, bar.1, (bar.2 * level).max(bh), bh); + c.shape(all, WHITE, if muted { 0.45 } else { 1.0 }, |x, y| round_rect(x, y, fill, bh * 0.5)); + } + + // The number, right-aligned. + if let Some(font) = font { + let text = if muted { "Némítva".to_string() } else { percent.to_string() }; + let px = if muted { TEXT_PX * 0.86 } else { TEXT_PX } * k; + let sf = font.as_scaled(PxScale::from(px)); + let width: f32 = text.chars().map(|ch| sf.h_advance(font.glyph_id(ch))).sum(); + let mut x = wf - PAD * k - width; + let baseline = hf * 0.5 + (sf.ascent() + sf.descent()) * 0.5; + for ch in text.chars() { + let id = font.glyph_id(ch); + let glyph = id.with_scale_and_position(px, ab_glyph::point(x, baseline)); + if let Some(outline) = font.outline_glyph(glyph) { + let b = outline.px_bounds(); + outline.draw(|gx, gy, cov| { + let (px_, py_) = (b.min.x as i32 + gx as i32, b.min.y as i32 + gy as i32); + if px_ >= 0 && py_ >= 0 { + c.over(px_ as usize, py_ as usize, WHITE, cov * if muted { 0.8 } else { 1.0 }); + } + }); + } + x += sf.h_advance(id); + } + } + c.bytes() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn draws_a_pill() { + let (w, h) = (460, 76); + let px = draw(w, h, 1.0, 45, false, None); + assert_eq!(px.len(), w * h * 4); + // Corners are transparent (rounded), the middle of the pill is not. + assert_eq!(px[3], 0); + let mid = (h / 2 * w + w / 2) * 4; + assert!(px[mid + 3] > 200); + } +} diff --git a/crates/sf-compositor/src/screencopy.rs b/crates/sf-compositor/src/screencopy.rs new file mode 100644 index 0000000..30fbd79 --- /dev/null +++ b/crates/sf-compositor/src/screencopy.rs @@ -0,0 +1,323 @@ +//! Remote viewing for development: wlr-screencopy (v3) and the virtual +//! keyboard, so `wayvnc` can show the TV and send keys (README, "Távoli +//! képernyő (VNC)"). +//! +//! Both are off unless the session sets `SMARTFOX_REMOTE_VIEW=1`, and even +//! then only trusted programs get them (`trusted`): sandboxed store apps +//! must not read the screen or type into other apps. +//! +//! A copy request waits for the next frame the backend renders and gets the +//! same render elements, drawn into the client's buffer (dmabuf: on the GPU, +//! which wayvnc's H.264 encoder needs; shm: read back). + +use std::os::unix::fs::MetadataExt; +use std::sync::Mutex; +use std::time::Duration; + +use anyhow::{Context, Result, anyhow, bail}; +use smithay::backend::allocator::{Buffer, Fourcc}; +use smithay::backend::allocator::dmabuf::Dmabuf; +use smithay::backend::renderer::gles::{GlesRenderbuffer, GlesRenderer}; +use smithay::backend::renderer::utils::draw_render_elements; +use smithay::backend::renderer::{Bind, ExportMem, Frame, Offscreen, Renderer, TextureMapping}; +use smithay::reexports::wayland_protocols_wlr::screencopy::v1::server::{ + zwlr_screencopy_frame_v1::{self, ZwlrScreencopyFrameV1}, + zwlr_screencopy_manager_v1::{self, ZwlrScreencopyManagerV1}, +}; +use smithay::reexports::wayland_server::backend::GlobalId; +use smithay::reexports::wayland_server::protocol::{wl_buffer::WlBuffer, wl_shm}; +use smithay::reexports::wayland_server::{Client, DataInit, Dispatch, DisplayHandle, GlobalDispatch, New, Resource}; +use smithay::utils::{Physical, Rectangle, Size, Transform}; +use smithay::wayland::dmabuf::get_dmabuf; +use smithay::wayland::shm::with_buffer_contents_mut; + +use crate::state::{SfElement, State}; + +const VERSION: u32 = 3; +/// Programs that may capture the screen and type: the VNC server, and grim +/// for screenshots. +const TRUSTED: &[&str] = &["wayvnc", "grim"]; + +/// Whether remote viewing is switched on for this session. +pub fn enabled() -> bool { + std::env::var("SMARTFOX_REMOTE_VIEW").is_ok_and(|v| v == "1") +} + +/// Whether a newly connected client may capture and type: one of +/// `TRUSTED`, running as our user, and outside any sandbox (bubblewrap gives +/// every store app its own mount namespace). Decided from the socket before +/// the client is inserted, and kept in its `ClientState`: asking the display +/// for credentials from inside a dispatch (can_view, filters) deadlocks. +pub fn trusted_peer(stream: &std::os::unix::net::UnixStream) -> bool { + use smithay::reexports::rustix; + let Ok(cred) = rustix::net::sockopt::socket_peercred(stream) else { return false }; + let pid = rustix::process::Pid::as_raw(Some(cred.pid)); + let proc = format!("/proc/{pid}"); + let same_user = std::fs::metadata("/proc/self").ok().map(|m| m.uid()) == Some(cred.uid.as_raw()); + let ns = |p: &str| std::fs::read_link(format!("{p}/ns/mnt")).ok(); + let same_ns = ns("/proc/self").is_some() && ns("/proc/self") == ns(&proc); + let exe = std::fs::read_link(format!("{proc}/exe")).ok(); + let name = exe.as_ref().and_then(|e| e.file_name()).and_then(|n| n.to_str()).unwrap_or("").to_string(); + let ok = same_user && same_ns && TRUSTED.contains(&name.as_str()); + if ok { + tracing::info!("remote view: pid {pid} ({name}) may capture and type"); + } + ok +} + +/// What `trusted_peer` said when the client connected. +pub fn trusted(client: &Client) -> bool { + client.get_data::().is_some_and(|d| d.remote_view) +} + +pub struct ScreencopyState { + _global: GlobalId, +} + +impl ScreencopyState { + pub fn new(dh: &DisplayHandle) -> Self { + let global = dh.create_global::(VERSION, ()); + ScreencopyState { _global: global } + } +} + +/// A copy waiting for the next rendered frame. +pub struct Pending { + frame: ZwlrScreencopyFrameV1, + buffer: WlBuffer, + with_damage: bool, +} + +/// What a frame object captures. +pub struct FrameData { + size: Size, + /// The output isn't there (or a region was asked for): every copy fails. + unusable: bool, + used: Mutex, +} + +impl GlobalDispatch for State { + fn bind(_: &mut State, _: &DisplayHandle, _: &Client, resource: New, _: &(), init: &mut DataInit<'_, State>) { + init.init(resource, ()); + } + + fn can_view(client: Client, _: &()) -> bool { + trusted(&client) + } +} + +impl Dispatch for State { + fn request( + state: &mut State, + _: &Client, + _: &ZwlrScreencopyManagerV1, + request: zwlr_screencopy_manager_v1::Request, + _: &(), + _: &DisplayHandle, + init: &mut DataInit<'_, State>, + ) { + let (frame, region) = match request { + zwlr_screencopy_manager_v1::Request::CaptureOutput { frame, .. } => (frame, false), + // Regions aren't supported (wayvnc and grim take the whole output). + zwlr_screencopy_manager_v1::Request::CaptureOutputRegion { frame, .. } => (frame, true), + zwlr_screencopy_manager_v1::Request::Destroy => return, + _ => return, + }; + let size = state.output_size(); + let unusable = region || state.output.is_none(); + let frame = init.init(frame, FrameData { size, unusable, used: Mutex::new(false) }); + if unusable { + frame.failed(); + return; + } + let (w, h) = (size.w as u32, size.h as u32); + frame.buffer(wl_shm::Format::Xrgb8888, w, h, w * 4); + if frame.version() >= 3 { + frame.linux_dmabuf(Fourcc::Xrgb8888 as u32, w, h); + frame.buffer_done(); + } + } +} + +impl Dispatch for State { + fn request( + state: &mut State, + _: &Client, + frame: &ZwlrScreencopyFrameV1, + request: zwlr_screencopy_frame_v1::Request, + data: &FrameData, + _: &DisplayHandle, + _: &mut DataInit<'_, State>, + ) { + let (buffer, with_damage) = match request { + zwlr_screencopy_frame_v1::Request::Copy { buffer } => (buffer, false), + zwlr_screencopy_frame_v1::Request::CopyWithDamage { buffer } => (buffer, true), + _ => return, + }; + { + let mut used = data.used.lock().unwrap(); + if *used { + frame.post_error(zwlr_screencopy_frame_v1::Error::AlreadyUsed, "frame already used"); + return; + } + *used = true; + } + if data.unusable || data.size != state.output_size() { + frame.failed(); + return; + } + state.screencopies.push(Pending { frame: frame.clone(), buffer, with_damage }); + } +} + +/// Answers the copies waiting for a frame, with the elements the backend +/// just rendered. `damaged`: the frame changed (copy-with-damage waits for +/// that; a plain copy is answered right away). +pub fn fulfil(state: &mut State, renderer: &mut GlesRenderer, elements: &[SfElement], damaged: bool) { + let size = state.output_size(); + let pending = std::mem::take(&mut state.screencopies); + let (ready, waiting): (Vec<_>, Vec<_>) = pending.into_iter().partition(|p| damaged || !p.with_damage); + state.screencopies = waiting.into_iter().filter(|p| p.frame.is_alive()).collect(); + if ready.is_empty() { + return; + } + let time: Duration = state.clock.now().into(); + for p in ready { + if !p.frame.is_alive() { + continue; + } + let result = match get_dmabuf(&p.buffer) { + Ok(dmabuf) => draw_dmabuf(renderer, &mut dmabuf.clone(), size, elements), + Err(_) => draw_shm(renderer, &p.buffer, size, elements), + }; + match result { + Ok(()) => { + p.frame.flags(zwlr_screencopy_frame_v1::Flags::empty()); + if p.with_damage { + p.frame.damage(0, 0, size.w as u32, size.h as u32); + } + let secs = time.as_secs(); + p.frame.ready((secs >> 32) as u32, secs as u32, time.subsec_nanos()); + } + Err(e) => { + tracing::warn!("screencopy: {e:#}"); + p.frame.failed(); + } + } + } +} + +fn draw(renderer: &mut GlesRenderer, fb: &mut ::Framebuffer<'_>, size: Size, elements: &[SfElement]) -> Result<()> { + let all = [Rectangle::from_size(size)]; + let mut frame = renderer.render(fb, size, Transform::Normal).map_err(|e| anyhow!("render: {e:?}"))?; + frame.clear([0.0, 0.0, 0.0, 1.0].into(), &all).map_err(|e| anyhow!("clear: {e:?}"))?; + draw_render_elements::(&mut frame, 1.0, elements, &all).map_err(|e| anyhow!("draw: {e:?}"))?; + let sync = frame.finish().map_err(|e| anyhow!("finish: {e:?}"))?; + renderer.wait(&sync).map_err(|e| anyhow!("wait: {e:?}"))?; + Ok(()) +} + +/// Straight into the client's dmabuf, on the GPU. +fn draw_dmabuf(renderer: &mut GlesRenderer, dmabuf: &mut Dmabuf, size: Size, elements: &[SfElement]) -> Result<()> { + if (dmabuf.width() as i32, dmabuf.height() as i32) != (size.w, size.h) { + bail!("dmabuf is {}x{}, the output {}x{}", dmabuf.width(), dmabuf.height(), size.w, size.h); + } + let mut fb = renderer.bind(dmabuf).map_err(|e| anyhow!("binding the dmabuf: {e:?}"))?; + draw(renderer, &mut fb, size, elements) +} + +/// Into an offscreen buffer, read back into the client's shm buffer. +fn draw_shm(renderer: &mut GlesRenderer, buffer: &WlBuffer, size: Size, elements: &[SfElement]) -> Result<()> { + let buf_size = Size::from((size.w, size.h)); + let mut rb: GlesRenderbuffer = renderer.create_buffer(Fourcc::Abgr8888, buf_size).map_err(|e| anyhow!("offscreen buffer: {e:?}"))?; + let mut fb = renderer.bind(&mut rb).map_err(|e| anyhow!("binding: {e:?}"))?; + draw(renderer, &mut fb, size, elements)?; + let mapping = renderer + .copy_framebuffer(&fb, Rectangle::from_size(buf_size), Fourcc::Xrgb8888) + .map_err(|e| anyhow!("read back: {e:?}"))?; + let flipped = mapping.flipped(); + let pixels = renderer.map_texture(&mapping).map_err(|e| anyhow!("map: {e:?}"))?; + let row = size.w as usize * 4; + let rows = size.h as usize; + anyhow::ensure!(pixels.len() >= row * rows, "short read back"); + with_buffer_contents_mut(buffer, |ptr, len, data| -> Result<()> { + if !matches!(data.format, wl_shm::Format::Xrgb8888 | wl_shm::Format::Argb8888) || (data.width, data.height) != (size.w, size.h) { + bail!("unexpected shm buffer {}x{} {:?}", data.width, data.height, data.format); + } + let stride = data.stride as usize; + let offset = data.offset as usize; + anyhow::ensure!(stride >= row && offset + stride * (rows - 1) + row <= len, "shm buffer too small"); + // SAFETY: bounds checked above; the pool stays mapped during the call. + let dst = unsafe { std::slice::from_raw_parts_mut(ptr.add(offset), len - offset) }; + for y in 0..rows { + // GL reads rows bottom-up unless the mapping says it is already flipped. + let src_y = if flipped { y } else { rows - 1 - y }; + dst[y * stride..y * stride + row].copy_from_slice(&pixels[src_y * row..src_y * row + row]); + } + Ok(()) + }) + .context("shm buffer")? +} + +// ---- virtual pointer ------------------------------------------------------ +// wayvnc won't start input without wlr-virtual-pointer. The TV has no +// pointer, so the device exists and its events are dropped; keys go through +// the virtual keyboard. + +use smithay::reexports::wayland_protocols_wlr::virtual_pointer::v1::server::{ + zwlr_virtual_pointer_manager_v1::{self, ZwlrVirtualPointerManagerV1}, + zwlr_virtual_pointer_v1::{self, ZwlrVirtualPointerV1}, +}; + +pub struct VirtualPointerState { + _global: GlobalId, +} + +impl VirtualPointerState { + pub fn new(dh: &DisplayHandle) -> Self { + VirtualPointerState { _global: dh.create_global::(2, ()) } + } +} + +impl GlobalDispatch for State { + fn bind(_: &mut State, _: &DisplayHandle, _: &Client, resource: New, _: &(), init: &mut DataInit<'_, State>) { + init.init(resource, ()); + } + + fn can_view(client: Client, _: &()) -> bool { + trusted(&client) + } +} + +impl Dispatch for State { + fn request( + _: &mut State, + _: &Client, + _: &ZwlrVirtualPointerManagerV1, + request: zwlr_virtual_pointer_manager_v1::Request, + _: &(), + _: &DisplayHandle, + init: &mut DataInit<'_, State>, + ) { + match request { + zwlr_virtual_pointer_manager_v1::Request::CreateVirtualPointer { id, .. } + | zwlr_virtual_pointer_manager_v1::Request::CreateVirtualPointerWithOutput { id, .. } => { + init.init(id, ()); + } + _ => {} + } + } +} + +impl Dispatch for State { + fn request( + _: &mut State, + _: &Client, + _: &ZwlrVirtualPointerV1, + _: zwlr_virtual_pointer_v1::Request, + _: &(), + _: &DisplayHandle, + _: &mut DataInit<'_, State>, + ) { + } +} diff --git a/crates/sf-compositor/src/state.rs b/crates/sf-compositor/src/state.rs index 1f246df..5820a52 100644 --- a/crates/sf-compositor/src/state.rs +++ b/crates/sf-compositor/src/state.rs @@ -12,7 +12,7 @@ use std::time::{Duration, Instant}; use smithay::backend::input::{Event, InputBackend, InputEvent, KeyState, KeyboardKeyEvent}; use smithay::backend::renderer::element::Kind; -use smithay::backend::renderer::element::solid::{SolidColorBuffer, SolidColorRenderElement}; +use smithay::backend::renderer::element::memory::MemoryRenderBufferRenderElement; use smithay::backend::renderer::element::surface::WaylandSurfaceRenderElement; use smithay::backend::renderer::element::utils::RescaleRenderElement; use smithay::backend::renderer::element::AsRenderElements; @@ -56,10 +56,11 @@ use smithay::wayland::shell::xdg::{ use smithay::wayland::shm::{ShmHandler, ShmState}; use smithay::wayland::socket::ListeningSocketSource; use smithay::wayland::viewporter::ViewporterState; +use smithay::wayland::virtual_keyboard::VirtualKeyboardManagerState; use smithay::{ delegate_compositor, delegate_data_device, delegate_dmabuf, delegate_output, delegate_pointer_constraints, delegate_presentation, delegate_relative_pointer, delegate_seat, delegate_shm, delegate_viewporter, - delegate_xdg_decoration, delegate_xdg_shell, + delegate_virtual_keyboard_manager, delegate_xdg_decoration, delegate_xdg_shell, }; use crate::output_mgmt::{OutputMgmtState, PendingConfig}; @@ -84,12 +85,16 @@ const KEY_MUTE: u32 = 113 + 8; const KEY_VOLUMEDOWN: u32 = 114 + 8; const KEY_VOLUMEUP: u32 = 115 + 8; const KEY_HOMEPAGE: u32 = 172 + 8; +const KEY_SPACE: u32 = 57 + 8; +/// Play/pause keys: the remote's (KEY_PLAYPAUSE), Bluetooth speakers and +/// HDMI-CEC (play, pause, the CD variants). +const MEDIA_PLAY_KEYS: [u32; 5] = [164 + 8, 207 + 8, 119 + 8, 200 + 8, 201 + 8]; smithay::backend::renderer::element::render_elements! { pub SfElement<=GlesRenderer>; Surface=WaylandSurfaceRenderElement, Scaled=RescaleRenderElement>, - Solid=SolidColorRenderElement, + Memory=MemoryRenderBufferRenderElement, } /// The event loop data: protocol state plus the display backend. @@ -196,6 +201,11 @@ pub struct State { pub clock: Clock, pub output_mgmt: OutputMgmtState, pub pending_configs: Vec, + /// Remote viewing (SMARTFOX_REMOTE_VIEW=1): screencopy and virtual + /// keyboard for wayvnc; screen copies waiting for the next frame. + #[allow(dead_code)] + remote_view: Option<(crate::screencopy::ScreencopyState, VirtualKeyboardManagerState, crate::screencopy::VirtualPointerState)>, + pub screencopies: Vec, pub popups: PopupManager, pub seat: Seat, pub space: Space, @@ -216,9 +226,7 @@ pub struct State { pub visible: Option, pub transition: Option, pub osd: Option, - osd_bg: SolidColorBuffer, - osd_track: SolidColorBuffer, - osd_fill: SolidColorBuffer, + osd_art: crate::osd::VolumeOsd, /// False while the screen is turned off (wlr-randr --off / standby). pub screen_on: bool, } @@ -226,6 +234,8 @@ pub struct State { #[derive(Default)] pub struct ClientState { pub compositor_state: CompositorClientState, + /// May use screencopy and the virtual keyboard (crate::screencopy). + pub remote_view: bool, } impl ClientData for ClientState { @@ -312,6 +322,14 @@ impl State { let relative_pointer_state = RelativePointerManagerState::new::(&dh); let pointer_constraints_state = PointerConstraintsState::new::(&dh); let output_mgmt = OutputMgmtState::new(&dh); + let remote_view = crate::screencopy::enabled().then(|| { + tracing::info!("remote view on: screencopy and virtual keyboard for wayvnc"); + ( + crate::screencopy::ScreencopyState::new(&dh), + VirtualKeyboardManagerState::new::(&dh, crate::screencopy::trusted), + crate::screencopy::VirtualPointerState::new(&dh), + ) + }); let mut seat: Seat = seat_state.new_wl_seat(&dh, "seat0"); // Same repeat as cage/wlroots: 600 ms delay, 25 per second. @@ -321,12 +339,14 @@ impl State { // relative pointer and pointer constraints work on a wl_pointer. seat.add_pointer(); + let remote_view_on = remote_view.is_some(); let socket = ListeningSocketSource::new_auto()?; let socket_name = socket.socket_name().to_os_string(); let handle = event_loop.handle(); handle - .insert_source(socket, |stream, _, app: &mut App| { - if let Err(e) = app.state.dh.insert_client(stream, Arc::new(ClientState::default())) { + .insert_source(socket, move |stream, _, app: &mut App| { + let data = ClientState { remote_view: remote_view_on && crate::screencopy::trusted_peer(&stream), ..Default::default() }; + if let Err(e) = app.state.dh.insert_client(stream, Arc::new(data)) { tracing::warn!("client: {e}"); } }) @@ -363,6 +383,8 @@ impl State { clock, output_mgmt, pending_configs: vec![], + remote_view, + screencopies: vec![], popups: PopupManager::default(), seat, space: Space::default(), @@ -378,9 +400,7 @@ impl State { visible: None, transition: None, osd: None, - osd_bg: SolidColorBuffer::default(), - osd_track: SolidColorBuffer::default(), - osd_fill: SolidColorBuffer::default(), + osd_art: Default::default(), screen_on: true, }) } @@ -582,6 +602,7 @@ impl State { let time = Event::time_msec(&event); let pressed = event.state() == KeyState::Pressed; let Some(kb) = self.seat.get_keyboard() else { return }; + let keycode = self.remap_media_key(&kb, event.key_code()); enum Action { Home, Volume(i32), @@ -591,7 +612,7 @@ impl State { /// Release or repeat of a key we handle: keep it from the app. Swallow, } - let action = kb.input::(self, event.key_code(), event.state(), serial, time, |_, mods, key| { + let action = kb.input::(self, keycode, event.state(), serial, time, |_, mods, key| { let code = key.raw_code().raw(); let sym = key.modified_sym().raw(); let hit = match code { @@ -631,6 +652,24 @@ impl State { } } + /// Play/pause for apps that can't see media keys. Slint (the Fennec SDK's + /// UI toolkit) has no media keys, so native apps get play/pause as + /// space, which they treat as play/pause. The web runtime (Chromium) + /// handles media keys itself and gets them as they are. + fn remap_media_key(&self, kb: &smithay::input::keyboard::KeyboardHandle, code: smithay::input::keyboard::Keycode) -> smithay::input::keyboard::Keycode { + if !MEDIA_PLAY_KEYS.contains(&code.raw()) { + return code; + } + let browser = kb + .current_focus() + .and_then(|s| s.client()) + .and_then(|c| c.get_credentials(&self.dh).ok()) + .and_then(|cred| std::fs::read_link(format!("/proc/{}/exe", cred.pid)).ok()) + .and_then(|exe| exe.file_name().map(|n| n.to_string_lossy().to_lowercase())) + .is_some_and(|name| name.contains("chrom")); + if browser { code } else { KEY_SPACE.into() } + } + /// Volume up/down by `delta` percent, or toggle mute (`None`), then show the OSD. fn change_volume(&mut self, delta: Option) { let (tx, rx) = smithay::reexports::calloop::channel::channel::<(f32, bool)>(); @@ -674,24 +713,16 @@ impl State { let size = self.output_size(); let now = Instant::now(); - // Volume OSD: a pill near the bottom with a level bar. + // Volume OSD (osd.rs): a pill at the top with icon, bar and number. if let Some(osd) = &self.osd { if now < osd.until { let fade = ((osd.until - now).as_secs_f32() / 0.3).min(1.0); - let (w, h) = (size.w as f32, size.h as f32); - let bar_w = (w * 0.26) as i32; - let bar_h = (h * 0.010).max(8.0) as i32; - let pad = (h * 0.022) as i32; - let x = (size.w - bar_w) / 2; - let y = (h * 0.86) as i32; - let fill_w = ((bar_w as f32) * osd.level.clamp(0.0, 1.0)) as i32; - let fill = if osd.muted { [1.0, 0.42, 0.42, 0.95] } else { [1.0, 1.0, 1.0, 0.95] }; - self.osd_fill.update((fill_w.max(1), bar_h), fill); - self.osd_track.update((bar_w, bar_h), [1.0, 1.0, 1.0, 0.22]); - self.osd_bg.update((bar_w + 2 * pad, bar_h + 2 * pad), [0.04, 0.05, 0.08, 0.72]); - out.push(SolidColorRenderElement::from_buffer(&self.osd_fill, (x, y), 1.0, fade, Kind::Unspecified).into()); - out.push(SolidColorRenderElement::from_buffer(&self.osd_track, (x, y), 1.0, fade, Kind::Unspecified).into()); - out.push(SolidColorRenderElement::from_buffer(&self.osd_bg, (x - pad, y - pad), 1.0, fade, Kind::Unspecified).into()); + let (level, muted) = (osd.level, osd.muted); + let (buf, at) = self.osd_art.image(level, muted, (size.w, size.h)); + match MemoryRenderBufferRenderElement::from_buffer(renderer, (at.0 as f64, at.1 as f64), buf, Some(fade), None, None, Kind::Unspecified) { + Ok(el) => out.push(el.into()), + Err(e) => tracing::warn!("volume OSD: {e:?}"), + } } else { self.osd = None; } @@ -1015,3 +1046,4 @@ delegate_viewporter!(State); delegate_presentation!(State); delegate_relative_pointer!(State); delegate_pointer_constraints!(State); +delegate_virtual_keyboard_manager!(State); diff --git a/crates/sf-compositor/src/udev.rs b/crates/sf-compositor/src/udev.rs index 382e541..29c3acb 100644 --- a/crates/sf-compositor/src/udev.rs +++ b/crates/sf-compositor/src/udev.rs @@ -65,14 +65,38 @@ pub struct UdevData { retry_scheduled: bool, } +/// The GPU that drives the screen. On a PC that's the primary GPU. On ARM +/// boards the display and the 3D engine are separate DRM devices (Raspberry +/// Pi: vc4 has the HDMI ports, v3d only renders), so a card without display +/// connectors is skipped; mesa renders on v3d through the vc4 device. +fn pick_gpu(seat: &str) -> Result { + let primary = primary_gpu(seat)?; + let all = all_gpus(seat).unwrap_or_default(); + let candidates: Vec<_> = primary.iter().cloned().chain(all.into_iter().filter(|p| Some(p) != primary.as_ref())).collect(); + candidates + .iter() + .find(|p| has_connectors(p)) + .or(candidates.first()) + .cloned() + .context("no GPU found") +} + +/// Whether a DRM card (/dev/dri/cardN) has display connectors, from sysfs +/// (/sys/class/drm/cardN-HDMI-A-1 ...). +fn has_connectors(path: &std::path::Path) -> bool { + let Some(card) = path.file_name().and_then(|n| n.to_str()) else { return false }; + let prefix = format!("{card}-"); + std::fs::read_dir("/sys/class/drm") + .map(|dir| dir.flatten().any(|e| e.file_name().to_str().is_some_and(|n| n.starts_with(&prefix) && !n.contains("Writeback")))) + .unwrap_or(false) +} + pub fn init(event_loop: &mut EventLoop<'static, App>, state: &mut State) -> Result { let (session, notifier) = LibSeatSession::new().map_err(|e| anyhow!("libseat session: {e}"))?; state.session = Some(session.clone()); let seat = session.seat(); - let path = primary_gpu(&seat)? - .or_else(|| all_gpus(&seat).ok()?.into_iter().next()) - .context("no GPU found")?; + let path = pick_gpu(&seat)?; tracing::info!("GPU {}", path.display()); let mut session_for_open = session.clone(); let fd = session_for_open @@ -93,6 +117,8 @@ pub fn init(event_loop: &mut EventLoop<'static, App>, state: &mut State) -> Resu state.shm_state.update_formats(renderer.shm_formats()); let dmabuf_formats = renderer.dmabuf_formats(); + // Clients render on the GPU's render node (Raspberry Pi: v3d). Not the + // display device: mesa would fall back to software rendering on vc4. let feedback = DmabufFeedbackBuilder::new(render_node.dev_id(), dmabuf_formats.clone()) .build() .map_err(|e| anyhow!("dmabuf feedback: {e}"))?; @@ -350,6 +376,9 @@ impl UdevData { false } }; + if !state.screencopies.is_empty() { + crate::screencopy::fulfil(state, &mut self.renderer, &elements, rendered); + } if rendered { match out.drm_output.queue_frame(state.presentation_feedback()) { Ok(()) => out.frame_pending = true, diff --git a/crates/sf-compositor/src/winit.rs b/crates/sf-compositor/src/winit.rs index c2e4b2c..dd203e4 100644 --- a/crates/sf-compositor/src/winit.rs +++ b/crates/sf-compositor/src/winit.rs @@ -71,22 +71,24 @@ pub fn init(event_loop: &mut EventLoop<'static, App>, state: &mut State) -> Resu fn render(app: &mut App) { let Backend::Winit(w) = &mut app.backend else { return }; let age = w.backend.buffer_age().unwrap_or(0); - let damage = match w.backend.bind() { + let (damage, elements) = match w.backend.bind() { Ok((renderer, mut fb)) => { let elements = app.state.elements(renderer); - match w.damage.render_output(renderer, &mut fb, age, &elements, [0.0, 0.0, 0.0, 1.0]) { + let damage = match w.damage.render_output(renderer, &mut fb, age, &elements, [0.0, 0.0, 0.0, 1.0]) { Ok(r) => r.damage.cloned(), Err(e) => { tracing::warn!("render: {e:?}"); None } - } + }; + (damage, Some(elements)) } Err(e) => { tracing::warn!("bind: {e:?}"); - None + (None, None) } }; + let damaged = damage.is_some(); if let Some(damage) = damage { let feedback = app.state.presentation_feedback(); match w.backend.submit(Some(&damage)) { @@ -99,6 +101,10 @@ fn render(app: &mut App) { Err(e) => tracing::warn!("submit: {e:?}"), } } + // After the swap: copying binds other targets. + if let Some(elements) = elements.filter(|_| !app.state.screencopies.is_empty()) { + crate::screencopy::fulfil(&mut app.state, w.backend.renderer(), &elements, damaged); + } app.state.send_frames(); w.backend.window().request_redraw(); } diff --git a/crates/sf-core/Cargo.toml b/crates/sf-core/Cargo.toml index d9dcbc4..c3c2cd1 100644 --- a/crates/sf-core/Cargo.toml +++ b/crates/sf-core/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "sf-core" -description = "Fennec OS core daemon: app lifecycle (systemd scopes, freeze/thaw), DIAL, AirPlay/Miracast receivers" +description = "Fennec OS core daemon: app lifecycle (systemd scopes, one app at a time), DIAL, AirPlay/Miracast receivers" version.workspace = true edition.workspace = true license.workspace = true diff --git a/crates/sf-core/src/apps.rs b/crates/sf-core/src/apps.rs index ab1a1e7..1915f15 100644 --- a/crates/sf-core/src/apps.rs +++ b/crates/sf-core/src/apps.rs @@ -1,12 +1,11 @@ -//! App lifecycle: start, bring to front, send to the background (freeze), -//! close. One app is in the foreground; with sf-compositor the others wait -//! frozen in the background, under cage they are closed. +//! App lifecycle: start and close. Only one app runs at a time: Home, a +//! new app or a cast closes the one on screen. use std::os::unix::process::CommandExt; use std::path::PathBuf; use std::process::Command as StdCommand; use std::sync::{Arc, Mutex}; -use std::time::{Duration, Instant}; +use std::time::Duration; use anyhow::{Context, Result, bail}; use sf_ipc::launch::{LaunchOptions, command}; @@ -15,21 +14,17 @@ use tokio::sync::broadcast; use crate::wm; -/// Frozen apps kept in the background; the oldest beyond this is closed. -const MAX_BACKGROUND: usize = 2; -/// Below this much available memory the oldest frozen app is closed. -const LOW_MEMORY_KB: u64 = 400 * 1024; -/// Freeze only after the compositor's switch animation has finished. -const FREEZE_DELAY: Duration = Duration::from_millis(600); +/// Close only after the compositor's switch animation has finished. +const CLOSE_DELAY: Duration = Duration::from_millis(600); struct Running { id: String, pid: u32, /// systemd scope (`sf-app--.scope`), if scopes are used. unit: Option, - frozen: bool, - last_used: Instant, serial: u64, + /// Being closed; it can't be brought back any more. + stopping: bool, } #[derive(Default)] @@ -38,8 +33,6 @@ struct State { running: Vec, foreground: Option, serial: u64, - /// While a cast window is up: what to show when it ends (None: launcher). - cast_return: Option>, } pub struct Core { @@ -80,12 +73,6 @@ async fn systemctl(verb: &str, unit: &str) -> Result<()> { Ok(()) } -fn mem_available_kb() -> Option { - let text = std::fs::read_to_string("/proc/meminfo").ok()?; - let line = text.lines().find(|l| l.starts_with("MemAvailable:"))?; - line.split_whitespace().nth(1)?.parse().ok() -} - impl Core { pub fn new(apps_dirs: Vec, store_dir: Option, settings_path: PathBuf) -> Result { let apps = sf_ipc::manifest::load_all(&apps_dirs, store_dir.as_deref())?; @@ -149,61 +136,57 @@ impl Core { if query.is_some() && self.is_running(id) { self.stop_and_wait(id).await; } - let switching = wm::available(); - - // Already running: thaw and show it. - let existing = { - let st = self.state.lock().unwrap(); - st.running.iter().find(|r| r.id == id).map(|r| (r.unit.clone(), r.pid, r.frozen)) - }; - if let Some((unit, pid, frozen)) = existing { - if frozen { - self.thaw(id, unit.as_deref(), pid).await; - } + // Still running (brought back before it closed): show it again. + let alive = self.state.lock().unwrap().running.iter().any(|r| r.id == id && !r.stopping); + if alive { let prev = self.set_foreground(Some(id)); - self.leave_foreground(prev, switching); + self.close_previous(prev); wm::focus(Some(id)); self.emit(CoreEvent::AppStarted { app_id: id.to_string(), cast }); return Ok(()); } let prev = self.set_foreground(None); - self.leave_foreground(prev, switching); - if !switching { - // Under cage only the newest window shows; don't leave others running. - let others: Vec = self.state.lock().unwrap().running.iter().map(|r| r.id.clone()).collect(); - for other in others { - self.stop(&other); - } + // One app at a time: anything else still running closes now. + let others: Vec = { + let st = self.state.lock().unwrap(); + st.running.iter().map(|r| r.id.clone()).filter(|r| Some(r) != prev.as_ref()).collect() + }; + for other in others { + self.stop(&other); } + self.close_previous(prev); + // Opened again while it was closing: start fresh once it is gone. + self.wait_gone(id).await; self.spawn(&app, query.as_deref())?; self.set_foreground(Some(id)); wm::focus(Some(id)); self.emit(CoreEvent::AppStarted { app_id: id.to_string(), cast }); - self.enforce_background_limit(); Ok(()) } fn set_foreground(&self, id: Option<&str>) -> Option { let mut st = self.state.lock().unwrap(); - if let Some(id) = id { - if let Some(r) = st.running.iter_mut().find(|r| r.id == id) { - r.last_used = Instant::now(); - } - } let prev = std::mem::replace(&mut st.foreground, id.map(str::to_string)); prev.filter(|p| Some(p.as_str()) != id) } - /// The previous foreground app goes to the background (or is closed - /// when the compositor can't keep it there). - fn leave_foreground(self: &Arc, prev: Option, switching: bool) { + /// Closes the app that was on screen, once the switch animation is + /// over (at once under cage, which has no animation). + fn close_previous(self: &Arc, prev: Option) { let Some(prev) = prev else { return }; - if switching { - self.freeze_later(prev); - } else { + if !wm::available() { self.stop(&prev); + return; } + let core = self.clone(); + tokio::spawn(async move { + tokio::time::sleep(CLOSE_DELAY).await; + if core.foreground().as_deref() == Some(prev.as_str()) { + return; // brought back in the meantime + } + core.stop(&prev); + }); } fn spawn(self: &Arc, app: &AppManifest, query: Option<&str>) -> Result<()> { @@ -251,9 +234,8 @@ impl Core { id: app.id.clone(), pid, unit, - frozen: false, - last_used: Instant::now(), serial, + stopping: false, }); let core = self.clone(); let id = app.id.clone(); @@ -276,11 +258,6 @@ impl Core { if fg { st.foreground = None; } - if let Some(Some(ret)) = &st.cast_return { - if ret == id { - st.cast_return = Some(None); - } - } fg }; if was_foreground { @@ -289,86 +266,34 @@ impl Core { self.emit(CoreEvent::AppStopped { app_id: id.to_string() }); } - /// Home: show the launcher; the foreground app waits frozen (or closes). + /// Home: show the launcher; the app on screen closes. pub fn go_home(self: &Arc) { let prev = self.set_foreground(None); - let switching = wm::available(); wm::focus(None); - self.leave_foreground(prev, switching); - self.enforce_background_limit(); - } - - fn freeze_later(self: &Arc, id: String) { - let core = self.clone(); - tokio::spawn(async move { - tokio::time::sleep(FREEZE_DELAY).await; - let target = { - let st = core.state.lock().unwrap(); - if st.foreground.as_deref() == Some(id.as_str()) { - return; // came back in the meantime - } - st.running.iter().find(|r| r.id == id && !r.frozen).map(|r| (r.unit.clone(), r.pid)) - }; - let Some((unit, pid)) = target else { return }; - let ok = match &unit { - Some(u) => systemctl("freeze", u).await.map_err(|e| log::warn!("{e:#}")).is_ok(), - None => kill_group(pid, libc::SIGSTOP), - }; - if ok { - // It may have been brought back while we were freezing it. - let back = { - let mut st = core.state.lock().unwrap(); - if let Some(r) = st.running.iter_mut().find(|r| r.id == id) { - r.frozen = true; - } - st.foreground.as_deref() == Some(id.as_str()) - }; - if back { - core.thaw(&id, unit.as_deref(), pid).await; - } else { - log::info!("{id} frozen"); - } - } - }); - } - - async fn thaw(&self, id: &str, unit: Option<&str>, pid: u32) { - match unit { - Some(u) => { - if let Err(e) = systemctl("thaw", u).await { - log::warn!("{e:#}"); - } - } - None => { - kill_group(pid, libc::SIGCONT); - } - } - if let Some(r) = self.state.lock().unwrap().running.iter_mut().find(|r| r.id == id) { - r.frozen = false; - } - log::info!("{id} thawed"); + self.close_previous(prev); } /// Closes the app (asynchronously); false if it wasn't running. pub fn stop(self: &Arc, id: &str) -> bool { let target = { - let st = self.state.lock().unwrap(); - st.running.iter().find(|r| r.id == id).map(|r| (r.unit.clone(), r.pid)) + let mut st = self.state.lock().unwrap(); + st.running.iter_mut().find(|r| r.id == id).map(|r| { + r.stopping = true; + (r.unit.clone(), r.pid) + }) }; let Some((unit, pid)) = target else { return false }; log::info!("stopping {id}"); tokio::spawn(async move { match unit { - // Stops every process of the scope, thawing it first. + // Stops every process of the scope. Some(u) => { - let _ = systemctl("thaw", &u).await; if let Err(e) = systemctl("stop", &u).await { log::warn!("{e:#}"); kill_group(pid, libc::SIGKILL); } } None => { - kill_group(pid, libc::SIGCONT); kill_group(pid, libc::SIGTERM); tokio::time::sleep(Duration::from_secs(3)).await; kill_group(pid, libc::SIGKILL); @@ -379,9 +304,13 @@ impl Core { } async fn stop_and_wait(self: &Arc, id: &str) { - if !self.stop(id) { - return; + if self.stop(id) { + self.wait_gone(id).await; } + } + + /// Waits (up to 6 s) until no instance of the app runs. + async fn wait_gone(&self, id: &str) { for _ in 0..60 { if !self.is_running(id) { return; @@ -391,70 +320,20 @@ impl Core { log::warn!("{id} did not stop in time"); } - /// The oldest frozen app, if any. - fn oldest_background(&self) -> Option { - let st = self.state.lock().unwrap(); - st.running - .iter() - .filter(|r| st.foreground.as_deref() != Some(r.id.as_str())) - .min_by_key(|r| r.last_used) - .map(|r| r.id.clone()) - } - - fn background_count(&self) -> usize { - let st = self.state.lock().unwrap(); - st.running.iter().filter(|r| st.foreground.as_deref() != Some(r.id.as_str())).count() - } - - fn enforce_background_limit(self: &Arc) { - while self.background_count() > MAX_BACKGROUND { - let Some(id) = self.oldest_background() else { break }; - log::info!("too many apps in the background, closing {id}"); - if !self.stop(&id) { - break; - } - // Don't pick it again while it shuts down. - self.state.lock().unwrap().running.retain(|r| r.id != id); - self.emit(CoreEvent::AppStopped { app_id: id }); - } - } - - /// A receiver (AirPlay/Miracast) got a connection: its window goes on - /// top, the foreground app pauses in the background. + /// A receiver (AirPlay/Miracast) got a connection: its window takes the + /// screen and the app on screen closes (one app at a time). pub fn cast_connected(self: &Arc, app_id: &str, device: &str) { - let switching = wm::available(); - let prev = { - let mut st = self.state.lock().unwrap(); - if st.cast_return.is_none() { - st.cast_return = Some(st.foreground.clone()); - } - if switching { st.foreground.take() } else { None } - }; - if let Some(prev) = prev { - self.freeze_later(prev); - } + let prev = self.set_foreground(None); + self.close_previous(prev); wm::focus(Some(app_id)); self.emit(CoreEvent::CastConnected { app_id: app_id.to_string(), device: device.to_string() }); } - /// The cast ended: back to what was on screen before. + /// The cast ended: back to the launcher, unless an app was opened meanwhile. pub fn cast_ended(self: &Arc, app_id: &str) { - let ret = self.state.lock().unwrap().cast_return.take(); self.emit(CoreEvent::CastEnded { app_id: app_id.to_string() }); - let Some(ret) = ret else { return }; - if !wm::available() { - return; - } - match ret.filter(|id| self.is_running(id)) { - Some(id) => { - let core = self.clone(); - tokio::spawn(async move { - if let Err(e) = core.launch(&id, None, false).await { - log::warn!("back to {id}: {e:#}"); - } - }); - } - None => wm::focus(None), + if wm::available() && self.foreground().is_none() { + wm::focus(None); } } @@ -463,31 +342,9 @@ impl Core { self.state.lock().unwrap().running.iter().map(|r| (r.unit.clone(), r.pid)).collect(); for (unit, pid) in ids { if let Some(u) = unit { - let _ = StdCommand::new("systemctl").args(["--user", "thaw", &u]).status(); let _ = StdCommand::new("systemctl").args(["--user", "stop", "--no-block", &u]).status(); } - kill_group(pid, libc::SIGCONT); kill_group(pid, libc::SIGTERM); } } } - -/// Closes the oldest frozen app when memory runs low. -pub async fn watch_memory(core: Arc) { - let mut tick = tokio::time::interval(Duration::from_secs(5)); - loop { - tick.tick().await; - let Some(avail) = mem_available_kb() else { continue }; - if avail >= LOW_MEMORY_KB { - continue; - } - let Some(id) = core.oldest_background() else { continue }; - let name = core.apps().into_iter().find(|a| a.id == id).map(|a| a.name).unwrap_or(id.clone()); - log::warn!("low memory ({} MB available), closing {id}", avail / 1024); - if core.stop(&id) { - core.state.lock().unwrap().running.retain(|r| r.id != id); - core.emit(CoreEvent::AppStopped { app_id: id }); - core.emit(CoreEvent::Toast { text: format!("Kevés a memória: {name} bezárva") }); - } - } -} diff --git a/crates/sf-core/src/main.rs b/crates/sf-core/src/main.rs index 8d875b4..ef54632 100644 --- a/crates/sf-core/src/main.rs +++ b/crates/sf-core/src/main.rs @@ -1,8 +1,7 @@ //! sf-core: the Fennec OS core daemon. //! //! - Starts apps for the launcher, each in its own systemd user scope. -//! Home freezes the foreground app (`systemctl --user freeze`) so it comes -//! back instantly; under memory pressure the oldest frozen app is closed. +//! Only one app runs at a time: Home, another app or a cast closes it. //! - Runs the DIAL server, so the YouTube app on a phone can cast to the TV. //! - Keeps the AirPlay (UxPlay) and Miracast receivers running and reports //! when a device connects. @@ -101,7 +100,6 @@ fn unix_main() -> anyhow::Result<()> { core.uses_scopes(), wm::available() ); - tokio::spawn(apps::watch_memory(core.clone())); if !opts.no_services { services::start_all(core.clone()); } diff --git a/crates/sf-ipc/src/message.rs b/crates/sf-ipc/src/message.rs index 40246ba..ce0bb47 100644 --- a/crates/sf-ipc/src/message.rs +++ b/crates/sf-ipc/src/message.rs @@ -9,15 +9,14 @@ use serde::{Deserialize, Serialize}; #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(tag = "type", rename_all = "snake_case")] pub enum LauncherRequest { - /// Start the app, or bring it back if it waits in the background. + /// Start the app (the one on screen closes). Launch { app_id: String, /// Extra query string for the start URL (DIAL uses this). #[serde(default, skip_serializing_if = "Option::is_none")] query: Option, }, - /// Show the launcher. The foreground app is frozen in the background if - /// the compositor can switch windows, otherwise it is closed. + /// Show the launcher. The app on screen closes. GoHome, /// Close the app. Stop { app_id: String }, @@ -28,7 +27,7 @@ pub enum LauncherRequest { pub enum CoreEvent { /// First message on every connection. Hello { - /// True if apps are kept (frozen) in the background on Home. + /// True if the compositor can switch windows (sf-compositor, not cage). switching: bool, /// The app in the foreground, if any. #[serde(default)] diff --git a/crates/sf-launcher/src/core_client.rs b/crates/sf-launcher/src/core_client.rs index 50f662f..e9a035d 100644 --- a/crates/sf-launcher/src/core_client.rs +++ b/crates/sf-launcher/src/core_client.rs @@ -1,5 +1,5 @@ #![cfg_attr(not(unix), allow(dead_code))] -//! Connection to sf-core. On the TV sf-core starts, freezes and closes apps; +//! Connection to sf-core. On the TV sf-core starts and closes apps; //! without it (desktop testing) the launcher starts apps itself. use sf_ipc::{CoreEvent, LauncherRequest}; diff --git a/crates/sf-launcher/src/devshot.rs b/crates/sf-launcher/src/devshot.rs index 0946f24..23b58f8 100644 --- a/crates/sf-launcher/src/devshot.rs +++ b/crates/sf-launcher/src/devshot.rs @@ -86,6 +86,11 @@ pub fn setup(ui: &App) -> Snapshot { } impl Snapshot { + /// A snapshot is still to be taken: keep frames coming until then. + pub fn pending(&self) -> bool { + self.path.is_some() + } + pub fn capture_if_due(&self, ui: &App, r: &GlassRenderer) { if !self.due.get() { return; diff --git a/crates/sf-launcher/src/main.rs b/crates/sf-launcher/src/main.rs index 514711a..4b768ce 100644 --- a/crates/sf-launcher/src/main.rs +++ b/crates/sf-launcher/src/main.rs @@ -24,7 +24,7 @@ use std::time::{Duration, Instant}; use anyhow::{Context, Result}; use chrono::{Datelike, Local, Timelike}; -use sf_ui::render::{Frame, GlassRenderer, Panel}; +use sf_ui::render::{Frame, GlassRenderer, Panel, Quality}; use sf_ipc::{AppKind, AppManifest, Settings}; use slint::{ComponentHandle, Model, ModelRc, SharedString, VecModel}; @@ -572,8 +572,8 @@ fn main() -> Result<()> { }); } - // Launching. On the TV sf-core starts apps (and keeps them frozen in the - // background on Home); without it the launcher starts them itself. + // Launching. On the TV sf-core starts apps (and closes them on Home); + // without it the launcher starts them itself. let toast_timer = Rc::new(slint::Timer::default()); let running: Rc>> = Rc::default(); let core = { @@ -676,8 +676,8 @@ fn main() -> Result<()> { } }); } - // Global "home" (remote's TV button): the foreground app goes to the - // background (sf-core) or closes, and the reverse morph plays. + // Global "home" (remote's TV button): the foreground app closes and + // the reverse morph plays. { let weak = ui.as_weak(); let core = core.clone(); @@ -753,6 +753,10 @@ fn main() -> Result<()> { let backdrop = Rc::new(RefCell::new(Backdrop { palette: palettes.first().copied().unwrap_or([0.0; 9]), last: 0.0 })); let renderer: Rc>> = Rc::default(); let frames = Rc::new(RefCell::new((Instant::now(), 0u32))); + // Glass quality, measured on the GPU for the window size (sf-ui), and + // whether the last frame left anything still easing. + let quality: Rc>> = Rc::default(); + let easing = Rc::new(std::cell::Cell::new(true)); let weak = ui.as_weak(); ui.window() @@ -777,13 +781,26 @@ fn main() -> Result<()> { let size = ui.window().size(); let scale = ui.window().scale_factor(); + let q = match quality.get() { + Some((q, at)) if at == (size.width, size.height) => q, + _ => { + // SAFETY: the rendering notifier runs with the GL context current. + let q = unsafe { r.choose_quality(size.width, size.height) }; + log::info!("glass quality: {}", q.name()); + quality.set(Some((q, (size.width, size.height)))); + q + } + }; + let mut bd = backdrop.borrow_mut(); let focus = ui.get_focus_index().max(0) as usize; + easing.set(false); if let Some(target) = palettes.get(focus) { let k = 1.0 - (-(time - bd.last).max(0.0) / CROSSFADE).exp(); for (c, t) in bd.palette.iter_mut().zip(target) { *c += (t - *c) * k; } + easing.set(bd.palette.iter().zip(target).any(|(c, t)| (c - t).abs() > 0.002)); } bd.last = time; @@ -811,7 +828,7 @@ fn main() -> Result<()> { images: &[], video: None, rects, - quality: Default::default(), + quality: q, }; drop(bd); // SAFETY: called on the UI thread with the Slint GL context current. @@ -825,12 +842,17 @@ fn main() -> Result<()> { } } slint::RenderingState::AfterRendering => { - // The backdrop is animated, so keep frames coming (vsync-limited). + // The glass backdrop is animated, so keep frames coming + // (vsync-limited). Material is still: frames only while the + // colours ease; Slint asks for its own animations. if let Some(ui) = weak.upgrade() { if let Some(r) = renderer.borrow().as_ref() { snapshot.capture_if_due(&ui, r); } - ui.window().request_redraw(); + let still = matches!(quality.get(), Some((Quality::Material, _))); + if !still || easing.get() || snapshot.pending() { + ui.window().request_redraw(); + } } } slint::RenderingState::RenderingTeardown => { diff --git a/crates/sf-update/src/appstore.rs b/crates/sf-update/src/appstore.rs index 1c57359..2ba3821 100644 --- a/crates/sf-update/src/appstore.rs +++ b/crates/sf-update/src/appstore.rs @@ -149,8 +149,7 @@ fn app_entry(agent: &ureq::Agent, repo: &Repo) -> Result> { let app: AppManifest = toml::from_str(&forge::asset_text(agent, manifest_asset)?).context("app.toml")?; app.check_store_rules()?; anyhow::ensure!(crate::registry::is_release(&app.version), "version {} is not a release version (1.2.3)", app.version); - let file = format!("{}-{}.tar.zst", app.id, app.version); - let package = release.asset(&file).with_context(|| format!("release {} has no {file}", release.tag))?; + let package = package_asset(&release, &app)?; Ok(Some(CatalogApp { id: app.id.clone(), name: app.name.clone(), @@ -171,6 +170,24 @@ fn app_entry(agent: &ureq::Agent, repo: &Repo) -> Result> { })) } +/// The release's package for this TV (docs/store.md): `-.tar.zst` +/// on x86-64, `--aarch64.tar.zst` on ARM. A web app is the same +/// everywhere, so its plain package is fine on any architecture; an exec app's +/// plain package is an x86-64 build. +fn package_asset<'a>(release: &'a forge::Release, app: &AppManifest) -> Result<&'a forge::Asset> { + let plain = format!("{}-{}.tar.zst", app.id, app.version); + let native = crate::arch::file_name(&app.id, &app.version); + if let Some(a) = release.asset(&native) { + return Ok(a); + } + if !crate::arch::IS_DEFAULT && app.kind == sf_ipc::manifest::AppKind::Web { + if let Some(a) = release.asset(&plain) { + return Ok(a); + } + } + anyhow::bail!("release {} has no {native}", release.tag) +} + /// Marks what's installed and what's held back, and returns the store /// packages to download (new installs and updates). pub fn plan(store: &Store, wanted: &Wanted, catalog: &mut Catalog) -> BTreeMap { diff --git a/crates/sf-update/src/arch.rs b/crates/sf-update/src/arch.rs new file mode 100644 index 0000000..75305fd --- /dev/null +++ b/crates/sf-update/src/arch.rs @@ -0,0 +1,45 @@ +//! The CPU architecture of this TV, and how packages built for it are named +//! (docs/updates.md, "Architektúrák"). +//! +//! Fennec OS started on x86-64: its package files carry no architecture +//! (`sf-shell-1.2.0.tar.zst`). Packages for any other architecture have a +//! suffix (`sf-shell-1.2.0-aarch64.tar.zst`). + +/// This build's architecture, as in Rust's `std::env::consts::ARCH`. +pub const NAME: &str = std::env::consts::ARCH; + +/// Whether this is the original architecture (unsuffixed package files). +pub const IS_DEFAULT: bool = cfg!(target_arch = "x86_64"); + +/// `name-version.tar.zst` for this architecture. +pub fn file_name(name: &str, version: &str) -> String { + if IS_DEFAULT { format!("{name}-{version}.tar.zst") } else { format!("{name}-{version}-{NAME}.tar.zst") } +} + +/// Whether a package that says it was built for `arch` (pkg.toml; missing = +/// an old package, built for x86-64) runs here. +pub fn runs_here(arch: Option<&str>) -> bool { + match arch { + Some(a) => a == NAME, + None => IS_DEFAULT, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn names() { + if IS_DEFAULT { + assert_eq!(file_name("sf-shell", "1.2.0"), "sf-shell-1.2.0.tar.zst"); + assert!(runs_here(None)); + assert!(!runs_here(Some("aarch64"))); + } else { + assert_eq!(file_name("sf-shell", "1.2.0"), format!("sf-shell-1.2.0-{NAME}.tar.zst")); + assert!(!runs_here(None)); + assert!(!runs_here(Some("x86_64"))); + } + assert!(runs_here(Some(NAME))); + } +} diff --git a/crates/sf-update/src/main.rs b/crates/sf-update/src/main.rs index 47d9ec0..68b9478 100644 --- a/crates/sf-update/src/main.rs +++ b/crates/sf-update/src/main.rs @@ -14,6 +14,7 @@ //! sf-update status print status.json mod appstore; +mod arch; mod config; mod forge; mod migrate; diff --git a/crates/sf-update/src/registry.rs b/crates/sf-update/src/registry.rs index a5efe14..84e7dd6 100644 --- a/crates/sf-update/src/registry.rs +++ b/crates/sf-update/src/registry.rs @@ -2,6 +2,11 @@ //! //! list: GET {server}/api/v1/packages/{owner}?type=generic&q=sf- //! download: GET {server}/api/packages/{owner}/generic/{name}/{version}/{name}-{version}.tar.zst (+ .sig) +//! files: GET {server}/api/v1/packages/{owner}/generic/{name}/{version}/files +//! +//! The shell is native code: on any architecture but x86-64 its file has a +//! suffix (`sf-shell-1.2.0-aarch64.tar.zst`, crate::arch). App packages are +//! manifests only and are the same everywhere. use std::collections::BTreeMap; use std::io::Read; @@ -73,10 +78,12 @@ struct PackageVersion { version: String, } -/// Newest release version of every package on the server. +/// Newest release version of every package on the server. A shell version +/// without a file for this architecture doesn't count. pub fn latest_versions(cfg: &Config) -> Result> { let agent = agent(); let mut latest: BTreeMap = BTreeMap::new(); + let mut shells: Vec = Vec::new(); for page in 1..=100 { let url = format!("{}/api/v1/packages/{}?type=generic&q=sf-&limit=50&page={page}", cfg.server, cfg.owner); let text = get(cfg, &agent, &url)?.body_mut().read_to_string()?; @@ -88,6 +95,10 @@ pub fn latest_versions(cfg: &Config) -> Result> { if !is_official(&p.name) || !is_release(&p.version) { continue; } + if p.name == SHELL && !crate::arch::IS_DEFAULT { + shells.push(p.version); + continue; + } match latest.get(&p.name) { Some(v) if version_cmp(v, &p.version).is_ge() => {} _ => { @@ -96,12 +107,46 @@ pub fn latest_versions(cfg: &Config) -> Result> { } } } + if !shells.is_empty() { + shells.sort_by(|a, b| version_cmp(b, a)); + shells.dedup(); + // Newest first; a few tries are enough (CI builds every architecture together). + for v in shells.iter().take(5) { + match has_file(cfg, &agent, SHELL, v) { + Ok(true) => { + latest.insert(SHELL.into(), v.clone()); + break; + } + Ok(false) => log::info!("{SHELL} {v}: no {} build", crate::arch::NAME), + Err(e) => { + log::warn!("{SHELL} {v}: {e:#}"); + break; + } + } + } + } Ok(latest) } +const SHELL: &str = "sf-shell"; + +#[derive(Deserialize)] +struct PackageFile { + name: String, +} + +/// Whether a package version has its file for this architecture. +fn has_file(cfg: &Config, agent: &ureq::Agent, name: &str, version: &str) -> Result { + let url = format!("{}/api/v1/packages/{}/generic/{name}/{version}/files", cfg.server, cfg.owner); + let text = get(cfg, agent, &url)?.body_mut().read_to_string()?; + let files: Vec = serde_json::from_str(&text).context("package files")?; + let want = file_name(name, version); + Ok(files.iter().any(|f| f.name == want)) +} + /// File name of a package in the registry. pub fn file_name(name: &str, version: &str) -> String { - format!("{name}-{version}.tar.zst") + if name == SHELL { crate::arch::file_name(name, version) } else { format!("{name}-{version}.tar.zst") } } /// Downloads a package and its signature into `dir`. diff --git a/crates/sf-update/src/store.rs b/crates/sf-update/src/store.rs index d67c36d..a57d158 100644 --- a/crates/sf-update/src/store.rs +++ b/crates/sf-update/src/store.rs @@ -81,6 +81,9 @@ const MAX_STORE_FILES: usize = 200_000; struct PkgInfo { name: String, version: String, + /// Native packages (the shell): the architecture they were built for. + #[serde(default)] + arch: Option, } #[cfg(unix)] @@ -263,6 +266,9 @@ impl Store { if info.name != expected_name || info.version != version { bail!("package says it is {} {}, expected {expected_name} {version}", info.name, info.version); } + if name == "sf-shell" && !crate::arch::runs_here(info.arch.as_deref()) { + bail!("{name} {version} is built for {}, this TV is {}", info.arch.as_deref().unwrap_or("x86_64"), crate::arch::NAME); + } if let Expect::Store { id, approved, .. } = expect { check_store_manifest(&tmp, id, version, approved)?; } diff --git a/docs/store.md b/docs/store.md index 9920cbf..4a117c3 100644 --- a/docs/store.md +++ b/docs/store.md @@ -66,6 +66,9 @@ Csak `https://` engedett. A repónak nyilvánosnak kell lennie: a TV bejelentkez |---|---| | `app.toml` | a manifest: név, leírás, engedélyek | | `-.tar.zst` | a csomag | +| `--aarch64.tar.zst` | opcionális: a csomag ARM-ra (Raspberry Pi) | + +**ARM-on** (`aarch64`) a TV az `-aarch64` csomagot keresi. Ha nincs, egy `web` app a sima csomagot is megkapja (az minden gépen ugyanaz). Egy `exec` app sima csomagja x86-64-es: ARM-on az ilyen app nem jelenik meg a store-ban. ## Biztonság - **Az app azonosítója** fordított domain név legalább egy ponttal (`io.github.valaki.app`). A hivatalos appok azonosítójában nincs pont, így store app sosem léphet egy hivatalos app helyére. Két forrás ugyanazzal az azonosítóval: az nyer, ahonnan telepítve van. diff --git a/docs/updates.md b/docs/updates.md index 430d8c5..7faff63 100644 --- a/docs/updates.md +++ b/docs/updates.md @@ -43,6 +43,12 @@ Registry: Gitea generic packages, `https://gitea.bluefox.support`, tulajdonos: ` - A privát kulcs: a `SF_SIGNING_KEY` CI-secret (a PEM fájl base64-ben, egy sorban, így a CI-napló maszkolja), és egy példány a fejlesztő gépén (`%USERPROFILE%\.smartfox\signing-key.pem`). - Aláírás nélküli vagy hibásan aláírt csomagot a TV nem telepít. Azt sem, amelyiknek a `pkg.toml`-ja más nevet vagy verziót mond. +**Architektúrák:** a Fennec OS x86-64-en indult, ezért ott a fájlnévben nincs architektúra. Más architektúrán az `sf-shell` fájl végződést kap: `sf-shell-1.2.0-aarch64.tar.zst`, ugyanabban a csomagverzióban. A `pkg.toml` `arch` mezője is megmondja, mire készült. +- A TV csak a saját architektúrájára épült shellt telepíti. Ha a legújabb verzióban nincs ilyen fájl, a shell nem frissül. +- `arch` nélküli shell x86-64-es (régi csomag). +- Az `sf-app-` csomagok csak manifestek, minden architektúrán ugyanazok. +- Építés: `SF_TARGET=aarch64-unknown-linux-gnu tools/pkg/packages.sh shell` (keresztfordítás, Debian multiarch; a függőségeket az `image/pi/build.sh` telepíti). + **Csak release verzió települ** (`1.2.3`, legfeljebb négy tag: a Steam `1.0.0.87`), előzetes verzió (`1.2.3-rc1`) nem. A TV csak a meglévőnél (a gyári és a telepített közül a nagyobbnál) újabbat tölt le. **Belépés:** a `fox-tv` felhasználó tokenje, csak `read:package` joggal. Az image építésekor az `image/secrets/update-token` fájlból kerül a `/usr/share/smartfox/update-token` fájlba (`fox-tv:`; a fájl nincs a gitben). Egy adott TV-n felülírható a `/var/lib/sf-pkg/update.toml` fájllal (`token_file`, `server` stb.). diff --git a/image/mkosi.extra/usr/bin/sf-launcher-start b/image/mkosi.extra/usr/bin/sf-launcher-start index be8de17..9d80e89 100644 --- a/image/mkosi.extra/usr/bin/sf-launcher-start +++ b/image/mkosi.extra/usr/bin/sf-launcher-start @@ -32,6 +32,15 @@ if [ -x "$PKG/current/bin/sf-launcher" ]; then rm -f "$TRIES" fi fi +# Remote viewing for development (README, "Távoli képernyő (VNC)"): wayvnc +# on localhost only, reached through an ssh tunnel. No --gpu by default: +# wayvnc's H.264 encoder crashes on the Raspberry Pi 4 (wayvnc 0.10); +# SMARTFOX_VNC_ARGS=--gpu in session.env turns it on where it works. +if [ "${SMARTFOX_REMOTE_VIEW:-0}" = 1 ] && command -v wayvnc >/dev/null; then + pkill -u "$(id -u)" -x wayvnc 2>/dev/null + # shellcheck disable=SC2086 + wayvnc ${SMARTFOX_VNC_ARGS:-} --max-fps=30 --name="Fennec OS" 127.0.0.1 5900 & +fi # sf-core starts and freezes apps, runs DIAL (YouTube cast) and the AirPlay / # Miracast receivers. It quits by itself when this Wayland session ends. pkill -u "$(id -u)" -x sf-core 2>/dev/null diff --git a/image/mkosi.extra/usr/bin/sf-session b/image/mkosi.extra/usr/bin/sf-session index 0814378..012c18b 100644 --- a/image/mkosi.extra/usr/bin/sf-session +++ b/image/mkosi.extra/usr/bin/sf-session @@ -22,11 +22,15 @@ export XCURSOR_THEME=smartfox-blank XCURSOR_SIZE=24 # Output mode: the TV's preferred mode, except in VMs where the host window # reports odd sizes. Override with SMARTFOX_MODE=WxH in /etc/default/smartfox. -[ -f /etc/default/smartfox ] && . /etc/default/smartfox -# Same, on the writable data partition (root is read-only), e.g. for debugging: +[ -f /etc/default/smartfox ] && { set -a; . /etc/default/smartfox; set +a; } +# Same, on the writable data partition (root is read-only); every variable +# set in these files is passed on. E.g. for debugging: # echo 'RUST_LOG=sf_launcher=debug' > /var/lib/smartfox/session.env (fps every 5 s) -[ -f /var/lib/smartfox/session.env ] && . /var/lib/smartfox/session.env +[ -f /var/lib/smartfox/session.env ] && { set -a; . /var/lib/smartfox/session.env; set +a; } export RUST_LOG +# Remote viewing for development (wayvnc, README "Távoli képernyő (VNC)"). +export SMARTFOX_REMOTE_VIEW="${SMARTFOX_REMOTE_VIEW:-0}" +export SMARTFOX_VNC_ARGS="${SMARTFOX_VNC_ARGS:-}" if [ -z "${SMARTFOX_MODE:-}" ] && systemd-detect-virt -q; then SMARTFOX_MODE=1920x1080 fi diff --git a/image/mkosi.extra/usr/lib/smartfox/blank-cursor.py b/image/mkosi.extra/usr/lib/smartfox/blank-cursor.py new file mode 100644 index 0000000..2efccd0 --- /dev/null +++ b/image/mkosi.extra/usr/lib/smartfox/blank-cursor.py @@ -0,0 +1,36 @@ +#!/usr/bin/env python3 +# Invisible mouse cursor: the TV only has a keyboard and the remote. Every +# cursor name is a 1x1 transparent image; the compositor, the launcher and +# Chromium all load cursors from this theme (XCURSOR_THEME in sf-session, and +# "default"). Run as root by mkosi.postinst.chroot and image/pi/install.sh. +import os, struct + +d = "/usr/share/icons/smartfox-blank/cursors" +os.makedirs(d, exist_ok=True) +img = struct.pack("<9I", 36, 0xFFFD0002, 24, 1, 1, 1, 0, 0, 0) + struct.pack("/usr/share/icons/smartfox-blank/index.theme -mkdir -p /usr/share/icons/default -printf '[Icon Theme]\nInherits=smartfox-blank\n' >/usr/share/icons/default/index.theme +# Invisible mouse cursor (the TV has no mouse). +python3 /usr/lib/smartfox/blank-cursor.py chmod +x /usr/bin/sf-session /usr/bin/sf-pair /usr/bin/sf-remote-debug /usr/bin/sf-diag /usr/bin/sf-shell-exec 2>/dev/null || true diff --git a/image/pi/build.sh b/image/pi/build.sh new file mode 100644 index 0000000..f207ee5 --- /dev/null +++ b/image/pi/build.sh @@ -0,0 +1,107 @@ +#!/usr/bin/env bash +# Builds Fennec OS for the Raspberry Pi (4 and 5; 64-bit Raspberry Pi OS or +# Debian trixie, arm64): a tarball that installs on top of the Pi's system. +# Cross-compiles in WSL Debian (or any Debian trixie host), as root: +# sudo bash /mnt/g/source/smartfox/image/pi/build.sh +# Writes image/out/fennec-os-pi--aarch64.tar.gz. On the Pi: +# tar xf fennec-os-pi-*.tar.gz && sudo fennec-os-pi/install.sh +set -euo pipefail + +SRC="$(cd "$(dirname "$0")/../.." && pwd)" +WORK="${SMARTFOX_PI_WORK:-/root/fennec-pi}" +TARGET=aarch64-unknown-linux-gnu +OUT_DIR="$SRC/image/out" + +echo "== toolchain" +if ! dpkg --print-foreign-architectures | grep -qx arm64; then + dpkg --add-architecture arm64 +fi +need=(gcc-aarch64-linux-gnu g++-aarch64-linux-gnu libc6-dev-arm64-cross pkg-config rsync + libfontconfig1-dev:arm64 libfreetype-dev:arm64 libxkbcommon-dev:arm64 libdbus-1-dev:arm64 + libudev-dev:arm64 libinput-dev:arm64 libgbm-dev:arm64 libseat-dev:arm64 libdrm-dev:arm64 libegl-dev:arm64) +missing=() +for p in "${need[@]}"; do dpkg-query -W -f='${Status}' "$p" 2>/dev/null | grep -q 'ok installed' || missing+=("$p"); done +if [ ${#missing[@]} -gt 0 ]; then + apt-get update -qq + DEBIAN_FRONTEND=noninteractive apt-get install -y -qq --no-install-recommends "${missing[@]}" +fi +if ! command -v cargo >/dev/null; then + [ -x "$HOME/.cargo/bin/cargo" ] || curl -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal + export PATH="$HOME/.cargo/bin:$PATH" +fi +rustup target list --installed | grep -qx "$TARGET" || rustup target add "$TARGET" + +echo "== sync $SRC -> $WORK/src" +mkdir -p "$WORK" +# Store apps checked out for development (apps//.git) and the local SDK +# patch (.cargo) stay out: the build uses the SDK tag, like CI. +rsync -a --delete --chmod=Du=rwx,Dgo=rx,Fu=rw,Fgo=r \ + --exclude /target --exclude '*/target' --exclude /.cargo --exclude /image/mkosi.output --exclude /image/mkosi.cache \ + --exclude /image/stage --exclude /image/out --exclude /image/iso --exclude /image/installer/mkosi.output \ + --exclude /image/installer/mkosi.cache --exclude /image/ovmf-vars.fd \ + "$SRC/" "$WORK/src/" +for d in "$WORK"/src/apps/*/; do [ -e "$d/.git" ] && rm -rf "$d"; done +cd "$WORK/src" + +echo "== cargo build ($TARGET)" +export CARGO_TARGET_AARCH64_UNKNOWN_LINUX_GNU_LINKER=aarch64-linux-gnu-gcc +export CC_aarch64_unknown_linux_gnu=aarch64-linux-gnu-gcc CXX_aarch64_unknown_linux_gnu=aarch64-linux-gnu-g++ +export PKG_CONFIG_ALLOW_CROSS=1 PKG_CONFIG_SYSROOT_DIR=/ PKG_CONFIG_PATH=/usr/lib/aarch64-linux-gnu/pkgconfig:/usr/share/pkgconfig +export CARGO_TARGET_DIR="$WORK/target" +BINS=(sf-launcher sf-remote sf-update sf-core sf-miracast sf-compositor) +args=() +for b in "${BINS[@]}"; do args+=(-p "$b"); done +cargo build --release --locked --target "$TARGET" "${args[@]}" +BIN_DIR="$CARGO_TARGET_DIR/$TARGET/release" + +echo "== stage" +VERSION=$(sed -n '/^\[workspace.package\]/,/^\[/ s/^version *= *"\(.*\)"/\1/p' Cargo.toml) +PKG="$WORK/stage/fennec-os-pi" +R="$PKG/root" +X=image/mkosi.extra +rm -rf "$WORK/stage" +mkdir -p "$R" +for b in "${BINS[@]}"; do install -Dm755 "$BIN_DIR/$b" "$R/usr/bin/$b"; done +install -Dm755 tools/siri-remote/fastpair.py "$R/usr/bin/sf-pair" +# The TV's session scripts as they are. Not taken: sf-remote-debug (it turns +# ssh off at boot), fstab, systemd-networkd/iwd, sshd and apt settings: the +# Pi keeps its own system, network and ssh. +for f in sf-session sf-launcher-start sf-shell-exec sf-diag; do install -Dm755 "$X/usr/bin/$f" "$R/usr/bin/$f"; done +for u in sf-remote.service sf-update-apply.service sf-update-auto.service sf-update-auto.timer \ + sf-update-requests.path sf-update-requests.service; do + install -Dm644 "$X/usr/lib/systemd/system/$u" "$R/usr/lib/systemd/system/$u" +done +install -Dm644 "$X/usr/lib/tmpfiles.d/smartfox.conf" "$R/usr/lib/tmpfiles.d/smartfox.conf" +install -Dm644 "$X/usr/lib/smartfox/blank-cursor.py" "$R/usr/lib/smartfox/blank-cursor.py" +install -Dm644 "$X/etc/systemd/system/bluetooth.service.d/smartfox.conf" "$R/etc/systemd/system/bluetooth.service.d/smartfox.conf" +# No data partition on the Pi: /var is part of the root file system. +install -d "$R/etc/systemd/system/sf-update-apply.service.d" +printf '# Fennec OS on Raspberry Pi OS: /var is not a separate partition.\n[Unit]\nConditionPathIsMountPoint=\n' \ + >"$R/etc/systemd/system/sf-update-apply.service.d/fennec-pi.conf" +for f in settings.toml update.toml; do install -Dm644 "$X/usr/share/smartfox/$f" "$R/usr/share/smartfox/$f"; done +install -Dm644 image/pi/factory-store.toml "$R/usr/share/smartfox/factory-store.toml" +if [ -f image/secrets/update-token ]; then + install -Dm600 image/secrets/update-token "$R/usr/share/smartfox/update-token" +else + echo "warning: image/secrets/update-token is missing, sf-update will log in anonymously" +fi +mkdir -p "$R/usr/share/smartfox/apps" +for d in apps/*/; do cp -r "$d" "$R/usr/share/smartfox/apps/"; done +chmod -R u=rwX,go=rX "$R/usr/share/smartfox/apps" +{ + echo "sf-shell = \"$VERSION\"" + for d in "$R"/usr/share/smartfox/apps/*/; do + v=$(sed -n 's/^version *= *"\(.*\)".*/\1/p' "$d/app.toml" | head -1) + [ -n "$v" ] && echo "sf-app-$(basename "$d") = \"$v\"" + done +} >"$R/usr/share/smartfox/factory-versions.toml" +mkdir -p "$R/usr/share/doc/smartfox" +cp docs/updates.md docs/store.md "$R/usr/share/doc/smartfox/" +install -m755 image/pi/install.sh "$PKG/install.sh" +echo "Fennec OS $VERSION · aarch64 · $(date +%Y-%m-%d)" >"$PKG/VERSION" + +echo "== tarball" +mkdir -p "$OUT_DIR" +TAR="$OUT_DIR/fennec-os-pi-$VERSION-aarch64.tar.gz" +tar --owner=0 --group=0 --numeric-owner -C "$WORK/stage" -czf "$TAR" fennec-os-pi +ls -lh "$TAR" diff --git a/image/pi/factory-store.toml b/image/pi/factory-store.toml new file mode 100644 index 0000000..89760b4 --- /dev/null +++ b/image/pi/factory-store.toml @@ -0,0 +1,12 @@ +# store.toml of a new Raspberry Pi install (docs/store.md). Same catalog as +# the TV. Steam is left out: Valve's client is x86-64 only. Netflex installs +# once its release has an aarch64 package (until then sf-update skips it). +sources = ["https://gitea.bluefox.support/fennec/store"] + +[apps."support.bluefox.netflex"] +source = "https://gitea.bluefox.support/fennec/netflex" +permissions = ["network", "gpu", "audio"] + +[apps."support.bluefox.youtube"] +source = "https://gitea.bluefox.support/fennec/youtube" +permissions = ["network", "gpu", "audio", "dial"] diff --git a/image/pi/install.sh b/image/pi/install.sh new file mode 100644 index 0000000..c657293 --- /dev/null +++ b/image/pi/install.sh @@ -0,0 +1,163 @@ +#!/bin/sh +# Installs Fennec OS on a Raspberry Pi (4 or 5) running 64-bit Raspberry Pi OS +# (Debian trixie). The Pi keeps its own system, network (NetworkManager) and +# ssh; Fennec OS takes over the screen: user tv logs in on tty1 and starts +# the TV session instead of the desktop. +# +# sudo ./install.sh install or update, then reboot +# sudo ./install.sh --no-session install, but keep booting to the desktop +# sudo ./install.sh --uninstall back to the desktop (keeps user tv and its data) +# sudo ./install.sh --purge uninstall and delete user tv and all Fennec OS data +# +# Built by image/pi/build.sh. +set -eu + +HERE=$(cd "$(dirname "$0")" && pwd) +STATE=/var/lib/smartfox/pi +FILES=$STATE/files +AUTOLOGIN=/etc/systemd/system/getty@tty1.service.d/smartfox-autologin.conf +UNITS="sf-remote.service sf-update-apply.service sf-update-requests.path sf-update-auto.timer" +# Runtime dependencies (the TV image's list, without its kernel, firmware, +# iwd/networkd and Steam parts). Most are already on Raspberry Pi OS. +PACKAGES="cage wlr-randr chromium fonts-noto-core fonts-dejavu-core libgl1-mesa-dri libegl1 libgles2 +libgbm1 libfontconfig1 libfreetype6 libxkbcommon0 libwayland-client0 libwayland-egl1 pipewire pipewire-pulse +wireplumber libspa-0.2-bluetooth pulseaudio-utils avahi-daemon uxplay dbus-user-session libpam-systemd libseat1 +libinput10 gstreamer1.0-tools gstreamer1.0-plugins-base gstreamer1.0-plugins-good gstreamer1.0-plugins-bad +gstreamer1.0-libav gstreamer1.0-pipewire glib-networking bubblewrap bluez python3 python3-dbus python3-gi wayvnc" + +say() { printf '== %s\n' "$*"; } +die() { printf 'install.sh: %s\n' "$*" >&2; exit 1; } + +[ "$(id -u)" = 0 ] || die "run it as root: sudo $0 $*" + +uninstall() { + purge=$1 + say "Fennec OS: uninstalling" + systemctl disable --now $UNITS 2>/dev/null || true + rm -f "$AUTOLOGIN" + rmdir /etc/systemd/system/getty@tty1.service.d 2>/dev/null || true + if [ -f "$FILES" ]; then + while IFS= read -r f; do rm -f "/$f"; done <"$FILES" + fi + rm -rf /usr/share/smartfox /usr/lib/smartfox /usr/share/icons/smartfox-blank /usr/share/doc/smartfox + rmdir /etc/systemd/system/sf-update-apply.service.d /etc/systemd/system/bluetooth.service.d 2>/dev/null || true + if [ -f "$STATE/icon-theme" ]; then + cp "$STATE/icon-theme" /usr/share/icons/default/index.theme + else + rm -f /usr/share/icons/default/index.theme + fi + target=$(cat "$STATE/default-target" 2>/dev/null || echo graphical.target) + systemctl set-default "$target" + systemctl daemon-reload + systemctl try-restart bluetooth.service || true + rm -rf "$STATE" + if [ "$purge" = 1 ]; then + say "deleting user tv and the Fennec OS data" + pkill -u tv 2>/dev/null || true + sleep 1 + userdel -r tv 2>/dev/null || true + rm -rf /var/lib/smartfox /var/lib/sf-pkg + fi + say "done; reboot to get the desktop back (or: systemctl isolate $target)" +} + +session=1 +case "${1:-}" in + --uninstall) uninstall 0; exit 0 ;; + --purge) uninstall 1; exit 0 ;; + --no-session) session=0 ;; + "") ;; + *) die "unknown option: $1" ;; +esac + +[ "$(uname -m)" = aarch64 ] || die "this build is for 64-bit ARM (aarch64), this is $(uname -m)" +[ -d "$HERE/root" ] || die "$HERE/root is missing (unpack the whole tarball)" +say "installing $(cat "$HERE/VERSION" 2>/dev/null || echo 'Fennec OS')" + +say "packages" +missing="" +for p in $PACKAGES; do + dpkg-query -W -f='${Status}' "$p" 2>/dev/null | grep -q 'ok installed' || missing="$missing $p" +done +if [ -n "$missing" ]; then + apt-get update -q + # shellcheck disable=SC2086 + DEBIAN_FRONTEND=noninteractive apt-get install -y -q --no-install-recommends $missing +fi + +say "files" +mkdir -p "$STATE" +# What was here before Fennec OS, for --uninstall (only the first time). +[ -f "$STATE/default-target" ] || systemctl get-default >"$STATE/default-target" +if [ ! -f "$STATE/icon-theme" ] && [ -f /usr/share/icons/default/index.theme ] && ! grep -q smartfox-blank /usr/share/icons/default/index.theme; then + cp /usr/share/icons/default/index.theme "$STATE/icon-theme" +fi +# Files of the previous version that are gone in this one. +new_files=$(cd "$HERE/root" && find . -type f | sed 's#^\./##' | sort) +if [ -f "$FILES" ]; then + printf '%s\n' "$new_files" | comm -23 "$FILES" - | while IFS= read -r f; do rm -f "/$f"; done +fi +rm -rf /usr/share/smartfox/apps +cd "$HERE/root" +printf '%s\n' "$new_files" | while IFS= read -r f; do + mode=$(stat -c %a "$f") + install -D -o root -g root -m "$mode" "$f" "/$f" +done +cd / +printf '%s\n' "$new_files" >"$FILES" +python3 /usr/lib/smartfox/blank-cursor.py + +say "user tv" +if ! id tv >/dev/null 2>&1; then + useradd -m -s /bin/bash tv +fi +for g in video render input audio bluetooth netdev; do + getent group "$g" >/dev/null && usermod -aG "$g" tv +done +TV_UID=$(id -u tv) +TV_HOME=$(getent passwd tv | cut -d: -f6) +# The TV image's tv is uid 1000; here 1000 is usually the Pi's own user. +sed -i "s#/run/user/1000#/run/user/$TV_UID#g" /usr/lib/systemd/system/sf-remote.service /usr/bin/sf-diag +cat >"$TV_HOME/.bash_profile" <<'EOF' +# Start the Fennec OS session on the first console (image/pi/install.sh). +if [ "$(tty)" = "/dev/tty1" ]; then + exec /usr/bin/sf-session +fi +EOF +chown tv:tv "$TV_HOME/.bash_profile" + +say "services" +systemd-tmpfiles --create /usr/lib/tmpfiles.d/smartfox.conf +[ -f /var/lib/smartfox/store.toml ] || install -o tv -g tv -m644 /usr/share/smartfox/factory-store.toml /var/lib/smartfox/store.toml +systemctl daemon-reload +# shellcheck disable=SC2086 +systemctl enable $UNITS +systemctl enable bluetooth.service avahi-daemon.service +# The Siri Remote needs Bluetooth: lift a soft block (Raspberry Pi OS keeps the +# desktop's Bluetooth switch there; systemd-rfkill saves the new state). +for r in /sys/class/rfkill/rfkill*; do + [ "$(cat "$r/type" 2>/dev/null)" = bluetooth ] && echo 0 >"$r/soft" +done +# bluetoothd without its input/HoG plugins: sf-remote reads the Siri Remote itself. +systemctl restart bluetooth.service || true +systemctl restart sf-remote.service || true + +say "store apps" +sf-update store || echo "warning: the store apps could not be installed now; the Pi installs them once online" >&2 + +if [ "$session" = 1 ]; then + say "session: tv on tty1, no desktop" + mkdir -p "$(dirname "$AUTOLOGIN")" + # After the Pi's own autologin.conf (raspi-config), so this one wins. + cat >"$AUTOLOGIN" <<'EOF' +# Fennec OS (image/pi/install.sh --uninstall removes it) +[Service] +ExecStart= +ExecStart=-/sbin/agetty --autologin tv --noclear --skip-login --nonewline --noissue %I $TERM +EOF + systemctl daemon-reload + systemctl set-default multi-user.target + say "done; reboot to start Fennec OS (or now: systemctl isolate multi-user.target && systemctl restart getty@tty1)" +else + say "done; the Pi still boots to its desktop (start Fennec OS: sudo $0)" +fi diff --git a/tools/pkg/packages.sh b/tools/pkg/packages.sh index 710e19d..c8bc07b 100644 --- a/tools/pkg/packages.sh +++ b/tools/pkg/packages.sh @@ -18,6 +18,10 @@ # SF_GITEA default https://gitea.bluefox.support # SF_OWNER default bluefox # SF_OUT output folder, default target/packages +# SF_TARGET Rust target of the shell, e.g. aarch64-unknown-linux-gnu +# (cross build against Debian multiarch libraries, see +# image/pi/build.sh). Default: this machine. A shell that +# isn't x86-64 gets a suffix: sf-shell-1.2.0-aarch64.tar.zst set -euo pipefail ROOT="$(cd "$(dirname "$0")/../.." && pwd)" @@ -55,7 +59,24 @@ auth() { } mapfile -t AUTH < <(auth) -url() { echo "$GITEA/api/packages/$OWNER/generic/$1/$2/$1-$2.tar.zst"; } +TARGET="${SF_TARGET:-}" +ARCH="${TARGET%%-*}" +ARCH="${ARCH:-$(uname -m)}" +SUFFIX="" +[ "$ARCH" = x86_64 ] || SUFFIX="-$ARCH" +if [ -n "$TARGET" ] && [ "$ARCH" != "$(uname -m)" ]; then + # Cross build against the target's multiarch libraries (Debian). + triple="$ARCH-linux-gnu" + upper=$(echo "$TARGET" | tr 'a-z-' 'A-Z_') + export "CARGO_TARGET_${upper}_LINKER=${triple}-gcc" + export "CC_${TARGET//-/_}=${triple}-gcc" "CXX_${TARGET//-/_}=${triple}-g++" + export PKG_CONFIG_ALLOW_CROSS=1 PKG_CONFIG_SYSROOT_DIR=/ + export PKG_CONFIG_PATH="/usr/lib/$triple/pkgconfig:/usr/share/pkgconfig" +fi + +# pkg_file : the shell is native code (architecture suffix), apps are not. +pkg_file() { if [ "$1" = sf-shell ]; then echo "$1-$2$SUFFIX.tar.zst"; else echo "$1-$2.tar.zst"; fi; } +url() { echo "$GITEA/api/packages/$OWNER/generic/$1/$2/$(pkg_file "$1" "$2")"; } published() { [ "$UPLOAD" = 1 ] || return 1 @@ -68,8 +89,9 @@ published() { pack() { local name=$1 version=$2 dir=$3 file printf 'name = "%s"\nversion = "%s"\n' "$name" "$version" >"$dir/pkg.toml" + if [ "$name" = sf-shell ]; then printf 'arch = "%s"\n' "$ARCH" >>"$dir/pkg.toml"; fi mkdir -p "$OUT" - file="$OUT/$name-$version.tar.zst" + file="$OUT/$(pkg_file "$name" "$version")" tar --sort=name --owner=0 --group=0 --numeric-owner --mtime=@0 -C "$dir" -cf - . | zstd -q -19 -T0 -f -o "$file" openssl pkeyutl -sign -inkey "$KEY_FILE" -rawin -in "$file" -out "$file.sig" echo "built $(basename "$file") ($(du -h "$file" | cut -f1))" @@ -87,16 +109,21 @@ do_shell() { local version version=$(sed -n '/^\[workspace.package\]/,/^\[/ s/^version *= *"\(.*\)"/\1/p' "$ROOT/Cargo.toml") if published sf-shell "$version"; then - echo "sf-shell $version: already published" + echo "sf-shell $version ($ARCH): already published" return fi local args=() for b in "${SHELL_BINS[@]}"; do args+=(-p "$b"); done + local bins="${CARGO_TARGET_DIR:-$ROOT/target}/release" + if [ -n "$TARGET" ]; then + args+=(--target "$TARGET") + bins="${CARGO_TARGET_DIR:-$ROOT/target}/$TARGET/release" + fi (cd "$ROOT" && cargo build --release --locked "${args[@]}") local dir="$TMP/sf-shell" rm -rf "$dir" mkdir -p "$dir/bin" - for b in "${SHELL_BINS[@]}"; do install -m755 "${CARGO_TARGET_DIR:-$ROOT/target}/release/$b" "$dir/bin/$b"; done + for b in "${SHELL_BINS[@]}"; do install -m755 "$bins/$b" "$dir/bin/$b"; done install -m755 "$ROOT/tools/siri-remote/fastpair.py" "$dir/bin/sf-pair" pack sf-shell "$version" "$dir" }