From deedf1416aac662a07683d5c03ff20782df994be Mon Sep 17 00:00:00 2001 From: Tamas Csikel Date: Sun, 25 Oct 2026 17:58:21 +0100 Subject: [PATCH] Split the apps and the SDK out of Fennec OS The apps are developed apart from the OS now, each in its own repo under gitea.bluefox.support/fennec: - sdk: sf-app (the app contract: manifest, permissions, store rules, sandbox, launch; from sf-ipc), sf-ui, sf-pack, the app template, the developer guide. The OS depends on it by tag (v0.1.0). - youtube, steam: store apps. netflex (native) replaces the Netflex web app. - store: the Fennec catalog, the store source a new TV starts with. This repo keeps the OS and its own apps (Settings, App Store, AirPlay, Miracast). sf-ipc re-exports sf-app, so OS code is mostly unchanged. - Store apps may register for DIAL (the `dial` permission); an official app with the same DIAL name wins. - Built-in icon names are for official apps only. - The image installs the catalog apps at build time (factory-store.toml, sf-update store in mkosi.postinst.chroot). Steam's system part stays in the image: 32-bit libraries, controller udev rules (from Valve's apt repo), Valve's key. - Older TVs move over by themselves: sf-update adds the replacements to store.toml once, the old factory app stays until its replacement is installed, YouTube's and Steam's data folders move to the new ids, and the old sf-app- packages are not installed any more. Shell 0.3.0. Co-Authored-By: Claude Opus 5.5 --- .gitea/workflows/packages.yml | 6 +- .gitignore | 1 + Cargo.lock | 622 +- Cargo.toml | 8 +- README.md | 41 +- apps/netflex/app.toml | 15 - apps/steam/app.toml | 21 - apps/steam/bin/smartfox-steam | 24 - apps/youtube/app.toml | 18 - crates/sf-core/Cargo.toml | 3 + crates/sf-core/src/dial.rs | 31 +- crates/sf-ipc/Cargo.toml | 3 +- crates/sf-ipc/src/launch.rs | 283 - crates/sf-ipc/src/lib.rs | 11 +- crates/sf-ipc/src/manifest.rs | 517 +- crates/sf-ipc/src/paths.rs | 34 +- crates/sf-ipc/src/sandbox.rs | 350 - crates/sf-ipc/src/settings.rs | 57 - crates/sf-launcher/Cargo.toml | 2 +- crates/sf-launcher/src/main.rs | 15 +- crates/sf-launcher/ui/app.slint | 5 +- crates/sf-launcher/ui/icons.slint | 56 +- crates/sf-pack/Cargo.toml | 14 - crates/sf-pack/src/main.rs | 220 - crates/sf-ui/Cargo.toml | 30 - crates/sf-ui/build.rs | 7 - crates/sf-ui/gallery/Cargo.toml | 21 - crates/sf-ui/gallery/build.rs | 7 - crates/sf-ui/gallery/src/main.rs | 101 - crates/sf-ui/gallery/ui/gallery.slint | 181 - crates/sf-ui/src/dev.rs | 103 - crates/sf-ui/src/glass.rs | 386 -- crates/sf-ui/src/images.rs | 259 - crates/sf-ui/src/lib.rs | 191 - crates/sf-ui/src/render/mod.rs | 167 - crates/sf-ui/src/render/renderer.rs | 735 --- crates/sf-ui/src/render/shaders.rs | 471 -- crates/sf-ui/src/text.rs | 39 - crates/sf-ui/src/video.rs | 483 -- crates/sf-ui/ui/fonts/Onest-Bold.ttf | Bin 98368 -> 0 bytes crates/sf-ui/ui/fonts/Onest-Medium.ttf | Bin 98372 -> 0 bytes crates/sf-ui/ui/fonts/Onest-OFL.txt | 93 - crates/sf-ui/ui/fonts/Onest-Regular.ttf | Bin 98088 -> 0 bytes crates/sf-ui/ui/fonts/Onest-SemiBold.ttf | Bin 98388 -> 0 bytes crates/sf-ui/ui/sf-ui.slint | 960 --- crates/sf-update/src/main.rs | 4 + crates/sf-update/src/migrate.rs | 99 + crates/sf-update/src/registry.rs | 12 +- docs/sf-ui.md | 442 -- docs/store-app-guide.md | 501 -- docs/store.md | 53 +- docs/updates.md | 7 +- image/build.sh | 18 +- .../share/keyrings}/valve-archive-keyring.gpg | Bin .../usr/share/smartfox/factory-store.toml | 17 + image/mkosi.postinst.chroot | 20 +- .../rust-app/.gitea/workflows/release.yml | 40 - .../rust-app/.github/workflows/release.yml | 36 - templates/rust-app/.gitignore | 4 - templates/rust-app/.gitlab-ci.yml | 30 - templates/rust-app/Cargo.lock | 5768 ----------------- templates/rust-app/Cargo.toml | 18 - templates/rust-app/app.toml | 29 - templates/rust-app/package.sh | 18 - templates/rust-app/src/main.rs | 60 - tools/pkg/packages.sh | 21 +- tools/pkg/steam/package.sh | 81 - 67 files changed, 393 insertions(+), 13476 deletions(-) delete mode 100644 apps/netflex/app.toml delete mode 100644 apps/steam/app.toml delete mode 100644 apps/steam/bin/smartfox-steam delete mode 100644 apps/youtube/app.toml delete mode 100644 crates/sf-ipc/src/launch.rs delete mode 100644 crates/sf-ipc/src/sandbox.rs delete mode 100644 crates/sf-ipc/src/settings.rs delete mode 100644 crates/sf-pack/Cargo.toml delete mode 100644 crates/sf-pack/src/main.rs delete mode 100644 crates/sf-ui/Cargo.toml delete mode 100644 crates/sf-ui/build.rs delete mode 100644 crates/sf-ui/gallery/Cargo.toml delete mode 100644 crates/sf-ui/gallery/build.rs delete mode 100644 crates/sf-ui/gallery/src/main.rs delete mode 100644 crates/sf-ui/gallery/ui/gallery.slint delete mode 100644 crates/sf-ui/src/dev.rs delete mode 100644 crates/sf-ui/src/glass.rs delete mode 100644 crates/sf-ui/src/images.rs delete mode 100644 crates/sf-ui/src/lib.rs delete mode 100644 crates/sf-ui/src/render/mod.rs delete mode 100644 crates/sf-ui/src/render/renderer.rs delete mode 100644 crates/sf-ui/src/render/shaders.rs delete mode 100644 crates/sf-ui/src/text.rs delete mode 100644 crates/sf-ui/src/video.rs delete mode 100644 crates/sf-ui/ui/fonts/Onest-Bold.ttf delete mode 100644 crates/sf-ui/ui/fonts/Onest-Medium.ttf delete mode 100644 crates/sf-ui/ui/fonts/Onest-OFL.txt delete mode 100644 crates/sf-ui/ui/fonts/Onest-Regular.ttf delete mode 100644 crates/sf-ui/ui/fonts/Onest-SemiBold.ttf delete mode 100644 crates/sf-ui/ui/sf-ui.slint create mode 100644 crates/sf-update/src/migrate.rs delete mode 100644 docs/sf-ui.md delete mode 100644 docs/store-app-guide.md rename {tools/pkg/steam => image/mkosi.extra/usr/share/keyrings}/valve-archive-keyring.gpg (100%) create mode 100644 image/mkosi.extra/usr/share/smartfox/factory-store.toml delete mode 100644 templates/rust-app/.gitea/workflows/release.yml delete mode 100644 templates/rust-app/.github/workflows/release.yml delete mode 100644 templates/rust-app/.gitignore delete mode 100644 templates/rust-app/.gitlab-ci.yml delete mode 100644 templates/rust-app/Cargo.lock delete mode 100644 templates/rust-app/Cargo.toml delete mode 100644 templates/rust-app/app.toml delete mode 100644 templates/rust-app/package.sh delete mode 100644 templates/rust-app/src/main.rs delete mode 100644 tools/pkg/steam/package.sh diff --git a/.gitea/workflows/packages.yml b/.gitea/workflows/packages.yml index a17154a..361d89f 100644 --- a/.gitea/workflows/packages.yml +++ b/.gitea/workflows/packages.yml @@ -19,10 +19,6 @@ on: - "tools/siri-remote/fastpair.py" - ".gitea/workflows/packages.yml" workflow_dispatch: - # Steam follows Valve's official steam-launcher package (tools/pkg/steam): - # look for a new one every Monday; nothing is built if it's published already. - schedule: - - cron: "17 4 * * 1" jobs: packages: @@ -47,7 +43,7 @@ jobs: run: | export DEBIAN_FRONTEND=noninteractive apt-get update -qq - apt-get install -y -qq --no-install-recommends build-essential pkg-config zstd gpgv dpkg \ + 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 rm -rf /var/lib/apt/lists/* diff --git a/.gitignore b/.gitignore index df0fb79..da940be 100644 --- a/.gitignore +++ b/.gitignore @@ -8,3 +8,4 @@ /image/secrets # Store apps developed in place, each its own git repository (apps//.git). /apps/netflex-tv/ +/.cargo/config.toml diff --git a/Cargo.lock b/Cargo.lock index bca93f6..7b9a14f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -18,114 +18,6 @@ version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618" -[[package]] -name = "accesskit" -version = "0.24.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d3b7f7f85a7e5f68090000ed7622545829afd484d210358702ae4cb97dd0c320" -dependencies = [ - "uuid", -] - -[[package]] -name = "accesskit_atspi_common" -version = "0.19.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "023da0e5097f46df7092d5280b02efb9bbf8d93298daeced42652463e357d636" -dependencies = [ - "accesskit", - "accesskit_consumer", - "atspi-common", - "phf", - "serde", - "zvariant", -] - -[[package]] -name = "accesskit_consumer" -version = "0.38.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5d10a236f96f87d70732e44520046785431ef01d5bcd6b041317bfadd2f88245" -dependencies = [ - "accesskit", - "hashbrown 0.16.1", -] - -[[package]] -name = "accesskit_ios" -version = "0.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "750c4e9f6ce888dfe8a10c0f1b5ceb646a7854fd46579d74919219d1bb314083" -dependencies = [ - "accesskit", - "accesskit_consumer", - "hashbrown 0.16.1", - "objc2 0.5.3", - "objc2-foundation 0.2.2", - "objc2-ui-kit 0.2.2", -] - -[[package]] -name = "accesskit_macos" -version = "0.26.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce02dc63b43f0c9296af9ac946312a2dc8814427d7a64d2d600971dac55b6076" -dependencies = [ - "accesskit", - "accesskit_consumer", - "hashbrown 0.16.1", - "objc2 0.5.3", - "objc2-app-kit 0.2.2", - "objc2-foundation 0.2.2", -] - -[[package]] -name = "accesskit_unix" -version = "0.22.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03e156ed3802e35eefe894ef2671bc6c889303d8a7e110b5e1b48f504b91362f" -dependencies = [ - "accesskit", - "accesskit_atspi_common", - "async-channel", - "async-executor", - "async-task", - "atspi", - "futures-lite", - "futures-util", - "serde", - "zbus", -] - -[[package]] -name = "accesskit_windows" -version = "0.34.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "106c2b961215864d1c2e703ee63269c25c4e80a577ffb2c1017b9c17dcdf83a1" -dependencies = [ - "accesskit", - "accesskit_consumer", - "hashbrown 0.16.1", - "static_assertions", - "windows", - "windows-core", -] - -[[package]] -name = "accesskit_winit" -version = "0.33.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d5b41e63a69f36d9f1f41e70464c7e5f72eee485ef26aab19f0b4f86e6c0a84c" -dependencies = [ - "accesskit", - "accesskit_ios", - "accesskit_macos", - "accesskit_unix", - "accesskit_windows", - "raw-window-handle", - "winit", -] - [[package]] name = "adler2" version = "2.0.1" @@ -318,15 +210,6 @@ dependencies = [ "x11rb", ] -[[package]] -name = "arc-swap" -version = "1.9.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "380962b3d93b99642e50b9febf72c071e97e8b32d86eae9cf4ef582bb960ae6e" -dependencies = [ - "rustversion", -] - [[package]] name = "arg_enum_proc_macro" version = "0.3.4" @@ -517,49 +400,6 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "628d228f918ac3b82fe590352cc719d30664a0c13ca3a60266fe02c7132d480a" -[[package]] -name = "atomic_refcell" -version = "0.1.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "21e4227379beff4205943696e6c3e0cd809bacdf3f0edd6e3dd153e2269571a4" - -[[package]] -name = "atspi" -version = "0.29.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c77886257be21c9cd89a4ae7e64860c6f0eefca799bb79127913052bd0eefb3d" -dependencies = [ - "atspi-common", - "atspi-proxies", -] - -[[package]] -name = "atspi-common" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "20c5617155740c98003016429ad13fe43ce7a77b007479350a9f8bf95a29f63d" -dependencies = [ - "enumflags2", - "serde", - "static_assertions", - "zbus", - "zbus-lockstep", - "zbus-lockstep-macros", - "zbus_names", - "zvariant", -] - -[[package]] -name = "atspi-proxies" -version = "0.13.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2230e48787ed3eb4088996eab66a32ca20c0b67bbd4fd6cdfe79f04f1f04c9fc" -dependencies = [ - "atspi-common", - "serde", - "zbus", -] - [[package]] name = "autocfg" version = "1.5.1" @@ -579,7 +419,7 @@ dependencies = [ "log", "num-rational", "num-traits", - "pastey 0.1.1", + "pastey", "rayon", "thiserror 2.0.21", "v_frame", @@ -902,16 +742,6 @@ dependencies = [ "nom 7.1.3", ] -[[package]] -name = "cfg-expr" -version = "0.20.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9ba9e9ec16c447027685b1f897b720e18e9a8afd00bd7332c483537e38086c9f" -dependencies = [ - "smallvec", - "target-lexicon", -] - [[package]] name = "cfg-if" version = "1.0.5" @@ -1159,15 +989,6 @@ dependencies = [ "crossbeam-utils", ] -[[package]] -name = "crossbeam-queue" -version = "0.3.14" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" -dependencies = [ - "crossbeam-utils", -] - [[package]] name = "crossbeam-utils" version = "0.8.23" @@ -2081,19 +1902,6 @@ dependencies = [ "weezl", ] -[[package]] -name = "gio-sys" -version = "0.22.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6c28739f914c15b87a9856000bed9cbd5b3a8afbca5e982d9a299e1601422cb5" -dependencies = [ - "glib-sys", - "gobject-sys", - "libc", - "system-deps", - "windows-sys 0.61.2", -] - [[package]] name = "gl_generator" version = "0.14.0" @@ -2105,49 +1913,6 @@ dependencies = [ "xml-rs", ] -[[package]] -name = "glib" -version = "0.22.10" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4cf9e5bd8713f1990a92c422998826e0fb34824277b46bc59757373483c6694" -dependencies = [ - "bitflags 2.13.2", - "futures-channel", - "futures-core", - "futures-executor", - "futures-task", - "futures-util", - "gio-sys", - "glib-macros", - "glib-sys", - "gobject-sys", - "libc", - "memchr", - "smallvec", -] - -[[package]] -name = "glib-macros" -version = "0.22.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c9597c68fa7bdf4154a3079642cd21c4dccac0b0bdd2897d82861523bf91e7b9" -dependencies = [ - "heck", - "proc-macro2", - "quote", - "syn 3.0.9", -] - -[[package]] -name = "glib-sys" -version = "0.22.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "99b38907e67e40dec9b60f858bcada952598719cb512a13eb13d6cdcd16f8295" -dependencies = [ - "libc", - "system-deps", -] - [[package]] name = "glob" version = "0.3.4" @@ -2244,17 +2009,6 @@ dependencies = [ "gl_generator", ] -[[package]] -name = "gobject-sys" -version = "0.22.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "07595c9ba696bd9819cb6a8df39f08078f3dd679508fe052dd558492c2053834" -dependencies = [ - "glib-sys", - "libc", - "system-deps", -] - [[package]] name = "gpu-allocator" version = "0.28.0" @@ -2275,129 +2029,6 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b40ca9252762c466af32d0b1002e91e4e1bc5398f77455e55474deb466355ff5" -[[package]] -name = "gstreamer" -version = "0.25.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4237e2066a25ecb7e54be6c066409e30615920265b9799b8d560ef8ac9857c6" -dependencies = [ - "cfg-if", - "futures-channel", - "futures-core", - "futures-util", - "glib", - "gstreamer-sys", - "itertools 0.15.0", - "kstring", - "libc", - "muldiv", - "num-integer", - "num-rational", - "option-operations", - "pastey 0.2.3", - "pin-project-lite", - "smallvec", - "thiserror 2.0.21", -] - -[[package]] -name = "gstreamer-app" -version = "0.25.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "97f8ae9238c2352398dcc084de28df3f7099af216ac6c160b52318d23f25c010" -dependencies = [ - "futures-core", - "futures-sink", - "glib", - "gstreamer", - "gstreamer-app-sys", - "gstreamer-base", - "libc", -] - -[[package]] -name = "gstreamer-app-sys" -version = "0.25.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0798b8aef6694341d40bb81edc759f8979b896b59f9f0f45d8cfa3bb7bf2e743" -dependencies = [ - "glib-sys", - "gstreamer-base-sys", - "gstreamer-sys", - "libc", - "system-deps", -] - -[[package]] -name = "gstreamer-base" -version = "0.25.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "17cbd8f59586a369c40d4b0d2f3a61cf9e9287b3cf5503cdcd8e7c5faa99265e" -dependencies = [ - "atomic_refcell", - "cfg-if", - "glib", - "gstreamer", - "gstreamer-base-sys", - "libc", -] - -[[package]] -name = "gstreamer-base-sys" -version = "0.25.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3b05f77bfd76b5afee6b29c27dae19eaf5018b5cf8d0d17520f3de44c6385c32" -dependencies = [ - "glib-sys", - "gobject-sys", - "gstreamer-sys", - "libc", - "system-deps", -] - -[[package]] -name = "gstreamer-sys" -version = "0.25.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "436d9532847489a8285d57b8c3670762c12a18f777fdc2ab159b52e0e6f521b9" -dependencies = [ - "cfg-if", - "glib-sys", - "gobject-sys", - "libc", - "system-deps", -] - -[[package]] -name = "gstreamer-video" -version = "0.25.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ffe4d77b2a5e679973d9c6b6c052da8cda86b83f5c268872f8691fde693fde84" -dependencies = [ - "cfg-if", - "futures-channel", - "glib", - "gstreamer", - "gstreamer-base", - "gstreamer-video-sys", - "libc", - "thiserror 2.0.21", -] - -[[package]] -name = "gstreamer-video-sys" -version = "0.25.4" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ef455da22edca97ac9299d682b868227f3d9217b303748ce0161b31ae82dc106" -dependencies = [ - "glib-sys", - "gobject-sys", - "gstreamer-base-sys", - "gstreamer-sys", - "libc", - "system-deps", -] - [[package]] name = "half" version = "2.7.1" @@ -2509,7 +2140,6 @@ version = "1.18.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0f519a8611a4982921e46e391015e5e40ceac5cc63813333ef91ada77df180d8" dependencies = [ - "bytemuck", "calloop 0.14.5", "cfg_aliases", "drm", @@ -2518,10 +2148,8 @@ dependencies = [ "i-slint-common", "i-slint-core", "i-slint-renderer-femtovg", - "i-slint-renderer-software", "input 0.10.0", "libseat", - "memmap2", "nix 0.31.3", "raw-window-handle", "xkbcommon 0.9.0", @@ -2536,7 +2164,6 @@ dependencies = [ "cfg-if", "cfg_aliases", "i-slint-backend-linuxkms", - "i-slint-backend-testing", "i-slint-backend-winit", "i-slint-common", "i-slint-core", @@ -2544,30 +2171,14 @@ dependencies = [ "i-slint-renderer-femtovg", ] -[[package]] -name = "i-slint-backend-testing" -version = "1.18.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01943d6c5ea5bc913d497bdaa423c309e7627afff47a6794bfd13be5c564209f" -dependencies = [ - "cfg_aliases", - "i-slint-common", - "i-slint-core", - "i-slint-renderer-software", - "vtable", -] - [[package]] name = "i-slint-backend-winit" version = "1.18.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dae4fcf1b19e9cb109984d2af87d2b9485388c619265bff71dd523133888bee2" dependencies = [ - "accesskit", - "accesskit_winit", "arboard", "block2 0.6.2", - "bytemuck", "cfg-if", "cfg_aliases", "futures", @@ -2578,8 +2189,6 @@ dependencies = [ "i-slint-core-macros", "i-slint-renderer-femtovg", "i-slint-renderer-skia", - "i-slint-renderer-software", - "imgref", "lyon_path", "muda", "objc2 0.6.5", @@ -2589,7 +2198,6 @@ dependencies = [ "objc2-ui-kit 0.3.2", "pin-weak", "raw-window-handle", - "rgb", "scoped-tls-hkt", "scopeguard", "softbuffer", @@ -2660,8 +2268,6 @@ version = "1.18.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed2ea15059d70bc31b1a8b1eb4c34f2c5df04cb7e53f36179b43c0261231d646" dependencies = [ - "accesskit", - "async-channel", "bitflags 2.13.2", "cfg-if", "chrono", @@ -2674,7 +2280,6 @@ dependencies = [ "icu_normalizer", "image", "js-sys", - "ksni", "lyon_algorithms", "lyon_extra", "lyon_geom", @@ -3301,35 +2906,6 @@ version = "3.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc" -[[package]] -name = "ksni" -version = "0.3.7" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1bcc1cb43797140f74b711f1c4a49f48a7a7429f211c5fb78264e7bcd1e99caf" -dependencies = [ - "arc-swap", - "async-executor", - "async-io", - "async-lock", - "crossbeam-queue", - "futures-channel", - "futures-lite", - "futures-util", - "pastey 0.2.3", - "serde", - "task-local", - "zbus", -] - -[[package]] -name = "kstring" -version = "2.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7a09b82a7f771ed02dc0dd9b27130a0fa5499fa15ed3027116c1e5e4e591bd9e" -dependencies = [ - "static_assertions", -] - [[package]] name = "kurbo" version = "0.13.1" @@ -3652,12 +3228,6 @@ dependencies = [ "windows-sys 0.61.2", ] -[[package]] -name = "muldiv" -version = "1.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "956787520e75e9bd233246045d19f42fb73242759cc57fba9611d940ae96d4b0" - [[package]] name = "naga" version = "30.0.1" @@ -4227,15 +3797,6 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" -[[package]] -name = "option-operations" -version = "0.6.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "aca39cf52b03268400c16eeb9b56382ea3c3353409309b63f5c8f0b1faf42754" -dependencies = [ - "pastey 0.2.3", -] - [[package]] name = "orbclient" version = "0.3.55" @@ -4325,7 +3886,6 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "22d2ff88bd3f7d68d1d9b09c7e6209f9a8e8c05088295140a2bcf2e9b17038c5" dependencies = [ - "accesskit", "fontique", "harfrust", "hashbrown 0.17.1", @@ -4359,12 +3919,6 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec" -[[package]] -name = "pastey" -version = "0.2.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" - [[package]] name = "percent-encoding" version = "2.3.2" @@ -4382,49 +3936,6 @@ dependencies = [ "indexmap", ] -[[package]] -name = "phf" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" -dependencies = [ - "phf_macros", - "phf_shared", - "serde", -] - -[[package]] -name = "phf_generator" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" -dependencies = [ - "fastrand", - "phf_shared", -] - -[[package]] -name = "phf_macros" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" -dependencies = [ - "phf_generator", - "phf_shared", - "proc-macro2", - "quote", - "syn 2.0.119", -] - -[[package]] -name = "phf_shared" -version = "0.13.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" -dependencies = [ - "siphasher", -] - [[package]] name = "pico-args" version = "0.5.0" @@ -5221,9 +4732,20 @@ dependencies = [ "serde_core", ] +[[package]] +name = "sf-app" +version = "0.1.0" +source = "git+https://gitea.bluefox.support/fennec/sdk?tag=v0.1.0#f00e8c68479ec5271d06be5737d5c60a831c944e" +dependencies = [ + "anyhow", + "log", + "serde", + "toml 0.9.12+spec-1.1.0", +] + [[package]] name = "sf-compositor" -version = "0.2.1" +version = "0.3.0" dependencies = [ "anyhow", "sf-ipc", @@ -5234,7 +4756,7 @@ dependencies = [ [[package]] name = "sf-core" -version = "0.2.1" +version = "0.3.0" dependencies = [ "anyhow", "env_logger", @@ -5244,11 +4766,12 @@ dependencies = [ "sf-dial", "sf-ipc", "tokio", + "toml 0.9.12+spec-1.1.0", ] [[package]] name = "sf-dial" -version = "0.2.1" +version = "0.3.0" dependencies = [ "anyhow", "log", @@ -5258,18 +4781,19 @@ dependencies = [ [[package]] name = "sf-ipc" -version = "0.2.1" +version = "0.3.0" dependencies = [ "anyhow", "log", "serde", "serde_json", + "sf-app", "toml 0.9.12+spec-1.1.0", ] [[package]] name = "sf-launcher" -version = "0.2.1" +version = "0.3.0" dependencies = [ "anyhow", "chrono", @@ -5289,7 +4813,7 @@ dependencies = [ [[package]] name = "sf-miracast" -version = "0.2.1" +version = "0.3.0" dependencies = [ "anyhow", "env_logger", @@ -5299,21 +4823,9 @@ dependencies = [ "zbus", ] -[[package]] -name = "sf-pack" -version = "0.2.1" -dependencies = [ - "anyhow", - "ruzstd", - "serde", - "sf-ipc", - "tar", - "toml 0.9.12+spec-1.1.0", -] - [[package]] name = "sf-remote" -version = "0.2.1" +version = "0.3.0" dependencies = [ "anyhow", "bluer", @@ -5327,35 +4839,19 @@ dependencies = [ [[package]] name = "sf-ui" -version = "0.2.1" +version = "0.1.0" +source = "git+https://gitea.bluefox.support/fennec/sdk?tag=v0.1.0#f00e8c68479ec5271d06be5737d5c60a831c944e" dependencies = [ "anyhow", "glow 0.16.0", - "gstreamer", - "gstreamer-app", - "gstreamer-video", - "image", "log", "png", "slint", - "ureq", -] - -[[package]] -name = "sf-ui-gallery" -version = "0.2.1" -dependencies = [ - "anyhow", - "env_logger", - "log", - "sf-ui", - "slint", - "slint-build", ] [[package]] name = "sf-update" -version = "0.2.1" +version = "0.3.0" dependencies = [ "anyhow", "base64 0.22.1", @@ -5908,19 +5404,6 @@ dependencies = [ "web-sys", ] -[[package]] -name = "system-deps" -version = "9.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "db551ad38aac61d5e0343e0eeeb0163be3115c4e23b6a025959570ee0c03c67d" -dependencies = [ - "cfg-expr", - "heck", - "pkg-config", - "toml 1.1.8+spec-1.1.0", - "version-compare", -] - [[package]] name = "taffy" version = "0.10.1" @@ -5950,21 +5433,6 @@ dependencies = [ "xattr", ] -[[package]] -name = "target-lexicon" -version = "0.13.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" - -[[package]] -name = "task-local" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2972044a9e5e448a506a7ff6f0d03b566d8ef4cd6918a58fc59835a0f8666626" -dependencies = [ - "pin-project-lite", -] - [[package]] name = "tempfile" version = "3.27.0" @@ -6549,12 +6017,6 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" -[[package]] -name = "version-compare" -version = "0.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e" - [[package]] name = "version_check" version = "0.9.5" @@ -7587,30 +7049,6 @@ dependencies = [ "zvariant", ] -[[package]] -name = "zbus-lockstep" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6998de05217a084b7578728a9443d04ea4cd80f2a0839b8d78770b76ccd45863" -dependencies = [ - "zbus_xml", - "zvariant", -] - -[[package]] -name = "zbus-lockstep-macros" -version = "0.5.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "10da05367f3a7b7553c8cdf8fa91aee6b64afebe32b51c95177957efc47ca3a0" -dependencies = [ - "proc-macro2", - "quote", - "syn 2.0.119", - "zbus-lockstep", - "zbus_xml", - "zvariant", -] - [[package]] name = "zbus_macros" version = "5.19.0" @@ -7637,18 +7075,6 @@ dependencies = [ "zvariant", ] -[[package]] -name = "zbus_xml" -version = "5.2.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1586c021a01ca0a9216dcd874e546382e156a5cbab5fab6cb5f10087e22682a" -dependencies = [ - "serde", - "winnow 1.0.4", - "zbus_names", - "zvariant", -] - [[package]] name = "zcheapstr" version = "1.1.0" diff --git a/Cargo.toml b/Cargo.toml index 2a95649..98fa78a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,14 +1,18 @@ [workspace] resolver = "3" -members = ["crates/sf-ipc", "crates/sf-pack", "crates/sf-ui", "crates/sf-ui/gallery", "crates/sf-launcher", "crates/sf-remote", "crates/sf-dial", "crates/sf-core", "crates/sf-update", "crates/sf-miracast", "crates/sf-compositor"] +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.2.1" +version = "0.3.0" edition = "2024" license = "MIT" [workspace.dependencies] 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-dial = { path = "crates/sf-dial" } serde = { version = "1", features = ["derive"] } serde_json = "1" diff --git a/README.md b/README.md index 9fc190b..1b83c33 100644 --- a/README.md +++ b/README.md @@ -46,7 +46,7 @@ cargo run --release -p sf-launcher Windowson (vagy `SMARTFOX_DEMO_SYSTEM=1`-gyel) demó adatokkal fut, a rendszert nem módosítja. -A Netflex szerver a Netflex app beállítása (a Részletek lapon látszik), a címét így adod meg: +A Netflex app (store app, [`fennec/netflex`](https://gitea.bluefox.support/fennec/netflex)) a szerverét maga kéri be. A kezdőlap Netflex-sávja a launcher beállításaiból olvassa a szervert: ```toml # settings.toml netflex_server = "https://netflex.furbidden.cloud" @@ -57,19 +57,17 @@ netflex_token = "..." # opcionális: a kezdőlap „Folytatás” sorához - Netflexen a felső sáv kártyákat mutat. Ha van `netflex_token`, a szerver `/api/home` végpontjáról jön a „Folytatás” sor (haladásjelzővel), különben a szerver első katalógussora. Token nélkül a Cinemeta nyilvános „Népszerű filmek” listája látszik. - A legutóbbi jó eredmény a `cache/shelf/` mappába kerül, így hálózat nélkül is megmarad. Ha semmi sincs, a sáv a Netflex saját leírását mutatja: a kezdőlap szerver nélkül is teljes. - A többi appnál a sáv az app nevét, leírását és élő adatait mutatja (pl. AirPlay: „Látható Fennec OS néven”, Beállítások: távirányító-akku, hálózat, felbontás). -- A kártyák egyelőre csak előnézetek: a Netflex webapp még nem kezel közvetlen linket egy címre. +- A kártyák egyelőre csak előnézetek: a Netflex app még nem kezel közvetlen linket egy címre. ## Felépítés ``` -crates/sf-ipc/ manifestek, beállítások, IPC üzenetek (közös a daemonokkal) +crates/sf-ipc/ IPC üzenetek, socketek, store-fájlok; újraexportálja az SDK sf-app crate-jét crates/sf-remote/ Siri Remote driver (BlueZ GATT -> uinput), csak Linux tools/siri-remote/ párosítás (fastpair.py), nyers HID/btmon elemzők, host setup scriptek crates/sf-launcher/ Slint UI (ui/*.slint) + src/glass/ (OpenGL háttér és üveg shaderek) -apps//app.toml appok: kind = "web" | "exec" | "builtin" +apps//app.toml a rendszer saját appjai (Beállítások, App Store, AirPlay, Miracast) crates/sf-update/ csomag-frissítő (root): aláírt shell- és app-csomagok a Gitea registryből és store appok a GitHub/Gitea/GitLab release-ekből -crates/sf-pack/ app-csomagoló fejlesztőknek: kulcs, csomag, aláírás, futtatás sandboxban -templates/rust-app/ sablon egy store apphoz Rustban, release pipeline-okkal tools/pkg/ csomagok építése, aláírása, feltöltése (a CI is ezt futtatja) crates/sf-core/ daemon: appok életciklusa, DIAL szerver, AirPlay/Miracast vevők felügyelete crates/sf-dial/ DIAL protokoll (SSDP + REST), a YouTube castoláshoz @@ -77,6 +75,26 @@ crates/sf-miracast/ kísérleti Miracast vevő (iwd Wi-Fi Direct + WFD RTSP + crates/sf-compositor/ Smithay kiosk kompozitor (DRM/KMS; fejlesztéshez ablakban is fut) ``` +**Külön repók** (`gitea.bluefox.support/fennec/...`): + +| Repó | Mi van benne | +|---|---| +| [`sdk`](https://gitea.bluefox.support/fennec/sdk) | Fennec SDK: `sf-app` (app-szerződés: manifest, engedélyek, sandbox, indítás), `sf-ui` (UI-készlet), `sf-pack` (csomagoló), app-sablon, fejlesztői útmutató | +| [`netflex`](https://gitea.bluefox.support/fennec/netflex) | Netflex, natív store app | +| [`youtube`](https://gitea.bluefox.support/fennec/youtube) | YouTube TV, web store app, castolható | +| [`steam`](https://gitea.bluefox.support/fennec/steam) | Steam, store app a Valve hivatalos csomagjából | +| [`store`](https://gitea.bluefox.support/fennec/store) | a Fennec katalógus: ezt a forrást kapja minden új TV | + +## Fennec SDK +Az OS egy SDK-tagre hivatkozik (`Cargo.toml` → `[workspace.dependencies]`: `sf-app`, `sf-ui`). Újabb SDK: emeld a `tag`-et, és futtass egy `cargo update -p sf-app -p sf-ui` parancsot. + +**Az SDK helyi fejlesztése az OS mellett:** klónozd a `G:\source\fennec\sdk` mappába, és tedd ezt a `.cargo/config.toml` fájlba (gitignore-olt): +```toml +[patch."https://gitea.bluefox.support/fennec/sdk"] +sf-app = { path = "../fennec/sdk/sf-app" } +sf-ui = { path = "../fennec/sdk/sf-ui" } +``` + **Hogyan készül a Liquid Glass hatás:** a Slint FemtoVG (OpenGL) rendererének `BeforeRendering` hookjában fut egy saját két passos GL réteg (`src/glass/`). 1. A háttér egy sötét, lassan áramló, homályos színátmenet a fókuszált app palettájából (néhány lágy színfolt, kettő árnyalat-eltolással). Mivel eleve homályos, kis felbontású (max. 640 px széles, RGBA16F, ha a driver tudja) mipmappelt textúrába renderelődik, majd ditherrel felskálázva kerül a képernyőre. Fókuszváltáskor a színek a CPU-n úsznak át, a GPU egyszer számol. 2. Az üvegpanelek egyenként, csak a saját téglalapjukon (plusz árnyék-margó) rajzolódnak, keveréssel (`dst * a + rgb`), így a teljes képernyőn nem fut végig minden panelre a shader. Az Apple Liquid Glass mintájára a fényt nem szórja (blur), hanem töri: @@ -174,9 +192,10 @@ Az image (a rendszer) csak újratelepítéssel változik. A részletek és a pro - a csomag-aláíró kulcs: `%USERPROFILE%\.smartfox\signing-key.pem` és a `SF_SIGNING_KEY` CI-secret. ## App Store és sandbox -**Store appok:** nyílt forrású, külső appok, mindegyik a saját GitHub-, Gitea/Forgejo- vagy GitLab-repójában. A release-eikből települnek, a szerzőjük kulcsával aláírva. A gyári appok maradnak ebben a repóban. +**Store appok:** minden app, ami nem a rendszer része, a saját GitHub-, Gitea/Forgejo- vagy GitLab-repójában él, és a release-eiből települ. Ilyen a Netflex, a YouTube és a Steam is (a Fennec katalógusból). Ebben a repóban csak a rendszer saját appjai maradnak: Beállítások, App Store, AirPlay, Miracast. - **Forrás hozzáadása:** az App Store → Források menüben. Lehet egy app repója, vagy egy katalógus-repó (`smartfox-store.toml`), amely sok appot hoz egyszerre. - **Telepítés:** előtte látszanak az app engedélyei. +- **Új TV-n:** a Fennec katalógus forrásként szerepel, a Netflex, a YouTube és a Steam telepítve van (az image építésekor kerülnek bele, lásd `image/mkosi.extra/usr/share/smartfox/factory-store.toml`). - **Frissítés:** ugyanaz a rendszer frissíti őket, mint a többi csomagot (6 óránként, vagy Frissítések → Telepítés most). Ha egy frissítés új engedélyt kér, jóváhagyásig vár. **Sandbox:** minden app bubblewrap sandboxban fut, mint a Flatpak. @@ -184,13 +203,9 @@ Az image (a rendszer) csak újratelepítéssel változik. A részletek és a pro - A képernyőt (Wayland) mindig eléri. Hálózat, GPU, hang, kontroller, D-Bus és eszközök csak engedéllyel. - Kivétel: az AirPlay és a Miracast vevő, mert ezek rendszer-szolgáltatások. -**Steam:** a Valve hivatalos `steam-launcher` csomagjából jön, előtelepítve. -- `gamescope`-ban fut, a kontrolleres felületével. -- `sf-app-steam` csomagként frissül: a CI hetente megnézi, van-e új hivatalos verzió. +**Steam:** store app ([`fennec/steam`](https://gitea.bluefox.support/fennec/steam)), a Valve hivatalos `steam-launcher` csomagjából. Az OS adja hozzá a rendszerszintű részt: `gamescope`, 32 bites könyvtárak, kontrolleres udev-szabályok. -**Rust (vagy bármilyen natív) app készítése:** [`templates/rust-app`](templates/rust-app). -- Az `sf-pack` eszköz kulcsot generál, csomagol és aláír. -- `sf-pack run `: ugyanabban a sandboxban futtatja az appot, mint a TV. +**App készítése:** a [Fennec SDK](https://gitea.bluefox.support/fennec/sdk)-val (útmutató, sablon, `sf-pack`). Az OS forráskódja nem kell hozzá. A részletek: [`docs/store.md`](docs/store.md). diff --git a/apps/netflex/app.toml b/apps/netflex/app.toml deleted file mode 100644 index 90e44b4..0000000 --- a/apps/netflex/app.toml +++ /dev/null @@ -1,15 +0,0 @@ -id = "netflex" -name = "Netflex" -version = "1.0.0" -kind = "web" -category = "Saját streaming" -description = "Filmek, sorozatok és anime a saját szerveredről. Válaszd ki, és már nézheted is, miközben töltődik." -url = "${settings.netflex_server}/" -icon = "netflex" -accent = "#E50914" -palette = ["#ff4a3d", "#8c0b14", "#120305"] -order = 10 - -[web] -# "SMART-TV" turns on the Netflex 10-foot UI (see packages/client/src/remote.ts → isTv). -user_agent_suffix = "SMART-TV FennecOS/0.1" diff --git a/apps/steam/app.toml b/apps/steam/app.toml deleted file mode 100644 index 099a221..0000000 --- a/apps/steam/app.toml +++ /dev/null @@ -1,21 +0,0 @@ -id = "steam" -name = "Steam" -# Set by tools/pkg/steam/package.sh to the official steam-launcher version: -# the package (sf-app-steam) is rebuilt whenever Valve releases a new one. -version = "0.0.0" -kind = "exec" -category = "Játékok" -description = "A hivatalos Steam kliens, kontrollerrel kezelhető Big Picture felülettel. Az első indításkor letölti magát, ez néhány percig tart." -# gamescope (Valve's own compositor, as on the Steam Deck) hosts the X11 -# Steam client and the games, and scales them to the TV. -exec = ["bin/smartfox-steam"] -icon = "steam" -accent = "#66C0F4" -palette = ["#66c0f4", "#1b4f7a", "#060b12"] -order = 25 - -[sandbox] -# Steam runs its games in its own container (pressure-vessel), nested in -# this sandbox. Its data, games included, are in the app's data folder -# (~/.local/share/smartfox/apps/steam). -permissions = ["network", "gpu", "audio", "gamepad", "dbus-session"] diff --git a/apps/steam/bin/smartfox-steam b/apps/steam/bin/smartfox-steam deleted file mode 100644 index 18699f4..0000000 --- a/apps/steam/bin/smartfox-steam +++ /dev/null @@ -1,24 +0,0 @@ -#!/bin/sh -# Starts the official Steam client (steam/, from Valve's steam-launcher -# package) in its gamepad UI, inside gamescope: the client and the games are -# X11 programs, gamescope gives them an X server and shows them as one -# Wayland window on the TV. -# -# Output: the TV's current mode. Games render at most at 1080p (an N100 can't -# do 4K) and gamescope scales them up. -APP="${SMARTFOX_APP_DIR:-$(cd "$(dirname "$0")/.." && pwd)}" - -mode=$(wlr-randr 2>/dev/null | awk '/current/ {print $1; exit}') -W=${mode%x*} -H=${mode#*x} -case "$W:$H" in - *[!0-9:]* | :* | *:) W=1920 H=1080 ;; -esac -GW=$W GH=$H -if [ "$H" -gt 1080 ]; then - GW=$((W * 1080 / H)) - GH=1080 -fi - -GAMESCOPE=$(command -v gamescope || echo /usr/games/gamescope) -exec "$GAMESCOPE" -e -f -W "$W" -H "$H" -w "$GW" -h "$GH" -- "$APP/steam/steam" -gamepadui "$@" diff --git a/apps/youtube/app.toml b/apps/youtube/app.toml deleted file mode 100644 index 48a501a..0000000 --- a/apps/youtube/app.toml +++ /dev/null @@ -1,18 +0,0 @@ -id = "youtube" -name = "YouTube" -version = "1.0.0" -kind = "web" -category = "Videó · Castolható" -description = "A YouTube TV-s felülete. Telefonról a YouTube appban a cast ikonnal küldhetsz ide videót." -url = "https://www.youtube.com/tv" -icon = "youtube" -accent = "#FF2D2D" -palette = ["#ff6a5c", "#a3121c", "#16070a"] -order = 20 - -[web] -# A Cobalt (TV) user agent makes YouTube serve its leanback UI. -user_agent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0 Safari/537.36 Cobalt/25.lts.30.1034943-gold (unlike Gecko), Unknown_TV_Unknown_0/Unknown (Fennec OS, SF1, Wired)" - -[dial] -name = "YouTube" diff --git a/crates/sf-core/Cargo.toml b/crates/sf-core/Cargo.toml index 59b0329..d9dcbc4 100644 --- a/crates/sf-core/Cargo.toml +++ b/crates/sf-core/Cargo.toml @@ -16,3 +16,6 @@ serde_json.workspace = true [target.'cfg(unix)'.dependencies] tokio = { version = "1", features = ["rt", "net", "time", "io-util", "sync", "macros", "process", "signal"] } libc = "0.2" + +[dev-dependencies] +toml.workspace = true diff --git a/crates/sf-core/src/dial.rs b/crates/sf-core/src/dial.rs index 7e02496..bb0043f 100644 --- a/crates/sf-core/src/dial.rs +++ b/crates/sf-core/src/dial.rs @@ -1,10 +1,12 @@ //! DIAL glue: apps with a `[dial]` section in their manifest (YouTube) can be -//! started from a phone. +//! started from a phone. Store apps may do it too (the `dial` permission the +//! user approved); an official app with the same DIAL name wins. use std::sync::Arc; use anyhow::{Context, Result}; use sf_dial::{AppState, Config, Handler, LaunchParams}; +use sf_ipc::{AppManifest, Origin}; use crate::apps::Core; @@ -12,7 +14,32 @@ struct Dial(Arc); impl Dial { fn app_for(&self, dial_name: &str) -> Option { - self.0.apps().into_iter().find(|a| a.dial.as_ref().is_some_and(|d| d.name == dial_name)).map(|a| a.id) + pick(self.0.apps(), dial_name) + } +} + +/// The app that answers to `dial_name`: official apps first, then store apps +/// (in the app list's order). +fn pick(apps: Vec, dial_name: &str) -> Option { + let mut found: Vec = apps.into_iter().filter(|a| a.dial.as_ref().is_some_and(|d| d.name == dial_name)).collect(); + found.sort_by_key(|a| a.origin == Origin::Store); + found.into_iter().next().map(|a| a.id) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn official_dial_app_wins() { + let app = |id: &str, origin| { + let mut a: AppManifest = toml::from_str(&format!("id = '{id}'\nname = 'x'\nkind = 'web'\nurl = 'https://x'\n[dial]\nname = 'YouTube'\n")).unwrap(); + a.origin = origin; + a + }; + assert_eq!(pick(vec![app("io.x.tube", Origin::Store), app("youtube", Origin::Official)], "YouTube").as_deref(), Some("youtube")); + assert_eq!(pick(vec![app("io.x.tube", Origin::Store)], "YouTube").as_deref(), Some("io.x.tube")); + assert_eq!(pick(vec![app("io.x.tube", Origin::Store)], "Netflix"), None); } } diff --git a/crates/sf-ipc/Cargo.toml b/crates/sf-ipc/Cargo.toml index 59b0a3b..22b458f 100644 --- a/crates/sf-ipc/Cargo.toml +++ b/crates/sf-ipc/Cargo.toml @@ -1,11 +1,12 @@ [package] name = "sf-ipc" -description = "Shared types for Fennec OS: app manifests, settings and IPC messages" +description = "Shared types for Fennec OS: IPC messages, sockets, store files; the app contract (sf-app) re-exported" version.workspace = true edition.workspace = true license.workspace = true [dependencies] +sf-app.workspace = true serde.workspace = true serde_json.workspace = true toml.workspace = true diff --git a/crates/sf-ipc/src/launch.rs b/crates/sf-ipc/src/launch.rs deleted file mode 100644 index a30701e..0000000 --- a/crates/sf-ipc/src/launch.rs +++ /dev/null @@ -1,283 +0,0 @@ -//! How apps are started: the command line for a web app (Chromium in kiosk or -//! app mode with its own profile) or an exec app. Shared by the launcher -//! (local testing on a desktop) and sf-core (the TV). - -use std::path::{Path, PathBuf}; -use std::process::Command; - -use anyhow::{Context, Result, bail}; - -use crate::{AppKind, AppManifest, Settings, paths, sandbox}; - -/// Environment variable carrying the app id into the app's processes. The -/// compositor reads it from `/proc//environ` to tell windows apart. -pub const APP_ENV: &str = "SMARTFOX_APP"; - -pub struct Browser { - pub exe: PathBuf, - /// Full version, used to build a realistic user agent. - pub version: String, -} - -pub fn find_browser() -> Option { - let mut candidates: Vec = Vec::new(); - if let Ok(p) = std::env::var("SMARTFOX_BROWSER") { - candidates.push(p.into()); - } - #[cfg(windows)] - { - for base in ["ProgramFiles", "ProgramFiles(x86)", "LOCALAPPDATA"] { - if let Some(b) = std::env::var_os(base) { - let b = PathBuf::from(b); - candidates.push(b.join(r"Google\Chrome\Application\chrome.exe")); - candidates.push(b.join(r"Chromium\Application\chrome.exe")); - candidates.push(b.join(r"Microsoft\Edge\Application\msedge.exe")); - } - } - } - #[cfg(not(windows))] - { - for name in ["chromium", "chromium-browser", "google-chrome-stable", "google-chrome"] { - for dir in ["/usr/bin", "/usr/local/bin", "/snap/bin"] { - candidates.push(Path::new(dir).join(name)); - } - } - } - let exe = candidates.into_iter().find(|p| p.is_file())?; - let version = browser_version(&exe).unwrap_or_else(|| "141.0.0.0".into()); - Some(Browser { exe, version }) -} - -fn browser_version(exe: &Path) -> Option { - // Windows installs keep a folder named after the version next to the exe. - if cfg!(windows) { - let dir = exe.parent()?; - let mut versions: Vec = std::fs::read_dir(dir) - .ok()? - .flatten() - .filter_map(|e| e.file_name().into_string().ok()) - .filter(|n| n.split('.').count() == 4 && n.split('.').all(|p| p.parse::().is_ok())) - .collect(); - versions.sort_by_key(|v| v.split('.').map(|p| p.parse::().unwrap_or(0)).collect::>()); - return versions.pop(); - } - let out = Command::new(exe).arg("--version").output().ok()?; - String::from_utf8_lossy(&out.stdout) - .split_whitespace() - .find(|w| w.chars().next().is_some_and(|c| c.is_ascii_digit()) && w.contains('.')) - .map(str::to_string) -} - -fn default_user_agent(version: &str) -> String { - let platform = if cfg!(windows) { "Windows NT 10.0; Win64; x64" } else { "X11; Linux x86_64" }; - let major = version.split('.').next().unwrap_or("141"); - format!("Mozilla/5.0 ({platform}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{major}.0.0.0 Safari/537.36") -} - -pub struct LaunchOptions<'a> { - /// Per-app browser profiles live in `/profiles/`. - pub data_dir: &'a Path, - pub fullscreen: bool, - /// Windowed mode: open the app exactly over the launcher (x, y, w, h). - pub bounds: Option<(i32, i32, u32, u32)>, - /// Extra query string for the start URL (DIAL launch parameters). - pub query: Option<&'a str>, -} - -/// A program with its arguments and environment, before it is (maybe) put -/// into the sandbox. -struct Inner { - program: String, - args: Vec, - env: Vec<(String, String)>, -} - -/// The bwrap binary if `app` runs sandboxed (`sandbox` module). Store apps -/// never run without it. Official apps run unsandboxed when bwrap is missing -/// (an older image under a newer shell) or with `SMARTFOX_SANDBOX=off` -/// (debugging), with a warning. -fn sandbox_for(app: &AppManifest) -> Result> { - if app.origin == crate::Origin::Store { - anyhow::ensure!(cfg!(target_os = "linux"), "store apps only run on the TV (Linux)"); - return sandbox::bwrap_path().context("bubblewrap (bwrap) is not installed, and store apps only run sandboxed").map(Some); - } - if !cfg!(target_os = "linux") || !app.sandboxed() { - return Ok(None); - } - if std::env::var("SMARTFOX_SANDBOX").is_ok_and(|v| v == "off") { - log::warn!("{}: SMARTFOX_SANDBOX=off, running without a sandbox", app.id); - return Ok(None); - } - let bwrap = sandbox::bwrap_path(); - if bwrap.is_none() { - log::warn!("{}: bubblewrap is not installed, running without a sandbox", app.id); - } - Ok(bwrap) -} - -/// The command that starts `app`. Not spawned yet, so callers can wrap it -/// (sf-core runs it inside a systemd scope). -pub fn command(app: &AppManifest, settings: &Settings, opts: &LaunchOptions) -> Result { - let bwrap = sandbox_for(app)?; - // Where the app's files are, as the app sees them. - let root = if bwrap.is_some() { PathBuf::from(sandbox::APP_DIR) } else { app.dir.clone() }; - let data = paths::app_data_dir(&app.id); - let inner = match app.kind { - AppKind::Web => web_command(app, settings, opts, &root, bwrap.is_some().then_some(data.as_path()))?, - AppKind::Exec => { - let line = app.resolved_exec(&root); - let (prog, args) = line.split_first().context("empty exec command")?; - Inner { program: prog.clone(), args: args.to_vec(), env: Vec::new() } - } - AppKind::Builtin => bail!("built-in app has no process"), - }; - let mut env = inner.env; - env.extend(app.env.iter().map(|(k, v)| (k.clone(), settings.expand(v)))); - - let mut cmd = match bwrap { - Some(bwrap) => { - std::fs::create_dir_all(&data).with_context(|| format!("creating {}", data.display()))?; - // Store apps sit behind symlinks (store/apps/ -> ../store-/current). - let app_dir = std::fs::canonicalize(&app.dir).unwrap_or_else(|_| app.dir.clone()); - let permissions = app.permissions(); - let spec = sandbox::Spec { - app_id: &app.id, - app_dir: &app_dir, - data_dir: &data, - extra_rw: Vec::new(), - permissions: &permissions, - env, - program: inner.program, - args: inner.args, - }; - let cmd = sandbox::command(&bwrap, &spec, &sandbox::Host::current()); - log::info!("{}: sandboxed, permissions: {:?}", app.id, permissions.iter().map(|p| p.key()).collect::>()); - cmd - } - None => { - let mut cmd = Command::new(&inner.program); - cmd.args(&inner.args).envs(env).env("SMARTFOX_APP_DIR", &app.dir); - cmd - } - }; - cmd.env(APP_ENV, &app.id); - // Own process group, so stopping the app also ends its helper processes. - #[cfg(unix)] - { - use std::os::unix::process::CommandExt; - cmd.process_group(0); - } - Ok(cmd) -} - -/// Adds `query` to `url`, before any `#fragment`. -pub fn with_query(url: &str, query: Option<&str>) -> String { - let Some(q) = query.map(|q| q.trim_start_matches(['?', '&'])).filter(|q| !q.is_empty()) else { - return url.to_string(); - }; - let (base, frag) = match url.find('#') { - Some(i) => (&url[..i], &url[i..]), - None => (url, ""), - }; - let sep = if base.contains('?') { '&' } else { '?' }; - format!("{base}{sep}{q}{frag}") -} - -/// First-run preferences for an app profile: no translate prompt, Hungarian -/// content language. Existing profiles are left alone. -fn seed_profile(profile: &Path) -> Result<()> { - let prefs = profile.join("Default").join("Preferences"); - if prefs.exists() { - return Ok(()); - } - std::fs::create_dir_all(prefs.parent().unwrap())?; - std::fs::write( - &prefs, - r#"{"translate":{"enabled":false},"intl":{"accept_languages":"hu-HU,hu,en"},"browser":{"has_seen_welcome_page":true}}"#, - )?; - Ok(()) -} - -/// The browser command for a web app. `sandbox_home`: the app's data folder -/// when it runs sandboxed; its Chromium profile then lives in there. -fn web_command(app: &AppManifest, settings: &Settings, opts: &LaunchOptions, root: &Path, sandbox_home: Option<&Path>) -> Result { - let browser = find_browser().context("no Chromium/Chrome/Edge found (set SMARTFOX_BROWSER)")?; - let url = app.resolved_url(settings).filter(|u| !u.is_empty()).context("app has no URL")?; - if url.starts_with('/') { - bail!("URL is not set (check settings: {url})"); - } - let url = with_query(&url, opts.query); - let old_profile = opts.data_dir.join("profiles").join(&app.id); - let profile = match sandbox_home { - Some(home) => { - let profile = home.join("chromium"); - // Profiles from before the sandbox (logins, settings) move along. - if old_profile.is_dir() && !profile.exists() { - std::fs::create_dir_all(home)?; - if let Err(e) = std::fs::rename(&old_profile, &profile) { - log::warn!("{}: moving the browser profile: {e}", app.id); - } - } - profile - } - None => old_profile, - }; - seed_profile(&profile)?; - - let ua = match (&app.web.user_agent, &app.web.user_agent_suffix) { - (Some(ua), _) => ua.clone(), - (None, Some(suffix)) => format!("{} {suffix}", default_user_agent(&browser.version)), - (None, None) => default_user_agent(&browser.version), - }; - - let mut args: Vec = vec![ - format!("--user-data-dir={}", profile.display()), - format!("--user-agent={ua}"), - "--no-first-run".into(), - "--no-default-browser-check".into(), - "--disable-session-crashed-bubble".into(), - "--hide-crash-restore-bubble".into(), - "--disable-features=Translate,TranslateUI,MediaRouter,LocalNetworkAccessChecks".into(), - "--lang=hu".into(), - "--accept-lang=hu-HU,hu,en".into(), - // Dark first paint instead of a white flash before the page draws. - "--force-dark-mode".into(), - "--autoplay-policy=no-user-gesture-required".into(), - "--overscroll-history-navigation=0".into(), - ]; - if opts.fullscreen { - args.extend(["--kiosk".into(), url]); - } else { - args.push(format!("--app={url}")); - match opts.bounds { - Some((x, y, w, h)) => args.extend([format!("--window-position={x},{y}"), format!("--window-size={w},{h}")]), - None => args.push("--window-size=1600,900".into()), - } - } - let mut env = Vec::new(); - if cfg!(target_os = "linux") { - // Chromium on Linux picks its UI language from the environment, not --lang. - env.push(("LANGUAGE".to_string(), "hu".to_string())); - args.push("--enable-features=VaapiVideoDecoder,VaapiIgnoreDriverChecks,PlatformHEVCDecoderSupport".into()); - if std::env::var_os("WAYLAND_DISPLAY").is_some() { - args.push("--ozone-platform=wayland".into()); - } - } - for ext in &app.web.extensions { - args.push(format!("--load-extension={}", root.join(ext).display())); - } - Ok(Inner { program: browser.exe.to_string_lossy().into_owned(), args, env }) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn adds_query() { - assert_eq!(with_query("https://www.youtube.com/tv", Some("a=1&b=2")), "https://www.youtube.com/tv?a=1&b=2"); - assert_eq!(with_query("https://x/tv?x=1#f", Some("?a=1")), "https://x/tv?x=1&a=1#f"); - assert_eq!(with_query("https://x/", None), "https://x/"); - assert_eq!(with_query("https://x/", Some("")), "https://x/"); - } -} diff --git a/crates/sf-ipc/src/lib.rs b/crates/sf-ipc/src/lib.rs index 0152e4d..46ad09a 100644 --- a/crates/sf-ipc/src/lib.rs +++ b/crates/sf-ipc/src/lib.rs @@ -1,12 +1,15 @@ //! Shared types for Fennec OS components (launcher, core daemon, remote daemon, -//! compositor). +//! compositor, updater). +//! +//! The app contract (manifests, permissions, sandbox, launching) lives in the +//! Fennec SDK (`sf-app`), so apps and their tools build without the OS. It is +//! re-exported here, so OS code keeps using `sf_ipc::manifest` and so on. + +pub use sf_app::{launch, sandbox, settings}; -pub mod launch; pub mod manifest; pub mod message; pub mod paths; -pub mod sandbox; -pub mod settings; pub mod store; pub use manifest::{AppKind, AppManifest, Origin, Permission, load_apps}; diff --git a/crates/sf-ipc/src/manifest.rs b/crates/sf-ipc/src/manifest.rs index 7e5d2e5..0aa249a 100644 --- a/crates/sf-ipc/src/manifest.rs +++ b/crates/sf-ipc/src/manifest.rs @@ -1,459 +1,110 @@ -//! App manifests: one `app.toml` per folder under the apps directory. -//! -//! Apps come from two places: -//! - factory apps (the image) and official packages (`sf-app-`, signed -//! with the Fennec OS key); -//! - the store: third-party apps from their own GitHub/Gitea/GitLab repos, -//! published in their own repo (docs/store.md). These always run sandboxed and -//! can never replace an official app. +//! App manifests: the Fennec SDK's `sf_app::manifest`, plus what only the OS +//! decides: which factory apps became store apps, and how a TV moves over. -use std::collections::BTreeMap; use std::path::{Path, PathBuf}; -use anyhow::{Context, Result}; -use serde::{Deserialize, Serialize}; +use anyhow::Result; -use crate::settings::Settings; +pub use sf_app::manifest::*; -#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] -#[serde(rename_all = "lowercase")] -pub enum AppKind { - /// Runs in the shared Chromium web runtime. - Web, - /// Any executable: AppImage, Rust binary, script. - Exec, - /// Built into the launcher (e.g. settings screen). - Builtin, +/// The Fennec catalog: the store source with the Bluefox apps. +pub const FENNEC_CATALOG: &str = "https://gitea.bluefox.support/fennec/store"; + +/// A factory app that became a store app (its own repo, Fennec catalog). +pub struct Retired { + /// The old official id (`apps/`, `sf-app-`). + pub id: &'static str, + /// The store app that replaces it. + pub replacement: &'static str, + /// Its repo (canonical https URL, as in store.toml). + pub source: &'static str, + /// What it asks for; the old app had the same, so it is approved. + pub permissions: &'static [Permission], + /// The old app's data folder (logins, Chromium profile) moves over. + pub move_data: bool, } -/// Where an app was loaded from. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub enum Origin { - /// The image or an official package. - #[default] - Official, - /// A store package from a third-party repo: always sandboxed. - Store, +pub const RETIRED: &[Retired] = &[ + Retired { + // The Netflex web app; the native app keeps its own login. + id: "netflex", + replacement: "support.bluefox.netflex", + source: "https://gitea.bluefox.support/fennec/netflex", + permissions: &[Permission::Network, Permission::Gpu, Permission::Audio], + move_data: false, + }, + Retired { + id: "youtube", + replacement: "support.bluefox.youtube", + source: "https://gitea.bluefox.support/fennec/youtube", + permissions: &[Permission::Network, Permission::Gpu, Permission::Audio, Permission::Dial], + move_data: true, + }, + Retired { + id: "steam", + replacement: "support.bluefox.steam", + source: "https://gitea.bluefox.support/fennec/steam", + permissions: &[Permission::Network, Permission::Gpu, Permission::Audio, Permission::Gamepad, Permission::DbusSession], + move_data: true, + }, +]; + +pub fn retired(id: &str) -> Option<&'static Retired> { + RETIRED.iter().find(|r| r.id == id) } -/// What a sandboxed app may reach besides its own files and the screen -/// (the Wayland socket). Shown to the user before installing. -#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)] -#[serde(rename_all = "kebab-case")] -pub enum Permission { - /// Internet and the local network. - Network, - /// Hardware graphics and video decoding (/dev/dri). - Gpu, - /// Sound output (PipeWire / PulseAudio socket). - Audio, - /// Game controllers: /dev/input, /dev/hidraw*, /dev/uinput. - Gamepad, - /// The user's D-Bus session bus (unfiltered). - DbusSession, - /// The system D-Bus (unfiltered). - DbusSystem, - /// Every device in /dev. - Devices, +pub fn is_retired(id: &str) -> bool { + retired(id).is_some() } -impl Permission { - pub const ALL: [Permission; 7] = [ - Permission::Network, - Permission::Gpu, - Permission::Audio, - Permission::Gamepad, - Permission::DbusSession, - Permission::DbusSystem, - Permission::Devices, - ]; - - /// Name used in app.toml and store.toml. - pub fn key(self) -> &'static str { - match self { - Permission::Network => "network", - Permission::Gpu => "gpu", - Permission::Audio => "audio", - Permission::Gamepad => "gamepad", - Permission::DbusSession => "dbus-session", - Permission::DbusSystem => "dbus-system", - Permission::Devices => "devices", - } - } - - pub fn from_key(key: &str) -> Option { - Permission::ALL.into_iter().find(|p| p.key() == key) - } - - /// Hungarian label for the store screen. - pub fn label(self) -> &'static str { - match self { - Permission::Network => "Internet és helyi hálózat", - Permission::Gpu => "Grafikus gyorsítás", - Permission::Audio => "Hang", - Permission::Gamepad => "Játékvezérlők", - Permission::DbusSession => "Munkamenet D-Bus", - Permission::DbusSystem => "Rendszer D-Bus", - Permission::Devices => "Minden eszköz (/dev)", - } - } - - /// Worth a warning: the app can reach far outside its sandbox. - pub fn risky(self) -> bool { - matches!(self, Permission::DbusSession | Permission::DbusSystem | Permission::Devices) - } -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct SandboxOptions { - /// Run in a bubblewrap sandbox. Only official apps may turn it off - /// (system receivers like AirPlay); store apps are always sandboxed. - /// Unset: on, except for official background services. - #[serde(default)] - pub enabled: Option, - #[serde(default)] - pub permissions: Vec, -} - -impl Default for SandboxOptions { - fn default() -> Self { - SandboxOptions { enabled: None, permissions: Vec::new() } - } -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct AppManifest { - pub id: String, - pub name: String, - pub kind: AppKind, - /// Package version (semver). Published as `sf-app-` when it changes; - /// the newer of a factory and an installed copy wins. - #[serde(default = "default_version")] - pub version: String, - /// Short label above the title in the hero ("Saját app", "Castolás"...). - #[serde(default)] - pub category: String, - #[serde(default)] - pub description: String, - /// Web apps: start URL. May contain `${settings.}` placeholders. - #[serde(default)] - pub url: Option, - /// Exec apps: command line. - #[serde(default)] - pub exec: Option>, - /// Built-in icon name used by the launcher. - #[serde(default)] - pub icon: String, - /// Accent color (hex), used for focus glow and buttons. - #[serde(default = "default_accent")] - pub accent: String, - /// Three colors for the animated hero backdrop: highlight, mid, deep. - #[serde(default)] - pub palette: Vec, - /// Sort order on the home row. - #[serde(default)] - pub order: i32, - #[serde(default)] - pub web: WebOptions, - #[serde(default)] - pub dial: Option, - /// Background receiver (AirPlay, Miracast): sf-core keeps it running all - /// the time and it shows its own window when something connects. The - /// launcher tile only opens the details sheet. - #[serde(default)] - pub service: bool, - #[serde(default)] - pub sandbox: SandboxOptions, - /// Extra environment for the app's process. - #[serde(default)] - pub env: BTreeMap, - /// Legacy store manifest field. Older signed releases may still contain it. - #[serde(default)] - pub public_key: Option, - /// Store apps: source code / home page, shown on the store screen. - #[serde(default)] - pub homepage: Option, - #[serde(default)] - pub author: Option, - #[serde(default)] - pub license: Option, - /// Folder the manifest was loaded from (not serialized). - #[serde(skip)] - pub dir: PathBuf, - #[serde(skip)] - pub origin: Origin, -} - -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub struct WebOptions { - /// Full user agent override. - #[serde(default)] - pub user_agent: Option, - /// Appended to the default user agent. - #[serde(default)] - pub user_agent_suffix: Option, - /// Unpacked extensions to load (paths relative to the app folder). - #[serde(default)] - pub extensions: Vec, -} - -#[derive(Debug, Clone, Serialize, Deserialize)] -pub struct DialOptions { - /// DIAL application name, e.g. "YouTube". - pub name: String, -} - -fn default_version() -> String { - "0.0.0".into() -} - -fn default_accent() -> String { - "#ffffff".into() -} - -impl AppManifest { - /// Start URL with `${settings.key}` placeholders filled in. - pub fn resolved_url(&self, settings: &Settings) -> Option { - self.url.as_ref().map(|u| settings.expand(u)) - } - - /// The command line with `${app}` replaced by `app_root` (where the app's - /// files are: its folder, or /app inside the sandbox). A relative program - /// path with a slash (`bin/hello`) is inside the app folder too; a bare - /// name (`uxplay`) is looked up in PATH. - pub fn resolved_exec(&self, app_root: &Path) -> Vec { - let root = app_root.to_string_lossy(); - let mut line: Vec = self.exec.iter().flatten().map(|a| a.replace("${app}", &root)).collect(); - if let Some(first) = line.first_mut() { - if first.contains('/') && !first.starts_with('/') { - *first = format!("{}/{}", root.trim_end_matches('/'), first.trim_start_matches("./")); - } - } - line - } - - /// What the app may reach from its sandbox. Web apps always get what a - /// browser needs. - pub fn permissions(&self) -> Vec { - let mut p = self.sandbox.permissions.clone(); - if self.kind == AppKind::Web { - p.extend([Permission::Network, Permission::Gpu, Permission::Audio]); - } - p.sort(); - p.dedup(); - p - } - - /// Store apps always run sandboxed; official ones unless they opt out. - pub fn sandboxed(&self) -> bool { - self.origin == Origin::Store || self.sandbox.enabled.unwrap_or(!self.service) - } - - /// An image file shipped with the app (`icon = "icon.png"`), if `icon` - /// isn't one of the launcher's built-in icon names. - pub fn icon_file(&self) -> Option { - let lower = self.icon.to_ascii_lowercase(); - if ![".png", ".svg", ".jpg", ".jpeg"].iter().any(|ext| lower.ends_with(ext)) { - return None; - } - if self.icon.contains("..") || Path::new(&self.icon).is_absolute() { - return None; - } - let path = self.dir.join(&self.icon); - path.is_file().then_some(path) - } - - /// Rules a store app must follow (checked by sf-update before installing - /// and by the launcher when loading). - pub fn check_store_rules(&self) -> Result<()> { - anyhow::ensure!(is_store_id(&self.id), "store app id {:?} must be a reverse domain name (io.github.user.app)", self.id); - anyhow::ensure!(self.kind != AppKind::Builtin, "store apps can't be built-in"); - anyhow::ensure!(!self.service, "store apps can't be background services"); - anyhow::ensure!(self.dial.is_none(), "store apps can't register for DIAL"); - anyhow::ensure!(self.sandbox.enabled != Some(false), "store apps can't turn off the sandbox"); - match self.kind { - AppKind::Exec => anyhow::ensure!(!self.resolved_exec(Path::new("/app")).is_empty(), "exec is missing"), - AppKind::Web => anyhow::ensure!(self.url.as_deref().is_some_and(|u| u.starts_with("https://")), "web apps need an https:// url"), - AppKind::Builtin => {} - } - Ok(()) - } -} - -/// Store app ids are reverse domain names with at least one dot -/// (`io.github.user.app`). Official app ids never have a dot, so a store app -/// can't take the place of one. -pub fn is_store_id(id: &str) -> bool { - let parts: Vec<&str> = id.split('.').collect(); - id.len() <= 128 - && parts.len() >= 2 - && parts.iter().all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')) - && parts[0].bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit()) -} - -/// Loads every `*/app.toml` under `dir`, sorted by `order` then name. -pub fn load_apps(dir: &Path) -> Result> { - let mut apps = Vec::new(); - let entries = std::fs::read_dir(dir).with_context(|| format!("reading {}", dir.display()))?; - for entry in entries.flatten() { - let path = entry.path().join("app.toml"); - if !path.is_file() { - continue; - } - match load_one(&path) { - Ok(app) => apps.push(app), - Err(e) => log::warn!("skipping {}: {e:#}", path.display()), - } - } - sort_apps(&mut apps); - Ok(apps) -} - -/// Loads apps from several folders (factory apps, then installed packages). -/// Missing folders are skipped; of two apps with the same id the higher -/// `version` wins, on a tie the later folder. -pub fn load_apps_from(dirs: &[PathBuf]) -> Result> { - let mut apps: Vec = Vec::new(); - let mut found = false; - for dir in dirs { - if !dir.is_dir() { - continue; - } - found = true; - for app in load_apps(dir)? { - // Official ids have no dot; a store app here (developed inside - // the apps folder) belongs to the store, not the factory set. - if is_store_id(&app.id) { - log::info!("skipping {}: a store app id in an official apps folder", app.id); - continue; - } - match apps.iter_mut().find(|a| a.id == app.id) { - Some(old) if version_cmp(&app.version, &old.version).is_ge() => *old = app, - Some(_) => {} - None => apps.push(app), - } - } - } - anyhow::ensure!(found, "none of the app folders exist: {dirs:?}"); - sort_apps(&mut apps); - Ok(apps) -} - -/// Official apps from `dirs` (see `load_apps_from`), plus store apps from -/// `store`. A store app is skipped if it breaks the store rules or has the id -/// of an official app. +/// `sf_app::manifest::load_all`, where a retired official app (the old +/// factory copy in an older image, or its `sf-app-` package) stays only +/// until its store replacement is installed: the TV never loses the app. pub fn load_all(dirs: &[PathBuf], store: Option<&Path>) -> Result> { - let mut apps = load_apps_from(dirs)?; - if let Some(store) = store.filter(|d| d.is_dir()) { - for mut app in load_apps(store)? { - app.origin = Origin::Store; - if let Err(e) = app.check_store_rules() { - log::warn!("skipping store app {}: {e:#}", app.dir.display()); - } else if apps.iter().any(|a| a.id == app.id) { - log::warn!("skipping store app {}: an app with this id is already installed", app.id); - } else { - apps.push(app); + let apps = sf_app::manifest::load_all(dirs, store)?; + let replaced = |id: &str| retired(id).is_some_and(|r| apps.iter().any(|a| a.origin == Origin::Store && a.id == r.replacement)); + let keep: Vec = apps.iter().map(|a| a.origin == Origin::Store || !replaced(&a.id)).collect(); + Ok(apps.into_iter().zip(keep).filter_map(|(a, k)| k.then_some(a)).collect()) +} + +/// Moves the data folder of a retired app to its replacement, once the +/// replacement is installed and has no data yet (runs as the TV user). +pub fn migrate_data(apps: &[AppManifest]) { + for r in RETIRED.iter().filter(|r| r.move_data) { + if !apps.iter().any(|a| a.origin == Origin::Store && a.id == r.replacement) { + continue; + } + let (old, new) = (sf_app::paths::app_data_dir(r.id), sf_app::paths::app_data_dir(r.replacement)); + if old.is_dir() && std::fs::symlink_metadata(&new).is_err() { + match std::fs::rename(&old, &new) { + Ok(()) => log::info!("moved the data of {} to {}", r.id, r.replacement), + Err(e) => log::warn!("moving {} to {}: {e}", old.display(), new.display()), } } - sort_apps(&mut apps); } - Ok(apps) -} - -fn sort_apps(apps: &mut [AppManifest]) { - apps.sort_by(|a, b| a.order.cmp(&b.order).then_with(|| a.name.cmp(&b.name))); -} - -/// Compares dotted numeric versions ("1.10.0" > "1.9.2"), up to four parts -/// (the Steam launcher is 1.0.0.87); anything that isn't a number compares as 0. -pub fn version_cmp(a: &str, b: &str) -> std::cmp::Ordering { - let parts = |v: &str| -> Vec { v.split(['.', '-', '+']).take(4).map(|p| p.parse().unwrap_or(0)).collect() }; - let (a, b) = (parts(a), parts(b)); - (0..4).map(|i| a.get(i).unwrap_or(&0).cmp(b.get(i).unwrap_or(&0))).find(|o| o.is_ne()).unwrap_or(std::cmp::Ordering::Equal) -} - -fn load_one(path: &Path) -> Result { - let text = std::fs::read_to_string(path)?; - let mut app: AppManifest = toml::from_str(&text)?; - app.dir = path.parent().unwrap_or(Path::new(".")).to_path_buf(); - Ok(app) } #[cfg(test)] mod tests { use super::*; - #[test] - fn parses_web_manifest() { - let app: AppManifest = toml::from_str( - r##" - id = "netflex" - name = "Netflex" - kind = "web" - url = "${settings.netflex_server}/" - accent = "#E50914" - palette = ["#ff3b3b", "#7a0a10", "#0c0203"] - [web] - user_agent_suffix = "SMART-TV FennecOS/0.1" - "##, - ) - .unwrap(); - assert_eq!(app.kind, AppKind::Web); - let mut s = Settings::default(); - s.values.insert("netflex_server".into(), "http://10.0.0.5:7880".into()); - assert_eq!(app.resolved_url(&s).unwrap(), "http://10.0.0.5:7880/"); - assert_eq!(app.version, "0.0.0"); + fn write(dir: &Path, id: &str, body: &str) { + std::fs::create_dir_all(dir.join(id)).unwrap(); + std::fs::write(dir.join(id).join("app.toml"), format!("id = \"{id}\"\nname = \"{id}\"\n{body}")).unwrap(); } #[test] - fn compares_versions() { - use std::cmp::Ordering::*; - assert_eq!(version_cmp("1.10.0", "1.9.2"), Greater); - assert_eq!(version_cmp("0.2", "0.2.0"), Equal); - assert_eq!(version_cmp("0.1.9", "0.2.0"), Less); - assert_eq!(version_cmp("1.0.0.87", "1.0.0.9"), Greater); - assert_eq!(version_cmp("1.0.0", "1.0.0.0"), Equal); - } - - #[test] - fn store_ids() { - assert!(is_store_id("io.github.user.app")); - assert!(is_store_id("org.example.My_App-2")); - assert!(!is_store_id("youtube")); - assert!(!is_store_id("IO.github.x")); - assert!(!is_store_id("io..x")); - assert!(!is_store_id("io.x/../y")); - assert!(!is_store_id(".io.x")); - } - - #[test] - fn exec_and_permissions() { - let app: AppManifest = toml::from_str( - r#" - id = "io.github.fox.hello" - name = "Hello" - kind = "exec" - exec = ["bin/hello", "--data", "${app}/share"] - [sandbox] - permissions = ["network", "gamepad"] - "#, - ) - .unwrap(); - assert_eq!(app.resolved_exec(Path::new("/app")), ["/app/bin/hello", "--data", "/app/share"]); - assert_eq!(app.permissions(), [Permission::Network, Permission::Gamepad]); - assert!(app.sandboxed()); - app.check_store_rules().unwrap(); - - let mut bad = app.clone(); - bad.sandbox.enabled = Some(false); - assert!(bad.check_store_rules().is_err()); - bad = app.clone(); - bad.id = "youtube".into(); - assert!(bad.check_store_rules().is_err()); - - let web: AppManifest = toml::from_str("id = 'a'\nname = 'A'\nkind = 'web'\nurl = 'https://x'\n").unwrap(); - assert_eq!(web.permissions(), [Permission::Network, Permission::Gpu, Permission::Audio]); - let path: AppManifest = toml::from_str("id = 'a'\nname = 'A'\nkind = 'exec'\nexec = ['uxplay', '-n']\n").unwrap(); - assert_eq!(path.resolved_exec(Path::new("/x")), ["uxplay", "-n"]); + fn retired_app_stays_until_replaced() { + let base = std::env::temp_dir().join(format!("sf-ipc-retired-{}", std::process::id())); + let (factory, store) = (base.join("factory"), base.join("store")); + write(&factory, "youtube", "kind = \"web\"\nurl = \"https://www.youtube.com/tv\"\n"); + write(&factory, "settings", "kind = \"builtin\"\n"); + let ids = |apps: Vec| apps.into_iter().map(|a| a.id).collect::>(); + assert_eq!(ids(load_all(&[factory.clone()], Some(&store)).unwrap()), ["settings", "youtube"]); + write(&store, "support.bluefox.youtube", "kind = \"web\"\nurl = \"https://www.youtube.com/tv\"\n"); + let mut got = ids(load_all(&[factory.clone()], Some(&store)).unwrap()); + got.sort(); + assert_eq!(got, ["settings", "support.bluefox.youtube"]); + std::fs::remove_dir_all(&base).unwrap(); } } diff --git a/crates/sf-ipc/src/paths.rs b/crates/sf-ipc/src/paths.rs index 139e331..9d3ec41 100644 --- a/crates/sf-ipc/src/paths.rs +++ b/crates/sf-ipc/src/paths.rs @@ -1,11 +1,9 @@ -//! Where the Fennec OS sockets and files live. +//! Where the Fennec OS sockets and files live. The app paths (data folder, +//! settings file) come from the Fennec SDK (`sf_app::paths`). use std::path::{Path, PathBuf}; -/// `$XDG_RUNTIME_DIR`, or the temp dir. -pub fn runtime_dir() -> PathBuf { - std::env::var_os("XDG_RUNTIME_DIR").map(PathBuf::from).unwrap_or_else(std::env::temp_dir) -} +pub use sf_app::paths::{app_data_dir, runtime_dir, settings_file}; fn from_env(var: &str, default: &str) -> PathBuf { match std::env::var_os(var) { @@ -29,30 +27,6 @@ pub fn wm_socket() -> PathBuf { from_env("SMARTFOX_WM_SOCKET", "smartfox-wm.sock") } -/// The settings file: `$SMARTFOX_SETTINGS`, else `/smartfox/settings.toml`. -pub fn settings_file() -> PathBuf { - if let Ok(p) = std::env::var("SMARTFOX_SETTINGS") { - return p.into(); - } - let base = std::env::var_os("XDG_CONFIG_HOME") - .map(PathBuf::from) - .or_else(|| std::env::var_os("APPDATA").map(PathBuf::from)) - .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config"))) - .unwrap_or_else(|| PathBuf::from(".")); - base.join("smartfox").join("settings.toml") -} - -/// An app's private data folder; its `$HOME` inside the sandbox: -/// `$XDG_DATA_HOME/smartfox/apps/` (default `~/.local/share/...`). -pub fn app_data_dir(id: &str) -> PathBuf { - let base = std::env::var_os("XDG_DATA_HOME") - .map(PathBuf::from) - .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".local").join("share"))) - .or_else(|| std::env::var_os("LOCALAPPDATA").map(PathBuf::from)) - .unwrap_or_else(|| PathBuf::from(".")); - base.join("smartfox").join("apps").join(id) -} - /// Installed store apps (`/var/lib/sf-pkg/store/apps/`), written by sf-update. pub const STORE_APPS: &str = "/var/lib/sf-pkg/store/apps"; @@ -69,7 +43,7 @@ pub fn apps_dir() -> PathBuf { for start in starts { for dir in start.ancestors() { let candidate = dir.join("apps"); - if candidate.join("netflex").is_dir() { + if candidate.join("settings").join("app.toml").is_file() { return candidate; } } diff --git a/crates/sf-ipc/src/sandbox.rs b/crates/sf-ipc/src/sandbox.rs deleted file mode 100644 index f1035cf..0000000 --- a/crates/sf-ipc/src/sandbox.rs +++ /dev/null @@ -1,350 +0,0 @@ -//! App sandbox: every app runs in its own bubblewrap (`bwrap`) container, -//! the same building block Flatpak uses. -//! -//! Inside the sandbox an app sees: -//! - the system read-only (`/usr`, `/etc`), no other user's or app's files; -//! - its own files read-only at `/app`; -//! - its own data folder as `$HOME` (on the host: -//! `~/.local/share/smartfox/apps/`), the only writable place that lasts; -//! - the Wayland socket (it can show a window), nothing else from -//! `$XDG_RUNTIME_DIR` (no launcher, sf-core or compositor sockets); -//! - fresh /tmp, /run, /var and its own PID, IPC and UTS namespaces; -//! - and only what its permissions allow (`Permission`): network, GPU, -//! sound, game controllers, D-Bus, devices. - -use std::path::{Path, PathBuf}; -use std::process::Command; - -use crate::manifest::Permission; - -/// Where the app's own files are inside the sandbox. -pub const APP_DIR: &str = "/app"; - -/// Environment variables passed through from the session when set. -const PASS_ENV: [&str; 7] = ["LANG", "LANGUAGE", "LC_ALL", "TZ", "XCURSOR_THEME", "XCURSOR_SIZE", "RUST_LOG"]; - -/// What a host path is, for building the mount list (a function so tests -/// can fake the file system). -#[derive(Debug, Clone, PartialEq, Eq)] -pub enum Entry { - Missing, - Dir, - Other, - Symlink(PathBuf), - /// There, but we may not read it (bwrap's `--*-bind-try` fails on that). - Denied, -} - -pub fn probe(path: &Path) -> Entry { - if let Err(e) = std::fs::metadata(path) { - if e.kind() == std::io::ErrorKind::PermissionDenied { - return Entry::Denied; - } - } - match std::fs::symlink_metadata(path) { - Err(_) => Entry::Missing, - Ok(m) if m.file_type().is_symlink() => std::fs::read_link(path).map(Entry::Symlink).unwrap_or(Entry::Missing), - Ok(m) if m.is_dir() => Entry::Dir, - Ok(_) => Entry::Other, - } -} - -/// The session the app is started from. -#[derive(Debug, Clone)] -pub struct Host { - pub uid: u32, - pub user: String, - pub home: PathBuf, - pub runtime_dir: PathBuf, - pub wayland_display: Option, - pub hostname: Option, - /// Allowed variables from the session (`PASS_ENV`). - pub env: Vec<(String, String)>, - /// /dev/hidraw* (controllers that talk raw HID, like DualSense). - pub hidraw: Vec, -} - -impl Host { - pub fn current() -> Host { - let var = |k: &str| std::env::var(k).ok().filter(|v| !v.is_empty()); - let home = var("HOME").map(PathBuf::from).unwrap_or_else(|| PathBuf::from("/tmp")); - let hidraw = std::fs::read_dir("/dev") - .map(|d| d.flatten().map(|e| e.path()).filter(|p| p.file_name().is_some_and(|n| n.to_string_lossy().starts_with("hidraw"))).collect()) - .unwrap_or_default(); - Host { - uid: current_uid(), - user: var("USER").unwrap_or_else(|| "tv".into()), - home, - runtime_dir: crate::paths::runtime_dir(), - wayland_display: var("WAYLAND_DISPLAY"), - hostname: std::fs::read_to_string("/etc/hostname").ok().map(|h| h.trim().to_string()).filter(|h| !h.is_empty()), - env: PASS_ENV.iter().filter_map(|k| var(k).map(|v| (k.to_string(), v))).collect(), - hidraw, - } - } -} - -#[cfg(unix)] -fn current_uid() -> u32 { - use std::os::unix::fs::MetadataExt; - // The owner of our own /proc entry is our uid (no libc needed). - std::fs::metadata("/proc/self").map(|m| m.uid()).unwrap_or(1000) -} - -#[cfg(not(unix))] -fn current_uid() -> u32 { - 1000 -} - -/// One sandboxed process. -#[derive(Debug, Clone)] -pub struct Spec<'a> { - pub app_id: &'a str, - /// The app's files (host path), read-only at `/app`. - pub app_dir: &'a Path, - /// The app's private data (host path), mounted as `$HOME`. - pub data_dir: &'a Path, - /// More writable folders, at the same path inside (a browser profile). - pub extra_rw: Vec, - pub permissions: &'a [Permission], - /// Extra environment for the app. - pub env: Vec<(String, String)>, - pub program: String, - pub args: Vec, -} - -pub fn bwrap_path() -> Option { - if let Ok(p) = std::env::var("SMARTFOX_BWRAP") { - return Some(p.into()); - } - ["/usr/bin/bwrap", "/usr/local/bin/bwrap"].iter().map(PathBuf::from).find(|p| p.is_file()) -} - -/// The bwrap command for `spec`. -pub fn command(bwrap: &Path, spec: &Spec, host: &Host) -> Command { - let mut cmd = Command::new(bwrap); - cmd.args(args(spec, host, &probe)); - cmd -} - -/// The bwrap arguments. Mount order matters: later mounts go on top. -pub fn args(spec: &Spec, host: &Host, fs: &dyn Fn(&Path) -> Entry) -> Vec { - let has = |p: Permission| spec.permissions.contains(&p); - let mut a: Vec = Vec::new(); - let mut push = |items: &[&str]| a.extend(items.iter().map(|s| s.to_string())); - - push(&["--die-with-parent", "--unshare-all"]); - if has(Permission::Network) { - push(&["--share-net"]); - } - if host.uid == 0 { - // Unprivileged bwrap drops every capability by itself; as root - // (development) do it explicitly. - push(&["--cap-drop", "ALL"]); - } - if let Some(h) = &host.hostname { - push(&["--hostname", h]); - } - - // The system, read-only. /bin, /lib... are symlinks into /usr on Debian. - push(&["--ro-bind", "/usr", "/usr"]); - for top in ["/bin", "/sbin", "/lib", "/lib32", "/lib64", "/libx32"] { - match fs(Path::new(top)) { - Entry::Symlink(t) => push(&["--symlink", &t.to_string_lossy(), top]), - Entry::Dir => push(&["--ro-bind", top, top]), - _ => {} - } - } - push(&["--ro-bind", "/etc", "/etc", "--proc", "/proc"]); - - // Devices. - if has(Permission::Devices) { - push(&["--dev-bind", "/dev", "/dev"]); - } else { - push(&["--dev", "/dev", "--tmpfs", "/dev/shm"]); - if has(Permission::Gpu) { - push(&["--dev-bind-try", "/dev/dri", "/dev/dri"]); - } - if has(Permission::Gamepad) { - push(&["--dev-bind-try", "/dev/input", "/dev/input", "--dev-bind-try", "/dev/uinput", "/dev/uinput"]); - for h in &host.hidraw { - let h = h.to_string_lossy(); - push(&["--dev-bind-try", &h, &h]); - } - } - } - if has(Permission::Gpu) || has(Permission::Gamepad) || has(Permission::Devices) { - push(&["--ro-bind", "/sys", "/sys"]); - } - - // Fresh writable scratch space. - push(&["--tmpfs", "/tmp", "--tmpfs", "/var", "--tmpfs", "/run", "--dir", "/var/tmp", "--symlink", "../run", "/var/run"]); - push(&["--ro-bind-try", "/var/cache/fontconfig", "/var/cache/fontconfig"]); - if has(Permission::Gamepad) || has(Permission::Devices) { - // Hotplug of controllers (SDL, Steam) goes through udev. - push(&["--ro-bind-try", "/run/udev", "/run/udev"]); - } - if has(Permission::Network) { - // /etc/resolv.conf points at systemd-resolved's stub file on the TV; - // elsewhere (WSL: /mnt/wsl/resolv.conf) bind whatever it points at. - push(&["--ro-bind-try", "/run/systemd/resolve", "/run/systemd/resolve"]); - if let Entry::Symlink(t) = fs(Path::new("/etc/resolv.conf")) { - let target = Path::new("/etc").join(t); - let target = target.to_string_lossy(); - if !target.starts_with("/run/systemd/resolve/") && !target.starts_with("/etc/") && !target.starts_with("/usr/") { - push(&["--ro-bind-try", &target, &target]); - } - } - } - if has(Permission::DbusSystem) { - push(&["--ro-bind-try", "/run/dbus/system_bus_socket", "/run/dbus/system_bus_socket"]); - } - - // The session's runtime dir: only the sockets the app may use. - let rt = host.runtime_dir.to_string_lossy().to_string(); - push(&["--perms", "0700", "--dir", &rt]); - let mut socket = |name: &str| { - let p = format!("{rt}/{name}"); - if fs(Path::new(&p)) != Entry::Denied { - push(&["--ro-bind-try", &p, &p]); - } - }; - if let Some(wl) = &host.wayland_display { - socket(wl); - } - if has(Permission::Audio) { - socket("pipewire-0"); - socket("pulse/native"); - } - if has(Permission::DbusSession) { - socket("bus"); - } - - // $HOME is the app's own data folder (at the real home path, so programs - // that remember absolute paths keep working). - let home = host.home.to_string_lossy().to_string(); - if let Entry::Symlink(t) = fs(Path::new("/home")) { - push(&["--symlink", &t.to_string_lossy(), "/home"]); - } - push(&["--bind", &spec.data_dir.to_string_lossy(), &home]); - for p in &spec.extra_rw { - let p = p.to_string_lossy(); - push(&["--bind", &p, &p]); - } - push(&["--ro-bind", &spec.app_dir.to_string_lossy(), APP_DIR, "--chdir", &home]); - - // A clean environment. - push(&["--clearenv"]); - let mut env: Vec<(String, String)> = vec![ - ("PATH".into(), "/usr/local/bin:/usr/bin:/bin:/usr/games".into()), - ("HOME".into(), home.clone()), - ("USER".into(), host.user.clone()), - ("LOGNAME".into(), host.user.clone()), - ("SHELL".into(), "/bin/sh".into()), - ("XDG_RUNTIME_DIR".into(), rt.clone()), - ("XDG_SESSION_TYPE".into(), "wayland".into()), - ("SMARTFOX_APP".into(), spec.app_id.into()), - ("SMARTFOX_APP_DIR".into(), APP_DIR.into()), - ]; - if let Some(wl) = &host.wayland_display { - env.push(("WAYLAND_DISPLAY".into(), wl.clone())); - } - if has(Permission::DbusSession) { - env.push(("DBUS_SESSION_BUS_ADDRESS".into(), format!("unix:path={rt}/bus"))); - } - env.extend(host.env.iter().cloned()); - env.extend(spec.env.iter().cloned()); - for (k, v) in env { - push(&["--setenv", &k, &v]); - } - - push(&["--", &spec.program]); - a.extend(spec.args.iter().cloned()); - a -} - -#[cfg(test)] -mod tests { - use super::*; - - fn host() -> Host { - Host { - uid: 1000, - user: "tv".into(), - home: "/var/home/tv".into(), - runtime_dir: "/run/user/1000".into(), - wayland_display: Some("wayland-1".into()), - hostname: Some("smartfox".into()), - env: vec![("LANG".into(), "C.UTF-8".into())], - hidraw: vec!["/dev/hidraw0".into()], - } - } - - fn fake_fs(p: &Path) -> Entry { - match p.to_str().unwrap() { - "/bin" => Entry::Symlink("usr/bin".into()), - "/lib" => Entry::Symlink("usr/lib".into()), - "/lib64" => Entry::Symlink("usr/lib64".into()), - "/home" => Entry::Symlink("var/home".into()), - _ => Entry::Missing, - } - } - - fn has_seq(args: &[String], seq: &[&str]) -> bool { - args.windows(seq.len()).any(|w| w.iter().zip(seq).all(|(a, b)| a == b)) - } - - #[test] - fn minimal_sandbox() { - let spec = Spec { - app_id: "io.github.fox.hello", - app_dir: Path::new("/var/lib/sf-pkg/store-io.github.fox.hello/1.0.0"), - data_dir: Path::new("/var/home/tv/.local/share/smartfox/apps/io.github.fox.hello"), - extra_rw: vec![], - permissions: &[], - env: vec![("FOO".into(), "bar".into())], - program: "/app/bin/hello".into(), - args: vec!["--x".into()], - }; - let a = args(&spec, &host(), &fake_fs); - assert!(has_seq(&a, &["--unshare-all"])); - assert!(!a.contains(&"--share-net".to_string())); - assert!(!a.iter().any(|s| s == "/dev/dri" || s == "/sys")); - assert!(!a.iter().any(|s| s.contains("pipewire") || s.ends_with("/bus"))); - assert!(has_seq(&a, &["--symlink", "usr/bin", "/bin"])); - assert!(has_seq(&a, &["--ro-bind-try", "/run/user/1000/wayland-1", "/run/user/1000/wayland-1"])); - assert!(has_seq(&a, &["--bind", "/var/home/tv/.local/share/smartfox/apps/io.github.fox.hello", "/var/home/tv"])); - assert!(has_seq(&a, &["--ro-bind", "/var/lib/sf-pkg/store-io.github.fox.hello/1.0.0", "/app"])); - assert!(has_seq(&a, &["--setenv", "SMARTFOX_APP", "io.github.fox.hello"])); - assert!(has_seq(&a, &["--setenv", "FOO", "bar"])); - assert!(has_seq(&a, &["--", "/app/bin/hello", "--x"])); - assert_eq!(a.last().unwrap(), "--x"); - // /run must be fresh before the runtime dir and sockets go in. - let run = a.iter().position(|s| s == "/run").unwrap(); - let sock = a.iter().position(|s| s == "/run/user/1000/wayland-1").unwrap(); - assert!(run < sock); - } - - #[test] - fn permissions_open_doors() { - let perms = [Permission::Network, Permission::Gpu, Permission::Audio, Permission::Gamepad, Permission::DbusSession]; - let spec = Spec { - app_id: "steam", - app_dir: Path::new("/usr/share/smartfox/apps/steam"), - data_dir: Path::new("/d"), - extra_rw: vec!["/var/home/tv/.config/smartfox/profiles/steam".into()], - permissions: &perms, - env: vec![], - program: "/app/x".into(), - args: vec![], - }; - let a = args(&spec, &host(), &fake_fs); - assert!(a.contains(&"--share-net".to_string())); - assert!(has_seq(&a, &["--dev-bind-try", "/dev/dri", "/dev/dri"])); - assert!(has_seq(&a, &["--dev-bind-try", "/dev/hidraw0", "/dev/hidraw0"])); - assert!(has_seq(&a, &["--ro-bind", "/sys", "/sys"])); - assert!(has_seq(&a, &["--ro-bind-try", "/run/user/1000/pipewire-0", "/run/user/1000/pipewire-0"])); - assert!(has_seq(&a, &["--setenv", "DBUS_SESSION_BUS_ADDRESS", "unix:path=/run/user/1000/bus"])); - assert!(has_seq(&a, &["--bind", "/var/home/tv/.config/smartfox/profiles/steam", "/var/home/tv/.config/smartfox/profiles/steam"])); - } -} diff --git a/crates/sf-ipc/src/settings.rs b/crates/sf-ipc/src/settings.rs deleted file mode 100644 index 486cdf4..0000000 --- a/crates/sf-ipc/src/settings.rs +++ /dev/null @@ -1,57 +0,0 @@ -//! Flat key/value settings stored in `settings.toml`. - -use std::collections::BTreeMap; -use std::path::Path; - -use anyhow::Result; -use serde::{Deserialize, Serialize}; - -#[derive(Debug, Clone, Default, Serialize, Deserialize)] -pub struct Settings { - #[serde(flatten)] - pub values: BTreeMap, -} - -impl Settings { - /// Missing file means default settings. - pub fn load(path: &Path) -> Result { - if !path.exists() { - return Ok(Self::default()); - } - Ok(toml::from_str(&std::fs::read_to_string(path)?)?) - } - - pub fn save(&self, path: &Path) -> Result<()> { - if let Some(dir) = path.parent() { - std::fs::create_dir_all(dir)?; - } - std::fs::write(path, toml::to_string_pretty(self)?)?; - Ok(()) - } - - pub fn get(&self, key: &str) -> Option<&str> { - self.values.get(key).map(String::as_str) - } - - /// Replaces `${settings.key}` with the value (or an empty string). - pub fn expand(&self, input: &str) -> String { - let mut out = String::with_capacity(input.len()); - let mut rest = input; - while let Some(start) = rest.find("${settings.") { - out.push_str(&rest[..start]); - let after = &rest[start + "${settings.".len()..]; - match after.find('}') { - Some(end) => { - out.push_str(self.get(&after[..end]).unwrap_or("")); - rest = &after[end + 1..]; - } - None => { - out.push_str(&rest[start..]); - rest = ""; - } - } - } - out.push_str(rest); - out - } -} diff --git a/crates/sf-launcher/Cargo.toml b/crates/sf-launcher/Cargo.toml index afc4b02..65e1330 100644 --- a/crates/sf-launcher/Cargo.toml +++ b/crates/sf-launcher/Cargo.toml @@ -8,7 +8,7 @@ license = "GPL-3.0-only" [dependencies] sf-ipc.workspace = true -sf-ui = { path = "../sf-ui", default-features = false } +sf-ui = { workspace = true, default-features = false } anyhow.workspace = true log.workspace = true env_logger.workspace = true diff --git a/crates/sf-launcher/src/main.rs b/crates/sf-launcher/src/main.rs index 306b557..514711a 100644 --- a/crates/sf-launcher/src/main.rs +++ b/crates/sf-launcher/src/main.rs @@ -81,7 +81,7 @@ fn find_apps_dir() -> Option { for start in starts { for dir in start.ancestors() { let candidate = dir.join("apps"); - if candidate.join("netflex").is_dir() { + if candidate.join("settings").join("app.toml").is_file() { return Some(candidate); } } @@ -134,6 +134,9 @@ fn entry_of(app: &AppManifest, settings: &Settings, services: bool) -> AppEntry }; let host = if kind == "web" { host_of(&target) } else { String::new() }; let kind_label = if app.origin == sf_ipc::Origin::Store { "Store app · saját sandboxban" } else { kind_label }; + // Built-in icon names (`icon = "settings"`) are for official apps only; + // a store app brings a picture, or gets its initial. + let icon = if app.origin == sf_ipc::Origin::Store { String::new() } else { app.icon.clone() }; let image = app.icon_file().and_then(|p| slint::Image::load_from_path(&p).map_err(|e| log::warn!("{}: icon {}: {e:?}", app.id, p.display())).ok()); let initial = app.name.chars().next().map(|c| c.to_uppercase().to_string()).unwrap_or_default(); AppEntry { @@ -141,7 +144,7 @@ fn entry_of(app: &AppManifest, settings: &Settings, services: bool) -> AppEntry name: app.name.clone().into(), category: app.category.clone().into(), description: app.description.clone().into(), - icon: app.icon.clone().into(), + icon: icon.into(), accent: to_color(parse_hex(&app.accent)), kind: kind.into(), kind_label: kind_label.into(), @@ -152,6 +155,7 @@ fn entry_of(app: &AppManifest, settings: &Settings, services: bool) -> AppEntry has_image: image.is_some(), image: image.unwrap_or_default(), initial: initial.into(), + cast: app.dial.is_some(), } } @@ -192,7 +196,8 @@ fn facts_for(entry: &AppEntry, st: &status::Status) -> Vec { }; let core = CORE_UP.with(Cell::get); match entry.id.as_str() { - "youtube" => { + // Apps a phone can cast to (DIAL), e.g. YouTube. + _ if entry.cast => { let mut out = Vec::new(); if core { out.push(fact("cast", "Telefonról is indítható", "")); @@ -528,6 +533,10 @@ fn main() -> Result<()> { let apps = sf_ipc::manifest::load_all(&opts.apps_dirs, opts.store_dir.as_deref()).with_context(|| format!("loading apps from {:?}", opts.apps_dirs))?; log::info!("{} apps from {:?}", apps.len(), opts.apps_dirs); + if !system::demo() { + // Official apps that became store apps: their data follows them. + sf_ipc::manifest::migrate_data(&apps); + } system::confirm_shell_trial(); let ui = App::new()?; diff --git a/crates/sf-launcher/ui/app.slint b/crates/sf-launcher/ui/app.slint index 84018a7..e71f2fc 100644 --- a/crates/sf-launcher/ui/app.slint +++ b/crates/sf-launcher/ui/app.slint @@ -44,6 +44,8 @@ export struct AppEntry { has-image: bool, // No picture and no built-in icon: the name's first letter is drawn. initial: string, + // A phone can start it by casting (DIAL). + cast: bool, } // Top Shelf card (Netflex: continue watching or its first home row). @@ -91,7 +93,8 @@ export component App inherits Window { in property net-label: ""; in property remote-battery: -1; // Top Shelf: shown while the app `shelf-app` is focused and there are items. - in property shelf-app: "netflex"; + // The Netflex store app (fennec/netflex); its cards come from shelf.rs. + in property shelf-app: "support.bluefox.netflex"; in property shelf-title; in property <[ShelfItem]> shelf-items; // Remote pairing guide (state comes from sf-remote). diff --git a/crates/sf-launcher/ui/icons.slint b/crates/sf-launcher/ui/icons.slint index a3eca38..b19464b 100644 --- a/crates/sf-launcher/ui/icons.slint +++ b/crates/sf-launcher/ui/icons.slint @@ -8,7 +8,7 @@ export component AppIcon inherits Rectangle { in property has-image: false; // No picture and no built-in icon: the app name's first letter. in property letter; - property builtin: root.icon == "netflex" || root.icon == "youtube" || root.icon == "airplay" || root.icon == "miracast" || root.icon == "settings" || root.icon == "store" || root.icon == "steam"; + property builtin: root.icon == "airplay" || root.icon == "miracast" || root.icon == "settings" || root.icon == "store"; if root.has-image: Image { width: 100%; @@ -46,60 +46,6 @@ export component AppIcon inherits Rectangle { } } - if root.icon == "steam": Rectangle { - // Steam mark: the piston and valve in a disc (Simple Icons, CC0). - Path { - width: 100%; height: 100%; - viewbox-x: -3; viewbox-y: -3; - viewbox-width: 30; viewbox-height: 30; - commands: "M11.979 0C5.678 0 .511 4.86.022 11.037l6.432 2.658c.545-.371 1.203-.59 1.912-.59.063 0 .125.004.188.006l2.861-4.142V8.91c0-2.495 2.028-4.524 4.524-4.524 2.494 0 4.524 2.031 4.524 4.527s-2.03 4.525-4.524 4.525h-.105l-4.076 2.911c0 .052.004.105.004.159 0 1.875-1.515 3.396-3.39 3.396-1.635 0-3.016-1.173-3.331-2.727L.436 15.27C1.862 20.307 6.486 24 11.979 24c6.627 0 11.999-5.373 11.999-12S18.605 0 11.979 0zM7.54 18.21l-1.473-.61c.262.543.714.999 1.314 1.25 1.297.539 2.793-.076 3.332-1.375.263-.63.264-1.319.005-1.949s-.75-1.121-1.377-1.383c-.624-.26-1.29-.249-1.878-.03l1.523.63c.956.4 1.409 1.5 1.009 2.455-.397.957-1.497 1.41-2.454 1.012H7.54zm11.415-9.303c0-1.662-1.353-3.015-3.015-3.015-1.665 0-3.015 1.353-3.015 3.015 0 1.665 1.35 3.015 3.015 3.015 1.663 0 3.015-1.35 3.015-3.015zm-5.273-.005c0-1.252 1.013-2.266 2.265-2.266 1.249 0 2.266 1.014 2.266 2.266 0 1.251-1.017 2.265-2.266 2.265-1.253 0-2.265-1.014-2.265-2.265z"; - fill: @linear-gradient(160deg, #ffffff 0%, #c7e4f8 100%); - } - } - - if root.icon == "netflex": Rectangle { - // Netflex mark: mirrored "N" in three ribbons (from netflex/apps/web/public/favicon.svg). - Path { - width: 100%; height: 100%; - viewbox-width: 32; viewbox-height: 32; - commands: "M7 3h6v26H7z"; - fill: @linear-gradient(180deg, #b20710 0%, #831010 100%); - } - Path { - width: 100%; height: 100%; - viewbox-width: 32; viewbox-height: 32; - commands: "M19 3h6v26h-6z"; - fill: @linear-gradient(0deg, #b20710 0%, #831010 100%); - } - Path { - width: 100%; height: 100%; - viewbox-width: 32; viewbox-height: 32; - commands: "M18.4 3h6.6L13.6 29H7z"; - fill: #00000059; - } - Path { - width: 100%; height: 100%; - viewbox-width: 32; viewbox-height: 32; - commands: "M19 3h6L13 29H7z"; - fill: @linear-gradient(35deg, #e50914 0%, #f6303a 100%); - } - } - - if root.icon == "youtube": Rectangle { - Path { - width: 100%; height: 100%; - viewbox-width: 32; viewbox-height: 32; - commands: "M3 11.2C3 8.4 5 6.6 7.8 6.4 11.4 6.1 20.6 6.1 24.2 6.4 27 6.6 29 8.4 29 11.2v9.6c0 2.8-2 4.6-4.8 4.8-3.6.3-12.8.3-16.4 0C5 25.4 3 23.6 3 20.8z"; - fill: @linear-gradient(160deg, #ff3b30 0%, #d90d1d 100%); - } - Path { - width: 100%; height: 100%; - viewbox-width: 32; viewbox-height: 32; - commands: "M13.2 11.6v8.8l7.6-4.4z"; - fill: #ffffff; - } - } - if root.icon == "airplay": Rectangle { Path { width: 100%; height: 100%; diff --git a/crates/sf-pack/Cargo.toml b/crates/sf-pack/Cargo.toml deleted file mode 100644 index cb0595e..0000000 --- a/crates/sf-pack/Cargo.toml +++ /dev/null @@ -1,14 +0,0 @@ -[package] -name = "sf-pack" -description = "Fennec OS store app packaging (docs/store.md)" -version.workspace = true -edition.workspace = true -license.workspace = true - -[dependencies] -sf-ipc.workspace = true -anyhow.workspace = true -serde.workspace = true -toml.workspace = true -tar = "0.4" -ruzstd = "0.8" diff --git a/crates/sf-pack/src/main.rs b/crates/sf-pack/src/main.rs deleted file mode 100644 index 39c0de1..0000000 --- a/crates/sf-pack/src/main.rs +++ /dev/null @@ -1,220 +0,0 @@ -//! sf-pack: builds Fennec OS store packages (docs/store.md). -//! -//! sf-pack build [out-dir] app.toml + -.tar.zst -//! sf-pack verify checks what `build` made -//! sf-pack run runs the app the way the TV does: in the -//! store sandbox (Linux, needs bwrap) -//! -//! The two files in out-dir are the release assets: upload them to a -//! release of the app's repo (GitHub, Gitea or GitLab). - -use std::io::Read; -use std::path::{Path, PathBuf}; - -use anyhow::{Context, Result, bail}; -use sf_ipc::AppManifest; - -fn main() { - let args: Vec = std::env::args().skip(1).collect(); - if let Err(e) = run(&args) { - eprintln!("sf-pack: {e:#}"); - std::process::exit(1); - } -} - -fn run(args: &[String]) -> Result<()> { - let arg = |i: usize| args.get(i).map(String::as_str); - match arg(0) { - Some("build") => { - let dir = arg(1).context("usage: sf-pack build [out-dir]")?; - build(Path::new(dir), Path::new(arg(2).unwrap_or("dist"))) - } - Some("verify") => verify(Path::new(arg(1).unwrap_or("dist"))), - Some("run") => run_app(Path::new(arg(1).context("usage: sf-pack run ")?)), - _ => bail!("usage: sf-pack build [out-dir] | verify [out-dir] | run "), - } -} - -fn read_manifest(dir: &Path) -> Result { - let path = dir.join("app.toml"); - let text = std::fs::read_to_string(&path).with_context(|| format!("reading {}", path.display()))?; - let mut app: AppManifest = toml::from_str(&text).with_context(|| format!("parsing {}", path.display()))?; - app.dir = dir.to_path_buf(); - Ok(app) -} - -fn is_release(v: &str) -> bool { - !v.is_empty() && v.split('.').count() <= 4 && v.split('.').all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit())) -} - -fn build(dir: &Path, out: &Path) -> Result<()> { - let app = read_manifest(dir)?; - app.check_store_rules().context("app.toml")?; - if !is_release(&app.version) { - bail!("version {:?} must be a release version like 1.2.3", app.version); - } - if app.icon.contains('.') && app.icon_file().is_none() { - bail!("icon {} is missing from {}", app.icon, dir.display()); - } - if let Some(exe) = app.resolved_exec(Path::new("/app")).first().and_then(|p| p.strip_prefix("/app/")) { - let path = dir.join(exe); - if !path.is_file() { - bail!("exec {} is missing from {}", exe, dir.display()); - } - check_executable(&path)?; - } - - std::fs::create_dir_all(out)?; - let file = format!("{}-{}.tar.zst", app.id, app.version); - let tar = pack_tar(dir, &app)?; - let zst = ruzstd::encoding::compress_to_vec(&tar[..], ruzstd::encoding::CompressionLevel::Fastest); - std::fs::write(out.join(&file), &zst)?; - std::fs::copy(dir.join("app.toml"), out.join("app.toml"))?; - println!("{}: {} ({} KiB)", app.id, out.join(&file).display(), zst.len() / 1024); - println!("Release assets: app.toml, {file}"); - Ok(()) -} - -#[cfg(unix)] -fn check_executable(path: &Path) -> Result<()> { - use std::os::unix::fs::PermissionsExt; - if std::fs::metadata(path)?.permissions().mode() & 0o111 == 0 { - bail!("{} is not executable (chmod +x)", path.display()); - } - Ok(()) -} - -#[cfg(not(unix))] -fn check_executable(_path: &Path) -> Result<()> { - Ok(()) -} - -/// The package: the app folder plus pkg.toml, reproducible (sorted, no -/// owners, fixed time). -fn pack_tar(dir: &Path, app: &AppManifest) -> Result> { - let mut files = Vec::new(); - collect(dir, Path::new(""), &mut files)?; - files.sort(); - let mut b = tar::Builder::new(Vec::new()); - b.follow_symlinks(false); - let pkg = format!("name = \"{}\"\nversion = \"{}\"\n", app.id, app.version); - let mut h = header(tar::EntryType::Regular, 0o644, pkg.len() as u64); - b.append_data(&mut h, "pkg.toml", pkg.as_bytes())?; - for rel in files { - let path = dir.join(&rel); - let meta = std::fs::symlink_metadata(&path)?; - let mode = file_mode(&meta); - if meta.file_type().is_symlink() { - let mut h = header(tar::EntryType::Symlink, 0o777, 0); - b.append_link(&mut h, &rel, std::fs::read_link(&path)?)?; - } else if meta.is_dir() { - let mut h = header(tar::EntryType::Directory, 0o755, 0); - b.append_data(&mut h, &rel, std::io::empty())?; - } else { - // Windows has no x bit: whatever is under bin/ is executable. - let exec = mode & 0o111 != 0 || rel.starts_with("bin"); - let mut h = header(tar::EntryType::Regular, if exec { 0o755 } else { 0o644 }, meta.len()); - b.append_data(&mut h, &rel, std::fs::File::open(&path)?)?; - } - } - Ok(b.into_inner()?) -} - -fn header(kind: tar::EntryType, mode: u32, size: u64) -> tar::Header { - let mut h = tar::Header::new_gnu(); - h.set_entry_type(kind); - h.set_mode(mode); - h.set_size(size); - h.set_mtime(0); - h.set_uid(0); - h.set_gid(0); - h -} - -#[cfg(unix)] -fn file_mode(meta: &std::fs::Metadata) -> u32 { - use std::os::unix::fs::PermissionsExt; - meta.permissions().mode() -} - -/// On Windows nothing is executable; binaries under bin/ are. -#[cfg(not(unix))] -fn file_mode(_meta: &std::fs::Metadata) -> u32 { - 0o644 -} - -fn collect(root: &Path, rel: &Path, out: &mut Vec) -> Result<()> { - for e in std::fs::read_dir(root.join(rel))? { - let e = e?; - let name = e.file_name(); - if name == "pkg.toml" && rel.as_os_str().is_empty() { - continue; - } - let r = rel.join(&name); - out.push(r.clone()); - if e.file_type()?.is_dir() { - collect(root, &r, out)?; - } - } - Ok(()) -} - -fn verify(out: &Path) -> Result<()> { - let app = read_manifest(out)?; - app.check_store_rules()?; - let file = out.join(format!("{}-{}.tar.zst", app.id, app.version)); - let data = std::fs::read(&file).with_context(|| format!("reading {}", file.display()))?; - let mut tar = Vec::new(); - ruzstd::decoding::StreamingDecoder::new(&data[..]).map_err(|e| anyhow::anyhow!("zstd: {e}"))?.read_to_end(&mut tar)?; - let mut archive = tar::Archive::new(&tar[..]); - let names: Vec = archive.entries()?.filter_map(|e| e.ok()?.path().ok().map(|p| p.to_string_lossy().into_owned())).collect(); - if !names.iter().any(|n| n == "pkg.toml") || !names.iter().any(|n| n == "app.toml") { - bail!("pkg.toml or app.toml missing from the package"); - } - println!("{} {}: package OK, {} files", app.id, app.version, names.len()); - Ok(()) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn builds_and_verifies() { - let tmp = std::env::temp_dir().join(format!("sf-pack-test-{}", std::process::id())); - let app = tmp.join("app"); - std::fs::create_dir_all(app.join("bin")).unwrap(); - std::fs::write( - app.join("app.toml"), - "id = \"io.github.fox.hello\"\nname = \"Hello\"\nversion = \"1.2.3\"\nkind = \"exec\"\nexec = [\"bin/hello\"]\n", - ) - .unwrap(); - std::fs::write(app.join("bin/hello"), "#!/bin/sh\necho hi\n").unwrap(); - #[cfg(unix)] - { - use std::os::unix::fs::PermissionsExt; - std::fs::set_permissions(app.join("bin/hello"), std::fs::Permissions::from_mode(0o755)).unwrap(); - } - let out = tmp.join("dist"); - build(&app, &out).unwrap(); - verify(&out).unwrap(); - std::fs::remove_dir_all(&tmp).unwrap(); - } -} - -/// Runs an app folder as a store app: same sandbox, same permissions. -fn run_app(dir: &Path) -> Result<()> { - let mut app = read_manifest(dir)?; - app.check_store_rules().context("app.toml")?; - app.origin = sf_ipc::Origin::Store; - let settings = sf_ipc::Settings::default(); - let data = std::env::temp_dir().join("sf-pack-run"); - let opts = sf_ipc::launch::LaunchOptions { data_dir: &data, fullscreen: false, bounds: None, query: None }; - let mut cmd = sf_ipc::launch::command(&app, &settings, &opts)?; - eprintln!("data folder ($HOME inside): {}", sf_ipc::paths::app_data_dir(&app.id).display()); - if std::env::var_os("SF_PACK_SHOW").is_some() { - eprintln!("{} {}", cmd.get_program().to_string_lossy(), cmd.get_args().map(|a| a.to_string_lossy()).collect::>().join(" ")); - } - let status = cmd.status().context("starting the app")?; - std::process::exit(status.code().unwrap_or(1)); -} diff --git a/crates/sf-ui/Cargo.toml b/crates/sf-ui/Cargo.toml deleted file mode 100644 index 0c8c162..0000000 --- a/crates/sf-ui/Cargo.toml +++ /dev/null @@ -1,30 +0,0 @@ -[package] -name = "sf-ui" -description = "SmartFox TV UI kit: Liquid Glass for Slint apps, TV components, artwork loading, video playback" -version.workspace = true -edition.workspace = true -# Slint is used under GPL-3.0 (its royalty-free license does not cover embedded -# devices like a TV box), so apps built on sf-ui are GPL-3.0 too. -license = "GPL-3.0-only" -# Lets the build script of an app read DEP_SF_UI_UI_DIR (the Slint library). -links = "sf_ui" -build = "build.rs" - -[features] -default = ["images"] -# Artwork over HTTP(S), decoded and scaled off the UI thread (images::Images). -images = ["dep:ureq", "dep:image"] -# Video playback with GStreamer (video::Player). Linux; needs GStreamer 1.22+. -video = ["dep:gstreamer", "dep:gstreamer-app", "dep:gstreamer-video"] - -[dependencies] -anyhow.workspace = true -log.workspace = true -slint = { version = "1.18", default-features = false, features = ["std", "backend-default", "renderer-femtovg", "compat-1-2", "image-default-formats"] } -glow = "0.16" -png = "0.18" -ureq = { version = "3", optional = true } -image = { version = "0.25", optional = true, default-features = false, features = ["jpeg", "png", "webp"] } -gstreamer = { version = "0.25", optional = true } -gstreamer-app = { version = "0.25", optional = true } -gstreamer-video = { version = "0.25", optional = true } diff --git a/crates/sf-ui/build.rs b/crates/sf-ui/build.rs deleted file mode 100644 index c52ddd8..0000000 --- a/crates/sf-ui/build.rs +++ /dev/null @@ -1,7 +0,0 @@ -// Tells the build scripts of apps that depend on sf-ui where its Slint -// library is: they read it as DEP_SF_UI_UI_DIR and map it to "@sf-ui". -fn main() { - let dir = std::path::Path::new(&std::env::var("CARGO_MANIFEST_DIR").unwrap()).join("ui"); - println!("cargo:ui_dir={}", dir.display()); - println!("cargo:rerun-if-changed=build.rs"); -} diff --git a/crates/sf-ui/gallery/Cargo.toml b/crates/sf-ui/gallery/Cargo.toml deleted file mode 100644 index 3048076..0000000 --- a/crates/sf-ui/gallery/Cargo.toml +++ /dev/null @@ -1,21 +0,0 @@ -[package] -name = "sf-ui-gallery" -description = "Every sf-ui component on one screen (example and visual test)" -version.workspace = true -edition.workspace = true -license = "GPL-3.0-only" -publish = false - -[dependencies] -sf-ui = { path = ".." } -slint = "1.18" -anyhow.workspace = true -log.workspace = true -env_logger.workspace = true - -[features] -# SF_UI_VIDEO=: plays a video as the backdrop (Linux, GStreamer). -video = ["sf-ui/video"] - -[build-dependencies] -slint-build = "1.18" diff --git a/crates/sf-ui/gallery/build.rs b/crates/sf-ui/gallery/build.rs deleted file mode 100644 index 7fba5c9..0000000 --- a/crates/sf-ui/gallery/build.rs +++ /dev/null @@ -1,7 +0,0 @@ -fn main() { - // sf-ui's build script publishes where its Slint library is. - let sf_ui = std::env::var("DEP_SF_UI_UI_DIR").expect("sf-ui must be a direct dependency"); - let config = slint_build::CompilerConfiguration::new() - .with_library_paths(std::collections::HashMap::from([("sf-ui".to_string(), sf_ui.into())])); - slint_build::compile_with_config("ui/gallery.slint", config).expect("compiling ui/gallery.slint"); -} diff --git a/crates/sf-ui/gallery/src/main.rs b/crates/sf-ui/gallery/src/main.rs deleted file mode 100644 index 7ae883a..0000000 --- a/crates/sf-ui/gallery/src/main.rs +++ /dev/null @@ -1,101 +0,0 @@ -//! sf-ui gallery: every component on one screen. -//! -//! cargo run -p sf-ui-gallery -//! SF_UI_SIZE=1920x1080 SF_UI_KEYS="down right" SF_UI_SNAPSHOT=shot.png cargo run -p sf-ui-gallery - -use std::time::Duration; - -use slint::{ComponentHandle, Model, Rgba8Pixel, SharedPixelBuffer, VecModel}; - -slint::include_modules!(); -sf_ui::glue!(Gallery); - -/// Stand-in artwork: a soft two-colour gradient with a light blob. -fn artwork(a: [u8; 3], b: [u8; 3], w: u32, h: u32) -> SharedPixelBuffer { - let mut px = SharedPixelBuffer::::new(w, h); - let (cw, ch) = (w as f32, h as f32); - for (i, p) in px.make_mut_slice().iter_mut().enumerate() { - let (x, y) = ((i as u32 % w) as f32 / cw, (i as u32 / w) as f32 / ch); - let t = (x * 0.6 + y * 0.4).clamp(0.0, 1.0); - let d = ((x - 0.7).powi(2) + (y - 0.3).powi(2)).sqrt(); - let glow = (1.0 - d * 2.2).max(0.0).powi(2) * 0.55; - let c = |k: usize| ((a[k] as f32 * (1.0 - t) + b[k] as f32 * t) * (1.0 - glow) + 255.0 * glow) as u8; - *p = Rgba8Pixel { r: c(0), g: c(1), b: c(2), a: 255 }; - } - px -} - -fn main() -> anyhow::Result<()> { - env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init(); - sf_ui::init()?; - let ui = Gallery::new()?; - ui.sf_ui_setup(); - - let colours = [ - ([190, 70, 40], [30, 10, 40]), - ([30, 110, 160], [10, 20, 40]), - ([60, 140, 80], [10, 30, 20]), - ([170, 140, 40], [40, 20, 10]), - ([120, 60, 170], [20, 10, 40]), - ]; - let pictures: Vec> = colours.iter().map(|(a, b)| artwork(*a, *b, 640, 360)).collect(); - let images: Vec = pictures.iter().map(|p| slint::Image::from_rgba8(p.clone())).collect(); - ui.set_art(slint::ModelRc::new(VecModel::from(images))); - let weak = ui.as_weak(); - ui.on_search(move |text| { - if let Some(ui) = weak.upgrade() { - ui.set_typed(text); - } - }); - - let glass = sf_ui::Glass::install(&ui, |ui, panels| { - panels.extend(ui.get_glass().iter()); - panels.extend(ui.get_glass_menu().iter()); - panels.extend(ui.get_glass_modal().iter()); - panels.extend(ui.get_glass_keyboard().iter()); - })?; - glass.set_palette(sf_ui::Palette::from_hex(["#ffb27a", "#8a3d12", "#120805"])); - - // SF_UI_VIDEO= (feature "video"): the film plays under the glass. - #[cfg(feature = "video")] - let _video = match std::env::var("SF_UI_VIDEO") { - Ok(uri) => { - sf_ui::video::init()?; - log::info!("hardware decoding: {}", sf_ui::video::hardware_decoding()); - let player = std::rc::Rc::new(std::cell::RefCell::new(sf_ui::video::Player::new(&uri, Default::default())?)); - glass.set_video(Some(player.borrow().video())); - let p = player.clone(); - let poll = slint::Timer::default(); - poll.start(slint::TimerMode::Repeated, Duration::from_millis(100), move || { - let mut p = p.borrow_mut(); - for ev in p.poll() { - log::info!("video: {ev:?}"); - if let sf_ui::video::Event::Ready { .. } = ev { - log::info!("audio: {:?}", p.audio_tracks()); - log::info!("text: {:?}", p.text_tracks()); - } - } - }); - Some((player, poll)) - } - Err(_) => None, - }; - - // The focused card's artwork becomes the backdrop (crossfades), and the - // light follows the focus. - let weak = ui.as_weak(); - let mut shown: Option = None; - let timer = slint::Timer::default(); - timer.start(slint::TimerMode::Repeated, Duration::from_millis(100), move || { - let Some(ui) = weak.upgrade() else { return }; - let want = (ui.get_area() == 2).then(|| ui.get_card() as usize); - if want != shown { - shown = want; - glass.set_backdrop(want.map(|i| sf_ui::Backdrop::new(pictures[i].clone()).dim(0.2))); - } - glass.set_light((ui.get_card() as f32 - 2.0) * 0.08); - }); - - ui.run()?; - Ok(()) -} diff --git a/crates/sf-ui/gallery/ui/gallery.slint b/crates/sf-ui/gallery/ui/gallery.slint deleted file mode 100644 index 3fb1ac3..0000000 --- a/crates/sf-ui/gallery/ui/gallery.slint +++ /dev/null @@ -1,181 +0,0 @@ -// sf-ui gallery: every component on one screen. Also the smallest complete -// example of an sf-ui app: TvWindow root, one FocusScope that owns the -// focus state, glass exported as [GlassRect] arrays for the Rust side. - -import { TvWindow, Tv, SfText, GlassRect, GlassPane, GlassButton, GlassMenu, MenuItem, ProgressBar, ArtworkCard, Spinner, Keyboard, Icon, Headline, Title, Body, Label, Caption, SectionTitle } from "@sf-ui/sf-ui.slint"; - -// Rust needs these two globals (sf_ui::glue! wires SfText). -export { Tv, SfText } - -export component Gallery inherits TvWindow { - title: "sf-ui gallery"; - forward-focus: keys; - - in property <[image]> art; - in-out property progress: 0.36; - in property typed; - callback search(string); - - // Focus: 0 = buttons, 1 = menu, 2 = cards. - in-out property area: 0; - in-out property button: 0; - in-out property item: 1; - in-out property card: 0; - in-out property kb-open; - out property kb-t: self.kb-open ? 1 : 0; - animate kb-t { duration: 480ms; easing: cubic-bezier(0.22, 1, 0.36, 1); } - // Content under the keyboard pane goes away completely before it arrives. - property dim: max(0, 1 - 1.6 * self.kb-t); - - keys := FocusScope { - key-pressed(event) => { - if root.kb-open { - return kb.key(event); - } - if event.text == Key.UpArrow { - if root.area == 1 { root.item = max(0, root.item - 1); } - if root.area == 2 { root.area = 0; } - } else if event.text == Key.DownArrow { - if root.area == 1 { if root.item < 4 { root.item += 1; } else { root.area = 2; } } - if root.area == 0 { root.area = 2; } - } else if event.text == Key.LeftArrow { - if root.area == 0 { root.button = max(0, root.button - 1); } - if root.area == 2 { root.card = max(0, root.card - 1); } - if root.area == 1 { root.area = 0; } - } else if event.text == Key.RightArrow { - if root.area == 0 { if root.button < 2 { root.button += 1; } else { root.area = 1; } } - if root.area == 2 { root.card = min(4, root.card + 1); } - } else if event.text == Key.Return { - if root.area == 0 && root.button == 1 { - kb.reset(); - root.kb-open = true; - } else if root.area == 0 && root.button == 0 { - root.progress = root.progress > 0.9 ? 0 : root.progress + 0.1; - } - } else { - return reject; - } - accept - } - } - - // ---- heading ---- - Headline { - x: Tv.safe-x; - y: Tv.safe-y; - text: "sf-ui"; - opacity: root.dim; - } - Caption { - x: Tv.safe-x; - y: Tv.safe-y + 72 * Tv.u; - text: "Nyilak: mozgás · OK: kiválasztás · Keresés: billentyűzet"; - opacity: root.dim; - } - - // ---- a details pane with buttons ---- - pane := GlassPane { - x: Tv.safe-x; - y: 200 * Tv.u; - width: 1040 * Tv.u; - height: 520 * Tv.u; - alpha: root.dim; - VerticalLayout { - padding: 56 * Tv.u; - spacing: 20 * Tv.u; - opacity: root.dim; - Label { text: "Film · 2024 · 2 ó 16 p"; } - Title { text: "A dűne második része"; } - Body { - text: "Paul Atreides egyesül Chanival és a fremenekkel, miközben bosszút áll a családját elpusztító összeesküvőkön."; - vertical-stretch: 1; - } - HorizontalLayout { - spacing: 24 * Tv.u; - alignment: start; - b0 := GlassButton { text: "Lejátszás"; icon: "play"; primary: true; nested: true; focused: root.area == 0 && root.button == 0; alpha: root.dim; } - b1 := GlassButton { text: "Keresés"; icon: "search"; nested: true; focused: root.area == 0 && root.button == 1; alpha: root.dim; } - b2 := GlassButton { icon: "plus"; nested: true; focused: root.area == 0 && root.button == 2; alpha: root.dim; } - } - bar := ProgressBar { value: root.progress; buffered: root.progress + 0.2; alpha: root.dim; } - } - } - - // ---- a menu ---- - menu := GlassMenu { - x: 1264 * Tv.u; - y: 200 * Tv.u; - title: "Hang"; - alpha: root.dim; - focused-index: root.area == 1 ? root.item : -1; - items: [ - { text: "Magyar", detail: "5.1", checked: root.item == 0 }, - { text: "Angol", detail: "Atmos", checked: root.item == 1 }, - { text: "Angol — Kommentár", detail: "Sztereó", checked: root.item == 2 }, - { text: "Német", detail: "5.1", checked: root.item == 3 }, - { text: "Francia", detail: "Sztereó", checked: root.item == 4 }, - ]; - } - - // ---- artwork ---- - SectionTitle { - x: Tv.safe-x; - y: 760 * Tv.u; - text: root.typed == "" ? "Népszerű" : "Keresés: " + root.typed; - opacity: root.dim; - } - for i in 5: ArtworkCard { - x: Tv.safe-x + i * 344 * Tv.u; - y: 830 * Tv.u; - width: 312 * Tv.u; - height: 176 * Tv.u; - image: i < root.art.length ? root.art[i] : @image-url(""); - placeholder: "Kártya \{i + 1}"; - progress: i == 1 ? 0.4 : -1; - badge: i == 0 ? "Új rész" : ""; - focused: root.area == 2 && root.card == i; - opacity: root.dim; - } - Spinner { - x: 1264 * Tv.u + 560 * Tv.u - self.width; - y: Tv.safe-y; - opacity: root.dim; - } - - // ---- keyboard on a modal pane ---- - modal := GlassPane { - x: (root.width - self.width) / 2; - y: (root.height - self.height) / 2; - width: 1720 * Tv.u; - height: 760 * Tv.u; - radius: 56 * Tv.u; - frost: 3.8; - tint: Tv.smoke.with-alpha(0.48); - glow: Tv.orange; - alpha: root.kb-t; - kb := Keyboard { - x: 0; - y: 96 * Tv.u; - width: parent.width; - title: "Keresés"; - subtitle: "Filmek és sorozatok címe"; - placeholder: "Cím"; - submit-label: "Keresés"; - min-length: 2; - alpha: root.kb-t; - submitted(text) => { - root.kb-open = false; - root.search(text); - } - cancelled => { - root.kb-open = false; - } - } - } - - // ---- glass, in drawing order ---- - out property <[GlassRect]> glass: [pane.glass, b0.glass, b1.glass, b2.glass, bar.glass]; - out property <[GlassRect]> glass-menu: menu.glass; - out property <[GlassRect]> glass-modal: [modal.glass]; - out property <[GlassRect]> glass-keyboard: kb.glass; -} diff --git a/crates/sf-ui/src/dev.rs b/crates/sf-ui/src/dev.rs deleted file mode 100644 index 3429b7f..0000000 --- a/crates/sf-ui/src/dev.rs +++ /dev/null @@ -1,103 +0,0 @@ -//! Dev helper, built into every [`crate::Glass`] window: scripted key presses -//! and a PNG snapshot of the window, so a UI can be checked (by you, a CI job -//! or an AI) without anyone at the screen. -//! -//! - `SF_UI_SIZE=1920x1080`: physical window size. -//! - `SF_UI_KEYS="down down right enter wait esc"`: keys sent one by one -//! (left, right, up, down, enter, esc, back = esc, backspace, space; -//! a single character types it, `wait` = pause, -//! `hold` = enter held 0.8 s), starting after 1.5 s, every 0.6 s. -//! - `SF_UI_SNAPSHOT=out.png`: saves the frame and quits, 1.5 s after the -//! last key (or after `SF_UI_SNAPSHOT_MS` milliseconds). - -use std::cell::{Cell, RefCell}; -use std::path::PathBuf; -use std::rc::Rc; -use std::time::Duration; - -use slint::ComponentHandle; -use slint::platform::{Key, WindowEvent}; - -const FIRST_KEY_MS: u64 = 1500; -const KEY_STEP_MS: u64 = 600; - -/// A snapshot waiting to be taken (shared with the rendering notifier). -#[derive(Default)] -pub(crate) struct Snapshot { - pub(crate) path: RefCell>, - pub(crate) due: Cell, -} - -pub(crate) fn setup(ui: &C) -> Rc { - let snap = Rc::new(Snapshot::default()); - if let Some((w, h)) = std::env::var("SF_UI_SIZE").ok().and_then(|s| { - let (w, h) = s.split_once('x')?; - Some((w.trim().parse().ok()?, h.trim().parse().ok()?)) - }) { - ui.window().set_size(slint::PhysicalSize::new(w, h)); - } - - let keys: Vec = - std::env::var("SF_UI_KEYS").map(|s| s.split_whitespace().map(str::to_string).collect()).unwrap_or_default(); - let mut at = FIRST_KEY_MS; - for k in &keys { - let hold = k == "hold"; - let text: Option = match k.to_lowercase().as_str() { - "hold" | "enter" => Some(Key::Return.into()), - "left" => Some(Key::LeftArrow.into()), - "right" => Some(Key::RightArrow.into()), - "up" => Some(Key::UpArrow.into()), - "down" => Some(Key::DownArrow.into()), - "esc" | "back" => Some(Key::Escape.into()), - "backspace" => Some(Key::Backspace.into()), - "space" => Some(" ".into()), - "wait" => None, - _ if k.chars().count() == 1 => Some(k.as_str().into()), - _ => None, - }; - let start = at; - at += if hold { 2 * KEY_STEP_MS } else { KEY_STEP_MS }; - let Some(text) = text else { continue }; - let weak = ui.as_weak(); - let t = text.clone(); - slint::Timer::single_shot(Duration::from_millis(start), move || { - if let Some(ui) = weak.upgrade() { - ui.window().dispatch_event(WindowEvent::KeyPressed { text: t.clone() }); - if !hold { - ui.window().dispatch_event(WindowEvent::KeyReleased { text: t }); - } - } - }); - if hold { - let weak = ui.as_weak(); - slint::Timer::single_shot(Duration::from_millis(start + 800), move || { - if let Some(ui) = weak.upgrade() { - ui.window().dispatch_event(WindowEvent::KeyReleased { text }); - } - }); - } - } - - if let Some(path) = std::env::var_os("SF_UI_SNAPSHOT").map(PathBuf::from) { - let ms = std::env::var("SF_UI_SNAPSHOT_MS").ok().and_then(|s| s.parse().ok()).unwrap_or(at + 1500); - *snap.path.borrow_mut() = Some(path); - let s = snap.clone(); - slint::Timer::single_shot(Duration::from_millis(ms), move || s.due.set(true)); - } - snap -} - -/// Writes top-down RGBA8 pixels as a PNG. -pub(crate) fn save_png(path: &std::path::Path, w: u32, h: u32, rgba: &[u8]) -> anyhow::Result<()> { - let file = std::io::BufWriter::new(std::fs::File::create(path)?); - let mut enc = png::Encoder::new(file, w, h); - enc.set_color(png::ColorType::Rgba); - enc.set_depth(png::BitDepth::Eight); - // The window has no meaningful alpha: make every pixel opaque. - let mut data = rgba.to_vec(); - for px in data.chunks_exact_mut(4) { - px[3] = 255; - } - enc.write_header()?.write_image_data(&data)?; - Ok(()) -} diff --git a/crates/sf-ui/src/glass.rs b/crates/sf-ui/src/glass.rs deleted file mode 100644 index 9bf591e..0000000 --- a/crates/sf-ui/src/glass.rs +++ /dev/null @@ -1,386 +0,0 @@ -//! The Liquid Glass layer for a Slint window: install it once, then tell it -//! each frame which panels to draw (usually the `[GlassRect]` arrays your -//! .slint file exports), and set the backdrop (palette, picture, video). -//! -//! ```ignore -//! sf_ui::init()?; // before creating the window -//! let ui = App::new()?; -//! ui.sf_ui_setup(); // from sf_ui::glue!(App) -//! let glass = sf_ui::Glass::install(&ui, |ui, panels| { -//! panels.extend(ui.get_glass().iter()); -//! })?; -//! glass.set_palette(sf_ui::Palette::from_hex(["#ffb27a", "#8a3d12", "#120805"])); -//! ui.run()?; -//! ``` - -use std::cell::RefCell; -use std::rc::Rc; -use std::time::Instant; - -use slint::{ComponentHandle, Rgba8Pixel, SharedPixelBuffer}; - -use crate::render::{Frame, GlassRenderer, ImageDraw, ImageId, Nv12Frame, Panel, Quality, VideoDraw}; -use crate::Palette; - -/// Time constant of palette and brightness changes (seconds). -const EASE: f32 = 0.35; -/// Crossfade time of pictures and video (seconds). -const FADE: f32 = 0.45; - -/// A picture for the backdrop (artwork behind a details page, a hero...). -/// Glass panels refract and frost it like the gradient. -#[derive(Clone)] -pub struct Backdrop { - pixels: SharedPixelBuffer, - dim: f32, - fade_left: f32, - fade_bottom: f32, - align: [f32; 2], - sharp: bool, -} - -impl Backdrop { - /// Defaults: slightly dimmed, darker towards the left and bottom (room - /// for titles), sharp, cropped around the centre. - pub fn new(pixels: SharedPixelBuffer) -> Backdrop { - Backdrop { pixels, dim: 0.12, fade_left: 0.75, fade_bottom: 0.6, align: [0.5, 0.35], sharp: true } - } - /// Darkens the whole picture: 0 = as is, 1 = black. - pub fn dim(mut self, v: f32) -> Self { - self.dim = v.clamp(0.0, 1.0); - self - } - /// Darkening towards the left edge, 0..1. - pub fn fade_left(mut self, v: f32) -> Self { - self.fade_left = v.clamp(0.0, 1.0); - self - } - /// Darkening towards the bottom edge, 0..1. - pub fn fade_bottom(mut self, v: f32) -> Self { - self.fade_bottom = v.clamp(0.0, 1.0); - self - } - /// Which part stays visible when cropped (0..1 per axis, 0.5 = centre). - pub fn align(mut self, x: f32, y: f32) -> Self { - self.align = [x.clamp(0.0, 1.0), y.clamp(0.0, 1.0)]; - self - } - /// Soft: only the blurred low-resolution copy shows (a frosted wallpaper). - pub fn soft(mut self) -> Self { - self.sharp = false; - self - } -} - -/// Where video frames come from (see `sf_ui::video::Player`, or your own -/// decoder). Called once per rendered frame on the UI thread. -pub trait VideoSource { - /// The newest frame since the last call, if any. - fn take_frame(&self) -> Option>; -} - -/// Collects the glass panels of one frame, in logical pixels (the units of -/// your .slint file). Draw order is push order: later panels lie on top. -pub struct Panels { - scale: f32, - out: Vec, -} - -impl Panels { - /// One panel (logical px). - pub fn push(&mut self, panel: impl Into) { - let p = panel.into(); - if p.alpha > 0.002 && p.w > 0.0 && p.h > 0.0 { - self.out.push(p.scaled(self.scale)); - } - } - - /// Many panels, e.g. `panels.extend(ui.get_glass().iter())`. - pub fn extend>(&mut self, panels: impl IntoIterator) { - for p in panels { - self.push(p); - } - } -} - -struct Slot { - backdrop: Backdrop, - id: Option, - alpha: f32, - target: f32, -} - -struct State { - palette: [f32; 9], - palette_target: [f32; 9], - brightness: f32, - brightness_target: f32, - images: Vec, - free: Vec, - video: Option>, - video_alpha: f32, - video_on: bool, - clear_video: bool, - light: f32, - zoom: f32, - last: f32, - quality: Quality, -} - -/// Handle to an installed glass layer (cheap to clone). -#[derive(Clone)] -pub struct Glass { - state: Rc>, -} - -impl Glass { - /// Draws the glass layer under `ui`'s window. `panels` runs before every - /// frame and adds that frame's panels. The backdrop animates, so frames - /// keep coming (vsync-limited). - /// - /// Call [`crate::init`] before creating the window: the layer needs the - /// OpenGL (FemtoVG) renderer. - pub fn install( - ui: &C, - mut panels: impl FnMut(&C, &mut Panels) + 'static, - ) -> anyhow::Result { - let neutral = Palette::NEUTRAL.to_floats(); - let state = Rc::new(RefCell::new(State { - palette: neutral, - palette_target: neutral, - brightness: 1.0, - brightness_target: 1.0, - images: Vec::new(), - free: Vec::new(), - video: None, - video_alpha: 0.0, - video_on: false, - clear_video: false, - light: 0.0, - zoom: 1.0, - last: 0.0, - quality: Quality::Full, - })); - let glass = Glass { state: state.clone() }; - let snapshot = crate::dev::setup(ui); - let renderer: Rc>> = Rc::default(); - let start = Instant::now(); - let weak = ui.as_weak(); - ui.window() - .set_rendering_notifier(move |rs, api| match rs { - slint::RenderingState::RenderingSetup => { - let slint::GraphicsAPI::NativeOpenGL { get_proc_address } = api else { - log::error!("sf-ui: the glass layer needs OpenGL (call sf_ui::init() first)"); - return; - }; - let gl = unsafe { glow::Context::from_loader_function_cstr(|s| get_proc_address(s)) }; - match unsafe { GlassRenderer::new(gl) } { - Ok(r) => *renderer.borrow_mut() = Some(r), - Err(e) => log::error!("sf-ui: glass layer disabled: {e:#}"), - } - } - slint::RenderingState::BeforeRendering => { - let mut guard = renderer.borrow_mut(); - let (Some(ui), Some(r)) = (weak.upgrade(), guard.as_mut()) else { return }; - let time = start.elapsed().as_secs_f32(); - let size = ui.window().size(); - let scale = ui.window().scale_factor(); - let mut list = Panels { scale, out: Vec::new() }; - panels(&ui, &mut list); - - let mut st = state.borrow_mut(); - let dt = (time - st.last).clamp(0.0, 0.25); - st.last = time; - st.step(dt); - // SAFETY: the rendering notifier runs with the GL context current. - unsafe { st.sync_images(r) }; - if std::mem::take(&mut st.clear_video) { - r.clear_video(); - } - let draws: Vec = st - .images - .iter() - .filter_map(|s| { - Some(ImageDraw { - image: s.id?, - alpha: s.alpha, - dim: s.backdrop.dim, - fade_left: s.backdrop.fade_left, - fade_bottom: s.backdrop.fade_bottom, - align: s.backdrop.align, - sharp: s.backdrop.sharp, - }) - }) - .collect(); - let video = st.video.clone(); - let frame_box = video.as_ref().and_then(|v| v.take_frame()); - let angle = -2.25 + 0.10 * (time * 0.35).sin() + st.light; - let frame = Frame { - width: size.width, - height: size.height, - scale, - time, - palette: st.palette, - brightness: st.brightness, - light: [angle.cos(), angle.sin()], - zoom: st.zoom, - images: &draws, - video: (st.video_alpha > 0.002 || frame_box.is_some()) - .then(|| VideoDraw { frame: frame_box.as_deref(), alpha: st.video_alpha }), - rects: list.out, - quality: st.quality, - }; - drop(st); - // SAFETY: as above. - unsafe { r.render(&frame) }; - } - slint::RenderingState::AfterRendering => { - let Some(ui) = weak.upgrade() else { return }; - if snapshot.due.get() { - if let (Some(path), Some(r)) = (snapshot.path.borrow_mut().take(), renderer.borrow().as_ref()) { - let size = ui.window().size(); - // SAFETY: after Slint rendered, context current. - let px = unsafe { r.read_pixels(size.width, size.height) }; - match crate::dev::save_png(&path, size.width, size.height, &px) { - Ok(()) => log::info!("sf-ui: snapshot {}", path.display()), - Err(e) => log::error!("sf-ui: snapshot {}: {e:#}", path.display()), - } - let _ = slint::quit_event_loop(); - } - } - ui.window().request_redraw(); - } - slint::RenderingState::RenderingTeardown => { - if let Some(mut r) = renderer.borrow_mut().take() { - unsafe { r.destroy() }; - } - // Textures died with the context: upload again if it comes back. - for s in state.borrow_mut().images.iter_mut() { - s.id = None; - } - } - _ => {} - }) - .map_err(|e| anyhow::anyhow!("sf-ui: rendering notifier: {e:?}"))?; - Ok(glass) - } - - /// The backdrop gradient's colours; eases over from the current ones. - pub fn set_palette(&self, palette: Palette) { - self.state.borrow_mut().palette_target = palette.to_floats(); - } - - /// Backdrop brightness, 0..1 (1 = full). Lower it to calm the backdrop - /// behind dense content. - pub fn set_brightness(&self, v: f32) { - self.state.borrow_mut().brightness_target = v.clamp(0.0, 1.0); - } - - /// A picture over the gradient (crossfades from the previous one), or - /// `None` to fade back to the gradient. - pub fn set_backdrop(&self, backdrop: Option) { - let mut st = self.state.borrow_mut(); - match backdrop { - Some(b) => { - // Already showing this very picture: keep it. - if let Some(last) = st.images.last_mut() { - if last.backdrop.pixels.as_bytes().as_ptr() == b.pixels.as_bytes().as_ptr() { - last.backdrop = b; - last.target = 1.0; - return; - } - } - st.images.push(Slot { backdrop: b, id: None, alpha: 0.0, target: 1.0 }); - } - None => { - for s in st.images.iter_mut() { - s.target = 0.0; - } - } - } - } - - /// Video as the backdrop (glass refracts the film), or `None` to fade it - /// out. The source is polled once per frame. - pub fn set_video(&self, source: Option>) { - let mut st = self.state.borrow_mut(); - st.video_on = source.is_some(); - if source.is_some() { - st.video = source; - st.clear_video = true; - } - } - - /// Turns the key light (radians, small values like ±0.3), e.g. to follow - /// the focus across the screen. - pub fn set_light(&self, offset: f32) { - self.state.borrow_mut().light = offset; - } - - /// How much of the glass effect to draw ([`Quality::Light`] or - /// [`Quality::Flat`] on weaker hardware). - pub fn set_quality(&self, q: Quality) { - self.state.borrow_mut().quality = q; - } - - /// Zooms the backdrop gradient (1 = none). - pub fn set_zoom(&self, zoom: f32) { - self.state.borrow_mut().zoom = zoom.max(0.1); - } -} - -impl State { - fn step(&mut self, dt: f32) { - let k = 1.0 - (-dt / EASE).exp(); - for (c, t) in self.palette.iter_mut().zip(self.palette_target) { - *c += (t - *c) * k; - } - self.brightness += (self.brightness_target - self.brightness) * k; - - let fade = dt / FADE; - for s in self.images.iter_mut() { - s.alpha = if s.target > s.alpha { (s.alpha + fade).min(s.target) } else { (s.alpha - fade).max(s.target) }; - } - // A picture fully covered by a newer, opaque one is no longer needed; - // faded-out ones neither. - let covered = self.images.iter().rposition(|s| s.alpha >= 0.999).unwrap_or(0); - let mut i = 0; - self.images.retain(|s| { - let keep = i >= covered && !(s.target == 0.0 && s.alpha <= 0.0); - i += 1; - if !keep { - if let Some(id) = s.id { - self.free.push(id); - } - } - keep - }); - - let target = if self.video_on { 1.0 } else { 0.0 }; - self.video_alpha = if target > self.video_alpha { - (self.video_alpha + dt / 0.3).min(1.0) - } else { - (self.video_alpha - dt / 0.3).max(0.0) - }; - if !self.video_on && self.video_alpha <= 0.0 { - self.video = None; - } - } - - unsafe fn sync_images(&mut self, r: &mut GlassRenderer) { - for id in self.free.drain(..) { - unsafe { r.free_image(id) }; - } - for s in self.images.iter_mut().filter(|s| s.id.is_none()) { - let px = &s.backdrop.pixels; - match unsafe { r.upload_image(px.width(), px.height(), px.as_bytes()) } { - Ok(id) => s.id = Some(id), - Err(e) => { - log::warn!("sf-ui: backdrop picture: {e:#}"); - s.target = 0.0; - s.alpha = 0.0; - } - } - } - } -} diff --git a/crates/sf-ui/src/images.rs b/crates/sf-ui/src/images.rs deleted file mode 100644 index 391d7c3..0000000 --- a/crates/sf-ui/src/images.rs +++ /dev/null @@ -1,259 +0,0 @@ -//! Artwork over HTTP(S): downloaded, decoded and scaled on worker threads, -//! kept in a memory cache, handed to you on the UI thread. -//! -//! ```ignore -//! let images = sf_ui::images::Images::new(256 << 20); -//! images.load(&poster_url, (240, 360), move |img| card.set_image(img)); -//! ``` -//! -//! Sizes are the size you show the picture at, in *physical* pixels (design -//! px × the window's scale): the picture is scaled down to cover that box -//! (never up), so a 4K TV gets sharper artwork and a 1080p one uses less memory. - -use std::cell::RefCell; -use std::collections::{HashMap, VecDeque}; -use std::io::Read; -use std::rc::{Rc, Weak}; -use std::sync::atomic::{AtomicU64, Ordering}; -use std::sync::mpsc; -use std::sync::{Arc, Mutex}; -use std::time::Duration; - -use slint::{Rgba8Pixel, SharedPixelBuffer}; - -/// Bigger downloads are refused. -const MAX_DOWNLOAD: u64 = 24 << 20; -const WORKERS: usize = 4; - -type Pixels = SharedPixelBuffer; -type Key = (String, u32, u32); -type Waiter = Box; - -struct Job { - owner: u64, - key: Key, -} - -struct Inner { - id: u64, - budget: usize, - used: RefCell, - cache: RefCell>, - order: RefCell>, - waiting: RefCell>>, - jobs: Mutex>>, - queue: Arc>>, -} - -thread_local! { - static OWNERS: RefCell>> = RefCell::new(HashMap::new()); -} - -static NEXT_ID: AtomicU64 = AtomicU64::new(1); - -/// The image loader and cache (cheap to clone; use it on the UI thread). -#[derive(Clone)] -pub struct Images { - inner: Rc, -} - -impl Images { - /// `budget`: bytes of decoded pixels to keep (e.g. `256 << 20`). - pub fn new(budget: usize) -> Images { - let id = NEXT_ID.fetch_add(1, Ordering::Relaxed); - let queue: Arc>> = Arc::default(); - let (tx, rx) = mpsc::channel::<()>(); - let rx = Arc::new(Mutex::new(rx)); - let agent: ureq::Agent = ureq::Agent::config_builder() - .timeout_global(Some(Duration::from_secs(30))) - .user_agent("SmartFox sf-ui") - .build() - .into(); - for _ in 0..WORKERS { - let rx = rx.clone(); - let queue = queue.clone(); - let agent = agent.clone(); - std::thread::spawn(move || { - // Wake-ups come over the channel; the newest request is served first - // (what the user looks at now), from the shared queue. - while rx.lock().unwrap().recv().is_ok() { - let Some(job) = queue.lock().unwrap().pop_back() else { continue }; - let result = fetch(&agent, &job.key.0, job.key.1, job.key.2); - if let Err(e) = &result { - log::debug!("image {}: {e:#}", job.key.0); - } - let (owner, key) = (job.owner, job.key); - let _ = slint::invoke_from_event_loop(move || deliver(owner, key, result.ok())); - } - }); - } - let inner = Rc::new(Inner { - id, - budget, - used: RefCell::new(0), - cache: RefCell::default(), - order: RefCell::default(), - waiting: RefCell::default(), - jobs: Mutex::new(Some(tx)), - queue, - }); - OWNERS.with(|o| o.borrow_mut().insert(id, Rc::downgrade(&inner))); - Images { inner } - } - - /// Loads `url` scaled to cover `size` (physical px) and calls `done` with - /// it on the UI thread: at once if cached, later otherwise. On failure - /// `done` is not called. - pub fn load(&self, url: &str, size: (u32, u32), done: impl FnOnce(slint::Image) + 'static) { - self.load_pixels(url, size, move |px| done(slint::Image::from_rgba8(px.clone()))); - } - - /// Like [`Images::load`], but hands over the pixels (for - /// [`crate::Backdrop`] or your own processing). - pub fn load_pixels(&self, url: &str, size: (u32, u32), done: impl FnOnce(&Pixels) + 'static) { - if url.is_empty() { - return; - } - let key: Key = (url.to_string(), size.0.max(1), size.1.max(1)); - if let Some(px) = self.inner.cache.borrow().get(&key).cloned() { - self.touch(&key); - done(&px); - return; - } - let mut waiting = self.inner.waiting.borrow_mut(); - if let Some(list) = waiting.get_mut(&key) { - list.push(Box::new(done)); - return; - } - waiting.insert(key.clone(), vec![Box::new(done)]); - drop(waiting); - self.inner.queue.lock().unwrap().push_back(Job { owner: self.inner.id, key }); - if let Some(tx) = self.inner.jobs.lock().unwrap().as_ref() { - let _ = tx.send(()); - } - } - - /// The cached picture, if it is already loaded. - pub fn cached(&self, url: &str, size: (u32, u32)) -> Option { - let key: Key = (url.to_string(), size.0.max(1), size.1.max(1)); - self.inner.cache.borrow().get(&key).map(|px| slint::Image::from_rgba8(px.clone())) - } - - /// Drops requests that have not started yet (e.g. after leaving a screen). - pub fn cancel_pending(&self) { - let mut q = self.inner.queue.lock().unwrap(); - let mut waiting = self.inner.waiting.borrow_mut(); - for job in q.drain(..) { - waiting.remove(&job.key); - } - } - - fn touch(&self, key: &Key) { - let mut order = self.inner.order.borrow_mut(); - if let Some(i) = order.iter().position(|k| k == key) { - let k = order.remove(i).unwrap(); - order.push_back(k); - } - } -} - -impl Inner { - fn insert(&self, key: Key, px: Pixels) { - let bytes = px.as_bytes().len(); - let mut cache = self.cache.borrow_mut(); - let mut order = self.order.borrow_mut(); - let mut used = self.used.borrow_mut(); - while *used + bytes > self.budget { - let Some(old) = order.pop_front() else { break }; - if let Some(p) = cache.remove(&old) { - *used -= p.as_bytes().len(); - } - } - *used += bytes; - order.push_back(key.clone()); - cache.insert(key, px); - } -} - -impl Drop for Inner { - fn drop(&mut self) { - // Ends the worker threads. - self.jobs.lock().unwrap().take(); - let id = self.id; - let _ = OWNERS.try_with(|o| o.borrow_mut().remove(&id)); - } -} - -fn deliver(owner: u64, key: Key, px: Option) { - let Some(inner) = OWNERS.with(|o| o.borrow().get(&owner).and_then(Weak::upgrade)) else { return }; - let waiters = inner.waiting.borrow_mut().remove(&key).unwrap_or_default(); - let Some(px) = px else { return }; - inner.insert(key, px.clone()); - for w in waiters { - w(&px); - } -} - -fn fetch(agent: &ureq::Agent, url: &str, w: u32, h: u32) -> anyhow::Result { - let mut resp = agent.get(url).call()?; - let mut bytes = Vec::new(); - resp.body_mut().as_reader().take(MAX_DOWNLOAD + 1).read_to_end(&mut bytes)?; - anyhow::ensure!((bytes.len() as u64) <= MAX_DOWNLOAD, "larger than {MAX_DOWNLOAD} bytes"); - decode(&bytes, w, h) -} - -/// Decodes and scales down to cover `w` x `h` (never up). -pub fn decode(bytes: &[u8], w: u32, h: u32) -> anyhow::Result { - let img = image::load_from_memory(bytes)?; - let (iw, ih) = (img.width().max(1), img.height().max(1)); - let k = (w as f32 / iw as f32).max(h as f32 / ih as f32); - let img = if k < 0.98 { - let (nw, nh) = (((iw as f32 * k).round() as u32).max(1), ((ih as f32 * k).round() as u32).max(1)); - img.resize_exact(nw, nh, image::imageops::FilterType::Triangle) - } else { - img - }; - let rgba = img.into_rgba8(); - Ok(SharedPixelBuffer::clone_from_slice(rgba.as_raw(), rgba.width(), rgba.height())) -} - -/// The average colour of a picture (for a matching [`crate::Palette`]), -/// leaning towards its saturated parts. -pub fn average_color(px: &Pixels) -> slint::Color { - let (mut r, mut g, mut b, mut n) = (0f64, 0f64, 0f64, 0f64); - let bytes = px.as_bytes(); - for p in bytes.chunks_exact(4).step_by(7) { - let (pr, pg, pb) = (p[0] as f64, p[1] as f64, p[2] as f64); - let max = pr.max(pg).max(pb); - let min = pr.min(pg).min(pb); - let wgt = 0.15 + (max - min) / 255.0 + max / 510.0; - r += pr * wgt; - g += pg * wgt; - b += pb * wgt; - n += wgt; - } - if n == 0.0 { - return slint::Color::from_rgb_u8(0x2a, 0x31, 0x40); - } - slint::Color::from_rgb_u8((r / n) as u8, (g / n) as u8, (b / n) as u8) -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn scales_to_cover() { - let mut png = Vec::new(); - let img = image::RgbaImage::from_pixel(400, 600, image::Rgba([200, 40, 30, 255])); - image::DynamicImage::ImageRgba8(img) - .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) - .unwrap(); - let px = decode(&png, 100, 100).unwrap(); - assert_eq!((px.width(), px.height()), (100, 150)); - let px = decode(&png, 1000, 1000).unwrap(); - assert_eq!((px.width(), px.height()), (400, 600)); - let c = average_color(&px); - assert!(c.red() > 150 && c.green() < 80); - } -} diff --git a/crates/sf-ui/src/lib.rs b/crates/sf-ui/src/lib.rs deleted file mode 100644 index fcbddcf..0000000 --- a/crates/sf-ui/src/lib.rs +++ /dev/null @@ -1,191 +0,0 @@ -//! sf-ui: the SmartFox TV UI kit for Slint apps. -//! -//! - **Liquid Glass** ([`Glass`]): the refracting, frosted glass of the -//! SmartFox launcher, drawn by an OpenGL layer under your Slint UI, over an -//! animated palette backdrop, a picture or a playing video. -//! - **Slint components** (`@sf-ui/sf-ui.slint`): design tokens (`Tv`), text -//! styles, glass panes, buttons, chips, a progress bar, an on-screen -//! keyboard, icons and the Onest font. -//! - **Images** ([`images::Images`], feature `images`): artwork over HTTP, -//! decoded and scaled off the UI thread, cached. -//! - **Video** (`video::Player`, feature `video`, Linux): GStreamer playback -//! with hardware decoding, its frames shown as the glass backdrop. -//! -//! Guide: `docs/sf-ui.md` in the SmartFox repository. - -pub mod render; - -mod dev; -mod glass; -#[cfg(feature = "images")] -pub mod images; -pub mod text; -#[cfg(feature = "video")] -pub mod video; - -pub use glass::{Backdrop, Glass, Panels, VideoSource}; -pub use render::{Matrix, Nv12Frame, Panel, Quality}; - -/// Selects Slint's OpenGL renderer (FemtoVG), which the glass layer draws -/// with. Call it first in `main`, before creating any window. -pub fn init() -> anyhow::Result<()> { - slint::BackendSelector::new() - .renderer_name("femtovg".into()) - .select() - .map_err(|e| anyhow::anyhow!("selecting the femtovg (OpenGL) renderer: {e}")) -} - -/// The backdrop gradient's three colours: highlight, mid, deep. Use the -/// `palette` of your app.toml, or one per screen / per focused item. -#[derive(Debug, Clone, Copy, PartialEq)] -pub struct Palette { - pub highlight: slint::Color, - pub mid: slint::Color, - pub deep: slint::Color, -} - -impl Palette { - /// The neutral system palette (no app colour). - pub const NEUTRAL: Palette = Palette { - highlight: slint::Color::from_rgb_u8(0x9a, 0xa4, 0xb5), - mid: slint::Color::from_rgb_u8(0x2a, 0x31, 0x40), - deep: slint::Color::from_rgb_u8(0x06, 0x07, 0x0a), - }; - - pub fn new(highlight: slint::Color, mid: slint::Color, deep: slint::Color) -> Palette { - Palette { highlight, mid, deep } - } - - /// From three "#rrggbb" strings (as in app.toml); bad ones fall back to - /// the neutral palette's colour. - pub fn from_hex(hex: [&str; 3]) -> Palette { - let n = Palette::NEUTRAL; - Palette { - highlight: parse_hex(hex[0]).unwrap_or(n.highlight), - mid: parse_hex(hex[1]).unwrap_or(n.mid), - deep: parse_hex(hex[2]).unwrap_or(n.deep), - } - } - - /// A palette from one colour, e.g. the average colour of a poster: - /// a lighter highlight, the colour itself, a near-black deep tone. - pub fn from_color(c: slint::Color) -> Palette { - let [r, g, b] = rgb(c); - let mix = |k: f32, t: f32| -> slint::Color { - let f = |v: f32| ((v * k + t * (1.0 - k)).clamp(0.0, 1.0) * 255.0) as u8; - slint::Color::from_rgb_u8(f(r), f(g), f(b)) - }; - Palette { highlight: mix(0.7, 1.0), mid: mix(0.55, 0.0), deep: mix(0.08, 0.0) } - } - - /// rgb 0..1 for the renderer. - pub fn to_floats(self) -> [f32; 9] { - let mut out = [0.0; 9]; - for (i, c) in [self.highlight, self.mid, self.deep].into_iter().enumerate() { - out[i * 3..i * 3 + 3].copy_from_slice(&rgb(c)); - } - out - } -} - -/// "#rrggbb" or "rrggbb". -pub fn parse_hex(hex: &str) -> Option { - let h = hex.trim().trim_start_matches('#'); - let v = u32::from_str_radix(h.get(..6)?, 16).ok()?; - Some(slint::Color::from_rgb_u8((v >> 16) as u8, (v >> 8) as u8, v as u8)) -} - -fn rgb(c: slint::Color) -> [f32; 3] { - [c.red() as f32 / 255.0, c.green() as f32 / 255.0, c.blue() as f32 / 255.0] -} - -impl Panel { - /// From the fields of a Slint `GlassRect` (used by [`glue!`]). - #[allow(clippy::too_many_arguments)] - pub fn from_slint( - x: f32, - y: f32, - w: f32, - h: f32, - r: f32, - focus: f32, - alpha: f32, - blur: f32, - glow: slint::Color, - tint: slint::Color, - group: i32, - ) -> Panel { - let [tr, tg, tb] = rgb(tint); - Panel { - x, - y, - w, - h, - radius: r, - focus, - alpha, - blur, - glow: rgb(glow), - group: group as f32, - tint: [tr, tg, tb, tint.alpha() as f32 / 255.0], - } - } -} - -/// Connects the types Slint generated in *your* crate to sf-ui. Put it once -/// next to `slint::include_modules!()`, with your root component's name: -/// -/// ```ignore -/// slint::include_modules!(); -/// sf_ui::glue!(App); -/// ``` -/// -/// It makes `GlassRect` convertible to [`Panel`] (so `panels.extend(...)` -/// takes your `[GlassRect]` arrays) and adds `App::sf_ui_setup()`, which -/// wires the Slint helper callbacks (`SfText`). Your main .slint file must -/// export the helpers: `export { Tv, SfText } from "@sf-ui/sf-ui.slint";`. -#[macro_export] -macro_rules! glue { - ($app:ident) => { - impl ::core::convert::From for $crate::Panel { - fn from(g: GlassRect) -> Self { - $crate::Panel::from_slint(g.x, g.y, g.w, g.h, g.r, g.focus, g.alpha, g.blur, g.glow.color(), g.tint.color(), g.group) - } - } - - impl $app { - /// Wires the sf-ui Slint helpers (text editing for the keyboard). - /// Call it once after creating the window. - #[allow(dead_code)] - pub fn sf_ui_setup(&self) { - use ::slint::ComponentHandle as _; - let t = self.global::(); - t.on_drop_last(|s| $crate::text::drop_last(&s).into()); - t.on_dots(|n| $crate::text::dots(n.max(0) as usize).into()); - t.on_truncate(|s, n| $crate::text::truncate(&s, n.max(0) as usize).into()); - t.on_typable(|s| $crate::text::typable(&s).into()); - } - } - }; -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn hex_colours() { - assert_eq!(parse_hex("#ff7a35"), Some(slint::Color::from_rgb_u8(0xff, 0x7a, 0x35))); - assert_eq!(parse_hex("121317"), Some(slint::Color::from_rgb_u8(0x12, 0x13, 0x17))); - assert_eq!(parse_hex("#12"), None); - let p = Palette::from_hex(["#ffffff", "nope", "#000000"]); - assert_eq!(p.mid, Palette::NEUTRAL.mid); - assert_eq!(p.to_floats()[0], 1.0); - } - - #[test] - fn panel_scaling() { - let p = Panel { x: 10.0, y: 20.0, w: 30.0, h: 40.0, radius: 5.0, alpha: 1.0, ..Panel::default() }.scaled(2.0); - assert_eq!((p.x, p.y, p.w, p.h, p.radius), (20.0, 40.0, 60.0, 80.0, 10.0)); - } -} diff --git a/crates/sf-ui/src/render/mod.rs b/crates/sf-ui/src/render/mod.rs deleted file mode 100644 index ab929e2..0000000 --- a/crates/sf-ui/src/render/mod.rs +++ /dev/null @@ -1,167 +0,0 @@ -//! The low-level Liquid Glass renderer: an OpenGL pass drawn *under* the -//! Slint UI. Most apps use [`crate::Glass`] instead, which drives this from a -//! Slint rendering notifier; use this module directly only if you need your -//! own notifier (the launcher does, for its dev snapshots). -//! -//! Per frame: the backdrop (animated gradient, optional pictures, optional -//! video) goes into a small mipmapped texture and onto the window; then every -//! glass panel is drawn as its own quad, refracting and frosting that texture. - -mod renderer; -mod shaders; - -pub use renderer::GlassRenderer; - -/// Panels drawn per frame at most (each one is its own small draw call). -pub const MAX_RECTS: usize = 48; -/// Members of one merged (liquid) group at most. -pub const MAX_GROUP: usize = 4; - -/// One glass panel. In [`Frame`] it is in physical pixels (top-left origin); -/// [`crate::Panels`] takes it in logical pixels and scales it. -#[derive(Debug, Clone, Copy, Default, PartialEq)] -pub struct Panel { - pub x: f32, - pub y: f32, - pub w: f32, - pub h: f32, - pub radius: f32, - /// 0..1, brightens the rim and adds the accent glow. - pub focus: f32, - pub alpha: f32, - /// Frost: mip level of the backdrop seen through it (higher = blurrier). - /// Negative = nested glass that sits on another pane. - pub blur: f32, - /// Accent light (rgb 0..1) for focus glow and rim. - pub glow: [f32; 3], - /// Consecutive panels with the same group (> 0) melt into one shape. - pub group: f32, - /// rgb + amount (0..1). - pub tint: [f32; 4], -} - -impl Panel { - /// The same panel with every length multiplied by `k` (logical → physical). - pub fn scaled(mut self, k: f32) -> Panel { - self.x *= k; - self.y *= k; - self.w *= k; - self.h *= k; - self.radius *= k; - self - } -} - -/// A picture uploaded with [`GlassRenderer::upload_image`]. -#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] -pub struct ImageId(pub(crate) u32); - -/// One picture on the backdrop, drawn over the gradient (and under the glass). -#[derive(Debug, Clone, Copy)] -pub struct ImageDraw { - pub image: ImageId, - /// 0..1, for crossfades. - pub alpha: f32, - /// Darkens the whole picture (0 = as is). - pub dim: f32, - /// Darkens towards the left edge (room for a title), 0..1. - pub fade_left: f32, - /// Darkens towards the bottom edge, 0..1. - pub fade_bottom: f32, - /// Which part stays visible when the picture is cropped to the screen - /// (0..1 per axis, 0.5 = centre). - pub align: [f32; 2], - /// Drawn sharp at full resolution. When false only the soft (blurred, - /// low resolution) copy shows, like a frosted wallpaper. - pub sharp: bool, -} - -/// Colour matrix of a video frame. -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub enum Matrix { - Bt601, - #[default] - Bt709, - Bt2020, -} - -/// One decoded video frame in NV12: a full-size Y plane and a half-size -/// plane of interleaved Cb/Cr bytes. -pub trait Nv12Frame { - fn width(&self) -> u32; - fn height(&self) -> u32; - /// Display aspect ratio (width / height, pixel aspect included). - fn aspect(&self) -> f32 { - self.width() as f32 / self.height().max(1) as f32 - } - /// Plane 0 (Y) or 1 (CbCr): bytes and the stride (bytes per row). - fn plane(&self, index: usize) -> (&[u8], usize); - fn matrix(&self) -> Matrix { - Matrix::Bt709 - } - fn full_range(&self) -> bool { - false - } -} - -/// The video layer of a frame. The renderer keeps the last uploaded frame, -/// so `frame` only needs to be set when a new one arrived. -pub struct VideoDraw<'a> { - pub frame: Option<&'a dyn Nv12Frame>, - /// 0..1, for fading in. - pub alpha: f32, -} - -/// How much of the glass effect to draw (weaker TVs: lighter modes). -#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)] -pub enum Quality { - /// Refraction, dispersion, Fresnel: the full Liquid Glass. - #[default] - Full, - /// Frosted glass with the lit rim, no lensing. - Light, - /// No frost: tinted panes with the rim only. - Flat, -} - -/// Everything the renderer needs for one frame. -pub struct Frame<'a> { - pub width: u32, - pub height: u32, - /// Physical pixels per logical pixel (glass sizes depend on it). - pub scale: f32, - /// Seconds since start (animation clock). - pub time: f32, - /// Backdrop palette (highlight, mid, deep), rgb 0..1 each. - pub palette: [f32; 9], - /// Backdrop brightness, 0..1 (1 = full). - pub brightness: f32, - /// Direction towards the key light (screen space, y down). - pub light: [f32; 2], - /// Backdrop zoom (1 = none), e.g. for a launch fly-in. - pub zoom: f32, - /// Pictures over the gradient, in drawing order. - pub images: &'a [ImageDraw], - pub video: Option>, - pub rects: Vec, - pub quality: Quality, -} - -impl Default for Frame<'_> { - fn default() -> Self { - Frame { - width: 0, - height: 0, - scale: 1.0, - time: 0.0, - palette: crate::Palette::NEUTRAL.to_floats(), - brightness: 1.0, - light: [-0.63, -0.78], - zoom: 1.0, - images: &[], - video: None, - rects: Vec::new(), - quality: Quality::Full, - } - } -} diff --git a/crates/sf-ui/src/render/renderer.rs b/crates/sf-ui/src/render/renderer.rs deleted file mode 100644 index 2114a21..0000000 --- a/crates/sf-ui/src/render/renderer.rs +++ /dev/null @@ -1,735 +0,0 @@ -//! OpenGL underlay drawn before Slint renders its items. -//! -//! Pass 1 renders the backdrop (gradient, then pictures, then video) into a -//! small, mipmapped texture: that is what the glass refracts and frosts. -//! Pass 2 puts the backdrop on the window: the small texture upscaled, then -//! sharp pictures and the video at full resolution. Pass 3 draws every glass -//! panel as its own quad, covering only the panel and its shadow. Uniform -//! locations are looked up once; GL state is handed back to Slint untouched. - -use std::collections::HashMap; - -use glow::HasContext; - -use super::shaders; -use super::{Frame, ImageDraw, ImageId, MAX_GROUP, MAX_RECTS, Matrix, Nv12Frame, Panel}; - -/// The backdrop is blurry by design, so it never needs more than this width. -const SCENE_MAX_W: i32 = 640; - -type Loc = Option; - -struct SceneLocs { - res: Loc, - time: Loc, - pal: Loc, - zoom: Loc, - bright: Loc, -} - -struct BlitLocs { - scene: Loc, - time: Loc, -} - -struct ImageLocs { - image: Loc, - img: Loc, - res: Loc, - align: Loc, - dim: Loc, - fade_left: Loc, - fade_bottom: Loc, - alpha: Loc, -} - -struct VideoLocs { - y: Loc, - uv: Loc, - res: Loc, - aspect: Loc, - matrix: Loc, - full: Loc, - alpha: Loc, -} - -struct GlassLocs { - box_: Loc, - res: Loc, - scene: Loc, - scale: Loc, - time: Loc, - light: Loc, - count: Loc, - rect: Loc, - param: Loc, - glow: Loc, - tint: Loc, - mode: Loc, -} - -struct Image { - tex: glow::Texture, - w: i32, - h: i32, -} - -/// The last uploaded video frame. -struct Video { - y: glow::Texture, - uv: glow::Texture, - size: (i32, i32), - aspect: f32, - matrix: Matrix, - full: bool, - ready: bool, -} - -pub struct GlassRenderer { - gl: glow::Context, - vao: glow::VertexArray, - scene_prog: glow::Program, - blit_prog: glow::Program, - image_prog: glow::Program, - video_prog: glow::Program, - glass_prog: glow::Program, - scene_locs: SceneLocs, - blit_locs: BlitLocs, - image_locs: ImageLocs, - video_locs: VideoLocs, - glass_locs: GlassLocs, - fbo: glow::Framebuffer, - tex: glow::Texture, - tex_size: (i32, i32), - /// RGBA16F if the driver can render to it (no banding in dark gradients). - half_float: bool, - images: HashMap, - next_image: u32, - video: Option