Compare commits

...

10 Commits

Author SHA1 Message Date
Tamas Csikel
edf54f0af4 Cargo.lock: the SDK from its git tag, not a local checkout
Some checks failed
packages / packages (push) Failing after 2m1s
The lock file was refreshed with the local [patch] in .cargo/config.toml
active, so sf-app and sf-ui had no source and CI's --locked build failed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 15:40:06 +01:00
Tamas Csikel
5f00c0877f Fennec OS 0.3.3: clear names for the sound outputs
Settings → Sound listed ALSA's descriptions, "Built-in Audio Digital
Stereo (HDMI)" and "Built-in Audio Stereo", which look alike; the second
is the 3.5 mm jack, and picking it left the TV silent. They now read
"TV · HDMI" (on the Raspberry Pi "TV · HDMI 1" / "TV · HDMI 2") and
"Jack-kimenet (3,5 mm)", listed after the TV and Bluetooth outputs.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 15:30:41 +01:00
Tamas Csikel
2985aa94a9 CI: arm64 dev packages install on Ubuntu
libglib2.0-dev:arm64 (pulled in by libinput-dev) depends on "python3 |
qemu-user | qemu-user-static", and python3:arm64 can't be configured on
amd64: install qemu-user-static first. The amd64 and arm64
libgudev-1.0-dev ship differing GUdev-1.0.gir files, so the arm64 set is
installed with --force-overwrite (throwaway container). Checked with a
full aarch64 shell build in ubuntu:24.04.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 20:40:41 +01:00
Tamas Csikel
9c710bedb9 Fennec OS 0.3.2: one app at a time, Raspberry Pi shell packages
- sf-core: only one app runs. Home, another app or a cast closes the app
  on screen (after the switch animation) instead of freezing it in the
  background. A frozen app that held a sound stream stalled PipeWire, so
  the next app could not play at all ("Failed to connect stream: No such
  entity" in Netflex after YouTube was sent home mid-video). The
  background limit and the low-memory watcher go with the freezing.
- Raspberry Pi: image/pi (installer on Raspberry Pi OS), aarch64 shell
  packages (sf-shell-<v>-aarch64, arch in pkg.toml, sf-update installs only
  its own architecture), CI builds the aarch64 shell too.
- sf-compositor: volume OSD, screencopy for remote view, blank cursor.
- SDK v0.1.2.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 19:38:09 +01:00
Tamas Csikel
54cdaf5e35 sf-compositor: the protocols gamescope needs, so Steam can start
gamescope (which hosts the Steam client) refuses to run nested without
wp_presentation, zwp_relative_pointer_manager_v1 and
zwp_pointer_constraints_v1 ("Couldn't create Wayland objects"), so Steam
quit right away.

- presentation-time with real feedback: on DRM with the page flip's
  kernel timestamp and sequence, on winit when the frame is submitted;
- relative pointer and pointer constraints (the seat gets a wl_pointer;
  no pointer device is attached, the cursor theme is blank).

Tested in the install VM: gamescope now gets past the Wayland setup; it
stops later only because the VM has no hardware Vulkan (llvmpipe lacks
VK_EXT_physical_device_drm). YouTube (Chromium, which uses presentation
feedback too) still renders and takes input.

Shell 0.3.1.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 20:20:31 +01:00
Tamas Csikel
62c3056f52 tools/vm: install-vm.sh, a VM that installs Fennec OS from the installer ISO
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 18:56:39 +01:00
Tamas Csikel
deedf1416a 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-<id> packages are not installed any more.

Shell 0.3.0.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 17:58:21 +01:00
Tamas Csikel
d7e9fe4568 Add Store support and unsigned app releases 2026-10-25 14:11:49 +01:00
Tamas Csikel
4975784491 README: updates section
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 09:45:54 +02:00
Tamas Csikel
8aaa702f9f sf-update: don't offer a version that was rolled back
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 09:38:41 +02:00
132 changed files with 12349 additions and 2152 deletions

1
.gitattributes vendored
View File

@@ -1,3 +1,4 @@
* text=auto eol=lf * text=auto eol=lf
*.ttf binary *.ttf binary
*.png binary *.png binary
*.gpg binary

View File

@@ -1,4 +1,4 @@
# Builds, signs and publishes the SmartFox packages (shell + apps) to the # Builds, signs and publishes the Fennec OS packages (shell + apps) to the
# Gitea generic package registry. A package is only built when its version # Gitea generic package registry. A package is only built when its version
# isn't published yet: bump the version to release (docs/updates.md). # isn't published yet: bump the version to release (docs/updates.md).
# #
@@ -42,11 +42,30 @@ jobs:
- name: Toolchain - name: Toolchain
run: | run: |
export DEBIAN_FRONTEND=noninteractive export DEBIAN_FRONTEND=noninteractive
# arm64 libraries for the Raspberry Pi shell (SF_TARGET=aarch64-...):
# Ubuntu serves them from ports.ubuntu.com, the main mirror is amd64 only.
. /etc/os-release
dpkg --add-architecture arm64
if [ -f /etc/apt/sources.list.d/ubuntu.sources ]; then
sed -i '/^Architectures:/d; /^Types:/a Architectures: amd64' /etc/apt/sources.list.d/ubuntu.sources
fi
[ -f /etc/apt/sources.list ] && sed -i 's/^deb \(http\)/deb [arch=amd64] \1/' /etc/apt/sources.list
printf 'Types: deb\nURIs: http://ports.ubuntu.com/ubuntu-ports/\nSuites: %s %s-updates %s-security\nComponents: main universe\nArchitectures: arm64\nSigned-By: /usr/share/keyrings/ubuntu-archive-keyring.gpg\n' \
"$VERSION_CODENAME" "$VERSION_CODENAME" "$VERSION_CODENAME" >/etc/apt/sources.list.d/arm64-ports.sources
apt-get update -qq apt-get update -qq
libs="libfontconfig1-dev libfreetype-dev libxkbcommon-dev libdbus-1-dev libudev-dev
libinput-dev libgbm-dev libseat-dev libdrm-dev libegl-dev"
# qemu-user-static: libglib2.0-dev:arm64 (via libinput-dev) wants
# "python3 | qemu-user-static"; python3:arm64 can't be set up on amd64.
apt-get install -y -qq --no-install-recommends build-essential pkg-config zstd \ apt-get install -y -qq --no-install-recommends build-essential pkg-config zstd \
libfontconfig1-dev libfreetype-dev libxkbcommon-dev libdbus-1-dev libudev-dev >/dev/null gcc-aarch64-linux-gnu g++-aarch64-linux-gnu libc6-dev-arm64-cross qemu-user-static \
$libs >/dev/null
# The amd64 and arm64 libgudev-1.0-dev ship differing GUdev-1.0.gir
# files; this throwaway container keeps either.
apt-get install -y -qq --no-install-recommends -o Dpkg::Options::=--force-overwrite \
$(for l in $libs; do printf '%s:arm64 ' "$l"; done) >/dev/null
rm -rf /var/lib/apt/lists/* rm -rf /var/lib/apt/lists/*
curl -sSf https://sh.rustup.rs | sh -s -- -y -q --profile minimal --no-modify-path curl -sSf https://sh.rustup.rs | sh -s -- -y -q --profile minimal --no-modify-path --target aarch64-unknown-linux-gnu
/tmp/sf-build/cargo/bin/rustc --version /tmp/sf-build/cargo/bin/rustc --version
- name: Build, sign, upload - name: Build, sign, upload
@@ -57,6 +76,8 @@ jobs:
export PATH="/tmp/sf-build/cargo/bin:$PATH" export PATH="/tmp/sf-build/cargo/bin:$PATH"
cd /tmp/sf-build/src cd /tmp/sf-build/src
bash tools/pkg/packages.sh --upload bash tools/pkg/packages.sh --upload
# The shell for the Raspberry Pi (sf-shell-<v>-aarch64; apps are the same).
SF_TARGET=aarch64-unknown-linux-gnu bash tools/pkg/packages.sh --upload shell
- name: Clean up - name: Clean up
if: always() if: always()

3
.gitignore vendored
View File

@@ -6,3 +6,6 @@
/image/ovmf-vars.fd /image/ovmf-vars.fd
/image/out /image/out
/image/secrets /image/secrets
# Store apps developed in place, each its own git repository (apps/<name>/.git).
/apps/netflex-tv/
/.cargo/config.toml

524
.impeccable/design.json Normal file
View File

@@ -0,0 +1,524 @@
{
"schemaVersion": 2,
"generatedAt": "2026-10-24T20:37:52+00:00",
"title": "Design System: Fennec OS",
"extensions": {
"colorMeta": {
"fennec-orange": {
"role": "primary",
"displayName": "Fennec Orange",
"canonical": "oklch(72.5% 0.181 44.9)",
"tonalRamp": [
"#1f0000",
"#461100",
"#702800",
"#9c420d",
"#cc5d21",
"#fd7934",
"#ffa56d",
"#ffd1a1"
]
},
"fennec-orange-ink": {
"role": "primary",
"displayName": "Fennec Orange Ink",
"canonical": "oklch(77.9% 0.144 50.8)",
"tonalRamp": [
"#1b0400",
"#3c1a04",
"#633415",
"#8d4f28",
"#b96c3c",
"#e78a51",
"#ffae75",
"#ffd8a6"
]
},
"state-ok": {
"role": "secondary",
"displayName": "Connected Green",
"canonical": "oklch(73.0% 0.194 147.4)",
"tonalRamp": [
"#001200",
"#003003",
"#005216",
"#03762b",
"#1d9c40",
"#32c457",
"#72e785",
"#a8ffb5"
]
},
"state-ok-ink": {
"role": "secondary",
"displayName": "Green Ink",
"canonical": "oklch(81.0% 0.182 148.1)",
"tonalRamp": [
"#001100",
"#032e0e",
"#134f22",
"#257338",
"#39994f",
"#4ec067",
"#6be884",
"#a2ffb3"
]
},
"state-warn": {
"role": "secondary",
"displayName": "Caution Amber",
"canonical": "oklch(78.2% 0.171 67.2)",
"tonalRamp": [
"#1a0400",
"#3c1c00",
"#623600",
"#8c5100",
"#b86f00",
"#e68e00",
"#ffb242",
"#ffdc83"
]
},
"state-warn-ink": {
"role": "secondary",
"displayName": "Amber Ink",
"canonical": "oklch(82.0% 0.152 73.2)",
"tonalRamp": [
"#180600",
"#362000",
"#5b3a03",
"#825712",
"#ac7622",
"#d89632",
"#ffb84a",
"#ffe187"
]
},
"state-danger": {
"role": "secondary",
"displayName": "Danger Red",
"canonical": "oklch(66.3% 0.224 28.3)",
"tonalRamp": [
"#280000",
"#520000",
"#800205",
"#b11f1a",
"#e5392f",
"#ff6354",
"#ff9584",
"#ffc5b4"
]
},
"state-danger-ink": {
"role": "secondary",
"displayName": "Danger Ink",
"canonical": "oklch(74.6% 0.154 26.1)",
"tonalRamp": [
"#1d0202",
"#421411",
"#6a2b27",
"#96453f",
"#c46058",
"#f47c72",
"#ffa499",
"#ffcfc4"
]
},
"text-primary": {
"role": "neutral",
"displayName": "White",
"canonical": "oklch(100.0% 0.000 89.9)",
"tonalRamp": [
"#0b0b0b",
"#252525",
"#424242",
"#616161",
"#828282",
"#a5a5a5",
"#c9c9c9",
"#eeeeee"
]
},
"text-secondary": {
"role": "neutral",
"displayName": "Secondary White (72%)",
"canonical": "oklch(100.0% 0.000 89.9 / 72%)",
"tonalRamp": [
"#0b0b0b",
"#252525",
"#424242",
"#616161",
"#828282",
"#a5a5a5",
"#c9c9c9",
"#eeeeee"
]
},
"text-tertiary": {
"role": "neutral",
"displayName": "Tertiary White (56%)",
"canonical": "oklch(100.0% 0.000 89.9 / 56%)",
"tonalRamp": [
"#0b0b0b",
"#252525",
"#424242",
"#616161",
"#828282",
"#a5a5a5",
"#c9c9c9",
"#eeeeee"
]
},
"ink-on-focus": {
"role": "neutral",
"displayName": "Focus Ink",
"canonical": "oklch(18.7% 0.008 274.5)",
"tonalRamp": [
"#0a0b0f",
"#242529",
"#414246",
"#606164",
"#818285",
"#a4a5a7",
"#c8c9cb",
"#eeeef0"
]
},
"focus-platter": {
"role": "neutral",
"displayName": "Focus Platter",
"canonical": "oklch(100.0% 0.000 89.9 / 88%)",
"tonalRamp": [
"#0b0b0b",
"#252525",
"#424242",
"#616161",
"#828282",
"#a5a5a5",
"#c9c9c9",
"#eeeeee"
]
},
"glass-smoke": {
"role": "neutral",
"displayName": "Glass Smoke",
"canonical": "oklch(15.6% 0.013 277.4)",
"tonalRamp": [
"#0a0b11",
"#24252b",
"#414247",
"#606166",
"#818286",
"#a4a5a8",
"#c8c9cc",
"#edeef1"
]
},
"hairline": {
"role": "neutral",
"displayName": "Hairline",
"canonical": "oklch(100.0% 0.000 89.9 / 12%)",
"tonalRamp": [
"#0b0b0b",
"#252525",
"#424242",
"#616161",
"#828282",
"#a5a5a5",
"#c9c9c9",
"#eeeeee"
]
},
"night-base": {
"role": "neutral",
"displayName": "Night Base",
"canonical": "oklch(11.6% 0.003 285.9)",
"tonalRamp": [
"#0b0b0c",
"#252526",
"#424243",
"#616162",
"#828283",
"#a5a5a6",
"#c9c9ca",
"#eeeeef"
]
},
"backdrop-highlight": {
"role": "neutral",
"displayName": "Fallback Backdrop Highlight",
"canonical": "oklch(71.6% 0.027 261.1)",
"tonalRamp": [
"#090b10",
"#21252c",
"#3d424b",
"#5b626d",
"#7a8391",
"#9ca6b7",
"#c1cad9",
"#e7effd"
]
},
"backdrop-mid": {
"role": "neutral",
"displayName": "Fallback Backdrop Mid",
"canonical": "oklch(31.3% 0.029 265.2)",
"tonalRamp": [
"#070b15",
"#1f2533",
"#3b4251",
"#5b616f",
"#7d828e",
"#a0a5af",
"#c5c9d1",
"#ebeef5"
]
},
"backdrop-deep": {
"role": "neutral",
"displayName": "Fallback Backdrop Deep",
"canonical": "oklch(12.9% 0.008 268.5)",
"tonalRamp": [
"#0a0b0e",
"#242528",
"#414245",
"#606164",
"#818285",
"#a4a5a7",
"#c8c9cb",
"#eeeef0"
]
}
},
"typographyMeta": {
"display": {
"displayName": "Display",
"purpose": "Focused app name on the home shelf; one per screen."
},
"clock": {
"displayName": "Clock",
"purpose": "The time, top-left of home; anchors the top bar."
},
"headline": {
"displayName": "Headline",
"purpose": "Screen titles; band 48-60 px (keyboard/splash 48, pairing 52, settings 56, sheet 60)."
},
"title": {
"displayName": "Title",
"purpose": "Settings page title."
},
"shelf-title": {
"displayName": "Shelf Title",
"purpose": "Heading of the Top Shelf artwork row."
},
"body": {
"displayName": "Body",
"purpose": "App descriptions on the shelf (max 2 lines, 1040 px) and the sheet."
},
"item": {
"displayName": "Item",
"purpose": "List, nav and menu items; shelf card titles."
},
"fact": {
"displayName": "Fact",
"purpose": "Live facts under the hero; the long date."
},
"label": {
"displayName": "Label",
"purpose": "App names under cards, capsule, toast, subtitles, chips; the readability floor."
},
"caption": {
"displayName": "Caption",
"purpose": "Shelf detail and hints; never below 20 px."
}
},
"shadows": [
{
"name": "glass-grounding",
"value": "GL shader: soft falloff around the panel SDF, strength 0.26 + 0.22*focus + size term",
"purpose": "Every glass panel grounds itself; drawn by the glass layer, not Slint."
},
{
"name": "artwork",
"value": "drop-shadow blur 28px, offset-y 12px, #00000080",
"purpose": "Top Shelf artwork cards (non-glass imagery) only."
},
{
"name": "glass-frost",
"value": "mip blur: cards/capsule 1.2, settings platter 2.2, menu 3.0, sheet 3.4, pairing pane 3.8, nested < 0",
"purpose": "Frost rises with the pane's role; nested glass lights what is beneath it."
}
],
"motion": [
{
"name": "ease-glass",
"value": "cubic-bezier(0.22, 1, 0.36, 1)",
"purpose": "Default for focus glides (200-420 ms) and sheets/screens (480-600 ms)."
},
{
"name": "ease-droplet",
"value": "cubic-bezier(0.3, 1.18, 0.4, 1)",
"purpose": "Context menu budding out of a card (460 ms); the toast uses cubic-bezier(0.22, 1.25, 0.36, 1) at 520 ms."
},
{
"name": "ease-launch",
"value": "cubic-bezier(0.72, 0, 0.16, 1)",
"purpose": "Card-to-fullscreen launch morph, 900 ms."
},
{
"name": "focus-glide",
"value": "380 ms x / 420 ms y",
"purpose": "App-row focus travel; the shelf cross-fades halfway between icons."
},
{
"name": "press",
"value": "160 ms ease-out, scale -5%",
"purpose": "OK held on the focused card; a 520 ms hold opens the menu."
},
{
"name": "light-sweep",
"value": "fract(time * 0.16) across each panel",
"purpose": "Slow specular sheen travelling over glass."
}
],
"breakpoints": [
{
"name": "design-grid",
"value": "1920x1080 design px, scaled by u = min(w/1920, h/1080)"
}
]
},
"components": [
{
"name": "App Card",
"kind": "card",
"refersTo": "app-card",
"description": "Accent-tinted glass card with centred mark and name below; lifts x1.12 with inner light on focus. Preview at half scale.",
"html": "<div class=\"ds-stage\"><div class=\"ds-card\" tabindex=\"0\"><svg viewBox=\"0 0 32 32\" width=\"52\" height=\"52\"><rect x=\"4\" y=\"7\" width=\"24\" height=\"16\" rx=\"3\" fill=\"none\" stroke=\"#fff\" stroke-width=\"2.2\"/><path d=\"M12 27h8\" stroke=\"#fff\" stroke-width=\"2.2\" stroke-linecap=\"round\"/></svg></div><span class=\"ds-card-name\">Miracast</span></div>",
"css": ".ds-stage{background: radial-gradient(120% 140% at 30% 20%, #1d4f4a 0%, #0c1f22 45%, #050506 100%); padding:32px 48px 24px; display:inline-flex; flex-direction:column; align-items:center; gap:8px; font-family: Onest, system-ui, sans-serif;} .ds-card{width:160px; height:96px; border-radius:18px; display:grid; place-items:center; background:rgba(34,161,138,.38); backdrop-filter: blur(18px) saturate(1.4); box-shadow: inset 0 1px 0 rgba(255,255,255,.35), inset 0 0 0 1px rgba(255,255,255,.14), 0 10px 30px rgba(0,0,0,.35); transition:transform .38s cubic-bezier(0.22, 1, 0.36, 1), background .38s cubic-bezier(0.22, 1, 0.36, 1), box-shadow .38s cubic-bezier(0.22, 1, 0.36, 1); outline:none;} .ds-card:hover,.ds-card:focus-visible{transform:scale(1.12); background:rgba(92,196,175,.5); box-shadow:inset 0 1px 0 rgba(255,255,255,.6), inset 0 0 24px rgba(255,255,255,.25), 0 0 0 1px rgba(255,255,255,.3), 0 14px 36px rgba(0,0,0,.4), 0 0 24px rgba(47,224,192,.35);} .ds-card:active{transform:scale(1.07);} .ds-card-name{font-size:12px; font-weight:600; color:rgba(255,255,255,.56); margin-top:8px;} .ds-card:hover + .ds-card-name,.ds-card:focus-visible + .ds-card-name{color:#fff;}"
},
{
"name": "Status Capsule",
"kind": "chip",
"refersTo": "status-capsule",
"description": "Clear glass capsule with remote battery and network; amber ink when low or offline.",
"html": "<div class=\"ds-stage2\"><div class=\"ds-capsule\"><svg viewBox=\"0 0 32 32\" width=\"15\" height=\"15\"><rect x=\"10\" y=\"3\" width=\"12\" height=\"26\" rx=\"5\" fill=\"none\" stroke=\"rgba(255,255,255,.82)\" stroke-width=\"2.2\"/></svg><b>82%</b><i></i><svg viewBox=\"0 0 32 32\" width=\"15\" height=\"15\"><path d=\"M4 12a17 17 0 0 1 24 0M8 17a11 11 0 0 1 16 0M12 22a5 5 0 0 1 8 0\" fill=\"none\" stroke=\"rgba(255,255,255,.82)\" stroke-width=\"2.4\" stroke-linecap=\"round\"/><circle cx=\"16\" cy=\"26\" r=\"1.8\" fill=\"rgba(255,255,255,.82)\"/></svg><span>Otthon-5G</span></div></div>",
"css": ".ds-stage2{background: radial-gradient(120% 140% at 30% 20%, #1d4f4a 0%, #0c1f22 45%, #050506 100%); padding:24px; font-family: Onest, system-ui, sans-serif;} .ds-capsule{display:inline-flex; align-items:center; gap:6px; height:32px; padding:0 14px 0 12px; border-radius:999px; background:rgba(255,255,255,.03); backdrop-filter: blur(18px) saturate(1.4); box-shadow: inset 0 1px 0 rgba(255,255,255,.35), inset 0 0 0 1px rgba(255,255,255,.14), 0 10px 30px rgba(0,0,0,.35); color:#fff; font-size:12px;} .ds-capsule b{font-weight:600;} .ds-capsule span{font-weight:500; color:rgba(255,255,255,.85);} .ds-capsule i{width:1px; height:13px; background:rgba(255,255,255,.22); margin:0 4px;}"
},
{
"name": "Settings Platter",
"kind": "nav",
"refersTo": "settings-platter",
"description": "One smoke glass platter per list; the focused row is a white focus platter with dark ink; hairlines hide next to focus.",
"html": "<div class=\"ds-stage3\"><div class=\"ds-platter\"><button class=\"ds-row\">Kapcsolat<span>Vezetékes</span></button><button class=\"ds-row\">IP-cím<span>192.168.1.42</span></button><button class=\"ds-row ds-danger\">Gyári visszaállítás<span></span></button></div></div>",
"css": ".ds-stage3{background: radial-gradient(120% 140% at 30% 20%, #1d4f4a 0%, #0c1f22 45%, #050506 100%); padding:24px; font-family: Onest, system-ui, sans-serif;} .ds-platter{width:440px; padding:4px; border-radius:16px; background:rgba(11,12,18,.30); backdrop-filter: blur(18px) saturate(1.4); box-shadow: inset 0 1px 0 rgba(255,255,255,.35), inset 0 0 0 1px rgba(255,255,255,.14), 0 10px 30px rgba(0,0,0,.35);} .ds-row{all:unset; box-sizing:border-box; display:flex; justify-content:space-between; align-items:center; width:100%; height:44px; padding:0 14px; border-radius:12px; font-size:13px; font-weight:600; color:#fff; border-top:1px solid rgba(255,255,255,.12); transition:transform .36s cubic-bezier(0.22, 1, 0.36, 1), background .36s cubic-bezier(0.22, 1, 0.36, 1);} .ds-row:first-child{border-top-color:transparent;} .ds-row span{font-weight:400; font-size:12px; color:rgba(255,255,255,.6);} .ds-row:hover,.ds-row:focus-visible{background:rgba(255,255,255,.88); color:#121317; transform:scale(1.015); border-top-color:transparent;} .ds-row:hover span,.ds-row:focus-visible span{color:rgba(18,19,23,.7);} .ds-row:hover + .ds-row,.ds-row:focus-visible + .ds-row{border-top-color:transparent;} .ds-danger{color:#ff8278;} .ds-danger:hover,.ds-danger:focus-visible{background:rgba(255,69,58,.86); color:#fff;}"
},
{
"name": "Settings Navigation",
"kind": "nav",
"refersTo": "nav-item",
"description": "Category list with no glass at rest; the focused category becomes a white capsule.",
"html": "<div class=\"ds-stage4\"><button class=\"ds-nav\">Kijelző</button><button class=\"ds-nav\">Hálózat</button><button class=\"ds-nav\">Energia</button></div>",
"css": ".ds-stage4{background: radial-gradient(120% 140% at 30% 20%, #1d4f4a 0%, #0c1f22 45%, #050506 100%); padding:24px; display:flex; flex-direction:column; gap:4px; width:280px; font-family: Onest, system-ui, sans-serif;} .ds-nav{all:unset; height:40px; padding:0 16px; border-radius:999px; font-size:13px; font-weight:600; color:rgba(255,255,255,.62); transition:transform .36s cubic-bezier(0.22, 1, 0.36, 1), background .3s ease-out;} .ds-nav:hover,.ds-nav:focus-visible{background:rgba(255,255,255,.86); color:#121317; transform:scale(1.03); box-shadow:inset 0 1px 0 #fff, 0 6px 18px rgba(0,0,0,.3);}"
},
{
"name": "Keyboard Chips",
"kind": "button",
"refersTo": "keyboard-chip",
"description": "Mode/action capsules: the selected mode has orange ink, focus is a white platter, and the submit chip is Fennec orange glass.",
"html": "<div class=\"ds-stage5\"><button class=\"ds-chip ds-sel\">abc</button><button class=\"ds-chip\">.?123</button><button class=\"ds-chip ds-submit\">Kész</button></div>",
"css": ".ds-stage5{background: radial-gradient(120% 140% at 30% 20%, #1d4f4a 0%, #0c1f22 45%, #050506 100%); padding:24px; display:flex; gap:8px; font-family: Onest, system-ui, sans-serif;} .ds-chip{all:unset; width:100px; height:36px; text-align:center; line-height:36px; border-radius:999px; font-size:12px; font-weight:500; color:rgba(255,255,255,.78); background:rgba(255,255,255,.04); backdrop-filter: blur(18px) saturate(1.4); box-shadow: inset 0 1px 0 rgba(255,255,255,.35), inset 0 0 0 1px rgba(255,255,255,.14), 0 10px 30px rgba(0,0,0,.35); transition:transform .3s cubic-bezier(0.22, 1, 0.36, 1), background .3s cubic-bezier(0.22, 1, 0.36, 1);} .ds-sel{color:#ff9a5c; font-weight:700; background:rgba(255,255,255,.2);} .ds-submit{color:#fff; font-weight:700; background:rgba(255,122,53,.34);} .ds-chip:hover,.ds-chip:focus-visible{transform:scale(1.05); background:rgba(255,255,255,.84); color:#121317;} .ds-submit:hover,.ds-submit:focus-visible{background:rgba(255,122,53,.9); color:#fff; box-shadow:0 0 22px rgba(255,122,53,.45);}"
},
{
"name": "Text Field",
"kind": "input",
"refersTo": "text-field",
"description": "Wide glass field with an orange glow and an orange-ink blinking caret.",
"html": "<div class=\"ds-stage6\"><div class=\"ds-field\" tabindex=\"0\"><span>Otthon-5G</span><i></i></div></div>",
"css": ".ds-stage6{background: radial-gradient(120% 140% at 30% 20%, #1d4f4a 0%, #0c1f22 45%, #050506 100%); padding:24px; font-family: Onest, system-ui, sans-serif;} .ds-field{display:flex; align-items:center; gap:2px; width:480px; height:48px; padding:0 18px; border-radius:15px; background:rgba(255,255,255,.07); backdrop-filter: blur(18px) saturate(1.4); box-shadow: inset 0 1px 0 rgba(255,255,255,.35), inset 0 0 0 1px rgba(255,255,255,.14), 0 10px 30px rgba(0,0,0,.35); color:#fff; font-size:17px; font-weight:500; letter-spacing:.5px; outline:none;} .ds-field:hover,.ds-field:focus-visible{box-shadow:inset 0 1px 0 rgba(255,255,255,.4), inset 0 0 0 1px rgba(255,154,92,.45), 0 0 20px rgba(255,122,53,.25);} .ds-field i{width:2px; height:22px; border-radius:1px; background:#ff9a5c; animation:ds-blink 1s steps(1) infinite;} @keyframes ds-blink{55%{opacity:0}}"
},
{
"name": "Context Menu",
"kind": "custom",
"refersTo": "menu-item-selected",
"description": "Smoke glass menu that buds out of the focused card; the selected item is a white capsule.",
"html": "<div class=\"ds-stage7\"><div class=\"ds-menu\"><button class=\"ds-mi\"><svg viewBox=\"0 0 32 32\" width=\"13\" height=\"13\"><path d=\"M9 5l18 11-18 11z\" fill=\"currentColor\"/></svg>Megnyitás</button><button class=\"ds-mi\"><svg viewBox=\"0 0 32 32\" width=\"14\" height=\"14\"><circle cx=\"16\" cy=\"16\" r=\"12\" fill=\"none\" stroke=\"currentColor\" stroke-width=\"2.4\"/><path d=\"M16 14v8\" stroke=\"currentColor\" stroke-width=\"2.4\" stroke-linecap=\"round\"/><circle cx=\"16\" cy=\"10\" r=\"1.6\" fill=\"currentColor\"/></svg>Részletek</button></div></div>",
"css": ".ds-stage7{background: radial-gradient(120% 140% at 30% 20%, #1d4f4a 0%, #0c1f22 45%, #050506 100%); padding:24px; font-family: Onest, system-ui, sans-serif;} .ds-menu{width:216px; padding:6px; border-radius:16px; background:rgba(11,12,18,.42); backdrop-filter: blur(18px) saturate(1.4); box-shadow: inset 0 1px 0 rgba(255,255,255,.35), inset 0 0 0 1px rgba(255,255,255,.14), 0 10px 30px rgba(0,0,0,.35);} .ds-mi{all:unset; box-sizing:border-box; display:flex; align-items:center; gap:14px; width:100%; height:36px; padding:0 14px; border-radius:999px; font-size:13px; font-weight:600; color:#fff; transition:background .24s cubic-bezier(0.22, 1, 0.36, 1);} .ds-mi:hover,.ds-mi:focus-visible{background:rgba(255,255,255,.86); color:#121317;}"
},
{
"name": "Hero Facts",
"kind": "custom",
"refersTo": "fact",
"description": "Bare icon + text lines under the hero description, with no glass; ok/warn tones use the ink colours.",
"html": "<div class=\"ds-stage8\"><span class=\"ds-fact\"><svg viewBox=\"0 0 32 32\" width=\"15\" height=\"15\"><path d=\"M7 16l6 6 12-12\" fill=\"none\" stroke=\"#5ee07a\" stroke-width=\"3\" stroke-linecap=\"round\" stroke-linejoin=\"round\"/></svg>Mindig fut</span><span class=\"ds-fact ds-warn\"><svg viewBox=\"0 0 32 32\" width=\"15\" height=\"15\"><path d=\"M16 6v13\" stroke=\"#ffb340\" stroke-width=\"3\" stroke-linecap=\"round\"/><circle cx=\"16\" cy=\"25\" r=\"2\" fill=\"#ffb340\"/></svg>Kísérleti</span></div>",
"css": ".ds-stage8{background: radial-gradient(120% 140% at 30% 20%, #1d4f4a 0%, #0c1f22 45%, #050506 100%); padding:24px; display:flex; gap:20px; font-family: Onest, system-ui, sans-serif;} .ds-fact{display:inline-flex; align-items:center; gap:6px; font-size:13px; font-weight:500; color:rgba(255,255,255,.88);} .ds-warn{color:#ffb340;}"
}
],
"narrative": {
"northStar": "The Living Top Shelf",
"overview": "Fennec OS is tvOS 26 Liquid Glass on open hardware: a dark, slowly flowing backdrop tinted by the focused app's three-colour palette, with real refracting glass on top. The home screen re-composes around focus. As the focus glides along the app row, the backdrop palette, the shelf content (artwork or the app's name, description and live facts) and the glass lift all move together. Nothing else competes; the screen is mostly backdrop and type.\n\nGlass is the material, not the decoration. It carries exactly three things: **focus** (the lifted card, the white focus platter), **grouping** (one platter per list, the sheet, the pairing pane), and **state** (the status capsule, the pairing status pill). Facts, hints, dates and descriptions sit bare on the backdrop as icon + text. The glass is drawn by a separate OpenGL layer underneath Slint (Snell refraction with per-channel dispersion, squircle bevel, Fresnel, a specular rim facing a key light, a slow light sweep, a soft grounding shadow), so Slint content never sits beneath a pane; covered content fades out entirely.\n\nDensity is 10-foot: few elements, big type, generous safe area, one obvious focus at a time.",
"keyCharacteristics": [
"Palette backdrop per focused app; system chrome stays neutral white-on-dark.",
"Glass only for focus, grouping and state; everything else bare.",
"Focus = scale lift (cards ×1.12, chips ×1.05, rows ×1.015) plus an inner glow, never a ring or outline.",
"Onest throughout, tight negative tracking on large sizes.",
"Merged-glass droplets: menus and toasts bud out of the element that spawned them.",
"Motion on one expressive ease, `cubic-bezier(0.22, 1, 0.36, 1)`."
],
"rules": [
{
"name": "The Borrowed Colour Rule",
"body": "Chrome never brings its own hue. Colour comes from the focused app (accent, palette) or carries meaning (orange = system action, green/amber/red = state).",
"section": "colors"
},
{
"name": "The Two Tones Rule",
"body": "Each state hue has a glass tone and a lighter ink tone. Saturated tones tint and glow glass; text and icons sitting directly on the moving backdrop use the ink tone.",
"section": "colors"
},
{
"name": "The Sofa Floor Rule",
"body": "Body text is at least 24px and secondary text at least 20px on the 1080 grid. If text won't fit, cut words; don't shrink the type.",
"section": "typography"
},
{
"name": "The Tighten-As-You-Grow Rule",
"body": "Tracking goes negative only at 48px and up (about −1/50 of the size). Smaller sizes stay at normal tracking.",
"section": "typography"
},
{
"name": "The Nothing-Under-Glass Rule",
"body": "Glass refracts the backdrop, never Slint content. Anything a pane would cover fades out completely before the pane arrives.",
"section": "elevation"
},
{
"name": "The Lift-Is-Focus Rule",
"body": "Focus is shown by scale lift, inner light and a brighter tint, never by an outline or ring. Pressing OK pushes the focused card back in by 5%.",
"section": "elevation"
},
{
"name": "The Droplet Rule",
"body": "A transient surface grows out of its source as merged glass. The context menu buds from the focused card, the toast from the status capsule, and the launch pane from the card that was opened.",
"section": "elevation"
}
],
"dos": [
"Do express every length on the 1920×1080 grid and multiply by `u`. Keep 96px side and 64px top/bottom safe area.",
"Do mirror every glass rect's geometry exactly between Slint and the Rust glass layer (`card_rects`, `settings_screen::glass`, `keyboard::glass`).",
"Do use one grouped platter per list and a white focus platter with `ink-on-focus` for the focused item.",
"Do show focus with lift (×1.12 cards, ×1.05 chips, ×1.03 nav, ×1.015 rows) plus inner light.",
"Do animate state with `cubic-bezier(0.22, 1, 0.36, 1)` at 200–600ms. Use the overshoot `cubic-bezier(0.3, 1.18, 0.4, 1)` only for droplets (menu, toast).",
"Do use Fennec orange only for system actions (pairing, keyboard submit, field focus) and state hues only for state.",
"Do keep readable text at 24px or more and secondary text at 20px or more."
],
"donts": [
"Don't put glass behind facts, hints, dates or descriptions. Those are bare icon + text on the backdrop.",
"Don't draw Slint content where a glass pane will sit. Fade it out first.",
"Don't mark focus with outlines, rings or borders.",
"Don't give chrome its own hue. Colour comes from the focused app or carries meaning.",
"Don't use saturated state hues for text on the backdrop. Use the ink tones.",
"Don't add a second typeface or a system display face. Everything is Onest.",
"Don't use glyph or emoji icons. Draw vector icons on the 32-unit viewbox."
]
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.2 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.6 MiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 942 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1016 KiB

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 MiB

View File

@@ -0,0 +1,26 @@
---
version: 1
slug: "crates-sf-launcher-ui-app-slint"
primary_target: "crates/sf-launcher/ui/app.slint"
related_targets: ["crates/sf-launcher/ui/settings.slint","crates/sf-launcher/ui/pairing.slint","crates/sf-launcher/ui/keyboard.slint"]
---
# Surface: Fennec OS launcher (home, details sheet, settings, keyboard, pairing)
Mode: Operate (a TV home screen and its system screens). Audience: the household on the sofa with a Siri Remote. Job: reach a show, an app or a cast receiver in one press; configure the box without seeing plumbing. Constraints: Slint draws above the GL glass layer; home must be complete without the Netflex server.
Pinned by the user: "a better Apple TV, same Liquid Glass style". Fix: buggy margins, AI-looking design, fonts, empty home screen. Direction is brief-pinned, so no concept roll.
## Direction contract
THESIS: The home screen is a living Top Shelf, not a wallpaper with five tiles. It refuses the empty-gradient-plus-icon-row default and the glass-on-everything habit: glass carries focus, grouping and state only.
OWN-WORLD: tvOS 26 Liquid Glass on the focused app's palette backdrop. Onest (400/500/600/700) on an 8-px grid scaled from 1920x1080, 96 px side and 64 px top/bottom safe area. White text with 72%/56% secondaries, Fennec orange #ff7a35 for system actions, green #34c759 / amber #ff9f0a for state. Glass families: tinted app cards, one grouped platter per list, white focus platter, the status capsule. Facts are bare icon + text lines, not pills (amended after review: glass only where it carries focus, grouping or state).
STORY: The viewer sees the time and the TV's state at a glance, sees what the focused app offers right now (continue watching, how to cast, remote battery), and opens it with one press.
FIRST VIEWPORT: Top bar at y=64: clock 64/600 + long date 26/500 on the left (amended from 44: the clock is the 'Most' band's anchor and must read across the room), glass status capsule (remote battery, network) sized to its content on the right. Shelf y=176-704: Netflex focused with server data shows "Folytatás" landscape artwork cards with progress; otherwise a hero: app name 96/700 (amended from 88 for 10-foot weight), description 28/400 (max 2 lines), a row of live facts; the network appears there only as a warning. Lower app rows stay hidden while the shelf shows. App row at y=768: five 320x192 glass cards, 32 px gaps, name under every card (focused full white).
FORM: brief-pinned tvOS 26 Liquid Glass (no seed; pinned direction beats the roll). Signature move: the shelf re-composes with the focused app (content, facts and backdrop palette change together), and the glass lift travels with focus.
FINISH: unreviewed and undocumented is unfinished; this build ends with the finish review, the verdict, DESIGN.md, and every shipping raster carrying its provenance

784
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,14 +1,19 @@
[workspace] [workspace]
resolver = "3" resolver = "3"
members = ["crates/sf-ipc", "crates/sf-launcher", "crates/sf-remote", "crates/sf-update"] 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] [workspace.package]
version = "0.1.0" version = "0.3.3"
edition = "2024" edition = "2024"
license = "MIT" license = "MIT"
[workspace.dependencies] [workspace.dependencies]
sf-ipc = { path = "crates/sf-ipc" } 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.4" }
sf-ui = { git = "https://gitea.bluefox.support/fennec/sdk", tag = "v0.1.4" }
sf-dial = { path = "crates/sf-dial" }
serde = { version = "1", features = ["derive"] } serde = { version = "1", features = ["derive"] }
serde_json = "1" serde_json = "1"
toml = "0.9" toml = "0.9"

317
DESIGN.md Normal file
View File

@@ -0,0 +1,317 @@
---
name: Fennec OS
description: A living-room TV home in tvOS 26 Liquid Glass, on open hardware the family owns.
colors:
fennec-orange: "#ff7a35"
fennec-orange-ink: "#ff9a5c"
state-ok: "#34c759"
state-ok-ink: "#5ee07a"
state-warn: "#ff9f0a"
state-warn-ink: "#ffb340"
state-danger: "#ff453a"
state-danger-ink: "#ff8278"
text-primary: "#ffffff"
text-secondary: "#ffffffb8"
text-tertiary: "#ffffff8f"
ink-on-focus: "#121317"
focus-platter: "#ffffffe0"
glass-smoke: "#0b0c12"
hairline: "#ffffff1f"
night-base: "#050506"
backdrop-highlight: "#9aa4b5"
backdrop-mid: "#2a3140"
backdrop-deep: "#06070a"
typography:
display:
fontFamily: "Onest"
fontSize: "96px"
fontWeight: 700
letterSpacing: "-2px"
clock:
fontFamily: "Onest"
fontSize: "64px"
fontWeight: 600
letterSpacing: "-1px"
headline:
fontFamily: "Onest"
fontSize: "56px"
fontWeight: 700
letterSpacing: "-1px"
title:
fontFamily: "Onest"
fontSize: "40px"
fontWeight: 700
shelf-title:
fontFamily: "Onest"
fontSize: "36px"
fontWeight: 600
body:
fontFamily: "Onest"
fontSize: "28px"
fontWeight: 400
item:
fontFamily: "Onest"
fontSize: "26px"
fontWeight: 600
fact:
fontFamily: "Onest"
fontSize: "26px"
fontWeight: 500
label:
fontFamily: "Onest"
fontSize: "24px"
fontWeight: 500
caption:
fontFamily: "Onest"
fontSize: "22px"
fontWeight: 500
rounded:
track: "8px"
pill-row: "24px"
artwork: "24px"
field: "30px"
platter: "32px"
card: "36px"
sheet: "48px"
pane: "56px"
capsule: "9999px"
spacing:
hairline: "1.5px"
xs: "8px"
icon-gap: "12px"
sm: "16px"
md: "24px"
card-gap: "32px"
fact-gap: "40px"
sheet-pad: "56px"
safe-y: "64px"
row-step: "88px"
safe-x: "96px"
components:
app-card:
rounded: "{rounded.card}"
width: "320px"
height: "192px"
app-card-label:
textColor: "{colors.text-tertiary}"
typography: "{typography.label}"
app-card-label-focused:
textColor: "{colors.text-primary}"
typography: "{typography.label}"
status-capsule:
textColor: "{colors.text-primary}"
typography: "{typography.label}"
rounded: "{rounded.capsule}"
height: "64px"
padding: "0 28px 0 24px"
settings-platter:
backgroundColor: "{colors.glass-smoke}"
rounded: "{rounded.platter}"
padding: "8px"
settings-row:
textColor: "{colors.text-primary}"
typography: "{typography.item}"
height: "88px"
padding: "0 28px"
settings-row-focused:
backgroundColor: "{colors.focus-platter}"
textColor: "{colors.ink-on-focus}"
rounded: "{rounded.pill-row}"
height: "88px"
nav-item:
textColor: "{colors.text-secondary}"
typography: "{typography.item}"
rounded: "{rounded.capsule}"
width: "512px"
height: "80px"
nav-item-focused:
backgroundColor: "{colors.focus-platter}"
textColor: "{colors.ink-on-focus}"
rounded: "{rounded.capsule}"
menu-item-selected:
backgroundColor: "{colors.focus-platter}"
textColor: "{colors.ink-on-focus}"
typography: "{typography.item}"
rounded: "{rounded.capsule}"
height: "72px"
keyboard-chip:
textColor: "{colors.text-secondary}"
typography: "{typography.label}"
rounded: "{rounded.capsule}"
width: "200px"
height: "72px"
keyboard-chip-submit:
backgroundColor: "{colors.fennec-orange}"
textColor: "{colors.text-primary}"
rounded: "{rounded.capsule}"
height: "72px"
text-field:
textColor: "{colors.text-primary}"
rounded: "{rounded.field}"
width: "1200px"
height: "96px"
padding: "0 36px"
details-sheet:
backgroundColor: "{colors.glass-smoke}"
rounded: "{rounded.sheet}"
width: "720px"
padding: "56px"
shelf-artwork:
rounded: "{rounded.artwork}"
width: "402px"
height: "226px"
---
# Design System: Fennec OS
All values are design px on a 1920x1080 grid; the launcher multiplies every length by `u = min(width/1920, height/1080)`. This is a native Slint + OpenGL TV UI, not CSS.
## Overview
**Creative North Star: "The Living Top Shelf"**
Fennec OS is tvOS 26 Liquid Glass on open hardware: a dark, slowly flowing backdrop tinted by the focused app's three-colour palette, with real refracting glass on top. The home screen re-composes around focus. As the focus glides along the app row, the backdrop palette, the shelf content (artwork or the app's name, description and live facts) and the glass lift all move together. Nothing else competes; the screen is mostly backdrop and type.
Glass is the material, not the decoration. It carries exactly three things: **focus** (the lifted card, the white focus platter), **grouping** (one platter per list, the sheet, the pairing pane), and **state** (the status capsule, the pairing status pill). Facts, hints, dates and descriptions sit bare on the backdrop as icon + text. The glass is drawn by a separate OpenGL layer underneath Slint (Snell refraction with per-channel dispersion, squircle bevel, Fresnel, a specular rim facing a key light, a slow light sweep, a soft grounding shadow), so Slint content never sits beneath a pane; covered content fades out entirely.
Density is 10-foot: few elements, big type, generous safe area, one obvious focus at a time.
**Key Characteristics:**
- Palette backdrop per focused app; system chrome stays neutral white-on-dark.
- Glass only for focus, grouping and state; everything else bare.
- Focus = scale lift (cards ×1.12, chips ×1.05, rows ×1.015) plus an inner glow, never a ring or outline.
- Onest throughout, tight negative tracking on large sizes.
- Merged-glass droplets: menus and toasts bud out of the element that spawned them.
- Motion on one expressive ease, `cubic-bezier(0.22, 1, 0.36, 1)`.
## Colors
Neutral white-on-night chrome; colour comes from the focused app's palette and from a small set of system and state hues.
### Primary
- **Fennec Orange** (`fennec-orange`): the system accent. Glows and tints glass that belongs to the system itself: the pairing pane and its step beads, the keyboard text field's glow, the keyboard submit chip. **Fennec Orange Ink** (`fennec-orange-ink`) is its lighter text tone for orange on dark: the caret, the selected keyboard mode, settings option values.
### Secondary (state)
- **Connected Green** (`state-ok`): glass glow/tint for success (pairing done). Text and icon ink on the backdrop use the lighter **Green Ink** (`state-ok-ink`).
- **Caution Amber** (`state-warn`): glass glow/tint for a warning state (no Bluetooth adapter). On the backdrop, icons and text use **Amber Ink** (`state-warn-ink`): low remote battery (≤15%), no network, experimental apps.
- **Danger Red** (`state-danger`): the focus platter tint for destructive settings rows. Unfocused destructive row text uses **Danger Ink** (`state-danger-ink`).
### Per-app accents (data, not tokens)
Every app manifest carries an `accent` and a three-stop `palette` (highlight, mid, deep). The accent tints its card glass (accent × 0.72 at 38% tint, lifting to 50% and toward white when focused) and glows the sheet, menu, toast and launch pane. The palette drives the backdrop shader. When a manifest omits a palette, the fallback is `backdrop-highlight` / `backdrop-mid` / `backdrop-deep`.
### Neutral
- **White** (`text-primary`): titles, focused names, values.
- **Secondary White** (`text-secondary`, 72%): date, category labels, unfocused settings nav, descriptions.
- **Tertiary White** (`text-tertiary`, 56%): unfocused app names, hints and details.
- **Focus Ink** (`ink-on-focus`): text and icons on the white focus platter.
- **Focus Platter** (`focus-platter`, white at ~86–88%): the white glass under a focused row, nav item, menu item, key or chip.
- **Glass Smoke** (`glass-smoke`): the dark tint of grouping glass, at 30% (settings platter), 38% (sheet), 42% (menu) and 48% (pairing pane). Larger, more modal panes are smokier.
- **Hairline** (`hairline`): 1.5 px dividers between platter rows and sheet info rows.
- **Night Base** (`night-base`): the window clear colour under the backdrop.
### Named Rules
**The Borrowed Colour Rule.** Chrome never brings its own hue. Colour comes from the focused app (accent, palette) or carries meaning (orange = system action, green/amber/red = state).
**The Two Tones Rule.** Each state hue has a glass tone and a lighter ink tone. Saturated tones tint and glow glass; text and icons sitting directly on the moving backdrop use the ink tone.
## Typography
**Display / Body Font:** Onest (static 400, 500, 600, 700; OFL; full Hungarian coverage including ő/ű)
**Character:** A friendly geometric grotesque with open counters that reads across a room. Large sizes run bold with tight negative tracking; small sizes stay at 500–600 so they hold up over a moving backdrop.
### Hierarchy
- **Display** (700, 96px, −2px): the focused app's name on the home shelf. One per screen.
- **Clock** (600, 64px, −1px): the time, top-left, anchoring the top bar.
- **Headline** (700, 56px, −1px): screen titles (Settings). The same band runs from 48 to 60 px: keyboard title and launch splash name at 48/−0.8, pairing title at 52, sheet app name at 60/−1.2.
- **Title** (700, 40px): the settings page title. **Shelf title** (600, 36px) heads the Top Shelf row.
- **Body** (400, 28px): app descriptions on the shelf and sheet, capped at 2 lines on the shelf (1040 px measure). 28/700 is used for settings option values.
- **Item** (600, 26px): list and menu items, settings nav, shelf card titles. **Fact** (500, 26px): live facts and the long date.
- **Label** (500–600, 24px): app names under cards (600), the status capsule, toast, subtitles, sheet info rows, keyboard chips. This is the floor for anything the household must read.
- **Caption** (500, 22px): shelf card detail, the keyboard hint, the "Back to close" hint on the splash. Settings row detail runs at 21px. Nothing goes below 20px.
### Named Rules
**The Sofa Floor Rule.** Body text is at least 24px and secondary text at least 20px on the 1080 grid. If text won't fit, cut words; don't shrink the type.
**The Tighten-As-You-Grow Rule.** Tracking goes negative only at 48px and up (about −1/50 of the size). Smaller sizes stay at normal tracking.
## Layout
A fixed 1920x1080 stage scaled uniformly by `u`. Safe area: 96px left and right (`safe-x`), 64px top and bottom (`safe-y`). Lengths sit on an 8px rhythm, with optical exceptions (12px icon-to-text gaps, a 28px row text inset).
**Home.** The top bar has the clock and long date at the left (block at y 44, clock line 88px tall) and the status capsule at the right (y 56, 64 tall, as wide as its content). The Top Shelf fills y ≈ 260–620 and shows either Netflex artwork (four 402×226 cards with 40px gaps, title +20, detail +56) or the hero (display name at y 260, description at y 384, facts row at y 512 with 40px between facts). The app row is at y 760: five 320×192 cards with 32px gaps, names 16px below, rows 296px apart. Lower rows stay hidden while the shelf shows. Moving into a lower row scrolls it to the middle and dims the shelf.
**Settings.** Uses the whole safe area. The headline sits at the top. Categories form a 512px column (80px items, 88px step) starting 184px down. The rows platter starts 608px from the left edge, has 88px rows, shows 7 rows and scrolls once focus passes row 5.
**Sheet.** 720px wide, inset 64px from the right/top/bottom edges, with 56px padding. It has a 128px icon tile, name at +160, category at +240, description at +296, and info rows (80px each) pinned to the bottom.
**Modal pane.** The pairing pane is 1312×720 and centred. Its content column starts 440px in.
## Elevation & Depth
Depth is real optics, not drop shadows. Every glass panel is a refracting slab whose bevel bends the backdrop. Bigger panels are thicker, with a wider bevel, stronger lensing and a deeper shadow. Each panel casts its own soft grounding shadow (ambient strength about 0.26, plus 0.22 when focused). Focus brings light from within, a stronger rim and a slight accent spill. Frost (backdrop blur) rises with the pane's role: about 1.2 for cards and the capsule, 2.2 for the settings platter, 3.0–3.8 for the menu, sheet and pairing pane. Nested glass (beads, pills and focus platters on another pane) sets frost below 0 and lights what is already beneath it.
Slint-drawn shadows appear only on non-glass imagery: shelf artwork (blur 28, y 12, black at 50%) and the illustrated Siri Remote.
### Named Rules
**The Nothing-Under-Glass Rule.** Glass refracts the backdrop, never Slint content. Anything a pane would cover fades out completely before the pane arrives.
**The Lift-Is-Focus Rule.** Focus is shown by scale lift, inner light and a brighter tint, never by an outline or ring. Pressing OK pushes the focused card back in by 5%.
**The Droplet Rule.** A transient surface grows out of its source as merged glass. The context menu buds from the focused card, the toast from the status capsule, and the launch pane from the card that was opened.
## Shapes
Continuous squircle corners everywhere, sized to the panel. Capsules (radius = height/2) are used for status, chips, nav items, menu items and pills. 24px is for focus rows and artwork, 30px for the text field and key lens, 32px for the settings platter and menu, 36px for app cards and the sheet icon tile (scaled with lift), 48px for the sheet, 56px for the pairing pane. Radius grows with panel size. There are no borders on glass; the rim is a lit hairline from the shader. Icons are original vector line drawings on a 32-unit viewbox at 2.2–2.4 stroke (3 for check and alert). App marks are filled, simplified originals.
## Components
### App Card
Coloured glass in the app's accent, with the mark centred at 104px and the name below. At rest the tint is 38% and the name is at 56% white. Focused, the card lifts ×1.12, the tint brightens toward white, light comes from within, and the name turns full white. A long press of OK (520ms) buds out the context menu.
### Status Capsule
Clear glass capsule, 64 tall: remote icon and battery %, a 1.5px divider, then network icon and label. Low battery or no network switches to amber ink. The toast grows out of it as a 640×72 droplet with a dot in the app's accent.
### Facts
Bare icon (30px) + fact text (26/500) lines, 40px apart, under the hero description. Tone `ok` uses green ink and `warn` uses amber ink. Facts are never pills.
### Grouped Platter (settings rows)
One smoke-tinted glass platter per list. Rows are 88px with hairlines between them; the hairline hides next to the focused row. Each row has a title (26/600), optional detail (21) and a right-aligned value (24/400 secondary). Choice and device rows end in a chevron; network rows end in a lock and signal bars. The focused row gets a white focus platter (24px radius, ×1.015) and dark ink. Destructive rows use a red platter with white ink.
### Settings Navigation
No glass at rest. The focused category gets a white capsule with dark ink (×1.03). While the rows have focus, the selected category keeps a faint 10% capsule.
### Context Menu
Smoke glass (42%) merged with the focused card, 432 wide. Items are 72px with an icon, and the selected item is a white capsule with dark ink.
### Details Sheet
Smoke glass slides in from the right (720 wide). It holds the accent-tinted icon tile, the name, category and description. Info rows sit at the bottom as bare key/value lines with hairlines.
### On-screen Keyboard
A tvOS single-row keyboard. It has a 1200×96 glass field with an orange glow and an orange-ink caret, and a faint key track with a white focus lens (86×112). Keys fisheye from 31 to 48px under the lens. Below are mode/action chips, 200×72 capsules. The selected mode has orange ink, the focused chip is a white platter, and the submit chip is Fennec orange glass (34% tint when submit is possible, 8% when not).
### Pairing Guide
A smoke pane with an orange glow. On the left is an illustrated Siri Remote whose relevant buttons pulse in orange. On the right are three numbered steps on orange glass beads, a live status pill (green or amber glass when resolved, three breathing dots while searching) and a "Kihagyás" skip chip.
### Launch Splash
The focused card's glass morphs into a full-screen pane over 900ms. The app mark flies to centre and grows, then the name (48/700) and an accent shimmer inside a 280×16 glass track appear, with a "press Back" caption at the bottom.
## Do's and Don'ts
### Do:
- **Do** express every length on the 1920×1080 grid and multiply by `u`. Keep 96px side and 64px top/bottom safe area.
- **Do** mirror every glass rect's geometry exactly between Slint and the Rust glass layer (`card_rects`, `settings_screen::glass`, `keyboard::glass`).
- **Do** use one grouped platter per list and a white focus platter with `ink-on-focus` for the focused item.
- **Do** show focus with lift (×1.12 cards, ×1.05 chips, ×1.03 nav, ×1.015 rows) plus inner light.
- **Do** animate state with `cubic-bezier(0.22, 1, 0.36, 1)` at 200–600ms. Use the overshoot `cubic-bezier(0.3, 1.18, 0.4, 1)` only for droplets (menu, toast).
- **Do** use Fennec orange only for system actions (pairing, keyboard submit, field focus) and state hues only for state.
- **Do** keep readable text at 24px or more and secondary text at 20px or more.
### Don't:
- **Don't** put glass behind facts, hints, dates or descriptions. Those are bare icon + text on the backdrop.
- **Don't** draw Slint content where a glass pane will sit. Fade it out first.
- **Don't** mark focus with outlines, rings or borders.
- **Don't** give chrome its own hue. Colour comes from the focused app or carries meaning.
- **Don't** use saturated state hues for text on the backdrop. Use the ink tones.
- **Don't** add a second typeface or a system display face. Everything is Onest.
- **Don't** use glyph or emoji icons. Draw vector icons on the 32-unit viewbox.

57
PRODUCT.md Normal file
View File

@@ -0,0 +1,57 @@
# Product
<!-- impeccable:product-schema 1 -->
## Platform
tv (native Linux kiosk; Rust + Slint UI on an OpenGL "Liquid Glass" layer; 10-foot UI driven by an Apple Siri Remote). Not web, not iOS.
## Users
A household: family members of mixed technical comfort, on the living-room sofa, a few metres from a 1080p/4K TV, holding a Siri Remote (clickpad, Back, TV/Home, volume). Their job is to get to something to watch (own Netflex server, YouTube) or to put a phone's screen on the TV (AirPlay, Miracast, YouTube cast) with as few presses as possible. The owner also configures the box (display mode, Wi-Fi, remote pairing, updates).
## Product Purpose
Fennec OS is a self-built smart-TV system on minimal Debian (Intel N100): a launcher, background cast receivers, a kiosk compositor and package-based updates. Success: the TV feels as calm and direct as an Apple TV, starts what you want in one press, and never shows plumbing to the family.
## Positioning
An Apple TV-class experience on open hardware the owner controls: the family's own media server (Netflex) is a first-class citizen next to YouTube, and phones of any brand can cast to it (AirPlay for Apple, Miracast for Android, DIAL for YouTube).
## Operating Context
- Input is a Siri Remote only (arrows/swipe, OK short and long press, Back, TV/Home); a keyboard works in development.
- The home screen is the resting state of the TV; apps run full-screen on top and return to it with Home.
- Receivers (AirPlay, Miracast) always run in the background; their tiles explain how to connect rather than launching anything.
- Development runs windowed on Windows with demo system data (`SMARTFOX_DEMO_SYSTEM`), and a dev-snapshot mode for screenshots.
## Capabilities and Constraints
- Apps come from manifests (`apps/<id>/app.toml`): name, category, description, icon, accent, palette, kind (web / exec / builtin / service).
- The Liquid Glass layer draws the animated backdrop and every glass panel in OpenGL underneath Slint; Slint draws only text, icons and images on top. Glass refracts the backdrop, never Slint content, so nothing Slint-drawn may sit under a glass pane.
- Netflex server API (`/api/continue`, `/api/home`) needs a per-profile auth token. The home screen must work fully without the server; server content is an optional enrichment, cached for offline.
- Deep links into Netflex titles are not supported by the Netflex web app yet (undecided).
- UI language: Hungarian (needs ő/ű in every face).
## Brand Commitments
- The visual language is Apple tvOS 26 "Liquid Glass" (user-pinned): refracting glass panels, focus lift, light sweep, palette backdrop per focused app.
- Fennec orange (#ff7a35) is the system accent (pairing, keyboard submit).
- App marks in `ui/icons.slint` are simplified original drawings.
## Evidence on Hand
- Five apps: Netflex, YouTube, AirPlay, Miracast (experimental), Beállítások.
- Real system data on the TV (network, Wi-Fi, Bluetooth devices with battery, display modes); demo equivalents on Windows.
- No poster or artwork assets ship with the launcher; title artwork can only come from the Netflex server.
## Product Principles
1. One press to what you came for; the remote is the only input.
2. Never show plumbing to the family: commands, IDs and interface names stay out of everyday screens.
3. The TV must be complete offline and without the media server.
4. Glass is the material, not the decoration: it carries focus, grouping and state.
## Accessibility & Inclusion
10-foot legibility: body text at least 24 px and secondary text at least 20 px on a 1080p grid, high contrast on the moving backdrop, focus always obvious from across the room.

171
README.md
View File

@@ -1,4 +1,4 @@
# SmartFox # Fennec OS
Egy saját okos-TV rendszer minimál Debianra (Intel N100). Rust launcher, Liquid Glass dizájn, Netflex, YouTube TV, DIAL/AirPlay/Miracast castolás és Siri Remote. Egy saját okos-TV rendszer minimál Debianra (Intel N100). Rust launcher, Liquid Glass dizájn, Netflex, YouTube TV, DIAL/AirPlay/Miracast castolás és Siri Remote.
A teljes terv: `C:\Users\csike\.claude\plans\szeretnek-egy-linux-alapra-resilient-nova.md`. A teljes terv: `C:\Users\csike\.claude\plans\szeretnek-egy-linux-alapra-resilient-nova.md`.
@@ -6,10 +6,10 @@ A teljes terv: `C:\Users\csike\.claude\plans\szeretnek-egy-linux-alapra-resilien
## Állapot ## Állapot
- [x] **1. fázis:** launcher prototípus (Slint + OpenGL Liquid Glass réteg) és manifest-alapú appok - [x] **1. fázis:** launcher prototípus (Slint + OpenGL Liquid Glass réteg) és manifest-alapú appok
- [x] **1b. fázis:** Siri Remote: protokoll visszafejtve (`docs/siri-remote.md`), `sf-remote` driver (gombok, ismétlés, swipe → uinput) - [x] **1b. fázis:** Siri Remote: protokoll visszafejtve (`docs/siri-remote.md`), `sf-remote` driver (gombok, ismétlés, swipe → uinput)
- [ ] 2: mkosi Debian image - [x] **2. fázis:** mkosi Debian image, telepítő ISO, csak olvasható rendszer + adatpartíció
- [ ] 3: `sf-core` (app indítás, Chromium web runtime) - [x] **3. fázis:** `sf-core`: appok indítása systemd scope-ban, egyszerre egy app; Chromium web runtime
- [ ] 4: DIAL (YouTube cast), AirPlay, Miracast - [x] **4. fázis:** DIAL (YouTube cast telefonról), AirPlay (UxPlay); Miracast **kísérleti**, valódi telefonnal még nincs kipróbálva
- [ ] 5: saját Smithay kompozitor - [x] **5. fázis:** saját Smithay kompozitor (`sf-compositor`): app-váltás animációval, hangerő-OSD, `wlr-randr` támogatás
## Futtatás (fejlesztés) ## Futtatás (fejlesztés)
```sh ```sh
@@ -30,6 +30,7 @@ cargo run --release -p sf-launcher
**Beállítások** (a „Beállítások” app): bal oldalt kategóriák, jobb oldalt a sorok (↑ ↓, Enter, ← / Esc vissza). **Beállítások** (a „Beállítások” app): bal oldalt kategóriák, jobb oldalt a sorok (↑ ↓, Enter, ← / Esc vissza).
- Kijelző: felbontás és frissítés választása (`wlr-randr`). Az új mód 15 mp-ig ideiglenes, megerősítés nélkül visszaáll; a megtartott mód a `settings.toml` `display_mode` kulcsába kerül, és induláskor újra beállítódik. - Kijelző: felbontás és frissítés választása (`wlr-randr`). Az új mód 15 mp-ig ideiglenes, megerősítés nélkül visszaáll; a megtartott mód a `settings.toml` `display_mode` kulcsába kerül, és induláskor újra beállítódik.
- Távirányító és Bluetooth: a párosított eszközök (`bluetoothctl`) állapottal, akkuval; eltávolítás, új Siri Remote párosítása. - Távirányító és Bluetooth: a párosított eszközök (`bluetoothctl`) állapottal, akkuval; eltávolítás, új Siri Remote párosítása.
- Hang: HDMI/vezetékes és Bluetooth hangkimenetek kiválasztása (`pactl`); a már futó hangfolyamok is átkerülnek az új kimenetre. Bluetooth fejhallgató vagy hangszóró kereshető, párosítható és csatlakoztatható.
- Hálózat: kapcsolat, IP és Wi-Fi (`iwd`). - Hálózat: kapcsolat, IP és Wi-Fi (`iwd`).
- A Wi-Fi ki- és bekapcsolható. A hálózatlista jelerősséget és lakatot mutat. - A Wi-Fi ki- és bekapcsolható. A hálózatlista jelerősséget és lakatot mutat.
- Új védett hálózatnál a képernyő-billentyűzeten kell megadni a jelszót. Ha a csatlakozás nem sikerül, a billentyűzet hibaüzenettel újra megnyílik. - Új védett hálózatnál a képernyő-billentyűzeten kell megadni a jelszót. Ha a csatlakozás nem sikerül, a billentyűzet hibaüzenettel újra megnyílik.
@@ -45,19 +46,53 @@ cargo run --release -p sf-launcher
Windowson (vagy `SMARTFOX_DEMO_SYSTEM=1`-gyel) demó adatokkal fut, a rendszert nem módosítja. 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 ```toml
# settings.toml # settings.toml
netflex_server = "https://netflex.furbidden.cloud" netflex_server = "https://netflex.furbidden.cloud"
netflex_token = "..." # opcionális: a kezdőlap „Folytatás” sorához
``` ```
**Kezdőlap (Top Shelf):** a fókuszált app felett élő sáv.
- 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 app még nem kezel közvetlen linket egy címre.
## Felépítés ## 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 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 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) crates/sf-launcher/ Slint UI (ui/*.slint) + src/glass/ (OpenGL háttér és üveg shaderek)
apps/<id>/app.toml appok: kind = "web" | "exec" | "builtin" apps/<id>/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
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
crates/sf-miracast/ kísérleti Miracast vevő (iwd Wi-Fi Direct + WFD RTSP + GStreamer)
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/`). **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/`).
@@ -72,7 +107,7 @@ apps/<id>/app.toml appok: kind = "web" | "exec" | "builtin"
- a kis vezérlők teljes kupolák (cseppszerű lencse), a nagy panelek vastag lapok széles, lekerekített peremmel; - a kis vezérlők teljes kupolák (cseppszerű lencse), a nagy panelek vastag lapok széles, lekerekített peremmel;
- negatív `blur` = beágyazott üveg egy másik panelen (beállítás-sorok, chipek, lépésszámok): nem töri újra a hátteret, csak formát, peremfényt és árnyékot ad. - negatív `blur` = beágyazott üveg egy másik panelen (beállítás-sorok, chipek, lépésszámok): nem töri újra a hátteret, csak formát, peremfényt és árnyékot ad.
Minden vezérlő üveg: státusz-kapszula, értesítés, app-ikonok, helyi menü, beállítás-panel és sorai, párosítási panel, státusz-pill, gyorsbillentyű-chipek, töltősáv. A Slint csak a szöveget és az ikonokat rajzolja rájuk. Korlát: az üveg a GL hátteret töri, a Slint által rajzolt tartalmat nem. Az üveg a fókuszt, a csoportosítást és az állapotot hordozza, nem díszítés: státusz-kapszula, értesítés, app-ikonok, helyi menü, részletek-lap, a beállítás-sorok közös panelje és a fókusz-pirula, párosítási panel, billentyűzet, töltősáv. A Slint csak a szöveget, az ikonokat és a képeket rajzolja rájuk. Korlát: az üveg a GL hátteret töri, a Slint által rajzolt tartalmat nem, ezért Slint-tartalom nem kerülhet üveg alá. Betűtípus: Onest (OFL, `ui/fonts`).
A panelek geometriáját a Slint adja: a `glass-under`, `glass-menu` és `glass-over` tömbökből, valamint a rács property-jeiből. A kártyák képlete a `ui/app.slint` és a `src/main.rs` (`card_rects`) fájlban szinkronban kell legyen. A helyi menü a fókuszált ikonnal egy csoportban van, ezért cseppként válik ki belőle. A panelek geometriáját a Slint adja: a `glass-under`, `glass-menu` és `glass-over` tömbökből, valamint a rács property-jeiből. A kártyák képlete a `ui/app.slint` és a `src/main.rs` (`card_rects`) fájlban szinkronban kell legyen. A helyi menü a fókuszált ikonnal egy csoportban van, ezért cseppként válik ki belőle.
@@ -94,7 +129,7 @@ Az eredmény: `image/out/smartfox-installer.iso`.
- **Rufus:** válaszd ki az ISO-t, Partíciós séma: GPT, Cél: UEFI (CSM nélkül), majd „ISO kép mód”. - **Rufus:** válaszd ki az ISO-t, Partíciós séma: GPT, Cél: UEFI (CSM nélkül), majd „ISO kép mód”.
- **balenaEtcher / dd:** is működik: az ISO-ban GPT és EFI rendszerpartíció van, így nyersen kiírva is bootol. - **balenaEtcher / dd:** is működik: az ISO-ban GPT és EFI rendszerpartíció van, így nyersen kiírva is bootol.
- **A gépen:** kapcsold ki a Secure Bootot (a bootloader nincs aláírva), és bootolj a pendrive-ról. - **A gépen:** kapcsold ki a Secure Bootot (a bootloader nincs aláírva), és bootolj a pendrive-ról.
- **A telepítő:** RAM-ból fut. Kiválasztod a belső lemezt, beírod, hogy `igen`, és a SmartFox image kiíródik rá. A lemezen minden adat törlődik. - **A telepítő:** RAM-ból fut. Kiválasztod a belső lemezt, beírod, hogy `igen`, és a Fennec OS image kiíródik rá. A lemezen minden adat törlődik.
**Lemezkiosztás a telepített gépen:** **Lemezkiosztás a telepített gépen:**
- `esp`: systemd-boot és a UKI. - `esp`: systemd-boot és a UKI.
@@ -105,6 +140,26 @@ Az eredmény: `image/out/smartfox-installer.iso`.
Az üres partíciót az `sf-data-init.service` tölti fel a `/usr/share/factory/var` gyári tartalmával. Az üres partíciót az `sf-data-init.service` tölti fel a `/usr/share/factory/var` gyári tartalmával.
## Raspberry Pi (4 és 5)
A Fennec OS felrakható egy meglévő 64 bites Raspberry Pi OS-re (Debian trixie, arm64). A Pi megtartja a saját rendszerét, a hálózatát (NetworkManager) és az SSH-t; a képernyőt a Fennec OS veszi át.
```sh
sudo bash /mnt/g/source/smartfox/image/pi/build.sh # WSL Debianban, keresztfordítással
scp image/out/fennec-os-pi-*-aarch64.tar.gz pi: # a Pi-re
tar xf fennec-os-pi-*-aarch64.tar.gz && sudo fennec-os-pi/install.sh # a Pi-n, aztán reboot
```
- A telepítő a hiányzó csomagokat apt-tal rakja fel. Létrehozza a `tv` felhasználót: ez automatikusan belép a tty1-en, és elindítja a TV-felületet. Az asztal (lightdm) nem indul.
- `--no-session`: csak telepít, a Pi az asztalra bootol tovább. `--uninstall`: vissza az asztalhoz, a `tv` és az adatai maradnak. `--purge`: azokat is törli.
- A frissítés ugyanúgy csomagokból megy, az `-aarch64` shell-csomagokkal (lásd `docs/updates.md`, Architektúrák).
- **Megjelenés:** a launcher és az SDK-s appok (pl. a Netflex) az első induláskor lemérik a GPU-t. Ahol az üveghatás nem fér bele egy képkockába, matt Material stílusra váltanak. A Pi 4-en ez a Material, ezzel navigálás közben 55–60 FPS.
- A mérés eredménye a `~/.cache/fennec-glass` fájlba kerül.
- Kézzel felülírható: `SMARTFOX_GLASS=full|light|flat|material` a `/var/lib/smartfox/session.env`-ben.
- Részletek: az SDK `docs/sf-ui.md` fájljában, „Megjelenés gyengébb GPU-n”.
- **Ami Pi-n nem megy:**
- Steam: csak x86-64.
- Netflex: amíg nincs ARM-csomagja.
- A Beállítások Wi-Fi része: iwd-t vár, a Pi-n NetworkManager van.
- A Távoli hibakeresés kapcsoló: az SSH-t itt a Pi saját beállítása kezeli.
## Alapértelmezett belépés ## Alapértelmezett belépés
| Felhasználó | Jelszó | Megjegyzés | | Felhasználó | Jelszó | Megjegyzés |
|---|---|---| |---|---|---|
@@ -136,6 +191,44 @@ A már megnyitott SSH-kapcsolatok a kikapcsolás után is élnek, újat nyitni v
3. A script indítja vagy leállítja az `ssh.service`-t. Bekapcsoláskor elindítja az `sf-remote-debug-off.timer`-t is, ez kapcsolja ki az SSH-t, amikor letelik az 1 óra. 3. A script indítja vagy leállítja az `ssh.service`-t. Bekapcsoláskor elindítja az `sf-remote-debug-off.timer`-t is, ez kapcsolja ki az SSH-t, amikor letelik az 1 óra.
4. Rendszerinduláskor az `sf-remote-debug-boot.service` törli a kapcsoló-fájlt, így a gép mindig kikapcsolt SSH-val indul. 4. Rendszerinduláskor az `sf-remote-debug-boot.service` törli a kapcsoló-fájlt, így a gép mindig kikapcsolt SSH-val indul.
## Frissítések
A TV csomagokat frissít, az image-et nem:
- `sf-shell`: a felület (launcher, `sf-remote`);
- `sf-app-<id>`: egy-egy app.
Az image (a rendszer) csak újratelepítéssel változik. A részletek és a protokoll: [`docs/updates.md`](docs/updates.md).
**Kiadás:** emeld a verziót, és pushold a `main` ágat. A Gitea CI megépíti, aláírja és feltölti azt a csomagot, amelyiknek a verziója még nincs fent.
- shell: `Cargo.toml` → `[workspace.package] version`;
- app: `apps/<id>/app.toml` → `version`.
**A TV-n:**
- 6 óránként magától letölti az újdonságokat, ezek a következő induláskor élesednek;
- a Beállítások → Rendszer → **Frissítések** oldalon azonnal is telepíthetők, utána a felület újraindul;
- ha egy új shell háromszor egymás után nem indul el, a TV visszaáll az előzőre.
**Titkok, nincsenek a gitben:**
- `image/secrets/update-token`: a TV-k csak olvasható registry-belépése (`fox-tv:<token>`);
- a csomag-aláíró kulcs: `%USERPROFILE%\.smartfox\signing-key.pem` és a `SF_SIGNING_KEY` CI-secret.
## App Store és sandbox
**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.
- Írni csak a saját adatmappájába tud (`~/.local/share/smartfox/apps/<id>`); a saját fájljai `/app` alatt vannak, csak olvashatóan.
- 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:** 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.
**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).
## Készenlét és alvás ## Készenlét és alvás
A Siri Remote bekapcsológombja készenlétbe teszi a TV-t. Mit jelent ez, azt a Beállítások → **Energia** → Bekapcsológomb sorban lehet választani: A Siri Remote bekapcsológombja készenlétbe teszi a TV-t. Mit jelent ez, azt a Beállítások → **Energia** → Bekapcsológomb sorban lehet választani:
@@ -164,6 +257,64 @@ A „Készenlét most” sor ugyanazt csinálja, mint a gomb. A beállítás a `
Ha az ébresztés megbízhatatlan, a **Képernyő kikapcsolása** mód mindig működik. Ha az ébresztés megbízhatatlan, a **Képernyő kikapcsolása** mód mindig működik.
## Appok és váltás (sf-core)
A TV-n az appokat az `sf-core` indítja, nem a launcher. A launcher csak kér a `$XDG_RUNTIME_DIR/smartfox-core.sock` socketen (JSON sorok, `crates/sf-ipc/src/message.rs`). Ha nincs `sf-core` (Windows, fejlesztés), a launcher maga indít.
- **Indítás:** minden app saját systemd user scope-ban fut (`sf-app-<id>-<n>.scope`), saját folyamatcsoportban. A web appok a közös Chromiumot kapják, appra szabott profillal (`~/.config/smartfox/profiles/<id>`).
- **Egyszerre egy app:** Home, egy másik app indítása vagy egy tükrözés (AirPlay, Miracast) bezárja a képernyőn lévő appot. A kompozitor a launchert hozza elő, az app 0,6 mp múlva, a váltás animációja után zárul be (`systemctl --user stop`); ha addig újra megnyitod, megmarad. Háttérben nem vár app, így nem foglal memóriát, és nem tartja lefoglalva a hangkimenetet.
- **cage alatt** (tartalék kompozitor) nincs animáció, ott az app azonnal bezárul.
- **Háttérszolgáltatások:** az `app.toml`-ban `service = true` (AirPlay, Miracast). Az `sf-core` folyamatosan futtatja és újraindítja őket. A csempe csak a Részletek lapot nyitja.
## Castolás
**YouTube (DIAL):** a telefonon a YouTube appban a cast ikon alatt megjelenik a „Fennec OS”.
- A TV SSDP-n hirdeti magát, a DIAL REST a 56789-es porton fut.
- A telefon kérésére az `sf-core` elindítja a YouTube TV-s felületét a telefon párosító adataival (`youtube.com/tv?pairingCode=…`), és a videó a TV-n indul.
- Az eszköz neve a `settings.toml` `device_name` kulcsával változtatható.
- Az azonosító a `/etc/machine-id`-ből származik, így a telefon újraindítás után is felismeri a TV-t.
- Csak a DIAL-ban megadott appok indíthatók így (`[dial] name = "YouTube"`).
**AirPlay:** iPhone, iPad vagy Mac Vezérlőközpont → Képernyőtükrözés → Fennec OS.
- Az UxPlay mindig fut.
- Kapcsolódáskor a kompozitor előre hozza a képét, az előtérben lévő app bezárul, a launcher értesítést mutat.
- A tükrözés végén a launcher látszik.
**Miracast (kísérleti):** Android → Képernyő tükrözése / Smart View → Fennec OS.
- Wi-Fi Directet tudó kártya kell (pl. Intel AX200/AX210). Ilyen kártya nélkül az `sf-miracast` csak naplóz, és vár.
- Az `sf-miracast` az iwd-n keresztül Wi-Fi Display vevőként regisztrálja a TV-t.
- Az iwd bejövő kapcsolatot nem fogad. Ezért, amikor egy telefon képernyőt keres (WFD forrásként látszik), a TV kapcsolódik hozzá; a telefon ezt jóváhagyást kérő ablakkal jelezheti.
- A kép MPEG-TS/RTP-n jön, a GStreamer játssza le (VA-API).
- Csak automata tesztek futottak rá (RTSP üzenetváltás), valódi telefonnal még nincs kipróbálva.
## Kompozitor (sf-compositor)
A session az `sf-compositor`-t indítja a cage helyett (`sf-session`). Ha az nem indul, vagy 20 mp-en belül összeomlik, a session cage-gel indul. Cage kényszeríthető: `SMARTFOX_COMPOSITOR=cage` a `/etc/default/smartfox` vagy a `/var/lib/smartfox/session.env` fájlban.
- **Ablakok:** minden ablak teljes képernyős, egyszerre egy látszik: a launcher vagy az az app, amelyet az `sf-core` előre hozott. Egyszerre csak egy app fut.
- Melyik ablak melyik appé: a kliens folyamatcsoportja (az `sf-core` bejelenti: `register <pgid> <app>`), vagy a systemd scope neve.
- **Váltás:** az app kicsiből nagyítva, áttűnve jelenik meg a launcher fölött, Home-ra ugyanígy tűnik el.
- **Gombok:**
- hangerő fel/le/némítás: PipeWire hangerő (`wpctl`) és OSD sáv a képernyő alján;
- Home (`KEY_HOMEPAGE`): a launcher socketjére megy;
- Ctrl+Alt+F1…F12: konzolváltás;
- Ctrl+Alt+Backspace: kilépés.
- **Kijelző:** a `wlr-output-management` protokollt valósítja meg, így a `wlr-randr` (a Beállítások kijelző-oldala és a készenlét) ugyanúgy működik, mint cage alatt. A HDMI ki-be dugását követi.
- **Vezérlés:** `$XDG_RUNTIME_DIR/smartfox-wm.sock`, soronként egy parancs: `focus launcher`, `focus <app>`, `register <pgid> <app>`, `status`.
- **Fejlesztés:** Linux asztalon ablakban fut: `sf-compositor --winit -- <parancs>`. WSL alatt a Slint X11-et választ, ezért ott a launcher nem a beágyazott kompozitorhoz csatlakozik.
### Távoli képernyő (VNC)
Fejlesztéshez: a TV képe VNC-n látszik, és billentyűzetről vezérelhető (nyilak, Enter, Esc, mint a távirányítóval).
```sh
echo 'SMARTFOX_REMOTE_VIEW=1' | sudo tee /var/lib/smartfox/session.env # a TV-n, aztán a felület újraindítása
ssh -N -L 5900:127.0.0.1:5900 <tv> # a gépeden
```
A VNC-kliensben (pl. TigerVNC) a cím: `localhost:5900`.
- **Biztonság:**
- A `wayvnc` csak a TV-n belülről érhető el (`127.0.0.1`), kívülről SSH-alagúton át.
- A kompozitor a képernyőmásolást (`wlr-screencopy`) és a virtuális billentyűzetet csak akkor kínálja, ha a kapcsoló be van kapcsolva. Akkor is csak a `wayvnc`-nek és a `grim`-nek, ha a felhasználójuk ugyanaz, és nem sandboxban futnak. A store appok nem látják a képernyőt, és nem gépelhetnek.
- **Kijelző nélkül:** egy HDMI-kimenet kényszeríthető a kernel parancssorában: `video=HDMI-A-1:1920x1080@60D`. Raspberry Pi-n ez a `/boot/firmware/cmdline.txt`.
- **Raspberry Pi 4:** 1080p-n kb. 5 FPS.
- A `wayvnc` 0.10 H.264-kódolója a Pi 4-en összeomlik (`v4l2m2m: Failed to enqueue buffer`; labwc alatt is), ezért alapból ki van kapcsolva.
- Ahol működik, bekapcsolható: `SMARTFOX_VNC_ARGS=--gpu` a `session.env`-ben.
## Licenc ## Licenc
- A Slint a GPL-3.0 alatt van használva (beágyazott eszközre a royalty-free licenc nem vonatkozik). - A Slint a GPL-3.0 alatt van használva (beágyazott eszközre a royalty-free licenc nem vonatkozik).
- Az Inter betűtípus OFL licencű (`crates/sf-launcher/ui/fonts/OFL-LICENSE.txt`). - Az Inter betűtípus OFL licencű (`crates/sf-launcher/ui/fonts/OFL-LICENSE.txt`).

View File

@@ -1,11 +1,20 @@
id = "airplay" id = "airplay"
name = "AirPlay" name = "AirPlay"
version = "1.0.0" version = "1.0.1"
kind = "exec" kind = "exec"
category = "Képernyőtükrözés" category = "Képernyőtükrözés"
description = "iPhone, iPad vagy Mac képernyőjének tükrözése. A Vezérlőközpontban válaszd a SmartFoxot." description = "iPhone, iPad vagy Mac képernyője a TV-n. A Vezérlőközpontban koppints a Képernyőtükrözésre, és válaszd a Fennec OS-t."
exec = ["uxplay", "-n", "SmartFox", "-nh", "-vs", "waylandsink"] # Always running (sf-core keeps it up); its window appears when an Apple
# device starts mirroring and closes when it stops.
service = true
exec = ["uxplay", "-n", "Fennec OS", "-nh", "-vs", "waylandsink", "-fs"]
icon = "airplay" icon = "airplay"
accent = "#4DA3FF" accent = "#4DA3FF"
palette = ["#7cc4ff", "#1d4fa8", "#050c1c"] palette = ["#7cc4ff", "#1d4fa8", "#050c1c"]
order = 30 order = 30
# A system receiver: needs the host D-Bus (Avahi, iwd) and the network
# stack as it is, so it runs outside the app sandbox. Only official apps
# may do this; store apps always run sandboxed.
[sandbox]
enabled = false

View File

@@ -1,11 +1,20 @@
id = "miracast" id = "miracast"
name = "Miracast" name = "Miracast"
version = "1.0.0" version = "1.0.1"
kind = "exec" kind = "exec"
category = "Képernyőtükrözés · Kísérleti" category = "Képernyőtükrözés · Kísérleti"
description = "Android telefon képernyőjének tükrözése Wi-Fi Directen keresztül." description = "Android telefon képernyője a TV-n. A telefonon a Képernyő tükrözése vagy Smart View menüben válaszd a Fennec OS-t."
exec = ["sf-miracast-sink"] # Always running: sf-miracast registers the TV as a Wi-Fi Display sink with
# iwd and plays the stream with GStreamer when a phone connects.
service = true
exec = ["sf-shell-exec", "sf-miracast", "--name", "Fennec OS"]
icon = "miracast" icon = "miracast"
accent = "#2FE0C0" accent = "#2FE0C0"
palette = ["#6ff5dc", "#0f7a6c", "#03130f"] palette = ["#6ff5dc", "#0f7a6c", "#03130f"]
order = 40 order = 40
# A system receiver: needs the host D-Bus (Avahi, iwd) and the network
# stack as it is, so it runs outside the app sandbox. Only official apps
# may do this; store apps always run sandboxed.
[sandbox]
enabled = false

View File

@@ -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 SmartFox/0.1"

10
apps/store/app.toml Normal file
View File

@@ -0,0 +1,10 @@
id = "store"
name = "App Store"
version = "1.0.0"
kind = "builtin"
category = "Rendszer"
description = "Nyílt forrású appok GitHubról, Giteáról és GitLabról. Mindegyik a saját repójából települ, és a saját sandboxában fut."
icon = "store"
accent = "#5FA8FF"
palette = ["#8cc4ff", "#24508f", "#050a14"]
order = 80

View File

@@ -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 (SmartFox, SF1, Wired)"
[dial]
name = "YouTube"

View File

@@ -0,0 +1,28 @@
[package]
name = "sf-compositor"
description = "Fennec OS kiosk Wayland compositor (Smithay): launcher + one full-screen app, animated switching, volume OSD"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
sf-ipc.workspace = true
anyhow.workspace = true
tracing = "0.1"
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
[target.'cfg(target_os = "linux")'.dependencies]
# Volume OSD text (osd.rs): pure Rust, the font comes from the system.
ab_glyph = "0.2"
smithay = { version = "0.7", default-features = false, features = [
"backend_drm",
"backend_gbm",
"backend_egl",
"backend_libinput",
"backend_udev",
"backend_session_libseat",
"backend_winit",
"renderer_gl",
"wayland_frontend",
"desktop",
] }

View File

@@ -0,0 +1,72 @@
//! Control socket for sf-core. One command per line, one reply line:
//! focus launcher | focus <app-id> -> ok
//! register <pgid> <app-id> -> ok (windows of that process group belong to the app)
//! status -> ok visible=<app|launcher|none> target=<...>
use std::io::{BufRead, BufReader, Write};
use std::os::unix::net::UnixListener;
use std::time::Duration;
use anyhow::Result;
use smithay::reexports::calloop::generic::Generic;
use smithay::reexports::calloop::{Interest, LoopHandle, Mode, PostAction};
use crate::state::{App, Target};
pub fn listen(handle: &LoopHandle<'static, App>) -> Result<()> {
let path = sf_ipc::paths::wm_socket();
let _ = std::fs::remove_file(&path);
let listener = UnixListener::bind(&path)?;
listener.set_nonblocking(true)?;
tracing::info!("control socket {}", path.display());
handle
.insert_source(Generic::new(listener, Interest::READ, Mode::Level), |_, listener, app: &mut App| {
while let Ok((stream, _)) = listener.accept() {
let _ = stream.set_nonblocking(false);
let _ = stream.set_read_timeout(Some(Duration::from_millis(300)));
let Ok(mut writer) = stream.try_clone() else { continue };
let mut line = String::new();
if BufReader::new(stream).read_line(&mut line).is_err() {
continue;
}
let reply = handle_command(app, line.trim());
let _ = writeln!(writer, "{reply}");
}
Ok(PostAction::Continue)
})
.map_err(|e| anyhow::anyhow!("control source: {e}"))?;
Ok(())
}
fn handle_command(app: &mut App, cmd: &str) -> String {
let st = &mut app.state;
match cmd.split_once(' ') {
Some(("focus", "launcher")) => {
st.set_target(Target::Launcher);
"ok".into()
}
Some(("focus", id)) if !id.trim().is_empty() => {
st.set_target(Target::App(id.trim().to_string()));
"ok".into()
}
Some(("register", rest)) => match rest.trim().split_once(' ') {
Some((pgid, id)) if pgid.parse::<i32>().is_ok() && !id.trim().is_empty() => {
st.register(pgid.parse().unwrap(), id.trim().to_string());
"ok".into()
}
_ => "err usage: register <pgid> <app-id>".into(),
},
_ if cmd == "status" => {
let visible = match &st.visible {
Some(w) => st.app_of_window(w).unwrap_or_else(|| "launcher".into()),
None => "none".into(),
};
let target = match &st.target {
Target::Launcher => "launcher".to_string(),
Target::App(id) => id.clone(),
};
format!("ok visible={visible} target={target} windows={} screen={}", st.wins.len(), if st.screen_on { "on" } else { "off" })
}
_ => format!("err unknown command {cmd:?}"),
}
}

View File

@@ -0,0 +1,116 @@
//! sf-compositor: the Fennec OS kiosk Wayland compositor (Smithay).
//!
//! - Every window is full screen. One is visible: the launcher or the app
//! sf-core put in front (`focus <app-id>` on the control socket). Other
//! app windows stay mapped but hidden, so a frozen app comes back at once.
//! - Switching animates: an app zooms and fades in over the launcher, and
//! back out on Home.
//! - Volume keys change the PipeWire volume and show an OSD bar; the Home key
//! (if it reaches us as a key) is sent to the launcher.
//! - wlr-output-management, so `wlr-randr` can list and set display modes
//! and turn the screen off (the launcher's display settings and standby).
//!
//! Usage: `sf-compositor [--winit] -- <startup command>`; exits when the
//! startup command exits (like cage).
#[cfg(target_os = "linux")]
mod control;
#[cfg(target_os = "linux")]
mod osd;
#[cfg(target_os = "linux")]
mod output_mgmt;
#[cfg(target_os = "linux")]
mod screencopy;
#[cfg(target_os = "linux")]
mod state;
#[cfg(target_os = "linux")]
mod udev;
#[cfg(target_os = "linux")]
mod winit;
fn main() -> anyhow::Result<()> {
let filter = tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info,smithay=warn"));
tracing_subscriber::fmt().with_env_filter(filter).init();
#[cfg(target_os = "linux")]
{
linux_main()
}
#[cfg(not(target_os = "linux"))]
{
anyhow::bail!("sf-compositor needs Linux (DRM/KMS or a Wayland/X11 session for --winit)")
}
}
#[cfg(target_os = "linux")]
fn linux_main() -> anyhow::Result<()> {
use std::time::Duration;
use anyhow::Context;
use smithay::reexports::calloop::EventLoop;
use smithay::reexports::calloop::timer::{TimeoutAction, Timer};
use smithay::reexports::wayland_server::Display;
let mut winit = std::env::var_os("WAYLAND_DISPLAY").is_some() || std::env::var_os("DISPLAY").is_some();
let mut command: Vec<String> = vec![];
let mut args = std::env::args().skip(1);
while let Some(a) = args.next() {
match a.as_str() {
"--winit" => winit = true,
"--drm" => winit = false,
"--" => {
command = args.by_ref().collect();
break;
}
other => command.push(other.to_string()),
}
}
let mut event_loop: EventLoop<state::App> = EventLoop::try_new()?;
let display: Display<state::State> = Display::new()?;
let mut st = state::State::new(&mut event_loop, display)?;
let backend = if winit {
tracing::info!("backend: winit (nested window)");
winit::init(&mut event_loop, &mut st)?
} else {
tracing::info!("backend: DRM/KMS");
udev::init(&mut event_loop, &mut st)?
};
control::listen(&event_loop.handle()).context("control socket")?;
// SAFETY-free env setup: done before any thread is spawned by us.
unsafe {
std::env::set_var("WAYLAND_DISPLAY", &st.socket_name);
std::env::set_var("SMARTFOX_WM_SOCKET", sf_ipc::paths::wm_socket());
}
tracing::info!("WAYLAND_DISPLAY={}", st.socket_name.to_string_lossy());
let mut app = state::App { state: st, backend };
if let Some((prog, rest)) = command.split_first() {
let mut child = std::process::Command::new(prog)
.args(rest)
.spawn()
.with_context(|| format!("starting {prog}"))?;
tracing::info!("started {prog} (pid {})", child.id());
event_loop
.handle()
.insert_source(Timer::from_duration(Duration::from_millis(500)), move |_, _, app: &mut state::App| {
match child.try_wait() {
Ok(Some(status)) => {
tracing::info!("startup command exited ({status}), quitting");
app.state.loop_signal.stop();
TimeoutAction::Drop
}
_ => TimeoutAction::ToDuration(Duration::from_millis(500)),
}
})
.map_err(|e| anyhow::anyhow!("timer: {e}"))?;
}
event_loop.run(Some(Duration::from_millis(16)), &mut app, |app| {
app.after_dispatch();
})?;
let _ = std::fs::remove_file(sf_ipc::paths::wm_socket());
Ok(())
}

View File

@@ -0,0 +1,234 @@
//! The volume OSD: a dark pill at the top of the screen with a speaker
//! icon, a level bar and the level as a number ("Némítva" when muted), in
//! the style of the launcher's status pill.
//!
//! Drawn on the CPU into a small image (anti-aliased shapes, text from the
//! system's Noto Sans), only when the level, the mute state or the output
//! size changes; the compositor shows it as one textured element.
use ab_glyph::{Font, FontVec, PxScale, ScaleFont};
use smithay::backend::allocator::Fourcc;
use smithay::backend::renderer::element::memory::MemoryRenderBuffer;
use smithay::utils::Transform;
/// Size at 1080p (scaled with the output height).
const W: f32 = 460.0;
const H: f32 = 76.0;
const TOP: f32 = 48.0;
const PAD: f32 = 30.0;
const ICON: f32 = 34.0;
const TEXT_W: f32 = 112.0;
const TEXT_PX: f32 = 28.0;
const FONTS: &[&str] = &[
"/usr/share/fonts/truetype/noto/NotoSans-SemiBold.ttf",
"/usr/share/fonts/truetype/noto/NotoSans-Bold.ttf",
"/usr/share/fonts/truetype/noto/NotoSans-Regular.ttf",
"/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf",
];
#[derive(Clone, Copy, PartialEq)]
struct Key {
percent: u32,
muted: bool,
out: (i32, i32),
}
#[derive(Default)]
pub struct VolumeOsd {
font: Option<FontVec>,
font_tried: bool,
cached: Option<(Key, MemoryRenderBuffer, (i32, i32))>,
}
impl VolumeOsd {
/// The OSD image for this level and output size, and where it goes
/// (top-left corner, physical px).
pub fn image(&mut self, level: f32, muted: bool, out: (i32, i32)) -> (&MemoryRenderBuffer, (i32, i32)) {
let key = Key { percent: (level.clamp(0.0, 1.0) * 100.0).round() as u32, muted, out };
if self.cached.as_ref().is_none_or(|(k, _, _)| *k != key) {
if !self.font_tried {
self.font_tried = true;
self.font = FONTS.iter().find_map(|p| std::fs::read(p).ok().and_then(|d| FontVec::try_from_vec(d).ok()));
if self.font.is_none() {
tracing::warn!("volume OSD: no font found, showing the bar only");
}
}
let k = (out.1 as f32 / 1080.0).max(0.5);
let (w, h) = ((W * k).round() as usize, (H * k).round() as usize);
let px = draw(w, h, k, key.percent, muted, self.font.as_ref());
let buf = MemoryRenderBuffer::from_slice(&px, Fourcc::Argb8888, (w as i32, h as i32), 1, Transform::Normal, None);
let at = ((out.0 - w as i32) / 2, (TOP * k).round() as i32);
self.cached = Some((key, buf, at));
}
let (_, buf, at) = self.cached.as_ref().unwrap();
(buf, *at)
}
}
/// Premultiplied RGBA, f32.
struct Canvas {
w: usize,
h: usize,
px: Vec<[f32; 4]>,
}
impl Canvas {
fn over(&mut self, x: usize, y: usize, rgb: [f32; 3], a: f32) {
if x >= self.w || y >= self.h || a <= 0.0 {
return;
}
let d = &mut self.px[y * self.w + x];
let a = a.min(1.0);
for i in 0..3 {
d[i] = rgb[i] * a + d[i] * (1.0 - a);
}
d[3] = a + d[3] * (1.0 - a);
}
/// A shape given by its signed distance (px, negative inside), drawn
/// with a one-pixel anti-aliased edge, within the box x0..x1, y0..y1.
fn shape(&mut self, (x0, y0, x1, y1): (f32, f32, f32, f32), rgb: [f32; 3], a: f32, sd: impl Fn(f32, f32) -> f32) {
let (xa, ya) = (x0.floor().max(0.0) as usize, y0.floor().max(0.0) as usize);
let (xb, yb) = ((x1.ceil() as usize).min(self.w), (y1.ceil() as usize).min(self.h));
for y in ya..yb {
for x in xa..xb {
let cov = (0.5 - sd(x as f32 + 0.5, y as f32 + 0.5)).clamp(0.0, 1.0);
self.over(x, y, rgb, a * cov);
}
}
}
/// BGRA bytes, premultiplied (DRM ARGB8888, little endian).
fn bytes(&self) -> Vec<u8> {
let mut out = Vec::with_capacity(self.px.len() * 4);
for p in &self.px {
let c = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;
out.extend_from_slice(&[c(p[2]), c(p[1]), c(p[0]), c(p[3])]);
}
out
}
}
fn round_rect(px: f32, py: f32, (x, y, w, h): (f32, f32, f32, f32), r: f32) -> f32 {
let (hw, hh) = (w * 0.5, h * 0.5);
let (qx, qy) = ((px - x - hw).abs() - hw + r, (py - y - hh).abs() - hh + r);
qx.max(qy).min(0.0) + (qx.max(0.0).hypot(qy.max(0.0))) - r
}
/// Distance to the segment a-b, minus half the stroke width.
fn capsule(px: f32, py: f32, (ax, ay): (f32, f32), (bx, by): (f32, f32), half: f32) -> f32 {
let (pax, pay, bax, bay) = (px - ax, py - ay, bx - ax, by - ay);
let t = ((pax * bax + pay * bay) / (bax * bax + bay * bay)).clamp(0.0, 1.0);
(pax - bax * t).hypot(pay - bay * t) - half
}
const WHITE: [f32; 3] = [1.0, 1.0, 1.0];
fn draw(w: usize, h: usize, k: f32, percent: u32, muted: bool, font: Option<&FontVec>) -> Vec<u8> {
let mut c = Canvas { w, h, px: vec![[0.0; 4]; w * h] };
let (wf, hf) = (w as f32, h as f32);
let all = (0.0, 0.0, wf, hf);
let pill = (0.5, 0.5, wf - 1.0, hf - 1.0);
let r = hf * 0.5 - 0.5;
// Pill: dark, nearly opaque, with a faint light rim.
c.shape(all, [0.09, 0.09, 0.11], 0.92, |x, y| round_rect(x, y, pill, r));
c.shape(all, WHITE, 0.14, |x, y| {
let d = round_rect(x, y, pill, r);
(d + 0.75 * k).abs() - 0.75 * k
});
// Speaker: a small box and a cone, then sound waves (or a cross when muted).
let s = ICON * k;
let (ix, iy) = (PAD * k, (hf - s) * 0.5);
let cy = iy + s * 0.5;
let ink = if muted { 0.55 } else { 1.0 };
c.shape((ix, iy, ix + s * 0.3, iy + s), WHITE, ink, |x, y| round_rect(x, y, (ix, cy - s * 0.17, s * 0.24, s * 0.34), 1.5 * k));
c.shape((ix, iy, ix + s * 0.62, iy + s), WHITE, ink, |x, y| {
// Cone: from the box (x = 0.20 s, half height 0.17 s) to x = 0.56 s (half height 0.42 s).
let (x0, x1, h0, h1) = (ix + s * 0.20, ix + s * 0.56, s * 0.17, s * 0.42);
let t = ((x - x0) / (x1 - x0)).clamp(0.0, 1.0);
let half = h0 + (h1 - h0) * t;
let dy = (y - cy).abs() - half;
let dx = (x0 - x).max(x - x1);
// Slanted edge: scale the vertical distance by the edge's slope.
let slope = ((h1 - h0) / (x1 - x0)).hypot(1.0);
dx.max(dy / slope)
});
let ax = ix + s * 0.56;
if muted {
let (x0, x1, half) = (ax + s * 0.14, ax + s * 0.46, s * 0.16);
let st = 1.3 * k;
c.shape((ax, iy, ix + s * 1.2, iy + s), WHITE, 0.85, |x, y| {
capsule(x, y, (x0, cy - half), (x1, cy + half), st).min(capsule(x, y, (x0, cy + half), (x1, cy - half), st))
});
} else {
let waves = if percent == 0 { 0 } else if percent < 34 { 1 } else if percent < 67 { 2 } else { 3 };
for i in 0..3 {
let rad = s * (0.18 + 0.17 * i as f32);
let a = if i < waves { 1.0 } else { 0.25 };
let st = 1.4 * k;
c.shape((ax, iy - 2.0, ix + s * 1.3, iy + s + 2.0), WHITE, a, |x, y| {
let (dx, dy) = (x - (ax - s * 0.06), y - cy);
let ring = (dx.hypot(dy) - rad).abs() - st;
// Only the right-hand 90 degrees of the circle.
let cone = dy.abs() - dx * 0.9;
ring.max(cone)
});
}
}
// Level bar.
let bx0 = (PAD + ICON + 24.0) * k;
let bx1 = wf - (PAD + TEXT_W + 16.0) * k;
let bh = 8.0 * k;
let bar = (bx0, (hf - bh) * 0.5, bx1 - bx0, bh);
c.shape(all, WHITE, 0.22, |x, y| round_rect(x, y, bar, bh * 0.5));
let level = percent as f32 / 100.0;
if level > 0.0 {
let fill = (bar.0, bar.1, (bar.2 * level).max(bh), bh);
c.shape(all, WHITE, if muted { 0.45 } else { 1.0 }, |x, y| round_rect(x, y, fill, bh * 0.5));
}
// The number, right-aligned.
if let Some(font) = font {
let text = if muted { "Némítva".to_string() } else { percent.to_string() };
let px = if muted { TEXT_PX * 0.86 } else { TEXT_PX } * k;
let sf = font.as_scaled(PxScale::from(px));
let width: f32 = text.chars().map(|ch| sf.h_advance(font.glyph_id(ch))).sum();
let mut x = wf - PAD * k - width;
let baseline = hf * 0.5 + (sf.ascent() + sf.descent()) * 0.5;
for ch in text.chars() {
let id = font.glyph_id(ch);
let glyph = id.with_scale_and_position(px, ab_glyph::point(x, baseline));
if let Some(outline) = font.outline_glyph(glyph) {
let b = outline.px_bounds();
outline.draw(|gx, gy, cov| {
let (px_, py_) = (b.min.x as i32 + gx as i32, b.min.y as i32 + gy as i32);
if px_ >= 0 && py_ >= 0 {
c.over(px_ as usize, py_ as usize, WHITE, cov * if muted { 0.8 } else { 1.0 });
}
});
}
x += sf.h_advance(id);
}
}
c.bytes()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn draws_a_pill() {
let (w, h) = (460, 76);
let px = draw(w, h, 1.0, 45, false, None);
assert_eq!(px.len(), w * h * 4);
// Corners are transparent (rounded), the middle of the pill is not.
assert_eq!(px[3], 0);
let mid = (h / 2 * w + w / 2) * 4;
assert!(px[mid + 3] > 200);
}
}

View File

@@ -0,0 +1,355 @@
//! wlr-output-management (v2), so `wlr-randr` works: it lists the TV's
//! modes, sets one, and turns the output off/on (standby).
//!
//! Changes are not applied here: `apply` queues a `PendingConfig`, and the
//! backend applies it after the dispatch (`App::after_dispatch`).
use std::sync::{Arc, Mutex};
use smithay::reexports::wayland_protocols_wlr::output_management::v1::server::{
zwlr_output_configuration_head_v1::{self, ZwlrOutputConfigurationHeadV1},
zwlr_output_configuration_v1::{self, ZwlrOutputConfigurationV1},
zwlr_output_head_v1::{self, ZwlrOutputHeadV1},
zwlr_output_manager_v1::{self, ZwlrOutputManagerV1},
zwlr_output_mode_v1::{self, ZwlrOutputModeV1},
};
use smithay::reexports::wayland_server::backend::GlobalId;
use smithay::reexports::wayland_server::protocol::wl_output;
use smithay::reexports::wayland_server::{
Client, DataInit, Dispatch, DisplayHandle, GlobalDispatch, New, Resource, WEnum,
};
use crate::state::State;
const VERSION: u32 = 2;
#[derive(Debug, Clone, PartialEq)]
pub struct ModeInfo {
pub width: i32,
pub height: i32,
/// mHz
pub refresh: i32,
pub preferred: bool,
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct HeadInfo {
pub name: String,
pub description: String,
pub make: String,
pub model: String,
pub physical: (i32, i32),
pub modes: Vec<ModeInfo>,
pub current: Option<usize>,
pub enabled: bool,
}
impl HeadInfo {
/// From the current output; the backend keeps the mode list in the
/// output's user data (`OutputModes`).
pub fn from_state(state: &State) -> Option<HeadInfo> {
let output = state.output.as_ref()?;
let props = output.physical_properties();
let modes: Vec<ModeInfo> = output
.user_data()
.get::<OutputModes>()
.map(|m| m.0.lock().unwrap().clone())
.unwrap_or_default();
let cur = output.current_mode();
let current = cur.and_then(|c| {
modes.iter().position(|m| m.width == c.size.w && m.height == c.size.h && (m.refresh - c.refresh).abs() < 500)
});
Some(HeadInfo {
name: output.name(),
description: format!("{} {} ({})", props.make, props.model, output.name()),
make: props.make.clone(),
model: props.model.clone(),
physical: (props.size.w, props.size.h),
modes,
current,
enabled: state.screen_on,
})
}
}
/// Mode list of an output, stored in `Output::user_data()` by the backend.
#[derive(Default)]
pub struct OutputModes(pub Mutex<Vec<ModeInfo>>);
/// What a client asked for in one configuration.
#[derive(Debug, Default, Clone)]
struct Requested {
enabled: Option<bool>,
mode: Option<ModeInfo>,
/// Refresh 0 in a custom mode: any rate.
any_refresh: bool,
}
struct ConfigData {
serial: u32,
req: Requested,
used: bool,
}
pub struct PendingConfig {
config: ZwlrOutputConfigurationV1,
pub enabled: bool,
/// Wanted mode; None keeps the current one.
pub mode: Option<ModeInfo>,
pub any_refresh: bool,
pub test_only: bool,
}
impl PendingConfig {
pub fn succeeded(&self) {
self.config.succeeded();
}
pub fn failed(&self) {
self.config.failed();
}
}
struct ManagerEntry {
manager: ZwlrOutputManagerV1,
head: Option<ZwlrOutputHeadV1>,
modes: Vec<ZwlrOutputModeV1>,
}
pub struct OutputMgmtState {
_global: GlobalId,
managers: Vec<ManagerEntry>,
info: Option<HeadInfo>,
serial: u32,
}
impl OutputMgmtState {
pub fn new(dh: &DisplayHandle) -> Self {
let global = dh.create_global::<State, ZwlrOutputManagerV1, _>(VERSION, ());
OutputMgmtState { _global: global, managers: vec![], info: None, serial: 1 }
}
/// New output state: resend it to every client if it changed.
pub fn update(&mut self, dh: &DisplayHandle, info: Option<HeadInfo>) {
if info == self.info {
return;
}
self.info = info;
self.serial += 1;
for i in 0..self.managers.len() {
self.send_heads(dh, i);
}
}
fn send_heads(&mut self, dh: &DisplayHandle, i: usize) {
let serial = self.serial;
let info = self.info.clone();
let entry = &mut self.managers[i];
// Simplest correct way to change heads and modes: retire the old
// objects and announce new ones.
for m in entry.modes.drain(..) {
m.finished();
}
if let Some(h) = entry.head.take() {
h.finished();
}
let Ok(client) = dh.get_client(entry.manager.id()) else { return };
if let Some(info) = info {
let version = entry.manager.version();
let Ok(head) = client.create_resource::<ZwlrOutputHeadV1, _, State>(dh, version, ()) else { return };
entry.manager.head(&head);
head.name(info.name.clone());
head.description(info.description.clone());
if info.physical.0 > 0 {
head.physical_size(info.physical.0, info.physical.1);
}
for m in &info.modes {
let Ok(mode) = client.create_resource::<ZwlrOutputModeV1, _, State>(dh, version, m.clone()) else {
continue;
};
head.mode(&mode);
mode.size(m.width, m.height);
mode.refresh(m.refresh);
if m.preferred {
mode.preferred();
}
entry.modes.push(mode);
}
head.enabled(i32::from(info.enabled));
if info.enabled {
if let Some(cur) = info.current.and_then(|c| entry.modes.get(c)) {
head.current_mode(cur);
}
head.position(0, 0);
head.transform(wl_output::Transform::Normal);
head.scale(1.0);
}
if version >= 2 {
head.make(info.make.clone());
head.model(info.model.clone());
}
entry.head = Some(head);
}
entry.manager.done(serial);
}
}
impl GlobalDispatch<ZwlrOutputManagerV1, ()> for State {
fn bind(
state: &mut State,
dh: &DisplayHandle,
_client: &Client,
resource: New<ZwlrOutputManagerV1>,
_global_data: &(),
data_init: &mut DataInit<'_, State>,
) {
let manager = data_init.init(resource, ());
state.output_mgmt.managers.push(ManagerEntry { manager, head: None, modes: vec![] });
let i = state.output_mgmt.managers.len() - 1;
state.output_mgmt.send_heads(dh, i);
}
}
impl Dispatch<ZwlrOutputManagerV1, ()> for State {
fn request(
state: &mut State,
_client: &Client,
resource: &ZwlrOutputManagerV1,
request: zwlr_output_manager_v1::Request,
_data: &(),
_dh: &DisplayHandle,
data_init: &mut DataInit<'_, State>,
) {
match request {
zwlr_output_manager_v1::Request::CreateConfiguration { id, serial } => {
data_init.init(id, Arc::new(Mutex::new(ConfigData { serial, req: Requested::default(), used: false })));
}
zwlr_output_manager_v1::Request::Stop => {
resource.finished();
state.output_mgmt.managers.retain(|m| &m.manager != resource);
}
_ => {}
}
}
fn destroyed(state: &mut State, _client: smithay::reexports::wayland_server::backend::ClientId, resource: &ZwlrOutputManagerV1, _data: &()) {
state.output_mgmt.managers.retain(|m| &m.manager != resource);
}
}
impl Dispatch<ZwlrOutputHeadV1, ()> for State {
fn request(
_state: &mut State,
_client: &Client,
_resource: &ZwlrOutputHeadV1,
_request: zwlr_output_head_v1::Request,
_data: &(),
_dh: &DisplayHandle,
_data_init: &mut DataInit<'_, State>,
) {
}
}
impl Dispatch<ZwlrOutputModeV1, ModeInfo> for State {
fn request(
_state: &mut State,
_client: &Client,
_resource: &ZwlrOutputModeV1,
_request: zwlr_output_mode_v1::Request,
_data: &ModeInfo,
_dh: &DisplayHandle,
_data_init: &mut DataInit<'_, State>,
) {
}
}
type ConfigRef = Arc<Mutex<ConfigData>>;
impl Dispatch<ZwlrOutputConfigurationV1, ConfigRef> for State {
fn request(
state: &mut State,
_client: &Client,
resource: &ZwlrOutputConfigurationV1,
request: zwlr_output_configuration_v1::Request,
data: &ConfigRef,
_dh: &DisplayHandle,
data_init: &mut DataInit<'_, State>,
) {
use zwlr_output_configuration_v1::Request;
match request {
Request::EnableHead { id, head: _ } => {
data.lock().unwrap().req.enabled = Some(true);
data_init.init(id, data.clone());
}
Request::DisableHead { head: _ } => {
data.lock().unwrap().req.enabled = Some(false);
}
Request::Apply | Request::Test => {
let test_only = matches!(request, Request::Test);
let mut d = data.lock().unwrap();
if d.used {
resource.post_error(zwlr_output_configuration_v1::Error::AlreadyUsed, "already used");
return;
}
d.used = true;
if d.serial != state.output_mgmt.serial {
resource.cancelled();
return;
}
state.pending_configs.push(PendingConfig {
config: resource.clone(),
enabled: d.req.enabled.unwrap_or(true),
mode: d.req.mode.clone(),
any_refresh: d.req.any_refresh,
test_only,
});
}
Request::Destroy => {}
_ => {}
}
}
}
impl Dispatch<ZwlrOutputConfigurationHeadV1, ConfigRef> for State {
fn request(
_state: &mut State,
_client: &Client,
_resource: &ZwlrOutputConfigurationHeadV1,
request: zwlr_output_configuration_head_v1::Request,
data: &ConfigRef,
_dh: &DisplayHandle,
_data_init: &mut DataInit<'_, State>,
) {
use zwlr_output_configuration_head_v1::Request;
let mut d = data.lock().unwrap();
match request {
Request::SetMode { mode } => {
if let Some(m) = mode.data::<ModeInfo>() {
d.req.mode = Some(m.clone());
d.req.any_refresh = false;
}
}
Request::SetCustomMode { width, height, refresh } => {
d.req.mode = Some(ModeInfo { width, height, refresh, preferred: false });
d.req.any_refresh = refresh == 0;
}
// One output at 0,0, normal, scale 1: accept and ignore.
Request::SetPosition { .. } | Request::SetScale { .. } => {}
Request::SetTransform { transform } => {
if !matches!(transform, WEnum::Value(wl_output::Transform::Normal)) {
tracing::info!("output transform not supported, ignored");
}
}
_ => {}
}
}
}
/// Picks the mode a client asked for from the available ones.
pub fn match_mode<'a>(modes: &'a [ModeInfo], want: &ModeInfo, any_refresh: bool) -> Option<(usize, &'a ModeInfo)> {
let same_size = modes.iter().enumerate().filter(|(_, m)| m.width == want.width && m.height == want.height);
if any_refresh {
same_size.max_by_key(|(_, m)| m.refresh)
} else {
same_size.min_by_key(|(_, m)| (m.refresh - want.refresh).abs()).filter(|(_, m)| (m.refresh - want.refresh).abs() < 1000)
}
}

View File

@@ -0,0 +1,323 @@
//! Remote viewing for development: wlr-screencopy (v3) and the virtual
//! keyboard, so `wayvnc` can show the TV and send keys (README, "Távoli
//! képernyő (VNC)").
//!
//! Both are off unless the session sets `SMARTFOX_REMOTE_VIEW=1`, and even
//! then only trusted programs get them (`trusted`): sandboxed store apps
//! must not read the screen or type into other apps.
//!
//! A copy request waits for the next frame the backend renders and gets the
//! same render elements, drawn into the client's buffer (dmabuf: on the GPU,
//! which wayvnc's H.264 encoder needs; shm: read back).
use std::os::unix::fs::MetadataExt;
use std::sync::Mutex;
use std::time::Duration;
use anyhow::{Context, Result, anyhow, bail};
use smithay::backend::allocator::{Buffer, Fourcc};
use smithay::backend::allocator::dmabuf::Dmabuf;
use smithay::backend::renderer::gles::{GlesRenderbuffer, GlesRenderer};
use smithay::backend::renderer::utils::draw_render_elements;
use smithay::backend::renderer::{Bind, ExportMem, Frame, Offscreen, Renderer, TextureMapping};
use smithay::reexports::wayland_protocols_wlr::screencopy::v1::server::{
zwlr_screencopy_frame_v1::{self, ZwlrScreencopyFrameV1},
zwlr_screencopy_manager_v1::{self, ZwlrScreencopyManagerV1},
};
use smithay::reexports::wayland_server::backend::GlobalId;
use smithay::reexports::wayland_server::protocol::{wl_buffer::WlBuffer, wl_shm};
use smithay::reexports::wayland_server::{Client, DataInit, Dispatch, DisplayHandle, GlobalDispatch, New, Resource};
use smithay::utils::{Physical, Rectangle, Size, Transform};
use smithay::wayland::dmabuf::get_dmabuf;
use smithay::wayland::shm::with_buffer_contents_mut;
use crate::state::{SfElement, State};
const VERSION: u32 = 3;
/// Programs that may capture the screen and type: the VNC server, and grim
/// for screenshots.
const TRUSTED: &[&str] = &["wayvnc", "grim"];
/// Whether remote viewing is switched on for this session.
pub fn enabled() -> bool {
std::env::var("SMARTFOX_REMOTE_VIEW").is_ok_and(|v| v == "1")
}
/// Whether a newly connected client may capture and type: one of
/// `TRUSTED`, running as our user, and outside any sandbox (bubblewrap gives
/// every store app its own mount namespace). Decided from the socket before
/// the client is inserted, and kept in its `ClientState`: asking the display
/// for credentials from inside a dispatch (can_view, filters) deadlocks.
pub fn trusted_peer(stream: &std::os::unix::net::UnixStream) -> bool {
use smithay::reexports::rustix;
let Ok(cred) = rustix::net::sockopt::socket_peercred(stream) else { return false };
let pid = rustix::process::Pid::as_raw(Some(cred.pid));
let proc = format!("/proc/{pid}");
let same_user = std::fs::metadata("/proc/self").ok().map(|m| m.uid()) == Some(cred.uid.as_raw());
let ns = |p: &str| std::fs::read_link(format!("{p}/ns/mnt")).ok();
let same_ns = ns("/proc/self").is_some() && ns("/proc/self") == ns(&proc);
let exe = std::fs::read_link(format!("{proc}/exe")).ok();
let name = exe.as_ref().and_then(|e| e.file_name()).and_then(|n| n.to_str()).unwrap_or("").to_string();
let ok = same_user && same_ns && TRUSTED.contains(&name.as_str());
if ok {
tracing::info!("remote view: pid {pid} ({name}) may capture and type");
}
ok
}
/// What `trusted_peer` said when the client connected.
pub fn trusted(client: &Client) -> bool {
client.get_data::<crate::state::ClientState>().is_some_and(|d| d.remote_view)
}
pub struct ScreencopyState {
_global: GlobalId,
}
impl ScreencopyState {
pub fn new(dh: &DisplayHandle) -> Self {
let global = dh.create_global::<State, ZwlrScreencopyManagerV1, _>(VERSION, ());
ScreencopyState { _global: global }
}
}
/// A copy waiting for the next rendered frame.
pub struct Pending {
frame: ZwlrScreencopyFrameV1,
buffer: WlBuffer,
with_damage: bool,
}
/// What a frame object captures.
pub struct FrameData {
size: Size<i32, Physical>,
/// The output isn't there (or a region was asked for): every copy fails.
unusable: bool,
used: Mutex<bool>,
}
impl GlobalDispatch<ZwlrScreencopyManagerV1, ()> for State {
fn bind(_: &mut State, _: &DisplayHandle, _: &Client, resource: New<ZwlrScreencopyManagerV1>, _: &(), init: &mut DataInit<'_, State>) {
init.init(resource, ());
}
fn can_view(client: Client, _: &()) -> bool {
trusted(&client)
}
}
impl Dispatch<ZwlrScreencopyManagerV1, ()> for State {
fn request(
state: &mut State,
_: &Client,
_: &ZwlrScreencopyManagerV1,
request: zwlr_screencopy_manager_v1::Request,
_: &(),
_: &DisplayHandle,
init: &mut DataInit<'_, State>,
) {
let (frame, region) = match request {
zwlr_screencopy_manager_v1::Request::CaptureOutput { frame, .. } => (frame, false),
// Regions aren't supported (wayvnc and grim take the whole output).
zwlr_screencopy_manager_v1::Request::CaptureOutputRegion { frame, .. } => (frame, true),
zwlr_screencopy_manager_v1::Request::Destroy => return,
_ => return,
};
let size = state.output_size();
let unusable = region || state.output.is_none();
let frame = init.init(frame, FrameData { size, unusable, used: Mutex::new(false) });
if unusable {
frame.failed();
return;
}
let (w, h) = (size.w as u32, size.h as u32);
frame.buffer(wl_shm::Format::Xrgb8888, w, h, w * 4);
if frame.version() >= 3 {
frame.linux_dmabuf(Fourcc::Xrgb8888 as u32, w, h);
frame.buffer_done();
}
}
}
impl Dispatch<ZwlrScreencopyFrameV1, FrameData> for State {
fn request(
state: &mut State,
_: &Client,
frame: &ZwlrScreencopyFrameV1,
request: zwlr_screencopy_frame_v1::Request,
data: &FrameData,
_: &DisplayHandle,
_: &mut DataInit<'_, State>,
) {
let (buffer, with_damage) = match request {
zwlr_screencopy_frame_v1::Request::Copy { buffer } => (buffer, false),
zwlr_screencopy_frame_v1::Request::CopyWithDamage { buffer } => (buffer, true),
_ => return,
};
{
let mut used = data.used.lock().unwrap();
if *used {
frame.post_error(zwlr_screencopy_frame_v1::Error::AlreadyUsed, "frame already used");
return;
}
*used = true;
}
if data.unusable || data.size != state.output_size() {
frame.failed();
return;
}
state.screencopies.push(Pending { frame: frame.clone(), buffer, with_damage });
}
}
/// Answers the copies waiting for a frame, with the elements the backend
/// just rendered. `damaged`: the frame changed (copy-with-damage waits for
/// that; a plain copy is answered right away).
pub fn fulfil(state: &mut State, renderer: &mut GlesRenderer, elements: &[SfElement], damaged: bool) {
let size = state.output_size();
let pending = std::mem::take(&mut state.screencopies);
let (ready, waiting): (Vec<_>, Vec<_>) = pending.into_iter().partition(|p| damaged || !p.with_damage);
state.screencopies = waiting.into_iter().filter(|p| p.frame.is_alive()).collect();
if ready.is_empty() {
return;
}
let time: Duration = state.clock.now().into();
for p in ready {
if !p.frame.is_alive() {
continue;
}
let result = match get_dmabuf(&p.buffer) {
Ok(dmabuf) => draw_dmabuf(renderer, &mut dmabuf.clone(), size, elements),
Err(_) => draw_shm(renderer, &p.buffer, size, elements),
};
match result {
Ok(()) => {
p.frame.flags(zwlr_screencopy_frame_v1::Flags::empty());
if p.with_damage {
p.frame.damage(0, 0, size.w as u32, size.h as u32);
}
let secs = time.as_secs();
p.frame.ready((secs >> 32) as u32, secs as u32, time.subsec_nanos());
}
Err(e) => {
tracing::warn!("screencopy: {e:#}");
p.frame.failed();
}
}
}
}
fn draw(renderer: &mut GlesRenderer, fb: &mut <GlesRenderer as smithay::backend::renderer::RendererSuper>::Framebuffer<'_>, size: Size<i32, Physical>, elements: &[SfElement]) -> Result<()> {
let all = [Rectangle::from_size(size)];
let mut frame = renderer.render(fb, size, Transform::Normal).map_err(|e| anyhow!("render: {e:?}"))?;
frame.clear([0.0, 0.0, 0.0, 1.0].into(), &all).map_err(|e| anyhow!("clear: {e:?}"))?;
draw_render_elements::<GlesRenderer, _, SfElement>(&mut frame, 1.0, elements, &all).map_err(|e| anyhow!("draw: {e:?}"))?;
let sync = frame.finish().map_err(|e| anyhow!("finish: {e:?}"))?;
renderer.wait(&sync).map_err(|e| anyhow!("wait: {e:?}"))?;
Ok(())
}
/// Straight into the client's dmabuf, on the GPU.
fn draw_dmabuf(renderer: &mut GlesRenderer, dmabuf: &mut Dmabuf, size: Size<i32, Physical>, elements: &[SfElement]) -> Result<()> {
if (dmabuf.width() as i32, dmabuf.height() as i32) != (size.w, size.h) {
bail!("dmabuf is {}x{}, the output {}x{}", dmabuf.width(), dmabuf.height(), size.w, size.h);
}
let mut fb = renderer.bind(dmabuf).map_err(|e| anyhow!("binding the dmabuf: {e:?}"))?;
draw(renderer, &mut fb, size, elements)
}
/// Into an offscreen buffer, read back into the client's shm buffer.
fn draw_shm(renderer: &mut GlesRenderer, buffer: &WlBuffer, size: Size<i32, Physical>, elements: &[SfElement]) -> Result<()> {
let buf_size = Size::from((size.w, size.h));
let mut rb: GlesRenderbuffer = renderer.create_buffer(Fourcc::Abgr8888, buf_size).map_err(|e| anyhow!("offscreen buffer: {e:?}"))?;
let mut fb = renderer.bind(&mut rb).map_err(|e| anyhow!("binding: {e:?}"))?;
draw(renderer, &mut fb, size, elements)?;
let mapping = renderer
.copy_framebuffer(&fb, Rectangle::from_size(buf_size), Fourcc::Xrgb8888)
.map_err(|e| anyhow!("read back: {e:?}"))?;
let flipped = mapping.flipped();
let pixels = renderer.map_texture(&mapping).map_err(|e| anyhow!("map: {e:?}"))?;
let row = size.w as usize * 4;
let rows = size.h as usize;
anyhow::ensure!(pixels.len() >= row * rows, "short read back");
with_buffer_contents_mut(buffer, |ptr, len, data| -> Result<()> {
if !matches!(data.format, wl_shm::Format::Xrgb8888 | wl_shm::Format::Argb8888) || (data.width, data.height) != (size.w, size.h) {
bail!("unexpected shm buffer {}x{} {:?}", data.width, data.height, data.format);
}
let stride = data.stride as usize;
let offset = data.offset as usize;
anyhow::ensure!(stride >= row && offset + stride * (rows - 1) + row <= len, "shm buffer too small");
// SAFETY: bounds checked above; the pool stays mapped during the call.
let dst = unsafe { std::slice::from_raw_parts_mut(ptr.add(offset), len - offset) };
for y in 0..rows {
// GL reads rows bottom-up unless the mapping says it is already flipped.
let src_y = if flipped { y } else { rows - 1 - y };
dst[y * stride..y * stride + row].copy_from_slice(&pixels[src_y * row..src_y * row + row]);
}
Ok(())
})
.context("shm buffer")?
}
// ---- virtual pointer ------------------------------------------------------
// wayvnc won't start input without wlr-virtual-pointer. The TV has no
// pointer, so the device exists and its events are dropped; keys go through
// the virtual keyboard.
use smithay::reexports::wayland_protocols_wlr::virtual_pointer::v1::server::{
zwlr_virtual_pointer_manager_v1::{self, ZwlrVirtualPointerManagerV1},
zwlr_virtual_pointer_v1::{self, ZwlrVirtualPointerV1},
};
pub struct VirtualPointerState {
_global: GlobalId,
}
impl VirtualPointerState {
pub fn new(dh: &DisplayHandle) -> Self {
VirtualPointerState { _global: dh.create_global::<State, ZwlrVirtualPointerManagerV1, _>(2, ()) }
}
}
impl GlobalDispatch<ZwlrVirtualPointerManagerV1, ()> for State {
fn bind(_: &mut State, _: &DisplayHandle, _: &Client, resource: New<ZwlrVirtualPointerManagerV1>, _: &(), init: &mut DataInit<'_, State>) {
init.init(resource, ());
}
fn can_view(client: Client, _: &()) -> bool {
trusted(&client)
}
}
impl Dispatch<ZwlrVirtualPointerManagerV1, ()> for State {
fn request(
_: &mut State,
_: &Client,
_: &ZwlrVirtualPointerManagerV1,
request: zwlr_virtual_pointer_manager_v1::Request,
_: &(),
_: &DisplayHandle,
init: &mut DataInit<'_, State>,
) {
match request {
zwlr_virtual_pointer_manager_v1::Request::CreateVirtualPointer { id, .. }
| zwlr_virtual_pointer_manager_v1::Request::CreateVirtualPointerWithOutput { id, .. } => {
init.init(id, ());
}
_ => {}
}
}
}
impl Dispatch<ZwlrVirtualPointerV1, ()> for State {
fn request(
_: &mut State,
_: &Client,
_: &ZwlrVirtualPointerV1,
_: zwlr_virtual_pointer_v1::Request,
_: &(),
_: &DisplayHandle,
_: &mut DataInit<'_, State>,
) {
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,442 @@
//! DRM/KMS backend for the TV: libseat session, one GPU, the first
//! connected output (HDMI), libinput keyboards. Handles HDMI hotplug, VT
//! switching, mode changes and turning the screen off (wlr-randr).
use std::time::Duration;
use anyhow::{Context, Result, anyhow, bail};
use smithay::backend::allocator::Fourcc;
use smithay::backend::allocator::gbm::{GbmAllocator, GbmBufferFlags, GbmDevice};
use smithay::backend::drm::compositor::FrameFlags;
use smithay::backend::drm::exporter::gbm::GbmFramebufferExporter;
use smithay::backend::drm::output::{DrmOutput, DrmOutputManager, DrmOutputRenderElements};
use smithay::backend::drm::{DrmDevice, DrmDeviceFd, DrmEvent, DrmEventMetadata, DrmEventTime, DrmNode};
use smithay::backend::egl::{EGLContext, EGLDevice, EGLDisplay};
use smithay::backend::libinput::{LibinputInputBackend, LibinputSessionInterface};
use smithay::backend::renderer::gles::GlesRenderer;
use smithay::backend::renderer::{ImportDma, ImportMemWl};
use smithay::backend::session::libseat::LibSeatSession;
use smithay::backend::session::{Event as SessionEvent, Session};
use smithay::backend::udev::{UdevBackend, UdevEvent, all_gpus, primary_gpu};
use smithay::desktop::utils::OutputPresentationFeedback;
use smithay::output::{Mode as WlMode, Output, PhysicalProperties, Subpixel};
use smithay::reexports::calloop::timer::{TimeoutAction, Timer};
use smithay::reexports::calloop::EventLoop;
use smithay::reexports::drm::control::{Device as ControlDevice, ModeTypeFlags, connector, crtc};
use smithay::reexports::input::Libinput;
use smithay::reexports::rustix::fs::OFlags;
use smithay::reexports::wayland_protocols::wp::presentation_time::server::wp_presentation_feedback;
use smithay::reexports::wayland_server::backend::GlobalId;
use smithay::wayland::presentation::Refresh;
use smithay::utils::DeviceFd;
use smithay::wayland::dmabuf::DmabufFeedbackBuilder;
use crate::output_mgmt::{ModeInfo, OutputModes, PendingConfig, match_mode};
use crate::state::{App, Backend, SfElement, State};
type Allocator = GbmAllocator<DrmDeviceFd>;
type Exporter = GbmFramebufferExporter<DrmDeviceFd>;
/// Travels with a queued frame: the clients' presentation feedback requests.
type Feedback = Option<OutputPresentationFeedback>;
const FORMATS: &[Fourcc] = &[Fourcc::Argb8888, Fourcc::Abgr8888, Fourcc::Xrgb8888];
struct Out {
drm_output: DrmOutput<Allocator, Exporter, Feedback, DrmDeviceFd>,
connector: connector::Handle,
crtc: crtc::Handle,
modes: Vec<smithay::reexports::drm::control::Mode>,
output: Output,
global: Option<GlobalId>,
frame_pending: bool,
/// The CRTC is off (DPMS) after wlr-randr --off.
cleared: bool,
}
pub struct UdevData {
/// Keeps the seat session (and device access) alive.
_session: LibSeatSession,
libinput: Libinput,
manager: DrmOutputManager<Allocator, Exporter, Feedback, DrmDeviceFd>,
renderer: GlesRenderer,
out: Option<Out>,
active: bool,
/// A render is queued on a timer (no damage last time).
retry_scheduled: bool,
}
/// The GPU that drives the screen. On a PC that's the primary GPU. On ARM
/// boards the display and the 3D engine are separate DRM devices (Raspberry
/// Pi: vc4 has the HDMI ports, v3d only renders), so a card without display
/// connectors is skipped; mesa renders on v3d through the vc4 device.
fn pick_gpu(seat: &str) -> Result<std::path::PathBuf> {
let primary = primary_gpu(seat)?;
let all = all_gpus(seat).unwrap_or_default();
let candidates: Vec<_> = primary.iter().cloned().chain(all.into_iter().filter(|p| Some(p) != primary.as_ref())).collect();
candidates
.iter()
.find(|p| has_connectors(p))
.or(candidates.first())
.cloned()
.context("no GPU found")
}
/// Whether a DRM card (/dev/dri/cardN) has display connectors, from sysfs
/// (/sys/class/drm/cardN-HDMI-A-1 ...).
fn has_connectors(path: &std::path::Path) -> bool {
let Some(card) = path.file_name().and_then(|n| n.to_str()) else { return false };
let prefix = format!("{card}-");
std::fs::read_dir("/sys/class/drm")
.map(|dir| dir.flatten().any(|e| e.file_name().to_str().is_some_and(|n| n.starts_with(&prefix) && !n.contains("Writeback"))))
.unwrap_or(false)
}
pub fn init(event_loop: &mut EventLoop<'static, App>, state: &mut State) -> Result<Backend> {
let (session, notifier) = LibSeatSession::new().map_err(|e| anyhow!("libseat session: {e}"))?;
state.session = Some(session.clone());
let seat = session.seat();
let path = pick_gpu(&seat)?;
tracing::info!("GPU {}", path.display());
let mut session_for_open = session.clone();
let fd = session_for_open
.open(&path, OFlags::RDWR | OFlags::CLOEXEC | OFlags::NOCTTY | OFlags::NONBLOCK)
.map_err(|e| anyhow!("opening {}: {e}", path.display()))?;
let fd = DrmDeviceFd::new(DeviceFd::from(fd));
let (drm, drm_notifier) = DrmDevice::new(fd.clone(), true).map_err(|e| anyhow!("drm: {e}"))?;
let gbm = GbmDevice::new(fd).context("gbm")?;
let node = DrmNode::from_path(&path).map_err(|e| anyhow!("drm node: {e}"))?;
let egl = unsafe { EGLDisplay::new(gbm.clone()) }.map_err(|e| anyhow!("egl display: {e}"))?;
let render_node = EGLDevice::device_for_display(&egl)
.ok()
.and_then(|d| d.try_get_render_node().ok().flatten())
.unwrap_or(node);
let ctx = EGLContext::new(&egl).map_err(|e| anyhow!("egl context: {e}"))?;
let renderer = unsafe { GlesRenderer::new(ctx) }.map_err(|e| anyhow!("gles: {e}"))?;
state.shm_state.update_formats(renderer.shm_formats());
let dmabuf_formats = renderer.dmabuf_formats();
// Clients render on the GPU's render node (Raspberry Pi: v3d). Not the
// display device: mesa would fall back to software rendering on vc4.
let feedback = DmabufFeedbackBuilder::new(render_node.dev_id(), dmabuf_formats.clone())
.build()
.map_err(|e| anyhow!("dmabuf feedback: {e}"))?;
state.dmabuf_global = Some(state.dmabuf_state.create_global_with_default_feedback::<State>(&state.dh, &feedback));
let render_formats = renderer.egl_context().dmabuf_render_formats().clone();
let allocator = GbmAllocator::new(gbm.clone(), GbmBufferFlags::RENDERING | GbmBufferFlags::SCANOUT);
let exporter = GbmFramebufferExporter::new(gbm.clone(), Some(render_node));
let manager = DrmOutputManager::new(drm, allocator, exporter, Some(gbm), FORMATS.iter().copied(), render_formats);
// Input.
let mut libinput = Libinput::new_with_udev::<LibinputSessionInterface<LibSeatSession>>(session.clone().into());
libinput.udev_assign_seat(&seat).map_err(|_| anyhow!("libinput: assigning seat {seat}"))?;
let handle = event_loop.handle();
handle
.insert_source(LibinputInputBackend::new(libinput.clone()), |event, _, app: &mut App| {
app.state.handle_input(event);
})
.map_err(|e| anyhow!("libinput source: {e}"))?;
// Vblanks.
handle
.insert_source(drm_notifier, |event, metadata, app: &mut App| match event {
DrmEvent::VBlank(_crtc) => {
if let Backend::Udev(u) = &mut app.backend {
u.frame_done(&mut app.state, metadata.take());
}
}
DrmEvent::Error(e) => tracing::error!("drm: {e:?}"),
})
.map_err(|e| anyhow!("drm source: {e}"))?;
// VT switches.
handle
.insert_source(notifier, |event, _, app: &mut App| {
let Backend::Udev(u) = &mut app.backend else { return };
match event {
SessionEvent::PauseSession => {
tracing::info!("session paused");
u.libinput.suspend();
u.manager.pause();
u.active = false;
}
SessionEvent::ActivateSession => {
tracing::info!("session active");
if u.libinput.resume().is_err() {
tracing::error!("libinput resume failed");
}
if let Err(e) = u.manager.activate(false) {
tracing::error!("drm activate: {e}");
}
u.active = true;
if let Some(out) = u.out.as_mut() {
out.frame_pending = false;
out.drm_output.reset_buffers();
}
u.render(&mut app.state);
}
}
})
.map_err(|e| anyhow!("session source: {e}"))?;
// HDMI hotplug: rescan connectors when the GPU reports a change.
let udev = UdevBackend::new(&seat)?;
handle
.insert_source(udev, |event, _, app: &mut App| {
if let UdevEvent::Changed { .. } = event {
if let Backend::Udev(u) = &mut app.backend {
u.scan(&mut app.state);
}
}
})
.map_err(|e| anyhow!("udev source: {e}"))?;
let mut data = UdevData { _session: session, libinput, manager, renderer, out: None, active: true, retry_scheduled: false };
data.scan(state);
if data.out.is_none() {
tracing::warn!("no connected display yet; waiting for hotplug");
}
Ok(Backend::Udev(data))
}
fn mode_info(m: &smithay::reexports::drm::control::Mode) -> ModeInfo {
let wl = WlMode::from(*m);
ModeInfo {
width: wl.size.w,
height: wl.size.h,
refresh: wl.refresh,
preferred: m.mode_type().contains(ModeTypeFlags::PREFERRED),
}
}
impl UdevData {
/// First connected connector and a CRTC for it.
fn find_connector(&self) -> Option<(connector::Info, crtc::Handle)> {
let dev = self.manager.device();
let res = dev.resource_handles().ok()?;
for handle in res.connectors() {
let Ok(info) = dev.get_connector(*handle, false) else { continue };
if info.state() != connector::State::Connected || info.modes().is_empty() {
continue;
}
// Keep the CRTC we already drive for this connector.
if let Some(out) = &self.out {
if out.connector == *handle {
return Some((info, out.crtc));
}
}
for enc in info.encoders() {
let Ok(enc) = dev.get_encoder(*enc) else { continue };
if let Some(crtc) = res.filter_crtcs(enc.possible_crtcs()).into_iter().next() {
return Some((info, crtc));
}
}
}
None
}
fn scan(&mut self, state: &mut State) {
let found = self.find_connector();
let same = match (&found, &self.out) {
(Some((info, _)), Some(out)) => info.handle() == out.connector,
(None, None) => true,
_ => false,
};
if same {
return;
}
if let Some(out) = self.out.take() {
tracing::info!("display disconnected: {}", out.output.name());
if let Some(g) = out.global {
state.dh.remove_global::<State>(g);
}
state.set_output(None);
}
let Some((info, crtc)) = found else { return };
if let Err(e) = self.setup_output(state, &info, crtc) {
tracing::error!("display setup: {e:#}");
}
}
fn setup_output(&mut self, state: &mut State, info: &connector::Info, crtc: crtc::Handle) -> Result<()> {
let name = format!("{}-{}", info.interface().as_str(), info.interface_id());
let modes = info.modes().to_vec();
let mode = *modes.iter().find(|m| m.mode_type().contains(ModeTypeFlags::PREFERRED)).unwrap_or(&modes[0]);
let wl_mode = WlMode::from(mode);
let (pw, ph) = info.size().unwrap_or((0, 0));
let output = Output::new(
name.clone(),
PhysicalProperties {
size: (pw as i32, ph as i32).into(),
subpixel: Subpixel::Unknown,
make: "TV".into(),
model: name.clone(),
},
);
let global = output.create_global::<State>(&state.dh);
output.set_preferred(wl_mode);
output.change_current_state(Some(wl_mode), None, None, Some((0, 0).into()));
*output.user_data().get_or_insert(OutputModes::default).0.lock().unwrap() = modes.iter().map(mode_info).collect();
let drm_output = self
.manager
.initialize_output::<_, SfElement>(
crtc,
mode,
&[info.handle()],
&output,
None,
&mut self.renderer,
&DrmOutputRenderElements::default(),
)
.map_err(|e| anyhow!("initializing {name}: {e:?}"))?;
tracing::info!("display {name}: {}x{}@{:.2}", wl_mode.size.w, wl_mode.size.h, wl_mode.refresh as f32 / 1000.0);
self.out = Some(Out {
drm_output,
connector: info.handle(),
crtc,
modes,
output: output.clone(),
global: Some(global),
frame_pending: false,
cleared: false,
});
state.set_output(Some(output));
self.render(state);
Ok(())
}
/// Called after every dispatch: start rendering if nothing is in flight.
pub fn kick(&mut self, state: &mut State) {
let idle = self.out.as_ref().is_some_and(|o| !o.frame_pending);
if idle && !self.retry_scheduled {
self.render(state);
}
}
fn frame_done(&mut self, state: &mut State, metadata: Option<DrmEventMetadata>) {
let Some(out) = self.out.as_mut() else { return };
match out.drm_output.frame_submitted() {
Ok(Some(Some(mut feedback))) => {
// The flip time from the kernel, else now (both monotonic).
let (time, seq) = match metadata {
Some(DrmEventMetadata { time: DrmEventTime::Monotonic(t), sequence }) => (t, sequence as u64),
_ => (state.clock.now().into(), 0),
};
let refresh = out
.output
.current_mode()
.map(|m| Refresh::fixed(Duration::from_nanos(1_000_000_000_000 / m.refresh.max(1) as u64)))
.unwrap_or(Refresh::Unknown);
let flags = wp_presentation_feedback::Kind::Vsync
| wp_presentation_feedback::Kind::HwClock
| wp_presentation_feedback::Kind::HwCompletion;
feedback.presented::<_, smithay::utils::Monotonic>(time, refresh, seq, flags);
}
Ok(_) => {}
Err(e) => tracing::warn!("frame_submitted: {e:?}"),
}
out.frame_pending = false;
state.send_frames();
self.render(state);
}
fn render(&mut self, state: &mut State) {
if !self.active {
return;
}
let Some(out) = self.out.as_mut() else { return };
if out.frame_pending {
return;
}
if !state.screen_on {
if !out.cleared {
if let Err(e) = out.drm_output.with_compositor(|c| c.clear()) {
tracing::warn!("screen off: {e}");
}
out.cleared = true;
tracing::info!("screen off");
}
// Apps still get (slow) frame callbacks so they don't hang.
self.schedule_retry(state, Duration::from_millis(250));
return;
}
if out.cleared {
out.cleared = false;
out.drm_output.reset_buffers();
tracing::info!("screen on");
}
let elements = state.elements(&mut self.renderer);
let rendered = match out.drm_output.render_frame(&mut self.renderer, &elements, [0.0, 0.0, 0.0, 1.0], FrameFlags::DEFAULT) {
Ok(r) => !r.is_empty,
Err(e) => {
tracing::warn!("render: {e:?}");
false
}
};
if !state.screencopies.is_empty() {
crate::screencopy::fulfil(state, &mut self.renderer, &elements, rendered);
}
if rendered {
match out.drm_output.queue_frame(state.presentation_feedback()) {
Ok(()) => out.frame_pending = true,
Err(e) => tracing::warn!("queue_frame: {e:?}"),
}
} else {
// Nothing changed: send frame callbacks, look again in a frame.
state.send_frames();
let frame = out.output.current_mode().map(|m| 1_000_000 / m.refresh.max(1) as u64).unwrap_or(16);
self.schedule_retry(state, Duration::from_millis(frame.max(4)));
}
}
fn schedule_retry(&mut self, state: &mut State, after: Duration) {
if self.retry_scheduled {
return;
}
self.retry_scheduled = true;
let _ = state.handle.insert_source(Timer::from_duration(after), |_, _, app: &mut App| {
if let Backend::Udev(u) = &mut app.backend {
u.retry_scheduled = false;
if !app.state.screen_on {
app.state.send_frames();
}
u.render(&mut app.state);
}
TimeoutAction::Drop
});
}
pub fn apply_config(&mut self, state: &mut State, cfg: &PendingConfig) -> Result<()> {
let Some(out) = self.out.as_mut() else { bail!("no display connected") };
let infos: Vec<ModeInfo> = out.modes.iter().map(mode_info).collect();
let target = match &cfg.mode {
Some(want) => {
let (idx, _) = match_mode(&infos, want, cfg.any_refresh)
.with_context(|| format!("{}x{}@{} is not offered by the display", want.width, want.height, want.refresh))?;
Some(out.modes[idx])
}
None => None,
};
if cfg.test_only {
return Ok(());
}
if let Some(mode) = target {
let wl = WlMode::from(mode);
if out.output.current_mode() != Some(wl) {
out.drm_output
.use_mode::<_, SfElement>(mode, &mut self.renderer, &DrmOutputRenderElements::default())
.map_err(|e| anyhow!("mode change: {e:?}"))?;
out.output.change_current_state(Some(wl), None, None, None);
tracing::info!("mode {}x{}@{:.2}", wl.size.w, wl.size.h, wl.refresh as f32 / 1000.0);
state.reconfigure_all();
}
}
state.screen_on = cfg.enabled;
out.frame_pending = false;
self.render(state);
Ok(())
}
}

View File

@@ -0,0 +1,125 @@
//! Nested backend: the compositor runs in a window of a desktop session
//! (WSLg, a Linux desktop). For development only.
use anyhow::{Result, anyhow, bail};
use smithay::backend::renderer::ImportDma;
use smithay::backend::renderer::ImportMemWl;
use smithay::backend::renderer::damage::OutputDamageTracker;
use smithay::backend::renderer::gles::GlesRenderer;
use smithay::backend::winit::{self, WinitEvent, WinitGraphicsBackend};
use smithay::output::{Mode, Output, PhysicalProperties, Subpixel};
use smithay::reexports::calloop::EventLoop;
use smithay::reexports::wayland_protocols::wp::presentation_time::server::wp_presentation_feedback;
use smithay::utils::Transform;
use std::time::Duration;
use crate::output_mgmt::{ModeInfo, OutputModes, PendingConfig};
use crate::state::{App, Backend, State};
pub struct WinitData {
backend: WinitGraphicsBackend<GlesRenderer>,
damage: OutputDamageTracker,
output: Output,
}
fn set_modes(output: &Output, mode: Mode) {
let modes = output.user_data().get_or_insert(OutputModes::default);
*modes.0.lock().unwrap() =
vec![ModeInfo { width: mode.size.w, height: mode.size.h, refresh: mode.refresh, preferred: true }];
}
pub fn init(event_loop: &mut EventLoop<'static, App>, state: &mut State) -> Result<Backend> {
let (mut backend, winit_loop) = winit::init::<GlesRenderer>().map_err(|e| anyhow!("winit: {e:?}"))?;
let mode = Mode { size: backend.window_size(), refresh: 60_000 };
let output = Output::new(
"WINIT-1".into(),
PhysicalProperties { size: (0, 0).into(), subpixel: Subpixel::Unknown, make: "Fennec OS".into(), model: "Nested".into() },
);
let _global = output.create_global::<State>(&state.dh);
output.change_current_state(Some(mode), Some(Transform::Flipped180), None, Some((0, 0).into()));
output.set_preferred(mode);
set_modes(&output, mode);
state.shm_state.update_formats(backend.renderer().shm_formats());
let formats = backend.renderer().dmabuf_formats();
state.dmabuf_global = Some(state.dmabuf_state.create_global::<State>(&state.dh, formats));
state.set_output(Some(output.clone()));
let damage = OutputDamageTracker::from_output(&output);
event_loop
.handle()
.insert_source(winit_loop, |event, _, app: &mut App| match event {
WinitEvent::Resized { size, .. } => {
let Backend::Winit(w) = &mut app.backend else { return };
let mode = Mode { size, refresh: 60_000 };
w.output.change_current_state(Some(mode), None, None, None);
w.output.set_preferred(mode);
set_modes(&w.output, mode);
app.state.reconfigure_all();
app.state.output_mgmt_refresh();
}
WinitEvent::Input(event) => app.state.handle_input(event),
WinitEvent::Redraw => render(app),
WinitEvent::CloseRequested => app.state.loop_signal.stop(),
_ => {}
})
.map_err(|e| anyhow!("winit source: {e}"))?;
Ok(Backend::Winit(WinitData { backend, damage, output }))
}
fn render(app: &mut App) {
let Backend::Winit(w) = &mut app.backend else { return };
let age = w.backend.buffer_age().unwrap_or(0);
let (damage, elements) = match w.backend.bind() {
Ok((renderer, mut fb)) => {
let elements = app.state.elements(renderer);
let damage = match w.damage.render_output(renderer, &mut fb, age, &elements, [0.0, 0.0, 0.0, 1.0]) {
Ok(r) => r.damage.cloned(),
Err(e) => {
tracing::warn!("render: {e:?}");
None
}
};
(damage, Some(elements))
}
Err(e) => {
tracing::warn!("bind: {e:?}");
(None, None)
}
};
let damaged = damage.is_some();
if let Some(damage) = damage {
let feedback = app.state.presentation_feedback();
match w.backend.submit(Some(&damage)) {
Ok(()) => {
if let Some(mut f) = feedback {
let refresh = smithay::wayland::presentation::Refresh::fixed(Duration::from_micros(16_667));
f.presented::<_, smithay::utils::Monotonic>(app.state.clock.now(), refresh, 0, wp_presentation_feedback::Kind::Vsync);
}
}
Err(e) => tracing::warn!("submit: {e:?}"),
}
}
// After the swap: copying binds other targets.
if let Some(elements) = elements.filter(|_| !app.state.screencopies.is_empty()) {
crate::screencopy::fulfil(&mut app.state, w.backend.renderer(), &elements, damaged);
}
app.state.send_frames();
w.backend.window().request_redraw();
}
impl WinitData {
pub fn apply_config(&mut self, state: &mut State, cfg: &PendingConfig) -> Result<()> {
if let Some(m) = &cfg.mode {
let cur = self.backend.window_size();
if (m.width, m.height) != (cur.w, cur.h) {
bail!("the nested window is {}x{}", cur.w, cur.h);
}
}
if !cfg.test_only {
state.screen_on = cfg.enabled;
}
Ok(())
}
}

21
crates/sf-core/Cargo.toml Normal file
View File

@@ -0,0 +1,21 @@
[package]
name = "sf-core"
description = "Fennec OS core daemon: app lifecycle (systemd scopes, one app at a time), DIAL, AirPlay/Miracast receivers"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
sf-ipc.workspace = true
sf-dial.workspace = true
anyhow.workspace = true
log.workspace = true
env_logger.workspace = true
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

350
crates/sf-core/src/apps.rs Normal file
View File

@@ -0,0 +1,350 @@
//! App lifecycle: start and close. Only one app runs at a time: Home, a
//! new app or a cast closes the one on screen.
use std::os::unix::process::CommandExt;
use std::path::PathBuf;
use std::process::Command as StdCommand;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use anyhow::{Context, Result, bail};
use sf_ipc::launch::{LaunchOptions, command};
use sf_ipc::{AppKind, AppManifest, CoreEvent, Settings};
use tokio::sync::broadcast;
use crate::wm;
/// Close only after the compositor's switch animation has finished.
const CLOSE_DELAY: Duration = Duration::from_millis(600);
struct Running {
id: String,
pid: u32,
/// systemd scope (`sf-app-<id>-<n>.scope`), if scopes are used.
unit: Option<String>,
serial: u64,
/// Being closed; it can't be brought back any more.
stopping: bool,
}
#[derive(Default)]
struct State {
apps: Vec<AppManifest>,
running: Vec<Running>,
foreground: Option<String>,
serial: u64,
}
pub struct Core {
apps_dirs: Vec<PathBuf>,
/// Installed store apps (sandboxed, see sf_ipc::sandbox).
store_dir: Option<PathBuf>,
settings_path: PathBuf,
scopes: bool,
pub events: broadcast::Sender<CoreEvent>,
state: Mutex<State>,
}
/// True if a systemd user manager answers (`systemctl --user`).
fn systemd_user_available() -> bool {
if std::env::var_os("SMARTFOX_NO_SCOPES").is_some() {
return false;
}
StdCommand::new("systemctl")
.args(["--user", "is-system-running"])
.output()
.map(|o| {
let s = String::from_utf8_lossy(&o.stdout);
["running", "degraded", "starting"].iter().any(|w| s.trim() == *w)
})
.unwrap_or(false)
}
fn kill_group(pid: u32, sig: libc::c_int) -> bool {
// SAFETY: plain syscall; a negative pid addresses the process group.
unsafe { libc::kill(-(pid as libc::pid_t), sig) == 0 }
}
async fn systemctl(verb: &str, unit: &str) -> Result<()> {
let st = tokio::process::Command::new("systemctl").args(["--user", verb, unit]).status().await?;
if !st.success() {
bail!("systemctl --user {verb} {unit}: {st}");
}
Ok(())
}
impl Core {
pub fn new(apps_dirs: Vec<PathBuf>, store_dir: Option<PathBuf>, settings_path: PathBuf) -> Result<Self> {
let apps = sf_ipc::manifest::load_all(&apps_dirs, store_dir.as_deref())?;
let (events, _) = broadcast::channel(64);
Ok(Core {
apps_dirs,
store_dir,
settings_path,
scopes: systemd_user_available(),
events,
state: Mutex::new(State { apps, ..Default::default() }),
})
}
pub fn app_count(&self) -> usize {
self.state.lock().unwrap().apps.len()
}
pub fn uses_scopes(&self) -> bool {
self.scopes
}
pub fn apps(&self) -> Vec<AppManifest> {
self.state.lock().unwrap().apps.clone()
}
pub fn foreground(&self) -> Option<String> {
self.state.lock().unwrap().foreground.clone()
}
pub fn is_running(&self, id: &str) -> bool {
self.state.lock().unwrap().running.iter().any(|r| r.id == id)
}
pub fn emit(&self, ev: CoreEvent) {
log::debug!("event {ev:?}");
let _ = self.events.send(ev);
}
/// Re-reads the manifests (new packages may have been installed).
fn reload_apps(&self) {
match sf_ipc::manifest::load_all(&self.apps_dirs, self.store_dir.as_deref()) {
Ok(apps) => self.state.lock().unwrap().apps = apps,
Err(e) => log::warn!("reloading apps: {e:#}"),
}
}
fn data_dir(&self) -> PathBuf {
self.settings_path.parent().map(PathBuf::from).unwrap_or_else(|| PathBuf::from("."))
}
/// Starts the app or brings it back. `query` (DIAL) restarts a running
/// app so it sees the new parameters.
pub async fn launch(self: &Arc<Self>, id: &str, query: Option<String>, cast: bool) -> Result<()> {
self.reload_apps();
let app = self.state.lock().unwrap().apps.iter().find(|a| a.id == id).cloned();
let app = app.with_context(|| format!("no app {id:?}"))?;
if app.kind == AppKind::Builtin || app.service {
return Ok(());
}
if query.is_some() && self.is_running(id) {
self.stop_and_wait(id).await;
}
// Still running (brought back before it closed): show it again.
let alive = self.state.lock().unwrap().running.iter().any(|r| r.id == id && !r.stopping);
if alive {
let prev = self.set_foreground(Some(id));
self.close_previous(prev);
wm::focus(Some(id));
self.emit(CoreEvent::AppStarted { app_id: id.to_string(), cast });
return Ok(());
}
let prev = self.set_foreground(None);
// One app at a time: anything else still running closes now.
let others: Vec<String> = {
let st = self.state.lock().unwrap();
st.running.iter().map(|r| r.id.clone()).filter(|r| Some(r) != prev.as_ref()).collect()
};
for other in others {
self.stop(&other);
}
self.close_previous(prev);
// Opened again while it was closing: start fresh once it is gone.
self.wait_gone(id).await;
self.spawn(&app, query.as_deref())?;
self.set_foreground(Some(id));
wm::focus(Some(id));
self.emit(CoreEvent::AppStarted { app_id: id.to_string(), cast });
Ok(())
}
fn set_foreground(&self, id: Option<&str>) -> Option<String> {
let mut st = self.state.lock().unwrap();
let prev = std::mem::replace(&mut st.foreground, id.map(str::to_string));
prev.filter(|p| Some(p.as_str()) != id)
}
/// Closes the app that was on screen, once the switch animation is
/// over (at once under cage, which has no animation).
fn close_previous(self: &Arc<Self>, prev: Option<String>) {
let Some(prev) = prev else { return };
if !wm::available() {
self.stop(&prev);
return;
}
let core = self.clone();
tokio::spawn(async move {
tokio::time::sleep(CLOSE_DELAY).await;
if core.foreground().as_deref() == Some(prev.as_str()) {
return; // brought back in the meantime
}
core.stop(&prev);
});
}
fn spawn(self: &Arc<Self>, app: &AppManifest, query: Option<&str>) -> Result<()> {
let settings = Settings::load(&self.settings_path).unwrap_or_default();
let data_dir = self.data_dir();
let opts = LaunchOptions { data_dir: &data_dir, fullscreen: true, bounds: None, query };
let inner = command(app, &settings, &opts)?;
let serial = {
let mut st = self.state.lock().unwrap();
st.serial += 1;
st.serial
};
let (mut cmd, unit) = if self.scopes {
let unit = format!("sf-app-{}-{serial}", app.id);
let mut cmd = StdCommand::new("systemd-run");
cmd.args(["--user", "--scope", "--quiet", "--collect"])
.arg(format!("--unit={unit}"))
.args(["-p", "TimeoutStopSec=3"])
.arg("--")
.arg(inner.get_program())
.args(inner.get_args());
(cmd, Some(format!("{unit}.scope")))
} else {
let mut cmd = StdCommand::new(inner.get_program());
cmd.args(inner.get_args());
(cmd, None)
};
for (k, v) in inner.get_envs() {
match v {
Some(v) => cmd.env(k, v),
None => cmd.env_remove(k),
};
}
cmd.process_group(0);
let mut child = tokio::process::Command::from(cmd)
.kill_on_drop(false)
.spawn()
.with_context(|| format!("starting {}", app.id))?;
let pid = child.id().context("no pid")?;
// The app runs in its own process group (pgid == pid).
wm::register(pid, &app.id);
log::info!("started {} (pid {pid}{})", app.id, unit.as_deref().map(|u| format!(", {u}")).unwrap_or_default());
self.state.lock().unwrap().running.push(Running {
id: app.id.clone(),
pid,
unit,
serial,
stopping: false,
});
let core = self.clone();
let id = app.id.clone();
tokio::spawn(async move {
let status = child.wait().await;
log::info!("{id} exited ({status:?})");
core.on_exit(&id, serial);
});
Ok(())
}
fn on_exit(&self, id: &str, serial: u64) {
let was_foreground = {
let mut st = self.state.lock().unwrap();
st.running.retain(|r| !(r.id == id && r.serial == serial));
if st.running.iter().any(|r| r.id == id) {
return; // a newer instance is already up
}
let fg = st.foreground.as_deref() == Some(id);
if fg {
st.foreground = None;
}
fg
};
if was_foreground {
wm::focus(None);
}
self.emit(CoreEvent::AppStopped { app_id: id.to_string() });
}
/// Home: show the launcher; the app on screen closes.
pub fn go_home(self: &Arc<Self>) {
let prev = self.set_foreground(None);
wm::focus(None);
self.close_previous(prev);
}
/// Closes the app (asynchronously); false if it wasn't running.
pub fn stop(self: &Arc<Self>, id: &str) -> bool {
let target = {
let mut st = self.state.lock().unwrap();
st.running.iter_mut().find(|r| r.id == id).map(|r| {
r.stopping = true;
(r.unit.clone(), r.pid)
})
};
let Some((unit, pid)) = target else { return false };
log::info!("stopping {id}");
tokio::spawn(async move {
match unit {
// Stops every process of the scope.
Some(u) => {
if let Err(e) = systemctl("stop", &u).await {
log::warn!("{e:#}");
kill_group(pid, libc::SIGKILL);
}
}
None => {
kill_group(pid, libc::SIGTERM);
tokio::time::sleep(Duration::from_secs(3)).await;
kill_group(pid, libc::SIGKILL);
}
}
});
true
}
async fn stop_and_wait(self: &Arc<Self>, id: &str) {
if self.stop(id) {
self.wait_gone(id).await;
}
}
/// Waits (up to 6 s) until no instance of the app runs.
async fn wait_gone(&self, id: &str) {
for _ in 0..60 {
if !self.is_running(id) {
return;
}
tokio::time::sleep(Duration::from_millis(100)).await;
}
log::warn!("{id} did not stop in time");
}
/// A receiver (AirPlay/Miracast) got a connection: its window takes the
/// screen and the app on screen closes (one app at a time).
pub fn cast_connected(self: &Arc<Self>, app_id: &str, device: &str) {
let prev = self.set_foreground(None);
self.close_previous(prev);
wm::focus(Some(app_id));
self.emit(CoreEvent::CastConnected { app_id: app_id.to_string(), device: device.to_string() });
}
/// The cast ended: back to the launcher, unless an app was opened meanwhile.
pub fn cast_ended(self: &Arc<Self>, app_id: &str) {
self.emit(CoreEvent::CastEnded { app_id: app_id.to_string() });
if wm::available() && self.foreground().is_none() {
wm::focus(None);
}
}
pub fn shutdown(self: &Arc<Self>) {
let ids: Vec<(Option<String>, u32)> =
self.state.lock().unwrap().running.iter().map(|r| (r.unit.clone(), r.pid)).collect();
for (unit, pid) in ids {
if let Some(u) = unit {
let _ = StdCommand::new("systemctl").args(["--user", "stop", "--no-block", &u]).status();
}
kill_group(pid, libc::SIGTERM);
}
}
}

View File

@@ -0,0 +1,84 @@
//! DIAL glue: apps with a `[dial]` section in their manifest (YouTube) can be
//! 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;
struct Dial(Arc<Core>);
impl Dial {
fn app_for(&self, dial_name: &str) -> Option<String> {
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<AppManifest>, dial_name: &str) -> Option<String> {
let mut found: Vec<AppManifest> = 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);
}
}
impl Handler for Dial {
fn state(&self, name: &str) -> Option<AppState> {
let id = self.app_for(name)?;
Some(if self.0.is_running(&id) { AppState::Running } else { AppState::Stopped })
}
fn launch(&self, name: &str, params: LaunchParams) -> Result<()> {
let id = self.app_for(name).context("unknown app")?;
log::info!("dial: {name} -> {id} from {}", params.peer);
let core = self.0.clone();
let query = params.query();
tokio::spawn(async move {
if let Err(e) = core.launch(&id, Some(query), true).await {
log::error!("dial launch {id}: {e:#}");
}
});
Ok(())
}
fn stop(&self, name: &str) -> bool {
match self.app_for(name) {
Some(id) => self.0.stop(&id),
None => false,
}
}
}
pub async fn run(core: Arc<Core>, port: u16) -> Result<()> {
let settings = sf_ipc::Settings::load(&sf_ipc::paths::settings_file()).unwrap_or_default();
let mut config = Config { http_port: port, ..Default::default() };
if let Some(name) = settings.get("device_name").filter(|n| !n.trim().is_empty()) {
config.friendly_name = name.trim().to_string();
}
if let Ok(id) = std::fs::read_to_string("/etc/machine-id") {
config.uuid = sf_dial::uuid_from_machine_id(&id);
}
log::info!("dial: \"{}\" uuid:{}", config.friendly_name, config.uuid);
sf_dial::run(config, Dial(core)).await
}

126
crates/sf-core/src/main.rs Normal file
View File

@@ -0,0 +1,126 @@
//! sf-core: the Fennec OS core daemon.
//!
//! - Starts apps for the launcher, each in its own systemd user scope.
//! Only one app runs at a time: Home, another app or a cast closes it.
//! - Runs the DIAL server, so the YouTube app on a phone can cast to the TV.
//! - Keeps the AirPlay (UxPlay) and Miracast receivers running and reports
//! when a device connects.
//!
//! Talks JSON lines with the launcher (`sf_ipc::message`) and plain text
//! lines with the compositor (`focus launcher`, `focus <app-id>`).
#[cfg(unix)]
mod apps;
#[cfg(unix)]
mod dial;
#[cfg(unix)]
mod server;
#[cfg(unix)]
mod services;
#[cfg(unix)]
mod wm;
fn main() -> anyhow::Result<()> {
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
#[cfg(unix)]
{
unix_main()
}
#[cfg(not(unix))]
{
anyhow::bail!("sf-core runs on the TV (Linux); on a desktop the launcher starts apps itself")
}
}
#[cfg(unix)]
struct Options {
apps_dirs: Vec<std::path::PathBuf>,
store_dir: Option<std::path::PathBuf>,
settings: std::path::PathBuf,
dial_port: u16,
no_dial: bool,
no_services: bool,
}
#[cfg(unix)]
fn parse_args() -> Options {
let mut o = Options {
apps_dirs: vec![],
store_dir: None,
settings: sf_ipc::paths::settings_file(),
dial_port: 56789,
no_dial: false,
no_services: false,
};
let mut args = std::env::args().skip(1);
while let Some(a) = args.next() {
match a.as_str() {
"--apps" => o.apps_dirs.extend(args.next().map(Into::into)),
"--store-apps" => o.store_dir = args.next().map(Into::into),
"--settings" => o.settings = args.next().map(Into::into).unwrap_or(o.settings),
"--dial-port" => o.dial_port = args.next().and_then(|p| p.parse().ok()).unwrap_or(o.dial_port),
"--no-dial" => o.no_dial = true,
"--no-services" => o.no_services = true,
other => log::warn!("unknown argument {other}"),
}
}
if o.apps_dirs.is_empty() {
o.apps_dirs.push(sf_ipc::paths::apps_dir());
}
o
}
/// Resolves when the Wayland display we started in goes away, so a new
/// session doesn't find an old sf-core still running.
#[cfg(unix)]
async fn session_gone() {
let Some(display) = std::env::var_os("WAYLAND_DISPLAY") else {
return std::future::pending().await;
};
let path = sf_ipc::paths::runtime_dir().join(display);
loop {
tokio::time::sleep(std::time::Duration::from_secs(5)).await;
if !path.exists() {
return;
}
}
}
#[cfg(unix)]
fn unix_main() -> anyhow::Result<()> {
use std::sync::Arc;
let opts = parse_args();
let rt = tokio::runtime::Builder::new_current_thread().enable_all().build()?;
rt.block_on(async move {
let core = Arc::new(apps::Core::new(opts.apps_dirs.clone(), opts.store_dir.clone(), opts.settings.clone())?);
log::info!(
"{} apps; systemd scopes: {}; window switching: {}",
core.app_count(),
core.uses_scopes(),
wm::available()
);
if !opts.no_services {
services::start_all(core.clone());
}
if !opts.no_dial {
let core = core.clone();
let port = opts.dial_port;
tokio::spawn(async move {
if let Err(e) = dial::run(core, port).await {
log::error!("dial: {e:#}");
}
});
}
let serve = server::serve(core.clone());
let mut term = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?;
tokio::select! {
r = serve => r?,
_ = session_gone() => log::info!("the Wayland session ended"),
_ = term.recv() => log::info!("terminating"),
_ = tokio::signal::ctrl_c() => log::info!("interrupted"),
}
core.shutdown();
Ok(())
})
}

View File

@@ -0,0 +1,81 @@
//! The core socket: the launcher sends requests, every client gets events.
use std::sync::Arc;
use anyhow::{Context, Result};
use sf_ipc::{CoreEvent, LauncherRequest};
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
use tokio::net::{UnixListener, UnixStream};
use tokio::sync::broadcast::error::RecvError;
use crate::apps::Core;
use crate::wm;
pub async fn serve(core: Arc<Core>) -> Result<()> {
let path = sf_ipc::paths::core_socket();
let _ = std::fs::remove_file(&path);
let listener = UnixListener::bind(&path).with_context(|| format!("binding {}", path.display()))?;
log::info!("core socket {}", path.display());
loop {
let (stream, _) = listener.accept().await?;
let core = core.clone();
tokio::spawn(async move {
if let Err(e) = client(core, stream).await {
log::debug!("client: {e:#}");
}
});
}
}
async fn client(core: Arc<Core>, stream: UnixStream) -> Result<()> {
let (read, mut write) = stream.into_split();
let mut events = core.events.subscribe();
let hello = CoreEvent::Hello { switching: wm::available(), foreground: core.foreground() };
write.write_all(hello.to_line().as_bytes()).await?;
let writer = tokio::spawn(async move {
loop {
match events.recv().await {
Ok(ev) => {
if write.write_all(ev.to_line().as_bytes()).await.is_err() {
break;
}
}
Err(RecvError::Lagged(n)) => log::warn!("client lagged, {n} events dropped"),
Err(RecvError::Closed) => break,
}
}
});
let mut lines = BufReader::new(read).lines();
while let Some(line) = lines.next_line().await? {
let line = line.trim();
if line.is_empty() {
continue;
}
match serde_json::from_str::<LauncherRequest>(line) {
Ok(req) => handle(&core, req).await,
Err(e) => log::warn!("bad request {line:?}: {e}"),
}
}
writer.abort();
Ok(())
}
async fn handle(core: &Arc<Core>, req: LauncherRequest) {
log::info!("request {req:?}");
match req {
LauncherRequest::Launch { app_id, query } => {
if let Err(e) = core.launch(&app_id, query, false).await {
log::error!("launch {app_id}: {e:#}");
let name = core.apps().into_iter().find(|a| a.id == app_id).map(|a| a.name).unwrap_or(app_id.clone());
core.emit(CoreEvent::Toast { text: format!("{name}: {e:#}") });
core.emit(CoreEvent::AppStopped { app_id });
}
}
LauncherRequest::GoHome => core.go_home(),
LauncherRequest::Stop { app_id } => {
core.stop(&app_id);
}
}
}

View File

@@ -0,0 +1,179 @@
//! Background receivers (manifests with `service = true`): AirPlay (UxPlay)
//! and Miracast (sf-miracast). They run all the time and are restarted if
//! they exit; their output tells us when a device connects.
use std::process::Stdio;
use std::sync::Arc;
use std::time::Duration;
use sf_ipc::launch::{LaunchOptions, command};
use sf_ipc::{AppManifest, Settings};
use tokio::io::{AsyncBufReadExt, BufReader};
use tokio::sync::mpsc;
use crate::apps::Core;
#[derive(Debug, PartialEq)]
pub enum Signal {
Connected(String),
Ended,
}
/// Recognizes connection events in a receiver's output.
/// - UxPlay: `connection request from <name> (<model>) with deviceID = …`,
/// `Open connections: <n>`;
/// - our own receivers: `SF-EVENT connected <name>`, `SF-EVENT ended`.
pub fn parse_line(line: &str, connected: bool) -> Option<Signal> {
let line = line.trim();
if let Some(rest) = line.strip_prefix("SF-EVENT ") {
return match rest.split_once(' ') {
Some(("connected", name)) => Some(Signal::Connected(name.trim().to_string())),
_ if rest == "connected" => Some(Signal::Connected(String::new())),
_ if rest.starts_with("ended") => Some(Signal::Ended),
_ => None,
};
}
if let Some(i) = line.find("connection request from ") {
let rest = &line[i + "connection request from ".len()..];
let name = rest.split(" (").next().unwrap_or(rest).trim();
return Some(Signal::Connected(name.to_string()));
}
if let Some(i) = line.find("Open connections: ") {
let n: u32 = line[i + "Open connections: ".len()..].trim().parse().ok()?;
return match (n, connected) {
(0, true) => Some(Signal::Ended),
(n, false) if n > 0 => Some(Signal::Connected(String::new())),
_ => None,
};
}
None
}
pub fn start_all(core: Arc<Core>) {
for app in core.apps().into_iter().filter(|a| a.service) {
tokio::spawn(supervise(core.clone(), app));
}
}
async fn supervise(core: Arc<Core>, app: AppManifest) {
let mut failures = 0u32;
loop {
let settings = Settings::load(&sf_ipc::paths::settings_file()).unwrap_or_default();
let data_dir = std::env::temp_dir();
let opts = LaunchOptions { data_dir: &data_dir, fullscreen: true, bounds: None, query: None };
let cmd = match command(&app, &settings, &opts) {
Ok(c) => c,
Err(e) => {
log::error!("{}: {e:#}", app.id);
return;
}
};
let mut cmd = cmd;
// The receiver must not outlive us: an orphaned UxPlay would keep its
// ports and make the next session's copy fail.
// SAFETY: prctl is async-signal-safe.
unsafe {
use std::os::unix::process::CommandExt;
cmd.pre_exec(|| {
libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM);
Ok(())
});
}
let mut cmd = tokio::process::Command::from(cmd);
cmd.stdout(Stdio::piped()).stderr(Stdio::piped()).stdin(Stdio::null()).kill_on_drop(true);
let mut child = match cmd.spawn() {
Ok(c) => c,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
log::warn!("{}: {:?} is not installed; retrying in 5 minutes", app.id, app.exec);
tokio::time::sleep(Duration::from_secs(300)).await;
continue;
}
Err(e) => {
log::error!("{}: {e}", app.id);
tokio::time::sleep(Duration::from_secs(30)).await;
continue;
}
};
log::info!("{} receiver running (pid {:?})", app.id, child.id());
if let Some(pid) = child.id() {
crate::wm::register(pid, &app.id);
}
let started = std::time::Instant::now();
let (tx, mut rx) = mpsc::unbounded_channel::<String>();
for out in [child.stdout.take().map(|s| Box::new(s) as Box<dyn tokio::io::AsyncRead + Unpin + Send>),
child.stderr.take().map(|s| Box::new(s) as Box<dyn tokio::io::AsyncRead + Unpin + Send>)]
.into_iter()
.flatten()
{
let tx = tx.clone();
tokio::spawn(async move {
let mut lines = BufReader::new(out).lines();
while let Ok(Some(line)) = lines.next_line().await {
if tx.send(line).is_err() {
break;
}
}
});
}
drop(tx);
let mut connected = false;
loop {
tokio::select! {
line = rx.recv() => {
let Some(line) = line else {
let status = child.wait().await;
log::warn!("{} receiver exited: {status:?}", app.id);
break;
};
log::debug!("[{}] {line}", app.id);
match parse_line(&line, connected) {
Some(Signal::Connected(name)) if !connected => {
connected = true;
let name = if name.is_empty() { "eszköz".to_string() } else { name };
log::info!("{}: {name} connected", app.id);
core.cast_connected(&app.id, &name);
}
Some(Signal::Ended) if connected => {
connected = false;
log::info!("{}: session ended", app.id);
core.cast_ended(&app.id);
}
_ => {}
}
}
status = child.wait() => {
log::warn!("{} receiver exited: {status:?}", app.id);
break;
}
}
}
let _ = child.kill().await;
if connected {
core.cast_ended(&app.id);
}
failures = if started.elapsed() > Duration::from_secs(60) { 0 } else { failures + 1 };
let wait = Duration::from_secs((2u64 << failures.min(5)).min(60));
tokio::time::sleep(wait).await;
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_receiver_output() {
assert_eq!(
parse_line("connection request from Peti iPhone-ja (iPhone15,2) with deviceID = AA:BB", false),
Some(Signal::Connected("Peti iPhone-ja".into()))
);
assert_eq!(parse_line("Open connections: 0", true), Some(Signal::Ended));
assert_eq!(parse_line("Open connections: 0", false), None);
assert_eq!(parse_line("Open connections: 1", false), Some(Signal::Connected(String::new())));
assert_eq!(parse_line("SF-EVENT connected Galaxy S24", false), Some(Signal::Connected("Galaxy S24".into())));
assert_eq!(parse_line("SF-EVENT ended", true), Some(Signal::Ended));
assert_eq!(parse_line("random", false), None);
}
}

56
crates/sf-core/src/wm.rs Normal file
View File

@@ -0,0 +1,56 @@
//! Client for the sf-compositor control socket. One command per line, one
//! reply line (`ok` or `err <reason>`):
//! focus launcher show the launcher
//! focus <app-id> show that app's window (as soon as it has one)
//! register <pgid> <app-id> windows of that process group belong to the app
//!
//! Without sf-compositor (e.g. under cage) there is no socket: the newest
//! window is always on top, so apps can't wait in the background.
use std::io::{BufRead, BufReader, Write};
use std::os::unix::net::UnixStream;
use std::time::Duration;
use anyhow::{Context, Result, bail};
pub fn available() -> bool {
sf_ipc::paths::wm_socket().exists()
}
pub fn send(cmd: &str) -> Result<()> {
let path = sf_ipc::paths::wm_socket();
let mut s = UnixStream::connect(&path).with_context(|| format!("connecting {}", path.display()))?;
s.set_read_timeout(Some(Duration::from_secs(2)))?;
s.set_write_timeout(Some(Duration::from_secs(2)))?;
writeln!(s, "{cmd}")?;
let mut reply = String::new();
BufReader::new(s).read_line(&mut reply)?;
let reply = reply.trim();
if reply == "ok" {
Ok(())
} else {
bail!("compositor: {reply}")
}
}
/// Shows an app, or the launcher with `None`. Logs instead of failing.
pub fn focus(app_id: Option<&str>) {
if !available() {
return;
}
let cmd = format!("focus {}", app_id.unwrap_or("launcher"));
if let Err(e) = send(&cmd) {
log::warn!("{cmd}: {e:#}");
}
}
/// Tells the compositor which app a process group belongs to (Chromium hides
/// its environment, so the compositor can't find out by itself).
pub fn register(pgid: u32, app_id: &str) {
if !available() {
return;
}
if let Err(e) = send(&format!("register {pgid} {app_id}")) {
log::warn!("register {app_id}: {e:#}");
}
}

15
crates/sf-dial/Cargo.toml Normal file
View File

@@ -0,0 +1,15 @@
[package]
name = "sf-dial"
description = "DIAL (DIscovery And Launch) server: SSDP discovery and the app REST API, so phones can cast YouTube"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
anyhow.workspace = true
log.workspace = true
tokio = { version = "1", features = ["rt", "net", "time", "io-util", "sync", "macros"] }
socket2 = { version = "0.6", features = ["all"] }
[dev-dependencies]
tokio = { version = "1", features = ["rt-multi-thread", "macros"] }

243
crates/sf-dial/src/http.rs Normal file
View File

@@ -0,0 +1,243 @@
//! Just enough HTTP/1.1 for DIAL: small requests, `Content-Length` bodies,
//! one request per connection (`Connection: close`).
use std::time::Duration;
use anyhow::{Context, Result, bail};
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
/// DIAL limits launch payloads; anything bigger is refused (413).
pub const MAX_BODY: usize = 4096;
const MAX_HEAD: usize = 8192;
#[derive(Debug, Default)]
pub struct Request {
pub method: String,
/// Path without the query string.
pub path: String,
pub query: String,
pub headers: Vec<(String, String)>,
pub body: Vec<u8>,
}
impl Request {
pub fn header(&self, name: &str) -> Option<&str> {
self.headers.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str())
}
}
#[derive(Debug)]
pub enum ReadError {
TooLarge,
Bad(anyhow::Error),
}
impl From<anyhow::Error> for ReadError {
fn from(e: anyhow::Error) -> Self {
ReadError::Bad(e)
}
}
pub async fn read_request<S: AsyncRead + Unpin>(stream: &mut S) -> Result<Request, ReadError> {
tokio::time::timeout(Duration::from_secs(10), read_inner(stream))
.await
.map_err(|_| ReadError::Bad(anyhow::anyhow!("timeout")))?
}
async fn read_inner<S: AsyncRead + Unpin>(stream: &mut S) -> Result<Request, ReadError> {
let mut buf = Vec::with_capacity(1024);
let head_end = loop {
if let Some(i) = find(&buf, b"\r\n\r\n") {
break i;
}
if buf.len() > MAX_HEAD {
return Err(ReadError::TooLarge);
}
let mut chunk = [0u8; 1024];
let n = stream.read(&mut chunk).await.context("read")?;
if n == 0 {
return Err(ReadError::Bad(anyhow::anyhow!("connection closed")));
}
buf.extend_from_slice(&chunk[..n]);
};
let head = std::str::from_utf8(&buf[..head_end]).context("head is not UTF-8")?;
let mut req = parse_head(head)?;
let len: usize = match req.header("content-length") {
Some(v) => v.trim().parse().context("bad content-length")?,
None => 0,
};
if len > MAX_BODY {
return Err(ReadError::TooLarge);
}
let mut body = buf[head_end + 4..].to_vec();
while body.len() < len {
let mut chunk = [0u8; 1024];
let n = stream.read(&mut chunk).await.context("read body")?;
if n == 0 {
break;
}
body.extend_from_slice(&chunk[..n]);
}
body.truncate(len);
req.body = body;
Ok(req)
}
fn find(hay: &[u8], needle: &[u8]) -> Option<usize> {
hay.windows(needle.len()).position(|w| w == needle)
}
fn parse_head(head: &str) -> Result<Request> {
let mut lines = head.split("\r\n");
let first = lines.next().context("empty request")?;
let mut parts = first.split(' ');
let (Some(method), Some(target), Some(version)) = (parts.next(), parts.next(), parts.next()) else {
bail!("bad request line {first:?}");
};
if !version.starts_with("HTTP/1.") {
bail!("unsupported {version}");
}
let (path, query) = match target.split_once('?') {
Some((p, q)) => (p, q),
None => (target, ""),
};
let headers = lines
.filter_map(|l| l.split_once(':'))
.map(|(k, v)| (k.trim().to_string(), v.trim().to_string()))
.collect();
Ok(Request { method: method.to_string(), path: path.to_string(), query: query.to_string(), headers, body: vec![] })
}
pub struct Response {
pub status: u16,
pub headers: Vec<(String, String)>,
pub body: Vec<u8>,
}
impl Response {
pub fn new(status: u16) -> Self {
Response { status, headers: vec![], body: vec![] }
}
pub fn header(mut self, k: &str, v: impl Into<String>) -> Self {
self.headers.push((k.to_string(), v.into()));
self
}
pub fn xml(status: u16, body: String) -> Self {
Response::new(status).header("Content-Type", "text/xml; charset=\"utf-8\"").with_body(body.into_bytes())
}
pub fn with_body(mut self, body: Vec<u8>) -> Self {
self.body = body;
self
}
pub async fn write<S: AsyncWrite + Unpin>(&self, stream: &mut S) -> std::io::Result<()> {
let mut out = format!("HTTP/1.1 {} {}\r\n", self.status, reason(self.status));
for (k, v) in &self.headers {
out.push_str(&format!("{k}: {v}\r\n"));
}
out.push_str(&format!("Content-Length: {}\r\nConnection: close\r\n\r\n", self.body.len()));
stream.write_all(out.as_bytes()).await?;
stream.write_all(&self.body).await?;
stream.flush().await
}
}
fn reason(status: u16) -> &'static str {
match status {
200 => "OK",
201 => "Created",
204 => "No Content",
400 => "Bad Request",
403 => "Forbidden",
404 => "Not Found",
405 => "Method Not Allowed",
413 => "Request Entity Too Large",
500 => "Internal Server Error",
503 => "Service Unavailable",
_ => "",
}
}
/// Decodes an `application/x-www-form-urlencoded` string into pairs.
pub fn parse_form(s: &str) -> Vec<(String, String)> {
s.split('&')
.filter(|p| !p.is_empty())
.map(|p| match p.split_once('=') {
Some((k, v)) => (url_decode(k), url_decode(v)),
None => (url_decode(p), String::new()),
})
.collect()
}
pub fn url_decode(s: &str) -> String {
let bytes = s.as_bytes();
let mut out = Vec::with_capacity(bytes.len());
let mut i = 0;
while i < bytes.len() {
match bytes[i] {
b'+' => out.push(b' '),
b'%' if i + 2 < bytes.len() => {
match u8::from_str_radix(std::str::from_utf8(&bytes[i + 1..i + 3]).unwrap_or("zz"), 16) {
Ok(b) => {
out.push(b);
i += 2;
}
Err(_) => out.push(b'%'),
}
}
b => out.push(b),
}
i += 1;
}
String::from_utf8_lossy(&out).into_owned()
}
pub fn url_encode(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for b in s.bytes() {
match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => out.push(b as char),
_ => out.push_str(&format!("%{b:02X}")),
}
}
out
}
pub fn xml_escape(s: &str) -> String {
s.replace('&', "&amp;").replace('<', "&lt;").replace('>', "&gt;").replace('"', "&quot;").replace('\'', "&apos;")
}
#[cfg(test)]
mod tests {
use super::*;
#[tokio::test]
async fn reads_post() {
let raw = b"POST /apps/YouTube?x=1 HTTP/1.1\r\nHost: a\r\nContent-Length: 11\r\n\r\npairingCode";
let req = read_request(&mut &raw[..]).await.unwrap();
assert_eq!(req.method, "POST");
assert_eq!(req.path, "/apps/YouTube");
assert_eq!(req.query, "x=1");
assert_eq!(req.header("content-length"), Some("11"));
assert_eq!(req.body, b"pairingCode");
}
#[tokio::test]
async fn refuses_big_body() {
let raw = b"POST / HTTP/1.1\r\nContent-Length: 99999\r\n\r\n";
assert!(matches!(read_request(&mut &raw[..]).await, Err(ReadError::TooLarge)));
}
#[test]
fn decodes_forms() {
assert_eq!(
parse_form("a=1&b=hello+world%21&c"),
vec![("a".into(), "1".into()), ("b".into(), "hello world!".into()), ("c".into(), "".into())]
);
assert_eq!(url_decode("100%"), "100%");
assert_eq!(url_encode("http://x/y z"), "http%3A%2F%2Fx%2Fy%20z");
}
}

372
crates/sf-dial/src/lib.rs Normal file
View File

@@ -0,0 +1,372 @@
//! DIAL server (DIAL 2.1): phones find the TV over SSDP and start apps on
//! it with a REST call. This is how the YouTube app casts to a TV that has
//! no Google Cast receiver: it POSTs a pairing code to `/apps/YouTube`, the
//! TV opens `youtube.com/tv?<that body>`, and the page pairs with the phone.
//!
//! The server only speaks the protocol; what "launch" means is up to the
//! [`Handler`] (sf-core starts the YouTube web app).
pub mod http;
pub mod ssdp;
use std::collections::HashMap;
use std::net::{IpAddr, SocketAddr};
use std::sync::{Arc, Mutex};
use anyhow::{Context, Result};
use tokio::net::TcpListener;
use http::{Request, Response, parse_form, url_encode, xml_escape};
pub use ssdp::DIAL_ST;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum AppState {
Running,
Stopped,
}
/// What a phone sent with a launch request.
#[derive(Debug, Clone)]
pub struct LaunchParams {
/// The POST body (YouTube: `pairingCode=…&v=…&t=…`).
pub body: String,
/// Where the running app may store data for the phone (DIAL `additionalDataUrl`).
pub additional_data_url: String,
pub peer: IpAddr,
}
impl LaunchParams {
/// Query string for the app's start URL: the body plus `additionalDataUrl`.
pub fn query(&self) -> String {
let body = self.body.trim().trim_start_matches(['?', '&']);
let extra = format!("additionalDataUrl={}", url_encode(&self.additional_data_url));
if body.is_empty() { extra } else { format!("{body}&{extra}") }
}
}
pub trait Handler: Send + Sync + 'static {
/// State of a DIAL app, `None` if we don't know the name (404).
fn state(&self, name: &str) -> Option<AppState>;
fn launch(&self, name: &str, params: LaunchParams) -> Result<()>;
/// Stop the app; false if it wasn't running.
fn stop(&self, name: &str) -> bool;
}
#[derive(Debug, Clone)]
pub struct Config {
pub friendly_name: String,
pub manufacturer: String,
pub model_name: String,
/// Stable device id (UPnP UDN without the `uuid:` prefix).
pub uuid: String,
pub http_port: u16,
}
impl Default for Config {
fn default() -> Self {
Config {
friendly_name: "Fennec OS".into(),
manufacturer: "Fennec OS".into(),
model_name: "Fennec OS TV".into(),
uuid: "2f6e7d1c-5a8b-4c3d-9e0f-736d61727466".into(),
http_port: 56789,
}
}
}
/// A UUID derived from a machine id (e.g. `/etc/machine-id`), so the TV keeps
/// its identity across reboots and phones remember it.
pub fn uuid_from_machine_id(id: &str) -> String {
let hex: String = id.chars().filter(|c| c.is_ascii_hexdigit()).take(32).collect::<String>().to_lowercase();
if hex.len() < 32 {
return Config::default().uuid;
}
format!("{}-{}-{}-{}-{}", &hex[0..8], &hex[8..12], &hex[12..16], &hex[16..20], &hex[20..32])
}
struct Server<H> {
config: Config,
handler: H,
/// `additionalData` posted by running apps, per DIAL app name.
data: Mutex<HashMap<String, Vec<(String, String)>>>,
}
/// Runs SSDP and the HTTP server until an error stops one of them.
pub async fn run<H: Handler>(config: Config, handler: H) -> Result<()> {
let listener = TcpListener::bind(("0.0.0.0", config.http_port))
.await
.with_context(|| format!("binding DIAL http port {}", config.http_port))?;
log::info!("dial: http on :{}", config.http_port);
let announce = ssdp::Announce {
uuid: config.uuid.clone(),
http_port: config.http_port,
server: "Linux/6 UPnP/1.1 FennecOS/0.1".into(),
};
let server = Arc::new(Server { config, handler, data: Mutex::default() });
let http = async move {
loop {
let (mut stream, peer) = listener.accept().await?;
let server = server.clone();
tokio::spawn(async move {
let local = stream.local_addr().ok();
let resp = match http::read_request(&mut stream).await {
Ok(req) => server.route(&req, peer, local),
Err(http::ReadError::TooLarge) => Response::new(413),
Err(http::ReadError::Bad(e)) => {
log::debug!("dial: bad request from {peer}: {e:#}");
Response::new(400)
}
};
let _ = resp.write(&mut stream).await;
});
}
#[allow(unreachable_code)]
Ok::<(), anyhow::Error>(())
};
tokio::select! {
r = http => r,
r = ssdp::run(announce) => r,
}
}
/// DIAL 2.1 asks servers to refuse web pages from other sites (CSRF).
/// Native apps send no Origin, or a non-web one like `package:…`.
fn origin_allowed(origin: Option<&str>) -> bool {
let Some(origin) = origin else { return true };
let Some(rest) = origin.strip_prefix("https://").or_else(|| origin.strip_prefix("http://")) else {
return true;
};
let host = rest.split(['/', ':']).next().unwrap_or("");
host == "localhost" || host == "127.0.0.1" || host == "youtube.com" || host.ends_with(".youtube.com")
}
impl<H: Handler> Server<H> {
fn base_url(&self, local: Option<SocketAddr>) -> String {
let ip = match local {
Some(SocketAddr::V4(a)) => a.ip().to_string(),
Some(SocketAddr::V6(a)) => match a.ip().to_ipv4_mapped() {
Some(v4) => v4.to_string(),
None => format!("[{}]", a.ip()),
},
None => "127.0.0.1".into(),
};
format!("http://{ip}:{}", self.config.http_port)
}
fn route(&self, req: &Request, peer: SocketAddr, local: Option<SocketAddr>) -> Response {
log::debug!("dial: {} {} from {peer}", req.method, req.path);
let cors = |r: Response| {
r.header("Access-Control-Allow-Origin", "*")
.header("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS")
.header("Access-Control-Allow-Headers", "Content-Type")
.header("Access-Control-Allow-Private-Network", "true")
};
if req.method == "OPTIONS" {
return cors(Response::new(204));
}
let segs: Vec<&str> = req.path.trim_matches('/').split('/').collect();
match (req.method.as_str(), segs.as_slice()) {
("GET", ["dd.xml"]) => self.device_description(local),
(_, ["apps", name, ..]) if !origin_allowed(req.header("origin")) => {
log::warn!("dial: {} {name} refused, origin {:?}", req.method, req.header("origin"));
Response::new(403)
}
("GET", ["apps", name]) => self.app_status(name),
("POST", ["apps", name]) => self.launch(name, req, peer, local),
("DELETE", ["apps", name, "run"]) => {
if self.handler.state(name).is_none() {
return Response::new(404);
}
if self.handler.stop(name) {
self.data.lock().unwrap().remove(*name);
log::info!("dial: {name} stopped by {peer}");
Response::new(200)
} else {
Response::new(404)
}
}
("POST", ["apps", name, "dial_data"]) => {
if self.handler.state(name).is_none() {
return Response::new(404);
}
let mut pairs = parse_form(&req.query);
pairs.extend(parse_form(&String::from_utf8_lossy(&req.body)));
self.data.lock().unwrap().insert(name.to_string(), pairs);
cors(Response::new(200))
}
(_, ["apps", ..]) => Response::new(405),
_ => Response::new(404),
}
}
fn device_description(&self, local: Option<SocketAddr>) -> Response {
let c = &self.config;
let xml = format!(
r#"<?xml version="1.0" encoding="UTF-8"?>
<root xmlns="urn:schemas-upnp-org:device-1-0">
<specVersion><major>1</major><minor>0</minor></specVersion>
<device>
<deviceType>urn:dial-multiscreen-org:device:dial:1</deviceType>
<friendlyName>{}</friendlyName>
<manufacturer>{}</manufacturer>
<modelName>{}</modelName>
<UDN>uuid:{}</UDN>
<serviceList>
<service>
<serviceType>urn:dial-multiscreen-org:service:dial:1</serviceType>
<serviceId>urn:dial-multiscreen-org:serviceId:dial</serviceId>
<controlURL>/ssdp/notfound</controlURL>
<eventSubURL>/ssdp/notfound</eventSubURL>
<SCPDURL>/ssdp/notfound</SCPDURL>
</service>
</serviceList>
</device>
</root>
"#,
xml_escape(&c.friendly_name),
xml_escape(&c.manufacturer),
xml_escape(&c.model_name),
xml_escape(&c.uuid),
);
Response::xml(200, xml)
.header("Application-URL", format!("{}/apps/", self.base_url(local)))
.header("Access-Control-Expose-Headers", "Application-URL")
}
fn app_status(&self, name: &str) -> Response {
let Some(state) = self.handler.state(name) else { return Response::new(404) };
let running = state == AppState::Running;
let data: String = self
.data
.lock()
.unwrap()
.get(name)
.filter(|_| running)
.map(|pairs| {
pairs
.iter()
.filter(|(k, _)| !k.is_empty() && k.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'))
.map(|(k, v)| format!("<{k}>{}</{k}>", xml_escape(v)))
.collect()
})
.unwrap_or_default();
let xml = format!(
r#"<?xml version="1.0" encoding="UTF-8"?>
<service xmlns="urn:dial-multiscreen-org:schemas:dial" dialVer="2.1">
<name>{}</name>
<options allowStop="true"/>
<state>{}</state>{}
<additionalData>{data}</additionalData>
</service>
"#,
xml_escape(name),
if running { "running" } else { "stopped" },
if running { "\n <link rel=\"run\" href=\"run\"/>" } else { "" },
);
Response::xml(200, xml)
}
fn launch(&self, name: &str, req: &Request, peer: SocketAddr, local: Option<SocketAddr>) -> Response {
if self.handler.state(name).is_none() {
return Response::new(404);
}
let params = LaunchParams {
body: String::from_utf8_lossy(&req.body).into_owned(),
// The app runs on this machine, so it reaches us on localhost
// (an https page may call http://localhost, not a LAN address).
additional_data_url: format!("http://localhost:{}/apps/{name}/dial_data", self.config.http_port),
peer: peer.ip(),
};
log::info!("dial: launch {name} from {peer} ({} bytes)", params.body.len());
match self.handler.launch(name, params) {
Ok(()) => Response::new(201)
.header("Location", format!("{}/apps/{name}/run", self.base_url(local)))
.header("Content-Type", "text/plain"),
Err(e) => {
log::error!("dial: launching {name}: {e:#}");
Response::new(503)
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicBool, Ordering};
#[derive(Default)]
struct Fake {
running: AtomicBool,
last: Mutex<Option<LaunchParams>>,
}
impl Handler for Arc<Fake> {
fn state(&self, name: &str) -> Option<AppState> {
(name == "YouTube").then(|| if self.running.load(Ordering::SeqCst) { AppState::Running } else { AppState::Stopped })
}
fn launch(&self, _name: &str, params: LaunchParams) -> Result<()> {
self.running.store(true, Ordering::SeqCst);
*self.last.lock().unwrap() = Some(params);
Ok(())
}
fn stop(&self, _name: &str) -> bool {
self.running.swap(false, Ordering::SeqCst)
}
}
fn req(method: &str, path: &str, body: &str, origin: Option<&str>) -> Request {
let mut headers = vec![];
if let Some(o) = origin {
headers.push(("Origin".to_string(), o.to_string()));
}
Request { method: method.into(), path: path.into(), query: String::new(), headers, body: body.as_bytes().to_vec() }
}
#[test]
fn launch_status_stop() {
let fake = Arc::new(Fake::default());
let s = Server { config: Config::default(), handler: fake.clone(), data: Mutex::default() };
let peer: SocketAddr = "10.0.0.20:5555".parse().unwrap();
let local: Option<SocketAddr> = Some("10.0.0.7:56789".parse().unwrap());
let dd = s.route(&req("GET", "/dd.xml", "", None), peer, local);
assert_eq!(dd.status, 200);
assert!(dd.headers.iter().any(|(k, v)| k == "Application-URL" && v == "http://10.0.0.7:56789/apps/"));
let st = s.route(&req("GET", "/apps/YouTube", "", None), peer, local);
assert!(String::from_utf8_lossy(&st.body).contains("<state>stopped</state>"));
assert_eq!(s.route(&req("GET", "/apps/Netflix", "", None), peer, local).status, 404);
let r = s.route(&req("POST", "/apps/YouTube", "pairingCode=abc&v=xyz", None), peer, local);
assert_eq!(r.status, 201);
assert!(r.headers.iter().any(|(k, v)| k == "Location" && v == "http://10.0.0.7:56789/apps/YouTube/run"));
let q = fake.last.lock().unwrap().as_ref().unwrap().query();
assert_eq!(q, "pairingCode=abc&v=xyz&additionalDataUrl=http%3A%2F%2Flocalhost%3A56789%2Fapps%2FYouTube%2Fdial_data");
s.route(&req("POST", "/apps/YouTube/dial_data", "screenId=s1&x<y=1", None), peer, local);
let st = s.route(&req("GET", "/apps/YouTube", "", None), peer, local);
let body = String::from_utf8_lossy(&st.body).into_owned();
assert!(body.contains("<state>running</state>"));
assert!(body.contains("<additionalData><screenId>s1</screenId></additionalData>"));
assert_eq!(s.route(&req("DELETE", "/apps/YouTube/run", "", None), peer, local).status, 200);
assert_eq!(s.route(&req("DELETE", "/apps/YouTube/run", "", None), peer, local).status, 404);
}
#[test]
fn refuses_foreign_web_origins() {
let s = Server { config: Config::default(), handler: Arc::new(Fake::default()), data: Mutex::default() };
let peer: SocketAddr = "10.0.0.20:5555".parse().unwrap();
assert_eq!(s.route(&req("POST", "/apps/YouTube", "", Some("https://evil.example")), peer, None).status, 403);
assert_eq!(s.route(&req("POST", "/apps/YouTube", "", Some("https://www.youtube.com")), peer, None).status, 201);
assert_eq!(s.route(&req("POST", "/apps/YouTube", "", Some("package:com.google.android.youtube")), peer, None).status, 201);
}
#[test]
fn uuid_from_machine_id_is_stable() {
assert_eq!(uuid_from_machine_id("0123456789abcdef0123456789ABCDEF\n"), "01234567-89ab-cdef-0123-456789abcdef");
assert_eq!(uuid_from_machine_id("short"), Config::default().uuid);
}
}

197
crates/sf-dial/src/ssdp.rs Normal file
View File

@@ -0,0 +1,197 @@
//! SSDP: answers M-SEARCH for the DIAL service and announces the TV with
//! NOTIFY, so phones on the same network find it.
use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, UdpSocket as StdUdp};
use std::sync::Arc;
use std::time::Duration;
use anyhow::{Context, Result};
use socket2::{Domain, Protocol, Socket, Type};
use tokio::net::UdpSocket;
pub const DIAL_ST: &str = "urn:dial-multiscreen-org:service:dial:1";
const GROUP: Ipv4Addr = Ipv4Addr::new(239, 255, 255, 250);
const PORT: u16 = 1900;
const MAX_AGE: u32 = 1800;
#[derive(Clone)]
pub struct Announce {
pub uuid: String,
pub http_port: u16,
pub server: String,
}
impl Announce {
fn location(&self, ip: Ipv4Addr) -> String {
format!("http://{ip}:{}/dd.xml", self.http_port)
}
fn usn(&self, st: &str) -> String {
if st == format!("uuid:{}", self.uuid) {
st.to_string()
} else {
format!("uuid:{}::{st}", self.uuid)
}
}
/// Unicast answer to an M-SEARCH.
pub fn search_response(&self, st: &str, ip: Ipv4Addr) -> String {
format!(
"HTTP/1.1 200 OK\r\nCACHE-CONTROL: max-age={MAX_AGE}\r\nEXT:\r\nLOCATION: {}\r\nSERVER: {}\r\nST: {st}\r\nUSN: {}\r\nBOOTID.UPNP.ORG: 1\r\nCONFIGID.UPNP.ORG: 1\r\n\r\n",
self.location(ip),
self.server,
self.usn(st),
)
}
fn notify(&self, nt: &str, ip: Ipv4Addr) -> String {
format!(
"NOTIFY * HTTP/1.1\r\nHOST: 239.255.255.250:1900\r\nCACHE-CONTROL: max-age={MAX_AGE}\r\nLOCATION: {}\r\nNT: {nt}\r\nNTS: ssdp:alive\r\nSERVER: {}\r\nUSN: {}\r\nBOOTID.UPNP.ORG: 1\r\nCONFIGID.UPNP.ORG: 1\r\n\r\n",
self.location(ip),
self.server,
self.usn(nt),
)
}
/// Which search targets we answer, for an M-SEARCH `ST` header.
pub fn targets_for(&self, st: &str) -> Vec<String> {
let own = format!("uuid:{}", self.uuid);
match st {
"ssdp:all" => vec![DIAL_ST.into(), "upnp:rootdevice".into(), own],
"upnp:rootdevice" => vec!["upnp:rootdevice".into()],
s if s == DIAL_ST || s == own => vec![s.to_string()],
_ => vec![],
}
}
}
/// The local address used to reach `peer` (picks the right interface).
pub fn local_ip_for(peer: Ipv4Addr) -> Option<Ipv4Addr> {
let s = StdUdp::bind("0.0.0.0:0").ok()?;
s.connect(SocketAddrV4::new(peer, PORT)).ok()?;
match s.local_addr().ok()? {
SocketAddr::V4(a) if !a.ip().is_unspecified() => Some(*a.ip()),
_ => None,
}
}
fn bind_multicast() -> Result<UdpSocket> {
let sock = Socket::new(Domain::IPV4, Type::DGRAM, Some(Protocol::UDP))?;
sock.set_reuse_address(true)?;
#[cfg(unix)]
sock.set_reuse_port(true)?;
sock.bind(&SocketAddr::from((Ipv4Addr::UNSPECIFIED, PORT)).into()).context("binding udp/1900")?;
sock.set_nonblocking(true)?;
sock.set_multicast_loop_v4(true)?;
sock.set_multicast_ttl_v4(2)?;
Ok(UdpSocket::from_std(sock.into())?)
}
fn parse_search(text: &str) -> Option<(String, u64)> {
let mut lines = text.split("\r\n");
if !lines.next()?.starts_with("M-SEARCH") {
return None;
}
let mut st = None;
let mut mx = 1u64;
let mut man_ok = false;
for line in lines {
let Some((k, v)) = line.split_once(':') else { continue };
let v = v.trim();
match k.trim().to_ascii_uppercase().as_str() {
"ST" => st = Some(v.to_string()),
"MX" => mx = v.parse().unwrap_or(1),
"MAN" => man_ok = v.trim_matches('"') == "ssdp:discover",
_ => {}
}
}
man_ok.then_some(())?;
Some((st?, mx.clamp(1, 5)))
}
/// Runs forever: answers searches and re-announces every few minutes.
pub async fn run(announce: Announce) -> Result<()> {
let sock = Arc::new(bind_multicast()?);
// Joining fails while the network is down; keep retrying.
let joiner = sock.clone();
let notifier_ann = announce.clone();
tokio::spawn(async move {
let mut joined = false;
let mut tick = 0u32;
loop {
if !joined {
match joiner.join_multicast_v4(GROUP, Ipv4Addr::UNSPECIFIED) {
Ok(()) => {
log::info!("ssdp: listening on 239.255.255.250:1900");
joined = true;
tick = 0;
}
Err(e) => log::debug!("ssdp: join: {e}"),
}
}
// Announce soon after joining, then every 5 minutes.
if joined && tick % 60 == 1 {
if let Some(ip) = local_ip_for(GROUP) {
for nt in ["upnp:rootdevice", DIAL_ST] {
let msg = notifier_ann.notify(nt, ip);
let _ = joiner.send_to(msg.as_bytes(), (GROUP, PORT)).await;
}
}
}
tick = tick.wrapping_add(1);
tokio::time::sleep(Duration::from_secs(5)).await;
}
});
let mut buf = [0u8; 2048];
loop {
let (n, from) = match sock.recv_from(&mut buf).await {
Ok(v) => v,
Err(e) => {
log::debug!("ssdp recv: {e}");
continue;
}
};
let Ok(text) = std::str::from_utf8(&buf[..n]) else { continue };
let Some((st, mx)) = parse_search(text) else { continue };
let SocketAddr::V4(peer) = from else { continue };
let targets = announce.targets_for(&st);
if targets.is_empty() {
continue;
}
let Some(ip) = local_ip_for(*peer.ip()) else { continue };
log::debug!("ssdp: M-SEARCH {st} from {peer}");
let sock = sock.clone();
let announce = announce.clone();
tokio::spawn(async move {
// Spread replies over part of MX, as the spec asks.
let delay = (u64::from(peer.port()) * 37 % (mx * 250)).min(900);
tokio::time::sleep(Duration::from_millis(delay)).await;
for t in targets {
let _ = sock.send_to(announce.search_response(&t, ip).as_bytes(), peer).await;
}
});
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_m_search() {
let msg = "M-SEARCH * HTTP/1.1\r\nHOST: 239.255.255.250:1900\r\nMAN: \"ssdp:discover\"\r\nMX: 1\r\nST: urn:dial-multiscreen-org:service:dial:1\r\n\r\n";
assert_eq!(parse_search(msg), Some((DIAL_ST.to_string(), 1)));
assert_eq!(parse_search("NOTIFY * HTTP/1.1\r\n\r\n"), None);
}
#[test]
fn answers_only_known_targets() {
let a = Announce { uuid: "abc".into(), http_port: 56789, server: "x".into() };
assert_eq!(a.targets_for(DIAL_ST), vec![DIAL_ST.to_string()]);
assert!(a.targets_for("urn:schemas-upnp-org:device:MediaRenderer:1").is_empty());
let r = a.search_response(DIAL_ST, Ipv4Addr::new(10, 0, 0, 7));
assert!(r.contains("LOCATION: http://10.0.0.7:56789/dd.xml\r\n"));
assert!(r.contains("USN: uuid:abc::urn:dial-multiscreen-org:service:dial:1\r\n"));
}
}

View File

@@ -1,11 +1,12 @@
[package] [package]
name = "sf-ipc" name = "sf-ipc"
description = "Shared types for SmartFox: 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 version.workspace = true
edition.workspace = true edition.workspace = true
license.workspace = true license.workspace = true
[dependencies] [dependencies]
sf-app.workspace = true
serde.workspace = true serde.workspace = true
serde_json.workspace = true serde_json.workspace = true
toml.workspace = true toml.workspace = true

View File

@@ -1,9 +1,17 @@
//! Shared types for SmartFox components (launcher, core daemon, remote daemon). //! Shared types for Fennec OS components (launcher, core daemon, remote daemon,
//! 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 manifest; pub mod manifest;
pub mod message; pub mod message;
pub mod settings; pub mod paths;
pub mod store;
pub use manifest::{AppKind, AppManifest, load_apps}; pub use manifest::{AppKind, AppManifest, Origin, Permission, load_apps};
pub use message::{CoreEvent, LauncherRequest}; pub use message::{CoreEvent, LauncherRequest};
pub use settings::Settings; pub use settings::Settings;

View File

@@ -1,195 +1,110 @@
//! App manifests: one `app.toml` per folder under the apps directory. //! 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::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use anyhow::{Context, Result}; use anyhow::Result;
use serde::{Deserialize, Serialize};
use crate::settings::Settings; pub use sf_app::manifest::*;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] /// The Fennec catalog: the store source with the Bluefox apps.
#[serde(rename_all = "lowercase")] pub const FENNEC_CATALOG: &str = "https://gitea.bluefox.support/fennec/store";
pub enum AppKind {
/// Runs in the shared Chromium web runtime. /// A factory app that became a store app (its own repo, Fennec catalog).
Web, pub struct Retired {
/// Any executable: AppImage, Rust binary, script. /// The old official id (`apps/<id>`, `sf-app-<id>`).
Exec, pub id: &'static str,
/// Built into the launcher (e.g. settings screen). /// The store app that replaces it.
Builtin, 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,
} }
#[derive(Debug, Clone, Serialize, Deserialize)] pub const RETIRED: &[Retired] = &[
pub struct AppManifest { Retired {
pub id: String, // The Netflex web app; the native app keeps its own login.
pub name: String, id: "netflex",
pub kind: AppKind, replacement: "support.bluefox.netflex",
/// Package version (semver). Published as `sf-app-<id>` when it changes; source: "https://gitea.bluefox.support/fennec/netflex",
/// the newer of a factory and an installed copy wins. permissions: &[Permission::Network, Permission::Gpu, Permission::Audio],
#[serde(default = "default_version")] move_data: false,
pub version: String, },
/// Short label above the title in the hero ("Saját app", "Castolás"...). Retired {
#[serde(default)] id: "youtube",
pub category: String, replacement: "support.bluefox.youtube",
#[serde(default)] source: "https://gitea.bluefox.support/fennec/youtube",
pub description: String, permissions: &[Permission::Network, Permission::Gpu, Permission::Audio, Permission::Dial],
/// Web apps: start URL. May contain `${settings.<key>}` placeholders. move_data: true,
#[serde(default)] },
pub url: Option<String>, Retired {
/// Exec apps: command line. id: "steam",
#[serde(default)] replacement: "support.bluefox.steam",
pub exec: Option<Vec<String>>, source: "https://gitea.bluefox.support/fennec/steam",
/// Built-in icon name used by the launcher. permissions: &[Permission::Network, Permission::Gpu, Permission::Audio, Permission::Gamepad, Permission::DbusSession],
#[serde(default)] move_data: true,
pub icon: String, },
/// Accent color (hex), used for focus glow and buttons. ];
#[serde(default = "default_accent")]
pub accent: String, pub fn retired(id: &str) -> Option<&'static Retired> {
/// Three colors for the animated hero backdrop: highlight, mid, deep. RETIRED.iter().find(|r| r.id == id)
#[serde(default)]
pub palette: Vec<String>,
/// Sort order on the home row.
#[serde(default)]
pub order: i32,
#[serde(default)]
pub web: WebOptions,
#[serde(default)]
pub dial: Option<DialOptions>,
/// 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,
/// Folder the manifest was loaded from (not serialized).
#[serde(skip)]
pub dir: PathBuf,
} }
#[derive(Debug, Clone, Default, Serialize, Deserialize)] pub fn is_retired(id: &str) -> bool {
pub struct WebOptions { retired(id).is_some()
/// Full user agent override.
#[serde(default)]
pub user_agent: Option<String>,
/// Appended to the default user agent.
#[serde(default)]
pub user_agent_suffix: Option<String>,
/// Unpacked extensions to load (paths relative to the app folder).
#[serde(default)]
pub extensions: Vec<String>,
} }
#[derive(Debug, Clone, Serialize, Deserialize)] /// `sf_app::manifest::load_all`, where a retired official app (the old
pub struct DialOptions { /// factory copy in an older image, or its `sf-app-<id>` package) stays only
/// DIAL application name, e.g. "YouTube". /// until its store replacement is installed: the TV never loses the app.
pub name: String, pub fn load_all(dirs: &[PathBuf], store: Option<&Path>) -> Result<Vec<AppManifest>> {
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<bool> = 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())
} }
fn default_version() -> String { /// Moves the data folder of a retired app to its replacement, once the
"0.0.0".into() /// 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) {
fn default_accent() -> String { if !apps.iter().any(|a| a.origin == Origin::Store && a.id == r.replacement) {
"#ffffff".into()
}
impl AppManifest {
/// Start URL with `${settings.key}` placeholders filled in.
pub fn resolved_url(&self, settings: &Settings) -> Option<String> {
self.url.as_ref().map(|u| settings.expand(u))
}
}
/// Loads every `*/app.toml` under `dir`, sorted by `order` then name.
pub fn load_apps(dir: &Path) -> Result<Vec<AppManifest>> {
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; continue;
} }
match load_one(&path) { let (old, new) = (sf_app::paths::app_data_dir(r.id), sf_app::paths::app_data_dir(r.replacement));
Ok(app) => apps.push(app), if old.is_dir() && std::fs::symlink_metadata(&new).is_err() {
Err(e) => log::warn!("skipping {}: {e:#}", path.display()), 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)
}
/// 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<Vec<AppManifest>> {
let mut apps: Vec<AppManifest> = Vec::new();
let mut found = false;
for dir in dirs {
if !dir.is_dir() {
continue;
}
found = true;
for app in load_apps(dir)? {
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)
}
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"); 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<u64> { v.split(['.', '-', '+']).take(3).map(|p| p.parse().unwrap_or(0)).collect() };
let (a, b) = (parts(a), parts(b));
(0..3).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<AppManifest> {
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)] #[cfg(test)]
mod tests { mod tests {
use super::*; use super::*;
#[test] fn write(dir: &Path, id: &str, body: &str) {
fn parses_web_manifest() { std::fs::create_dir_all(dir.join(id)).unwrap();
let app: AppManifest = toml::from_str( std::fs::write(dir.join(id).join("app.toml"), format!("id = \"{id}\"\nname = \"{id}\"\n{body}")).unwrap();
r##"
id = "netflex"
name = "Netflex"
kind = "web"
url = "${settings.netflex_server}/"
accent = "#E50914"
palette = ["#ff3b3b", "#7a0a10", "#0c0203"]
[web]
user_agent_suffix = "SMART-TV SmartFox/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");
} }
#[test] #[test]
fn compares_versions() { fn retired_app_stays_until_replaced() {
use std::cmp::Ordering::*; let base = std::env::temp_dir().join(format!("sf-ipc-retired-{}", std::process::id()));
assert_eq!(version_cmp("1.10.0", "1.9.2"), Greater); let (factory, store) = (base.join("factory"), base.join("store"));
assert_eq!(version_cmp("0.2", "0.2.0"), Equal); write(&factory, "youtube", "kind = \"web\"\nurl = \"https://www.youtube.com/tv\"\n");
assert_eq!(version_cmp("0.1.9", "0.2.0"), Less); write(&factory, "settings", "kind = \"builtin\"\n");
let ids = |apps: Vec<AppManifest>| apps.into_iter().map(|a| a.id).collect::<Vec<_>>();
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();
} }
} }

View File

@@ -1,23 +1,81 @@
//! Messages between the launcher and the core daemon (newline-delimited JSON //! Messages between the launcher and the core daemon: newline-delimited JSON
//! over a unix socket). The core daemon itself comes in phase 3. //! over the core socket (`paths::core_socket`).
//!
//! The launcher sends `LauncherRequest`s; the core sends `CoreEvent`s to
//! every connected client (and `Hello` right after connecting).
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")] #[serde(tag = "type", rename_all = "snake_case")]
pub enum LauncherRequest { pub enum LauncherRequest {
Launch { app_id: String }, /// Start the app (the one on screen closes).
/// Bring the launcher back to the front (freezes the foreground app). Launch {
app_id: String,
/// Extra query string for the start URL (DIAL uses this).
#[serde(default, skip_serializing_if = "Option::is_none")]
query: Option<String>,
},
/// Show the launcher. The app on screen closes.
GoHome, GoHome,
SetSetting { key: String, value: String }, /// Close the app.
Stop { app_id: String },
} }
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")] #[serde(tag = "type", rename_all = "snake_case")]
pub enum CoreEvent { pub enum CoreEvent {
AppStarted { app_id: String }, /// First message on every connection.
Hello {
/// True if the compositor can switch windows (sf-compositor, not cage).
switching: bool,
/// The app in the foreground, if any.
#[serde(default)]
foreground: Option<String>,
},
/// An app came to the front: newly started or thawed.
AppStarted {
app_id: String,
/// Started from a phone (DIAL), not from the launcher.
#[serde(default)]
cast: bool,
},
/// The app's process ended.
AppStopped { app_id: String }, AppStopped { app_id: String },
/// Something connected over DIAL/AirPlay/Miracast. /// Something connected over DIAL/AirPlay/Miracast.
CastConnected { app_id: String, device: String }, CastConnected { app_id: String, device: String },
/// The cast session ended.
CastEnded { app_id: String },
Toast { text: String }, Toast { text: String },
} }
impl LauncherRequest {
pub fn to_line(&self) -> String {
let mut s = serde_json::to_string(self).unwrap_or_default();
s.push('\n');
s
}
}
impl CoreEvent {
pub fn to_line(&self) -> String {
let mut s = serde_json::to_string(self).unwrap_or_default();
s.push('\n');
s
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_trips() {
let r = LauncherRequest::Launch { app_id: "youtube".into(), query: None };
assert_eq!(r.to_line(), "{\"type\":\"launch\",\"app_id\":\"youtube\"}\n");
let back: LauncherRequest = serde_json::from_str(r.to_line().trim()).unwrap();
assert_eq!(back, r);
let e: CoreEvent = serde_json::from_str(r#"{"type":"app_started","app_id":"netflex"}"#).unwrap();
assert_eq!(e, CoreEvent::AppStarted { app_id: "netflex".into(), cast: false });
}
}

View File

@@ -0,0 +1,52 @@
//! 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};
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) {
Some(p) => p.into(),
None => runtime_dir().join(default),
}
}
/// Launcher command socket (`home`, `remote <state>`, `power`, `wake`).
pub fn launcher_socket() -> PathBuf {
from_env("SMARTFOX_SOCKET", "smartfox.sock")
}
/// sf-core: app lifecycle (JSON lines, see `message`).
pub fn core_socket() -> PathBuf {
from_env("SMARTFOX_CORE_SOCKET", "smartfox-core.sock")
}
/// sf-compositor control socket (`focus launcher`, `focus <app-id>`).
pub fn wm_socket() -> PathBuf {
from_env("SMARTFOX_WM_SOCKET", "smartfox-wm.sock")
}
/// Installed store apps (`/var/lib/sf-pkg/store/apps/<id>`), written by sf-update.
pub const STORE_APPS: &str = "/var/lib/sf-pkg/store/apps";
/// Looks for an `apps` folder next to the binary or above the cwd (dev
/// checkout), else the installed one.
pub fn apps_dir() -> PathBuf {
let mut starts = vec![];
if let Ok(cwd) = std::env::current_dir() {
starts.push(cwd);
}
if let Ok(exe) = std::env::current_exe() {
starts.extend(exe.parent().map(Path::to_path_buf));
}
for start in starts {
for dir in start.ancestors() {
let candidate = dir.join("apps");
if candidate.join("settings").join("app.toml").is_file() {
return candidate;
}
}
}
PathBuf::from("/usr/share/smartfox/apps")
}

View File

@@ -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<String, String>,
}
impl Settings {
/// Missing file means default settings.
pub fn load(path: &Path) -> Result<Self> {
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
}
}

180
crates/sf-ipc/src/store.rs Normal file
View File

@@ -0,0 +1,180 @@
//! The app store's files, shared by the launcher and sf-update (docs/store.md).
//!
//! /var/lib/smartfox/store.toml what the user wants: sources, apps and
//! the permissions they approved (the
//! launcher writes it, user tv)
//! /var/lib/sf-pkg/store/catalog.json what the sources offer, and why an
//! update is held back (sf-update, root)
//! /var/lib/sf-pkg/store/apps/<id> installed store apps (sf-update)
use std::collections::BTreeMap;
use std::path::Path;
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use crate::manifest::Permission;
pub const WANTED_FILE: &str = "/var/lib/smartfox/store.toml";
pub const CATALOG_FILE: &str = "/var/lib/sf-pkg/store/catalog.json";
/// Package (folder) name of a store app in /var/lib/sf-pkg.
pub const PACKAGE_PREFIX: &str = "store-";
/// The file a catalog repo keeps on its default branch.
pub const INDEX_FILE: &str = "smartfox-store.toml";
/// Largest store.toml sf-update reads.
pub const MAX_WANTED: u64 = 256 * 1024;
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct Wanted {
/// Repos the user added: app repos and catalogs.
#[serde(default)]
pub sources: Vec<String>,
/// Installed (or to be installed) apps by id.
#[serde(default)]
pub apps: BTreeMap<String, WantedApp>,
}
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
pub struct WantedApp {
/// The repo the app comes from (canonical https URL).
pub source: String,
/// Permissions the user approved; an update that asks for more waits
/// for a new approval.
#[serde(default)]
pub permissions: Vec<Permission>,
}
impl Wanted {
pub fn parse(text: &str) -> Result<Wanted> {
toml::from_str(text).context("store.toml")
}
pub fn load(path: &Path) -> Result<Wanted> {
match std::fs::read_to_string(path) {
Ok(text) => Wanted::parse(&text),
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Wanted::default()),
Err(e) => Err(e).with_context(|| format!("reading {}", path.display())),
}
}
/// Writes atomically (the updater may read it at any time).
pub fn save(&self, path: &Path) -> Result<()> {
let tmp = path.with_extension("toml.tmp");
std::fs::write(&tmp, toml::to_string_pretty(self)?).with_context(|| format!("writing {}", tmp.display()))?;
std::fs::rename(&tmp, path).with_context(|| format!("writing {}", path.display()))?;
Ok(())
}
}
/// `smartfox-store.toml` in a catalog repo.
#[derive(Debug, Clone, Default, Deserialize)]
pub struct Index {
#[serde(default)]
pub name: String,
#[serde(default)]
pub description: String,
/// App repo addresses.
#[serde(default)]
pub apps: Vec<String>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Catalog {
/// Unix time of the last refresh (0: never).
#[serde(default)]
pub updated_at: u64,
#[serde(default)]
pub sources: Vec<SourceInfo>,
#[serde(default)]
pub apps: Vec<CatalogApp>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct SourceInfo {
/// As in store.toml.
pub url: String,
/// "app" or "catalog"
#[serde(default)]
pub kind: String,
#[serde(default)]
pub name: String,
/// Apps found in it.
#[serde(default)]
pub apps: usize,
#[serde(default)]
pub error: Option<String>,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct CatalogApp {
pub id: String,
pub name: String,
pub version: String,
#[serde(default)]
pub kind: String,
#[serde(default)]
pub category: String,
#[serde(default)]
pub description: String,
#[serde(default)]
pub author: String,
#[serde(default)]
pub homepage: String,
#[serde(default)]
pub license: String,
#[serde(default)]
pub accent: String,
#[serde(default)]
pub permissions: Vec<Permission>,
/// The app's repo (canonical https URL).
pub source: String,
/// The catalog it was listed in, if any.
#[serde(default)]
pub catalog: Option<String>,
pub package_url: String,
/// Installed version, if any.
#[serde(default)]
pub installed: Option<String>,
/// Why the newest version isn't installed: "permissions" (asks for more
/// than approved).
#[serde(default)]
pub blocked: Option<String>,
}
impl Catalog {
pub fn load(path: &Path) -> Option<Catalog> {
serde_json::from_str(&std::fs::read_to_string(path).ok()?).ok()
}
pub fn app(&self, id: &str) -> Option<&CatalogApp> {
self.apps.iter().find(|a| a.id == id)
}
}
/// Permissions in `want` that `approved` doesn't have.
pub fn missing_permissions(want: &[Permission], approved: &[Permission]) -> Vec<Permission> {
want.iter().filter(|p| !approved.contains(p)).copied().collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn wanted_round_trip() {
let w = Wanted::parse(
r#"
sources = ["https://github.com/fox/store"]
[apps."io.github.fox.hello"]
source = "https://github.com/fox/hello"
permissions = ["network", "audio"]
"#,
)
.unwrap();
assert_eq!(w.apps["io.github.fox.hello"].permissions, [Permission::Network, Permission::Audio]);
let again = Wanted::parse(&toml::to_string_pretty(&w).unwrap()).unwrap();
assert_eq!(w, again);
assert!(Wanted::parse("[apps.x]\nsource = 'a'\npermissions = ['root']\n").is_err());
assert_eq!(missing_permissions(&[Permission::Network, Permission::Gpu], &[Permission::Network]), [Permission::Gpu]);
}
}

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "sf-launcher" name = "sf-launcher"
description = "SmartFox TV launcher: Slint UI on top of a Liquid Glass OpenGL layer" description = "Fennec OS TV launcher: Slint UI on top of a Liquid Glass OpenGL layer"
version.workspace = true version.workspace = true
edition.workspace = true edition.workspace = true
# Slint is used under GPL-3.0 (or its royalty-free license on desktop). # Slint is used under GPL-3.0 (or its royalty-free license on desktop).
@@ -8,11 +8,14 @@ license = "GPL-3.0-only"
[dependencies] [dependencies]
sf-ipc.workspace = true sf-ipc.workspace = true
sf-ui = { workspace = true, default-features = false }
anyhow.workspace = true anyhow.workspace = true
log.workspace = true log.workspace = true
env_logger.workspace = true env_logger.workspace = true
serde_json.workspace = true serde_json.workspace = true
slint = { version = "1.18", default-features = false, features = ["std", "backend-default", "renderer-femtovg", "compat-1-2"] } serde.workspace = true
ureq = "3"
slint = { version = "1.18", default-features = false, features = ["std", "backend-default", "renderer-femtovg", "compat-1-2", "image-default-formats"] }
glow = "0.16" glow = "0.16"
png = "0.18" png = "0.18"
chrono = { version = "0.4", default-features = false, features = ["clock", "std"] } chrono = { version = "0.4", default-features = false, features = ["clock", "std"] }

View File

@@ -1,3 +1,7 @@
fn main() { fn main() {
slint_build::compile("ui/app.slint").expect("compiling ui/app.slint"); // The Onest font comes from sf-ui's Slint library ("@sf-ui/fonts/...").
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/app.slint", config).expect("compiling ui/app.slint");
} }

View File

@@ -0,0 +1,65 @@
#![cfg_attr(not(unix), allow(dead_code))]
//! Connection to sf-core. On the TV sf-core starts and closes apps;
//! without it (desktop testing) the launcher starts apps itself.
use sf_ipc::{CoreEvent, LauncherRequest};
#[derive(Clone)]
pub struct CoreClient {
#[cfg(unix)]
stream: std::sync::Arc<std::sync::Mutex<std::os::unix::net::UnixStream>>,
}
impl CoreClient {
/// Connects if sf-core is running. `on_event` runs on the Slint event loop.
#[cfg(unix)]
pub fn connect(on_event: impl Fn(CoreEvent) + Send + Sync + Clone + 'static) -> Option<Self> {
use std::io::{BufRead, BufReader};
use std::os::unix::net::UnixStream;
let path = sf_ipc::paths::core_socket();
// sf-core may start a moment after the launcher.
let stream = (0..20).find_map(|i| {
if i > 0 {
std::thread::sleep(std::time::Duration::from_millis(100));
}
UnixStream::connect(&path).ok()
});
let Some(stream) = stream else {
log::info!("no sf-core at {}, starting apps locally", path.display());
return None;
};
log::info!("connected to sf-core");
let reader = stream.try_clone().ok()?;
std::thread::spawn(move || {
for line in BufReader::new(reader).lines().map_while(Result::ok) {
match serde_json::from_str::<CoreEvent>(&line) {
Ok(ev) => {
let f = on_event.clone();
let _ = slint::invoke_from_event_loop(move || f(ev));
}
Err(e) => log::warn!("sf-core: bad event {line:?}: {e}"),
}
}
log::warn!("sf-core connection closed");
});
Some(CoreClient { stream: std::sync::Arc::new(std::sync::Mutex::new(stream)) })
}
#[cfg(not(unix))]
pub fn connect(_on_event: impl Fn(CoreEvent) + Send + Sync + Clone + 'static) -> Option<Self> {
None
}
pub fn send(&self, req: LauncherRequest) {
#[cfg(unix)]
{
use std::io::Write;
if let Err(e) = self.stream.lock().unwrap().write_all(req.to_line().as_bytes()) {
log::error!("sf-core: {e}");
}
}
#[cfg(not(unix))]
let _ = req;
}
}

View File

@@ -17,7 +17,7 @@ use slint::ComponentHandle;
use slint::platform::{Key, WindowEvent}; use slint::platform::{Key, WindowEvent};
use crate::App; use crate::App;
use crate::glass::GlassRenderer; use sf_ui::render::GlassRenderer;
pub struct Snapshot { pub struct Snapshot {
path: Option<PathBuf>, path: Option<PathBuf>,
@@ -86,6 +86,11 @@ pub fn setup(ui: &App) -> Snapshot {
} }
impl Snapshot { impl Snapshot {
/// A snapshot is still to be taken: keep frames coming until then.
pub fn pending(&self) -> bool {
self.path.is_some()
}
pub fn capture_if_due(&self, ui: &App, r: &GlassRenderer) { pub fn capture_if_due(&self, ui: &App, r: &GlassRenderer) {
if !self.due.get() { if !self.due.get() {
return; return;

View File

@@ -1,49 +0,0 @@
//! "Liquid Glass" layer: an OpenGL pass under the Slint UI that draws the
//! animated backdrop and the frosted, refracting glass panels.
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 physical pixels (top-left origin).
#[derive(Debug, Clone, Copy)]
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,
/// Mip level used for the frost (higher = blurrier). Negative = nested glass.
pub blur: f32,
pub glow: [f32; 3],
/// Consecutive panels with the same group (> 0) melt into one shape.
pub group: f32,
/// rgb + amount.
pub tint: [f32; 4],
}
/// Everything the renderer needs for one frame.
#[derive(Debug, Clone)]
pub struct Frame {
pub width: u32,
pub height: u32,
pub scale: f32,
pub time: f32,
/// Backdrop palette (highlight, mid, deep), already crossfaded.
pub palette: [f32; 9],
/// 1 = top shelf visible (bright backdrop), 0 = scrolled down into the grid.
pub shelf: f32,
pub light: [f32; 2],
/// Backdrop zoom (1 = none), used for the launch fly-in.
pub zoom: f32,
pub rects: Vec<Panel>,
}

View File

@@ -1,425 +0,0 @@
//! OpenGL underlay drawn before Slint renders its items.
//!
//! Pass 1 renders the backdrop (a smooth gradient) into a small, mipmapped
//! texture. Pass 2 upscales it to the window. Pass 3 draws every glass panel
//! as its own quad, covering only the panel and its shadow, blended onto the
//! window. Uniform locations are looked up once.
use glow::HasContext;
use super::shaders;
use super::{Frame, MAX_GROUP, MAX_RECTS, Panel};
/// The backdrop is blurry by design, so it never needs more than this width.
const SCENE_MAX_W: i32 = 640;
type Loc = Option<glow::UniformLocation>;
struct SceneLocs {
res: Loc,
time: Loc,
pal: Loc,
zoom: Loc,
shelf: Loc,
}
struct BlitLocs {
scene: Loc,
time: 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,
}
pub struct GlassRenderer {
gl: glow::Context,
vao: glow::VertexArray,
scene_prog: glow::Program,
blit_prog: glow::Program,
glass_prog: glow::Program,
scene_locs: SceneLocs,
blit_locs: BlitLocs,
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,
}
/// GL state we touch and must hand back to the Slint renderer untouched.
struct SavedState {
program: i32,
vao: i32,
array_buffer: i32,
framebuffer: i32,
active_texture: i32,
texture0: i32,
viewport: [i32; 4],
blend: bool,
blend_func: [i32; 4],
blend_eq: [i32; 2],
scissor: bool,
depth: bool,
stencil: bool,
cull: bool,
}
impl GlassRenderer {
/// # Safety
/// Must be called with the Slint OpenGL context current.
pub unsafe fn new(gl: glow::Context) -> anyhow::Result<Self> {
unsafe {
let version = gl.get_parameter_string(glow::VERSION);
let is_es = version.contains("OpenGL ES");
log::info!("OpenGL: {version} ({})", gl.get_parameter_string(glow::RENDERER));
let header = if is_es {
"#version 300 es\nprecision highp float;\nprecision highp int;\n"
} else {
"#version 330 core\n"
};
let scene_prog = link(&gl, header, shaders::VERTEX, shaders::SCENE)?;
let blit_prog = link(&gl, header, shaders::VERTEX, shaders::BLIT)?;
let glass_prog = link(&gl, header, shaders::QUAD_VERTEX, shaders::GLASS)?;
let loc = |p: glow::Program, name: &str| gl.get_uniform_location(p, name);
let scene_locs = SceneLocs {
res: loc(scene_prog, "uRes"),
time: loc(scene_prog, "uTime"),
pal: loc(scene_prog, "uPal"),
zoom: loc(scene_prog, "uZoom"),
shelf: loc(scene_prog, "uShelf"),
};
let blit_locs = BlitLocs { scene: loc(blit_prog, "uScene"), time: loc(blit_prog, "uTime") };
let glass_locs = GlassLocs {
box_: loc(glass_prog, "uBox"),
res: loc(glass_prog, "uRes"),
scene: loc(glass_prog, "uScene"),
scale: loc(glass_prog, "uScale"),
time: loc(glass_prog, "uTime"),
light: loc(glass_prog, "uLight"),
count: loc(glass_prog, "uCount"),
rect: loc(glass_prog, "uRect"),
param: loc(glass_prog, "uParam"),
glow: loc(glass_prog, "uGlow"),
tint: loc(glass_prog, "uTint"),
};
let vao = gl.create_vertex_array().map_err(anyhow::Error::msg)?;
let fbo = gl.create_framebuffer().map_err(anyhow::Error::msg)?;
let tex = gl.create_texture().map_err(anyhow::Error::msg)?;
Ok(Self {
gl,
vao,
scene_prog,
blit_prog,
glass_prog,
scene_locs,
blit_locs,
glass_locs,
fbo,
tex,
tex_size: (0, 0),
half_float: true,
})
}
}
unsafe fn save(&self) -> SavedState {
let gl = &self.gl;
unsafe {
let mut viewport = [0; 4];
gl.get_parameter_i32_slice(glow::VIEWPORT, &mut viewport);
let active_texture = gl.get_parameter_i32(glow::ACTIVE_TEXTURE);
gl.active_texture(glow::TEXTURE0);
SavedState {
program: gl.get_parameter_i32(glow::CURRENT_PROGRAM),
vao: gl.get_parameter_i32(glow::VERTEX_ARRAY_BINDING),
array_buffer: gl.get_parameter_i32(glow::ARRAY_BUFFER_BINDING),
framebuffer: gl.get_parameter_i32(glow::FRAMEBUFFER_BINDING),
active_texture,
texture0: gl.get_parameter_i32(glow::TEXTURE_BINDING_2D),
viewport,
blend: gl.is_enabled(glow::BLEND),
blend_func: [
gl.get_parameter_i32(glow::BLEND_SRC_RGB),
gl.get_parameter_i32(glow::BLEND_DST_RGB),
gl.get_parameter_i32(glow::BLEND_SRC_ALPHA),
gl.get_parameter_i32(glow::BLEND_DST_ALPHA),
],
blend_eq: [
gl.get_parameter_i32(glow::BLEND_EQUATION_RGB),
gl.get_parameter_i32(glow::BLEND_EQUATION_ALPHA),
],
scissor: gl.is_enabled(glow::SCISSOR_TEST),
depth: gl.is_enabled(glow::DEPTH_TEST),
stencil: gl.is_enabled(glow::STENCIL_TEST),
cull: gl.is_enabled(glow::CULL_FACE),
}
}
}
unsafe fn restore(&self, s: SavedState) {
let gl = &self.gl;
let nz = |v: i32| std::num::NonZeroU32::new(v as u32);
unsafe {
gl.use_program(nz(s.program).map(glow::NativeProgram));
gl.bind_vertex_array(nz(s.vao).map(glow::NativeVertexArray));
gl.bind_buffer(glow::ARRAY_BUFFER, nz(s.array_buffer).map(glow::NativeBuffer));
gl.bind_framebuffer(glow::FRAMEBUFFER, nz(s.framebuffer).map(glow::NativeFramebuffer));
gl.active_texture(glow::TEXTURE0);
gl.bind_texture(glow::TEXTURE_2D, nz(s.texture0).map(glow::NativeTexture));
gl.active_texture(s.active_texture as u32);
gl.viewport(s.viewport[0], s.viewport[1], s.viewport[2], s.viewport[3]);
let [sr, dr, sa, da] = s.blend_func.map(|v| v as u32);
gl.blend_func_separate(sr, dr, sa, da);
gl.blend_equation_separate(s.blend_eq[0] as u32, s.blend_eq[1] as u32);
let set = |cap, on: bool| if on { gl.enable(cap) } else { gl.disable(cap) };
set(glow::BLEND, s.blend);
set(glow::SCISSOR_TEST, s.scissor);
set(glow::DEPTH_TEST, s.depth);
set(glow::STENCIL_TEST, s.stencil);
set(glow::CULL_FACE, s.cull);
}
}
unsafe fn alloc_target(&self, w: i32, h: i32, half_float: bool) -> bool {
let gl = &self.gl;
unsafe {
gl.bind_texture(glow::TEXTURE_2D, Some(self.tex));
let (internal, ty) =
if half_float { (glow::RGBA16F, glow::HALF_FLOAT) } else { (glow::RGBA8, glow::UNSIGNED_BYTE) };
gl.tex_image_2d(
glow::TEXTURE_2D,
0,
internal as i32,
w,
h,
0,
glow::RGBA,
ty,
glow::PixelUnpackData::Slice(None),
);
gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_MIN_FILTER, glow::LINEAR_MIPMAP_LINEAR as i32);
gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_MAG_FILTER, glow::LINEAR as i32);
gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_WRAP_S, glow::CLAMP_TO_EDGE as i32);
gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_WRAP_T, glow::CLAMP_TO_EDGE as i32);
gl.generate_mipmap(glow::TEXTURE_2D);
gl.bind_framebuffer(glow::FRAMEBUFFER, Some(self.fbo));
gl.framebuffer_texture_2d(glow::FRAMEBUFFER, glow::COLOR_ATTACHMENT0, glow::TEXTURE_2D, Some(self.tex), 0);
gl.check_framebuffer_status(glow::FRAMEBUFFER) == glow::FRAMEBUFFER_COMPLETE
}
}
unsafe fn ensure_target(&mut self, w: i32, h: i32) {
if self.tex_size == (w, h) {
return;
}
unsafe {
if self.half_float && !self.alloc_target(w, h, true) {
log::info!("glass: RGBA16F not renderable, using RGBA8 for the backdrop");
self.half_float = false;
}
if !self.half_float {
self.alloc_target(w, h, false);
}
}
self.tex_size = (w, h);
}
/// # Safety
/// Must be called from the Slint rendering notifier with the context current.
pub unsafe fn render(&mut self, f: &Frame) {
let (w, h) = (f.width as i32, f.height as i32);
if w <= 0 || h <= 0 {
return;
}
unsafe {
let saved = self.save();
let gl = &self.gl;
gl.disable(glow::BLEND);
gl.disable(glow::SCISSOR_TEST);
gl.disable(glow::DEPTH_TEST);
gl.disable(glow::STENCIL_TEST);
gl.disable(glow::CULL_FACE);
gl.bind_vertex_array(Some(self.vao));
// Pass 1: backdrop at low resolution (it is a smooth gradient).
let sw = (w / 4).clamp(1, SCENE_MAX_W);
let sh = ((sw as i64 * h as i64 / w as i64) as i32).max(1);
self.ensure_target(sw, sh);
let gl = &self.gl;
gl.bind_framebuffer(glow::FRAMEBUFFER, Some(self.fbo));
gl.viewport(0, 0, sw, sh);
let l = &self.scene_locs;
gl.use_program(Some(self.scene_prog));
gl.uniform_2_f32(l.res.as_ref(), sw as f32, sh as f32);
gl.uniform_1_f32(l.time.as_ref(), f.time);
gl.uniform_3_f32_slice(l.pal.as_ref(), &f.palette);
gl.uniform_1_f32(l.zoom.as_ref(), f.zoom);
gl.uniform_1_f32(l.shelf.as_ref(), f.shelf);
gl.draw_arrays(glow::TRIANGLES, 0, 3);
gl.bind_texture(glow::TEXTURE_2D, Some(self.tex));
gl.generate_mipmap(glow::TEXTURE_2D);
// Pass 2: upscale to the window framebuffer.
gl.bind_framebuffer(
glow::FRAMEBUFFER,
std::num::NonZeroU32::new(saved.framebuffer as u32).map(glow::NativeFramebuffer),
);
gl.viewport(0, 0, w, h);
let l = &self.blit_locs;
gl.use_program(Some(self.blit_prog));
gl.uniform_1_i32(l.scene.as_ref(), 0);
gl.uniform_1_f32(l.time.as_ref(), f.time);
gl.draw_arrays(glow::TRIANGLES, 0, 3);
// Pass 3: glass, one quad per panel or merged group: dst * a + rgb.
gl.enable(glow::BLEND);
gl.blend_equation_separate(glow::FUNC_ADD, glow::FUNC_ADD);
gl.blend_func_separate(glow::ONE, glow::SRC_ALPHA, glow::ZERO, glow::ONE);
let l = &self.glass_locs;
gl.use_program(Some(self.glass_prog));
gl.uniform_1_i32(l.scene.as_ref(), 0);
gl.uniform_2_f32(l.res.as_ref(), w as f32, h as f32);
gl.uniform_1_f32(l.scale.as_ref(), f.scale);
gl.uniform_1_f32(l.time.as_ref(), f.time);
gl.uniform_2_f32(l.light.as_ref(), f.light[0], f.light[1]);
let rects = &f.rects[..f.rects.len().min(MAX_RECTS)];
let mut rect = [0f32; MAX_GROUP * 4];
let mut param = [0f32; MAX_GROUP * 4];
let mut glow_c = [0f32; MAX_GROUP * 4];
let mut tint = [0f32; MAX_GROUP * 4];
for run in runs(rects) {
let n = run.len();
// Bounds plus room for the shadow (spread + downward offset).
let margin = 132.0 * f.scale;
let (mut x0, mut y0, mut x1, mut y1) = (f32::MAX, f32::MAX, f32::MIN, f32::MIN);
for (i, r) in run.iter().enumerate() {
rect[i * 4..i * 4 + 4].copy_from_slice(&[r.x, r.y, r.w, r.h]);
param[i * 4..i * 4 + 4].copy_from_slice(&[r.radius, r.focus, r.alpha, r.blur]);
glow_c[i * 4..i * 4 + 4].copy_from_slice(&[r.glow[0], r.glow[1], r.glow[2], 0.0]);
tint[i * 4..i * 4 + 4].copy_from_slice(&r.tint);
x0 = x0.min(r.x);
y0 = y0.min(r.y);
x1 = x1.max(r.x + r.w);
y1 = y1.max(r.y + r.h);
}
let bx = [
(x0 - margin).max(0.0),
(y0 - margin).max(0.0),
(x1 + margin).min(w as f32),
(y1 + margin + 46.0 * f.scale).min(h as f32),
];
if bx[0] >= bx[2] || bx[1] >= bx[3] {
continue;
}
gl.uniform_4_f32(l.box_.as_ref(), bx[0], bx[1], bx[2], bx[3]);
gl.uniform_1_i32(l.count.as_ref(), n as i32);
gl.uniform_4_f32_slice(l.rect.as_ref(), &rect[..n * 4]);
gl.uniform_4_f32_slice(l.param.as_ref(), &param[..n * 4]);
gl.uniform_4_f32_slice(l.glow.as_ref(), &glow_c[..n * 4]);
gl.uniform_4_f32_slice(l.tint.as_ref(), &tint[..n * 4]);
gl.draw_arrays(glow::TRIANGLE_STRIP, 0, 4);
}
self.restore(saved);
}
}
/// Reads the current window framebuffer as top-down RGBA8 (dev snapshots).
///
/// # Safety
/// Must be called with the context current, after Slint has rendered.
pub unsafe fn read_pixels(&self, w: u32, h: u32) -> Vec<u8> {
let mut buf = vec![0u8; (w * h * 4) as usize];
unsafe {
self.gl.pixel_store_i32(glow::PACK_ALIGNMENT, 1);
self.gl.read_pixels(
0,
0,
w as i32,
h as i32,
glow::RGBA,
glow::UNSIGNED_BYTE,
glow::PixelPackData::Slice(Some(&mut buf)),
);
}
let row = (w * 4) as usize;
let mut flipped = Vec::with_capacity(buf.len());
for y in (0..h as usize).rev() {
flipped.extend_from_slice(&buf[y * row..(y + 1) * row]);
}
flipped
}
/// # Safety
/// Must be called with the context current.
pub unsafe fn destroy(&mut self) {
unsafe {
self.gl.delete_program(self.scene_prog);
self.gl.delete_program(self.blit_prog);
self.gl.delete_program(self.glass_prog);
self.gl.delete_vertex_array(self.vao);
self.gl.delete_framebuffer(self.fbo);
self.gl.delete_texture(self.tex);
}
}
}
/// Splits the panels into draw runs: consecutive panels sharing a group
/// (> 0) melt together and are drawn as one; the rest are drawn alone.
fn runs(rects: &[Panel]) -> impl Iterator<Item = &[Panel]> {
let mut rest = rects;
std::iter::from_fn(move || {
let first = rest.first()?;
let mut n = 1;
if first.group > 0.5 {
while n < rest.len() && n < MAX_GROUP && (rest[n].group - first.group).abs() < 0.5 {
n += 1;
}
}
let (run, tail) = rest.split_at(n);
rest = tail;
Some(run)
})
}
unsafe fn link(gl: &glow::Context, header: &str, vs: &str, fs: &str) -> anyhow::Result<glow::Program> {
unsafe {
let program = gl.create_program().map_err(anyhow::Error::msg)?;
let mut shaders = Vec::new();
for (kind, src) in [(glow::VERTEX_SHADER, vs), (glow::FRAGMENT_SHADER, fs)] {
let sh = gl.create_shader(kind).map_err(anyhow::Error::msg)?;
gl.shader_source(sh, &format!("{header}{src}"));
gl.compile_shader(sh);
if !gl.get_shader_compile_status(sh) {
anyhow::bail!("shader compile failed: {}", gl.get_shader_info_log(sh));
}
gl.attach_shader(program, sh);
shaders.push(sh);
}
gl.link_program(program);
if !gl.get_program_link_status(program) {
anyhow::bail!("program link failed: {}", gl.get_program_info_log(program));
}
for sh in shaders {
gl.detach_shader(program, sh);
gl.delete_shader(sh);
}
Ok(program)
}
}

View File

@@ -1,384 +0,0 @@
//! GLSL sources. The `#version` line is added at runtime (desktop GL 3.3 core or GLES 3.0).
/// Fullscreen triangle without vertex buffers.
pub const VERTEX: &str = r#"
out vec2 vUv;
void main() {
vec2 p = vec2(float((gl_VertexID << 1) & 2), float(gl_VertexID & 2));
vUv = p;
gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0);
}
"#;
/// A quad over `uBox` (x0, y0, x1, y1 in px, top-left origin), drawn as a
/// 4-vertex triangle strip. Glass panels only shade the pixels they can reach.
pub const QUAD_VERTEX: &str = r#"
uniform vec4 uBox;
uniform vec2 uRes;
void main() {
vec2 c = vec2(float(gl_VertexID & 1), float((gl_VertexID >> 1) & 1));
vec2 p = mix(uBox.xy, uBox.zw, c);
gl_Position = vec4(p.x / uRes.x * 2.0 - 1.0, 1.0 - p.y / uRes.y * 2.0, 0.0, 1.0);
}
"#;
/// Backdrop: a dark, slowly flowing mesh gradient (soft colour fields in the
/// focused app's palette), like Apple's dark dynamic wallpapers.
///
/// It is smooth by design, so it is rendered at low resolution and upscaled.
/// Cost per pixel: a handful of exp() calls, no noise, no loops over shapes.
pub const SCENE: &str = r#"
in vec2 vUv;
out vec4 fragColor;
uniform vec2 uRes;
uniform float uTime;
uniform vec3 uPal[3]; // highlight, mid, deep
uniform float uZoom; // launch fly-in
uniform float uShelf; // 1 = top shelf showing, 0 = scrolled into the grid
float field(vec2 d, float r) {
return exp(-dot(d, d) / (r * r));
}
// Rotates the hue around the grey axis (keeps brightness roughly the same).
vec3 hueRot(vec3 c, float ang) {
const vec3 k = vec3(0.57735);
float ca = cos(ang);
return max(c * ca + cross(k, c) * sin(ang) + k * dot(k, c) * (1.0 - ca), 0.0);
}
void main() {
vec2 uv = vec2(vUv.x, 1.0 - vUv.y); // top-left origin
uv = (uv - 0.5) / uZoom + 0.5;
float aspect = uRes.x / uRes.y;
float t = uTime;
// Gentle flow: two layers of low-frequency sine warp make the fields drift
// and bend like liquid without any visible shapes.
vec2 w = uv;
w += 0.050 * vec2(sin(uv.y * 3.1 + t * 0.110), sin(uv.x * 2.3 - t * 0.090));
w += 0.022 * vec2(sin(uv.y * 5.7 - t * 0.070 + 1.3), sin(uv.x * 4.9 + t * 0.130 + 0.7));
vec2 a = vec2(aspect, 1.0);
vec3 hi = uPal[0];
vec3 mid = uPal[1];
vec3 deep = uPal[2];
// Near-black base; colour lives in a few soft fields with dark gaps between.
vec3 col = deep * 0.35 + vec3(0.003, 0.003, 0.005);
// Fields on slow Lissajous paths. Two are hue-shifted for depth, like
// Apple's dark gradients (never a single flat hue).
vec2 c0 = vec2(0.76 + 0.10 * sin(t * 0.050), 0.18 + 0.08 * cos(t * 0.043));
vec2 c1 = vec2(0.20 + 0.12 * cos(t * 0.037 + 1.0), 0.26 + 0.10 * sin(t * 0.041));
vec2 c2 = vec2(0.52 + 0.20 * sin(t * 0.029 + 2.0), 0.62 + 0.08 * cos(t * 0.033 + 0.5));
vec2 c3 = vec2(0.96 + 0.05 * cos(t * 0.045), 0.88 + 0.06 * sin(t * 0.052));
vec2 c4 = vec2(0.04 + 0.06 * sin(t * 0.031 + 4.0), 0.94 + 0.05 * cos(t * 0.027));
col += hi * 0.34 * field((w - c0) * a, 0.40);
col += mid * 0.62 * field((w - c1) * a, 0.48);
col += hueRot(mix(mid, hi, 0.4), 0.55) * 0.34 * field((w - c2) * a, 0.38);
col += hueRot(mid, -0.70) * 0.40 * field((w - c3) * a, 0.36);
col += mid * 0.30 * field((w - c4) * a, 0.34);
// Soft shoulder so bright palettes stay "dark mode".
col = col / (1.0 + col * 1.2);
// Calmer at the bottom where the icons sit; dimmer when the shelf is gone.
col *= mix(1.0, 0.62, smoothstep(0.45, 1.0, uv.y));
col *= mix(0.42, 1.0, uShelf);
vec2 v = uv - 0.5;
col *= 1.0 - 0.30 * dot(v, v);
fragColor = vec4(col, 1.0);
}
"#;
/// Upscales the backdrop to the window with dithering (no banding).
pub const BLIT: &str = r#"
in vec2 vUv;
out vec4 fragColor;
uniform sampler2D uScene;
uniform float uTime;
float hash12(vec2 p) {
vec3 p3 = fract(vec3(p.xyx) * 0.1031);
p3 += dot(p3, p3.yzx + 33.33);
return fract((p3.x + p3.y) * p3.z);
}
void main() {
vec3 col = textureLod(uScene, vUv, 0.0).rgb;
col += (hash12(gl_FragCoord.xy + fract(uTime) * 61.0) - 0.5) / 255.0;
fragColor = vec4(col, 1.0);
}
"#;
/// One Liquid Glass panel (or one merged group of panels), drawn as a quad
/// over its bounds plus the shadow margin.
///
/// The model follows Apple's Liquid Glass: light is *bent*, not scattered.
/// Each panel is a slab of glass (IOR ~1.5) whose edge is a convex squircle
/// bevel. The backdrop seen through it is displaced by a real refraction ray
/// (Snell), with per-channel IOR for dispersion. Bigger panels are thicker:
/// wider bevel, stronger lensing, deeper shadow. On top: Fresnel reflection,
/// a geometry-aware specular rim, light from within when focused, and
/// "materialize" (alpha ramps the lensing, not just the opacity).
///
/// The result is written as `dst * a + rgb` (blend ONE, SRC_ALPHA), so the
/// shader never needs to read the framebuffer: shadows multiply, glass
/// replaces, and nested glass (on another pane) lights what is already there.
pub const GLASS: &str = r#"
out vec4 fragColor;
#define MAX_GROUP 4
uniform sampler2D uScene;
uniform vec2 uRes; // physical px
uniform float uScale; // physical px per design px
uniform float uTime;
uniform vec2 uLight; // direction towards the key light (screen space, y down)
uniform int uCount; // members of this run (> 1 = merged group)
uniform vec4 uRect[MAX_GROUP]; // x, y, w, h (px, top-left origin)
uniform vec4 uParam[MAX_GROUP]; // radius, focus, alpha, frost (mip lod; < 0 = nested on other glass)
uniform vec4 uGlow[MAX_GROUP]; // accent rgb, unused
uniform vec4 uTint[MAX_GROUP]; // tint rgb, tint amount
float sdRoundRect(vec2 p, vec2 b, float r) {
vec2 q = abs(p) - b + r;
return min(max(q.x, q.y), 0.0) + length(max(q, 0.0)) - r;
}
// Analytic outward gradient of sdRoundRect.
vec2 gradRoundRect(vec2 p, vec2 b, float r) {
vec2 w = abs(p) - b + r;
vec2 q = max(w, 0.0);
vec2 g = (max(w.x, w.y) > 0.0) ? q / max(length(q), 1e-5) : ((w.x > w.y) ? vec2(1.0, 0.0) : vec2(0.0, 1.0));
return sign(p) * g;
}
float sdPanel(int i, vec2 p) {
vec4 R = uRect[i];
vec2 hs = R.zw * 0.5;
float r = min(uParam[i].x, min(hs.x, hs.y));
return sdRoundRect(p - (R.xy + hs), hs, r);
}
// Polynomial smooth minimum: the "liquid bridge" between merged panels.
float smin(float a, float b, float k) {
float h = max(k - abs(a - b), 0.0) / k;
return min(a, b) - h * h * k * 0.25;
}
float sdGroup(vec2 p, float k) {
float d = 1e5;
for (int i = 0; i < MAX_GROUP; i++) {
if (i >= uCount) break;
if (uParam[i].z <= 0.001) continue;
d = smin(d, sdPanel(i, p), k);
}
return d;
}
// uv has a top-left origin; the scene texture is stored GL-style (bottom row first).
vec3 sceneAt(vec2 uv, float lod) {
uv = clamp(uv, vec2(0.001), vec2(0.999));
return textureLod(uScene, vec2(uv.x, 1.0 - uv.y), lod).rgb;
}
float luma(vec3 c) { return dot(c, vec3(0.2126, 0.7152, 0.0722)); }
// Convex squircle bevel: height (0 at the rim, 1 on the flat top) and slope.
// u = distance from the rim / bevel width.
vec2 squircle(float u) {
u = clamp(u, 0.0, 1.0);
float a = 1.0 - u;
float a4 = a * a * a * a;
float h = pow(max(1.0 - a4, 1e-4), 0.25);
float dh = a * a * a * pow(max(1.0 - a4, 1e-3), -0.75);
return vec2(h, dh);
}
// Where a vertical ray through the glass lands on the backdrop (px offset).
vec2 refractOffset(vec3 N, float height, float ior) {
vec3 t = refract(vec3(0.0, 0.0, -1.0), N, 1.0 / ior);
return t.xy / max(-t.z, 0.2) * height;
}
void main() {
vec2 p = vec2(gl_FragCoord.x, uRes.y - gl_FragCoord.y); // px, top-left
float s = uScale;
float mergeK = 30.0 * s;
bool merged = uCount > 1;
// Combined distance, and parameters blended towards the nearest member.
float d = 1e5;
float wsum = 0.0;
vec4 P = vec4(0.0);
vec3 accent = vec3(0.0);
vec4 tint = vec4(0.0);
vec2 center = vec2(0.0);
vec2 halfSize = vec2(0.0);
for (int k = 0; k < MAX_GROUP; k++) {
if (k >= uCount) break;
float a = uParam[k].z;
if (a <= 0.001) continue;
float dk = sdPanel(k, p);
d = merged ? smin(d, dk, mergeK) : dk;
float w = exp(-max(dk, 0.0) / (12.0 * s)) + 1e-4;
wsum += w;
P += uParam[k] * w;
accent += uGlow[k].rgb * w;
tint += uTint[k] * w;
vec4 R = uRect[k];
center += (R.xy + R.zw * 0.5) * w;
halfSize += R.zw * 0.5 * w;
}
if (wsum <= 0.0) discard;
P /= wsum; accent /= wsum; tint /= wsum; center /= wsum; halfSize /= wsum;
float focus = P.y;
float alpha = P.z;
float minHalf = min(halfSize.x, halfSize.y);
bool nested = P.w < 0.0;
// Size-dependent thickness: small controls are full domes (a drop of
// liquid), big panes are thick slabs with a wide rounded edge.
float bezel = min(minHalf * 0.80, 9.0 * s + minHalf * 0.10);
bezel = clamp(bezel, 5.0 * s, 40.0 * s);
float sizeK = clamp(minHalf / (240.0 * s), 0.0, 1.0);
float small = 1.0 - clamp(minHalf / (90.0 * s), 0.0, 1.0);
// Output is dst * mul + add.
float mul = 1.0;
vec3 add = vec3(0.0);
// ---- outside: grounding shadow and a little accent light spill ----
if (d > 0.0) {
vec2 off = vec2(0.0, (10.0 + 18.0 * focus + 14.0 * sizeK) * s);
float ds = merged ? sdGroup(p - off, mergeK) : sdPanel(0, p - off);
float spread = (34.0 + 34.0 * focus + 50.0 * sizeK) * s * (nested ? 0.5 : 1.0);
float shadow = (1.0 - smoothstep(-spread * 0.5, spread, ds)) * (0.26 + 0.22 * focus + 0.18 * sizeK);
shadow += (1.0 - smoothstep(0.0, 6.0 * s, d)) * 0.10;
mul = 1.0 - shadow * alpha;
add = accent * exp(-d / (22.0 * s)) * focus * 0.16 * alpha;
if (d > 1.0) {
if (mul > 0.998 && dot(add, vec3(1.0)) < 0.002) discard;
fragColor = vec4(add, mul);
return;
}
}
// ---- surface geometry ----
vec2 n2;
if (merged) {
vec2 e = vec2(0.75, 0.0);
vec2 g2 = vec2(sdGroup(p + e.xy, mergeK) - sdGroup(p - e.xy, mergeK),
sdGroup(p + e.yx, mergeK) - sdGroup(p - e.yx, mergeK));
n2 = g2 / max(length(g2), 1e-5);
} else {
vec4 R = uRect[0];
vec2 hs = R.zw * 0.5;
n2 = gradRoundRect(p - (R.xy + hs), hs, min(uParam[0].x, min(hs.x, hs.y)));
}
float inside = max(-d, 0.0);
float u = inside / bezel;
vec2 hp = squircle(u);
float thick = bezel * (1.1 + 0.3 * focus); // glass height in px
float height = thick * hp.x;
float slope = (u < 1.0) ? hp.y * thick / bezel : 0.0;
slope = min(slope, 6.0);
vec3 N = normalize(vec3(n2 * slope, 1.0));
// Materialize: lensing and frost ramp up with alpha instead of a plain fade.
float mat = smoothstep(0.0, 1.0, alpha);
float lens = (1.25 + 0.35 * focus) * mat;
vec2 mag = -(p - center) * (0.025 + 0.035 * focus) * mat;
float lod = abs(P.w) * mix(0.35, 1.0, mat);
// The glass colour is affine in what is underneath: g = dst * A + B.
float A = 0.0;
vec3 B;
if (nested) {
A = 1.0;
B = vec3(0.0);
} else if (slope > 0.02) {
// Bevel: refract each channel with its own IOR (dispersion).
B.r = sceneAt((p + refractOffset(N, height, 1.46) * lens + mag) / uRes, lod).r;
B.g = sceneAt((p + refractOffset(N, height, 1.50) * lens + mag) / uRes, lod).g;
B.b = sceneAt((p + refractOffset(N, height, 1.56) * lens + mag) / uRes, lod).b;
} else {
B = sceneAt((p + mag) / uRes, lod);
}
// ---- body ----
// Adaptive tone: lift glass over dark content, hold it back over bright content.
float bgL = luma(sceneAt(center / uRes, 6.0));
float kb = 1.02 + 0.10 * focus;
A *= kb;
B = B * kb + mix(0.045, -0.01, clamp(bgL * 2.0, 0.0, 1.0)) + (nested ? 0.025 : 0.0);
A *= 1.0 - tint.a;
B = mix(B, tint.rgb, tint.a);
// Light from within when focused: starts at the center, spreads to the rim.
vec2 qn = (p - center) / max(halfSize, vec2(1.0));
float core = exp(-dot(qn, qn) * 1.3);
vec3 inner = mix(vec3(1.0), accent, 0.45);
B += inner * focus * (0.06 + 0.12 * core);
// Focus sheen: a soft diagonal band of light glides across the glass now and then.
float sweep = fract(uTime * 0.16 + center.x * 0.0007);
float band = (qn.x * 0.8 + qn.y * 0.45) * 0.5 + 0.5;
float sheen = exp(-pow((band - (sweep * 1.8 - 0.4)) * 7.0, 2.0));
B += vec3(1.0) * sheen * focus * 0.10 * mat;
// Soft vertical sheen, as if lit from above.
float vy = clamp((p.y - (center.y - halfSize.y)) / (2.0 * halfSize.y), 0.0, 1.0);
B += vec3(0.06 + 0.05 * focus) * pow(1.0 - vy, 2.5);
// ---- light ----
float wob = focus * 0.35 * sin(uTime * 0.9);
vec2 L2 = mat2(cos(wob), sin(wob), -sin(wob), cos(wob)) * uLight;
vec3 L = normalize(vec3(L2, 0.55));
vec3 V = vec3(0.0, 0.0, 1.0);
// Fresnel: steep bevel reflects the (blurred, brightened) surroundings.
float cosT = clamp(N.z, 0.0, 1.0);
float F = 0.04 + 0.96 * pow(1.0 - cosT, 5.0);
float Fm = clamp(F, 0.0, 1.0) * 0.35 * mat;
vec3 env = mix(sceneAt((p + n2 * 60.0 * s) / uRes, 5.0) * 1.6, vec3(0.92), 0.35);
A *= 1.0 - Fm;
B = mix(B, env, Fm);
// Specular on the bevel: key light, plus a weaker bounce on the far side.
vec3 H = normalize(L + V);
vec3 H2 = normalize(vec3(-L2, 0.55) + V);
float spec = pow(max(dot(N, H), 0.0), 26.0);
float spec2 = pow(max(dot(N, H2), 0.0), 26.0);
float bevelMask = 1.0 - smoothstep(0.0, 1.0, u);
B += vec3(1.0) * (spec * 0.60 + spec2 * 0.38) * bevelMask * (0.8 + 0.6 * focus) * mat;
// Glossy highlight on small domes, like a water drop.
vec2 hl = qn - uLight * 0.42;
float gloss = exp(-dot(hl * vec2(1.4, 2.2), hl * vec2(1.4, 2.2)) * 3.0);
B += vec3(1.0) * gloss * small * 0.14 * mat;
// Crisp rim: a bright hairline all around, strongest towards the light
// and again on the far side where light exits the glass.
float facing = max(dot(n2, uLight), 0.0);
float away = max(dot(n2, -uLight), 0.0);
float rimLine = exp(-inside / (1.0 * s));
float rimGlow = exp(-inside / (6.0 * s));
B += rimLine * (0.22 + 0.80 * pow(facing, 2.0) + 0.55 * pow(away, 2.0) + 0.22 * focus) * mat;
B += rimGlow * (0.06 + 0.10 * facing + 0.06 * away + 0.08 * focus) * mat;
B += accent * rimGlow * focus * 0.10 * mat;
// Subtle inner shade on the side away from the light gives the slab depth.
float shade = 1.0 - 0.08 * bevelMask * away * mat;
A *= shade;
B *= shade;
float cov = clamp(0.5 - d, 0.0, 1.0) * clamp(alpha * 2.0, 0.0, 1.0);
float keep = 1.0 - cov + cov * A;
fragColor = vec4(add * keep + cov * B, mul * keep);
}
"#;

View File

@@ -1,5 +1,5 @@
#![cfg_attr(not(unix), allow(dead_code))] #![cfg_attr(not(unix), allow(dead_code))]
//! Tiny command socket so other SmartFox components (the remote daemon) can //! Tiny command socket so other Fennec OS components (the remote daemon) can
//! reach the launcher even while an app has focus. //! reach the launcher even while an app has focus.
//! Protocol: one command per line: //! Protocol: one command per line:
//! `home` bring the launcher to the front //! `home` bring the launcher to the front

View File

@@ -8,7 +8,7 @@ use std::cell::RefCell;
use slint::ComponentHandle; use slint::ComponentHandle;
use crate::App; use crate::App;
use crate::glass::Panel; use sf_ui::render::Panel;
pub struct Request { pub struct Request {
pub title: String, pub title: String,

View File

@@ -1,27 +1,30 @@
//! SmartFox launcher. //! Fennec OS launcher.
//! //!
//! Slint draws text and icons; the `glass` module draws the animated backdrop //! Slint draws text and icons; sf-ui's glass renderer draws the animated
//! and frosted glass panels underneath via a rendering notifier. //! backdrop and frosted glass panels underneath via a rendering notifier.
mod glass; mod core_client;
mod ipc; mod ipc;
mod devshot; mod devshot;
mod keyboard; mod keyboard;
mod power; mod power;
mod runtime; mod runtime;
mod settings_screen; mod settings_screen;
mod shelf;
mod status;
mod store_screen;
mod system; mod system;
#[cfg(windows)] #[cfg(windows)]
mod winfade; mod winfade;
use std::cell::RefCell; use std::cell::{Cell, RefCell};
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use std::rc::Rc; use std::rc::Rc;
use std::time::{Duration, Instant}; use std::time::{Duration, Instant};
use anyhow::{Context, Result}; use anyhow::{Context, Result};
use chrono::{Datelike, Local, Timelike}; use chrono::{Datelike, Local, Timelike};
use glass::{Frame, GlassRenderer, Panel}; use sf_ui::render::{Frame, GlassRenderer, Panel, Quality};
use sf_ipc::{AppKind, AppManifest, Settings}; use sf_ipc::{AppKind, AppManifest, Settings};
use slint::{ComponentHandle, Model, ModelRc, SharedString, VecModel}; use slint::{ComponentHandle, Model, ModelRc, SharedString, VecModel};
@@ -33,18 +36,22 @@ const CROSSFADE: f32 = 0.35;
struct Options { struct Options {
/// Factory apps, then installed app packages (`--apps` may repeat). /// Factory apps, then installed app packages (`--apps` may repeat).
apps_dirs: Vec<PathBuf>, apps_dirs: Vec<PathBuf>,
/// Installed store apps (sandboxed; docs/store.md).
store_dir: Option<PathBuf>,
settings_path: PathBuf, settings_path: PathBuf,
fullscreen: bool, fullscreen: bool,
} }
fn parse_args() -> Options { fn parse_args() -> Options {
let mut apps_dirs = Vec::new(); let mut apps_dirs = Vec::new();
let mut store_dir = None;
let mut settings_path = None; let mut settings_path = None;
let mut fullscreen = false; let mut fullscreen = false;
let mut args = std::env::args().skip(1); let mut args = std::env::args().skip(1);
while let Some(a) = args.next() { while let Some(a) = args.next() {
match a.as_str() { match a.as_str() {
"--apps" => apps_dirs.extend(args.next().map(PathBuf::from)), "--apps" => apps_dirs.extend(args.next().map(PathBuf::from)),
"--store-apps" => store_dir = args.next().map(PathBuf::from),
"--settings" => settings_path = args.next().map(PathBuf::from), "--settings" => settings_path = args.next().map(PathBuf::from),
"--fullscreen" | "-f" => fullscreen = true, "--fullscreen" | "-f" => fullscreen = true,
other => log::warn!("unknown argument {other}"), other => log::warn!("unknown argument {other}"),
@@ -56,6 +63,7 @@ fn parse_args() -> Options {
} else { } else {
apps_dirs apps_dirs
}, },
store_dir,
settings_path: settings_path.unwrap_or_else(default_settings_path), settings_path: settings_path.unwrap_or_else(default_settings_path),
fullscreen, fullscreen,
} }
@@ -73,7 +81,7 @@ fn find_apps_dir() -> Option<PathBuf> {
for start in starts { for start in starts {
for dir in start.ancestors() { for dir in start.ancestors() {
let candidate = dir.join("apps"); let candidate = dir.join("apps");
if candidate.join("netflex").is_dir() { if candidate.join("settings").join("app.toml").is_file() {
return Some(candidate); return Some(candidate);
} }
} }
@@ -114,25 +122,161 @@ fn palette_of(app: &AppManifest) -> [f32; 9] {
out out
} }
fn entry_of(app: &AppManifest, settings: &Settings) -> AppEntry { /// `services`: sf-core runs the background receivers. Without it (an older
/// image, or a desktop) a receiver tile starts the app like any other.
/// Demo mode (Windows) shows receivers as running, like on the TV.
fn entry_of(app: &AppManifest, settings: &Settings, services: bool) -> AppEntry {
let (kind, kind_label, target) = match app.kind { let (kind, kind_label, target) = match app.kind {
AppKind::Web => ("web", "Webes alkalmazás (Chromium)", app.resolved_url(settings).unwrap_or_default()), _ if app.service && services => ("service", "Mindig fut a háttérben", app.exec.clone().unwrap_or_default().join(" ")),
AppKind::Exec => ("exec", "Natív alkalmazás", app.exec.clone().unwrap_or_default().join(" ")), AppKind::Web => ("web", "Webes alkalmazás", app.resolved_url(settings).unwrap_or_default()),
AppKind::Builtin => ("builtin", "Beépített", String::new()), AppKind::Exec => ("exec", "Alkalmazás", app.exec.clone().unwrap_or_default().join(" ")),
AppKind::Builtin => ("builtin", "A rendszer része", String::new()),
}; };
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 { AppEntry {
id: app.id.clone().into(), id: app.id.clone().into(),
name: app.name.clone().into(), name: app.name.clone().into(),
category: app.category.clone().into(), category: app.category.clone().into(),
description: app.description.clone().into(), description: app.description.clone().into(),
icon: app.icon.clone().into(), icon: icon.into(),
accent: to_color(parse_hex(&app.accent)), accent: to_color(parse_hex(&app.accent)),
kind: kind.into(), kind: kind.into(),
kind_label: kind_label.into(), kind_label: kind_label.into(),
target: target.into(), target: target.into(),
version: app.version.clone().into(),
host: host.into(),
facts: ModelRc::default(),
has_image: image.is_some(),
image: image.unwrap_or_default(),
initial: initial.into(),
cast: app.dial.is_some(),
} }
} }
/// Starts the launcher again, in the same process (same pid, so the
/// compositor and sf-core carry on and running apps stay as they are): the
/// simplest way to pick up a changed app list after a store install.
fn restart_launcher() {
log::info!("app list changed, restarting the launcher");
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
let Ok(exe) = std::env::current_exe() else { return };
let err = std::process::Command::new(exe).args(std::env::args_os().skip(1)).exec();
log::error!("restarting the launcher: {err}");
}
}
/// "https://netflex.example.com/" -> "netflex.example.com".
fn host_of(url: &str) -> String {
let rest = url.split_once("://").map_or(url, |(_, r)| r);
rest.trim_end_matches('/').to_string()
}
thread_local! {
/// sf-core is running (receivers in the background, DIAL casting).
static CORE_UP: Cell<bool> = const { Cell::new(false) };
}
/// Live lines under the focused app's name on the home screen.
fn facts_for(entry: &AppEntry, st: &status::Status) -> Vec<Fact> {
let fact = |icon: &str, text: &str, tone: &str| Fact { icon: icon.into(), text: text.into(), tone: tone.into() };
// The status capsule already shows the network; facts repeat it only as a warning.
let offline = st.net == "none";
let net = |out: &mut Vec<Fact>| {
if offline {
out.push(fact("alert", "Nincs hálózat", "warn"));
}
};
let core = CORE_UP.with(Cell::get);
match entry.id.as_str() {
// 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ó", ""));
}
net(&mut out);
out
}
"airplay" | "miracast" => {
let mut out = Vec::new();
if entry.kind == "service" {
out.push(fact("check", "Látható „Fennec OS” néven", "ok"));
}
if entry.id == "miracast" {
out.push(fact("alert", "Kísérleti", "warn"));
}
net(&mut out);
out
}
"settings" => {
let mut out = Vec::new();
match st.remote_battery {
Some(b) => out.push(fact("remote", &format!("Siri Remote · {b}%"), if b <= 15 { "warn" } else { "" })),
None if st.remote_connected => out.push(fact("remote", "Siri Remote", "")),
None => {}
}
net(&mut out);
if let Some(d) = &st.display {
out.push(fact("display", d, ""));
}
out
}
_ => {
let mut out = Vec::new();
net(&mut out);
out
}
}
}
/// Status capsule and the facts of every app.
fn apply_status(ui: &App, st: &status::Status) {
ui.set_net_icon(st.net.into());
ui.set_net_label(st.net_label.clone().into());
ui.set_remote_battery(st.remote_battery.map_or(-1, i32::from));
let apps = ui.get_apps();
for i in 0..apps.row_count() {
if let Some(mut entry) = apps.row_data(i) {
entry.facts = ModelRc::new(VecModel::from(facts_for(&entry, st)));
apps.set_row_data(i, entry);
}
}
}
/// Top Shelf cards; artwork that does not load falls back to the title.
fn apply_shelf(ui: &App, shelf: shelf::Shelf, dir: &Path) {
let items: Vec<ShelfItem> = shelf
.items
.into_iter()
.map(|item| {
let image = item.image.as_ref().and_then(|name| match slint::Image::load_from_path(&dir.join(name)) {
Ok(img) => Some(img),
Err(e) => {
log::info!("shelf artwork {name}: {e:?}");
None
}
});
ShelfItem {
title: item.title.into(),
detail: item.detail.into(),
has_image: image.is_some(),
image: image.unwrap_or_default(),
progress: item.progress,
}
})
.collect();
ui.set_shelf_title(shelf.title.into());
ui.set_shelf_items(ModelRc::new(VecModel::from(items)));
}
/// Backdrop colours, eased towards the focused app's palette every frame. /// Backdrop colours, eased towards the focused app's palette every frame.
struct Backdrop { struct Backdrop {
palette: [f32; 9], palette: [f32; 9],
@@ -175,6 +319,7 @@ fn card_rects(ui: &App, scale: f32, accents: &[[f32; 3]]) -> Vec<Panel> {
let (fx, fy, active, intro) = (ui.get_focus_x(), ui.get_focus_y(), ui.get_row_active(), ui.get_intro()); let (fx, fy, active, intro) = (ui.get_focus_x(), ui.get_focus_y(), ui.get_row_active(), ui.get_intro());
let (lift, press_in, press) = (ui.get_lift(), ui.get_press_in(), ui.get_press()); let (lift, press_in, press) = (ui.get_lift(), ui.get_press_in(), ui.get_press());
let scroll = ui.get_grid_scroll(); let scroll = ui.get_grid_scroll();
let shelf = ui.get_shelf_t();
let menu_t = ui.get_menu_t().clamp(0.0, 1.0); let menu_t = ui.get_menu_t().clamp(0.0, 1.0);
let focus_index = ui.get_focus_index().max(0) as usize; let focus_index = ui.get_focus_index().max(0) as usize;
let hidden = (1.0 - ui.get_launch_t()) * (1.0 - ui.get_sheet_t()) * ui.get_dim(); let hidden = (1.0 - ui.get_launch_t()) * (1.0 - ui.get_sheet_t()) * ui.get_dim();
@@ -184,6 +329,8 @@ fn card_rects(ui: &App, scale: f32, accents: &[[f32; 3]]) -> Vec<Panel> {
let s = 1.0 + (lift - press_in * press) * f; let s = 1.0 + (lift - press_in * press) * f;
let appear = (intro * 2.2 - col * 0.12 - row * 0.2 - 0.4).clamp(0.0, 1.0); let appear = (intro * 2.2 - col * 0.12 - row * 0.2 - 0.4).clamp(0.0, 1.0);
let others = if i == focus_index { 1.0 } else { 1.0 - 0.55 * menu_t }; let others = if i == focus_index { 1.0 } else { 1.0 - 0.55 * menu_t };
// Lower rows stay hidden under the shelf (no sliver at the screen edge).
let others = if row > 0.0 { others * (1.0 - shelf) } else { others };
let (w, h) = (cw * s, ch * s); let (w, h) = (cw * s, ch * s);
let x = row_x + col * (cw + gap) + (cw - w) / 2.0; let x = row_x + col * (cw + gap) + (cw - w) / 2.0;
let y = row_y + row * step - scroll + (ch - h) / 2.0 + (1.0 - appear) * 60.0 * u; let y = row_y + row * step - scroll + (ch - h) / 2.0 + (1.0 - appear) * 60.0 * u;
@@ -222,7 +369,8 @@ fn card_rects(ui: &App, scale: f32, accents: &[[f32; 3]]) -> Vec<Panel> {
} }
const DAYS: [&str; 7] = ["hétfő", "kedd", "szerda", "csütörtök", "péntek", "szombat", "vasárnap"]; const DAYS: [&str; 7] = ["hétfő", "kedd", "szerda", "csütörtök", "péntek", "szombat", "vasárnap"];
const MONTHS: [&str; 12] = ["jan.", "febr.", "márc.", "ápr.", "máj.", "jún.", "júl.", "aug.", "szept.", "okt.", "nov.", "dec."]; const MONTHS: [&str; 12] =
["január", "február", "március", "április", "május", "június", "július", "augusztus", "szeptember", "október", "november", "december"];
fn update_clock(ui: &App) { fn update_clock(ui: &App) {
let now = Local::now(); let now = Local::now();
@@ -296,6 +444,73 @@ fn show_toast(ui: &App, text: impl Into<SharedString>, timer: &slint::Timer) {
}); });
} }
thread_local! {
/// The app sf-core shows in the foreground, as far as the UI knows.
static CORE_APP: RefCell<Option<String>> = const { RefCell::new(None) };
static CORE_TOAST: slint::Timer = slint::Timer::default();
}
fn app_name(apps: &[AppManifest], id: &str) -> String {
apps.iter().find(|a| a.id == id).map(|a| a.name.clone()).unwrap_or_else(|| id.to_string())
}
/// Shows an app as running: the launch morph covers the home screen.
fn show_running(ui: &App, apps: &[AppManifest], id: &str) {
let Some(index) = apps.iter().position(|a| a.id == id) else { return };
CORE_APP.with(|c| *c.borrow_mut() = Some(id.to_string()));
ui.set_focus_index(index as i32);
ui.set_menu_open(false);
ui.set_sheet_open(false);
ui.set_settings_open(false);
// The splash (with its loading bar) stays until the compositor fades the
// app in on top of it, which waits for the page to load.
ui.set_launching(true);
}
/// Events from sf-core (apps starting and stopping, casting).
fn on_core_event(ui: &App, apps: &[AppManifest], ev: sf_ipc::CoreEvent) {
use sf_ipc::CoreEvent::*;
let toast = |text: String| CORE_TOAST.with(|t| show_toast(ui, text, t));
match ev {
Hello { foreground, switching } => {
log::info!("sf-core: switching={switching} foreground={foreground:?}");
if let Some(id) = foreground {
show_running(ui, apps, &id);
}
}
AppStarted { app_id, cast } => {
let current = CORE_APP.with(|c| c.borrow().clone());
if current.as_deref() != Some(app_id.as_str()) || !ui.get_launching() {
show_running(ui, apps, &app_id);
} else {
CORE_APP.with(|c| *c.borrow_mut() = Some(app_id.clone()));
}
if cast {
toast(format!("{}: indítás telefonról", app_name(apps, &app_id)));
}
}
AppStopped { app_id } => {
let was_shown = CORE_APP.with(|c| {
let mut c = c.borrow_mut();
let shown = c.as_deref() == Some(app_id.as_str());
if shown {
*c = None;
}
shown
});
if was_shown {
// Reverse morph: the full-screen glass shrinks back into the card.
ui.set_launching(false);
ui.set_app_ready(false);
toast(format!("{} bezárva", app_name(apps, &app_id)));
}
}
CastConnected { app_id, device } => toast(format!("{}: {device} csatlakozott", app_name(apps, &app_id))),
CastEnded { app_id } => toast(format!("{}: a tükrözés véget ért", app_name(apps, &app_id))),
Toast { text } => toast(text),
}
}
fn main() -> Result<()> { fn main() -> Result<()> {
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init(); env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
let opts = parse_args(); let opts = parse_args();
@@ -316,14 +531,22 @@ fn main() -> Result<()> {
} }
let data_dir = opts.settings_path.parent().map(Path::to_path_buf).unwrap_or_else(|| PathBuf::from(".")); let data_dir = opts.settings_path.parent().map(Path::to_path_buf).unwrap_or_else(|| PathBuf::from("."));
let apps = sf_ipc::manifest::load_apps_from(&opts.apps_dirs).with_context(|| format!("loading apps from {:?}", opts.apps_dirs))?; 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); 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(); system::confirm_shell_trial();
let ui = App::new()?; let ui = App::new()?;
let entries: Vec<AppEntry> = apps.iter().map(|a| entry_of(a, &settings)).collect(); let entries: Vec<AppEntry> = apps.iter().map(|a| entry_of(a, &settings, true)).collect();
ui.set_apps(ModelRc::new(VecModel::from(entries))); ui.set_apps(ModelRc::new(VecModel::from(entries)));
let _screen = settings_screen::Screen::install(&ui, opts.settings_path.clone()); let _screen = settings_screen::Screen::install(&ui, opts.settings_path.clone());
let store = store_screen::Screen::install(&ui);
if !system::demo() {
store.on_apps_changed(restart_launcher);
}
keyboard::install(&ui); keyboard::install(&ui);
power::configure_from(&settings); power::configure_from(&settings);
power::install(&ui, opts.settings_path.clone()); power::install(&ui, opts.settings_path.clone());
@@ -349,9 +572,41 @@ fn main() -> Result<()> {
}); });
} }
// Launching. Locally the launcher starts apps itself; on the TV this moves to sf-core. // Launching. On the TV sf-core starts apps (and closes them on Home);
// without it the launcher starts them itself.
let toast_timer = Rc::new(slint::Timer::default()); let toast_timer = Rc::new(slint::Timer::default());
let running: Rc<RefCell<Option<(String, std::process::Child)>>> = Rc::default(); let running: Rc<RefCell<Option<(String, std::process::Child)>>> = Rc::default();
let core = {
let weak = ui.as_weak();
let apps = apps.clone();
core_client::CoreClient::connect(move |ev| {
let Some(ui) = weak.upgrade() else { return };
on_core_event(&ui, &apps, ev);
})
};
if core.is_none() {
let entries: Vec<AppEntry> = apps.iter().map(|a| entry_of(a, &settings, system::demo())).collect();
ui.set_apps(ModelRc::new(VecModel::from(entries)));
}
CORE_UP.with(|c| c.set(core.is_some()));
apply_status(&ui, &status::Status { net: "wired", ..Default::default() });
{
let weak = ui.as_weak();
status::spawn(move |st| {
let _ = weak.upgrade_in_event_loop(move |ui| apply_status(&ui, &st));
});
}
{
let weak = ui.as_weak();
let source = shelf::Source {
server: settings.get("netflex_server").map(str::to_string),
token: settings.get("netflex_token").filter(|t| !t.is_empty()).map(str::to_string),
dir: data_dir.join("cache").join("shelf"),
};
shelf::spawn(source, move |shelf, dir| {
let _ = weak.upgrade_in_event_loop(move |ui| apply_shelf(&ui, shelf, &dir));
});
}
{ {
let weak = ui.as_weak(); let weak = ui.as_weak();
let apps = apps.clone(); let apps = apps.clone();
@@ -360,20 +615,27 @@ fn main() -> Result<()> {
let running = running.clone(); let running = running.clone();
let data_dir = data_dir.clone(); let data_dir = data_dir.clone();
let fullscreen = opts.fullscreen; let fullscreen = opts.fullscreen;
let core = core.clone();
ui.on_launch(move |index| { ui.on_launch(move |index| {
let Some(ui) = weak.upgrade() else { return }; let Some(ui) = weak.upgrade() else { return };
let Some(app) = apps.get(index as usize) else { return }; let Some(app) = apps.get(index as usize) else { return };
ui.set_launch_detail("indítása…".into());
ui.set_app_ready(false);
if let Some(core) = &core {
CORE_APP.with(|c| *c.borrow_mut() = Some(app.id.clone()));
core.send(sf_ipc::LauncherRequest::Launch { app_id: app.id.clone(), query: None });
return;
}
if let Some((_, mut old)) = running.borrow_mut().take() { if let Some((_, mut old)) = running.borrow_mut().take() {
runtime::stop(&mut old); runtime::stop(&mut old);
} }
ui.set_launch_detail("indítása…".into());
ui.set_app_ready(false);
let pos = ui.window().position(); let pos = ui.window().position();
let size = ui.window().size(); let size = ui.window().size();
let opts = runtime::LaunchOptions { let opts = sf_ipc::launch::LaunchOptions {
data_dir: &data_dir, data_dir: &data_dir,
fullscreen, fullscreen,
bounds: Some((pos.x, pos.y, size.width, size.height)), bounds: Some((pos.x, pos.y, size.width, size.height)),
query: None,
}; };
match runtime::launch(app, &settings, &opts) { match runtime::launch(app, &settings, &opts) {
Ok(child) => { Ok(child) => {
@@ -382,7 +644,7 @@ fn main() -> Result<()> {
{ {
// Keep the window hidden until the morph finishes and the page loads. // Keep the window hidden until the morph finishes and the page loads.
let weak = ui.as_weak(); let weak = ui.as_weak();
let not_before = std::time::Instant::now() + Duration::from_millis(950); let not_before = std::time::Instant::now() + Duration::from_millis(720);
winfade::reveal_when_ready(child.id(), not_before, move || { winfade::reveal_when_ready(child.id(), not_before, move || {
let _ = weak.upgrade_in_event_loop(|ui| ui.set_app_ready(true)); let _ = weak.upgrade_in_event_loop(|ui| ui.set_app_ready(true));
}); });
@@ -399,22 +661,38 @@ fn main() -> Result<()> {
} }
{ {
let running = running.clone(); let running = running.clone();
let core = core.clone();
ui.on_cancel_launch(move || { ui.on_cancel_launch(move || {
// Back pressed on the launch splash: close the app that is starting.
if let Some(core) = &core {
if let Some(id) = CORE_APP.with(|c| c.borrow_mut().take()) {
core.send(sf_ipc::LauncherRequest::Stop { app_id: id });
}
return;
}
if let Some((name, mut child)) = running.borrow_mut().take() { if let Some((name, mut child)) = running.borrow_mut().take() {
log::info!("closing {name}"); log::info!("closing {name}");
runtime::stop(&mut child); runtime::stop(&mut child);
} }
}); });
} }
// Global "home" (remote's TV button): close the foreground app and play the reverse morph. // Global "home" (remote's TV button): the foreground app closes and
// the reverse morph plays.
{ {
let weak = ui.as_weak(); let weak = ui.as_weak();
let core = core.clone();
ipc::listen(move |cmd| { ipc::listen(move |cmd| {
let Some(ui) = weak.upgrade() else { return }; let Some(ui) = weak.upgrade() else { return };
match cmd { match cmd {
ipc::Command::Home => { ipc::Command::Home => {
log::info!("home"); log::info!("home");
ui.invoke_cancel_launch(); match &core {
Some(core) => {
CORE_APP.with(|c| *c.borrow_mut() = None);
core.send(sf_ipc::LauncherRequest::GoHome);
}
None => ui.invoke_cancel_launch(),
}
ui.set_launching(false); ui.set_launching(false);
ui.set_app_ready(false); ui.set_app_ready(false);
ui.set_sheet_open(false); ui.set_sheet_open(false);
@@ -475,6 +753,10 @@ fn main() -> Result<()> {
let backdrop = Rc::new(RefCell::new(Backdrop { palette: palettes.first().copied().unwrap_or([0.0; 9]), last: 0.0 })); let backdrop = Rc::new(RefCell::new(Backdrop { palette: palettes.first().copied().unwrap_or([0.0; 9]), last: 0.0 }));
let renderer: Rc<RefCell<Option<GlassRenderer>>> = Rc::default(); let renderer: Rc<RefCell<Option<GlassRenderer>>> = Rc::default();
let frames = Rc::new(RefCell::new((Instant::now(), 0u32))); let frames = Rc::new(RefCell::new((Instant::now(), 0u32)));
// Glass quality, measured on the GPU for the window size (sf-ui), and
// whether the last frame left anything still easing.
let quality: Rc<std::cell::Cell<Option<(Quality, (u32, u32))>>> = Rc::default();
let easing = Rc::new(std::cell::Cell::new(true));
let weak = ui.as_weak(); let weak = ui.as_weak();
ui.window() ui.window()
@@ -499,13 +781,26 @@ fn main() -> Result<()> {
let size = ui.window().size(); let size = ui.window().size();
let scale = ui.window().scale_factor(); let scale = ui.window().scale_factor();
let q = match quality.get() {
Some((q, at)) if at == (size.width, size.height) => q,
_ => {
// SAFETY: the rendering notifier runs with the GL context current.
let q = unsafe { r.choose_quality(size.width, size.height) };
log::info!("glass quality: {}", q.name());
quality.set(Some((q, (size.width, size.height))));
q
}
};
let mut bd = backdrop.borrow_mut(); let mut bd = backdrop.borrow_mut();
let focus = ui.get_focus_index().max(0) as usize; let focus = ui.get_focus_index().max(0) as usize;
easing.set(false);
if let Some(target) = palettes.get(focus) { if let Some(target) = palettes.get(focus) {
let k = 1.0 - (-(time - bd.last).max(0.0) / CROSSFADE).exp(); let k = 1.0 - (-(time - bd.last).max(0.0) / CROSSFADE).exp();
for (c, t) in bd.palette.iter_mut().zip(target) { for (c, t) in bd.palette.iter_mut().zip(target) {
*c += (t - *c) * k; *c += (t - *c) * k;
} }
easing.set(bd.palette.iter().zip(target).any(|(c, t)| (c - t).abs() > 0.002));
} }
bd.last = time; bd.last = time;
@@ -527,10 +822,13 @@ fn main() -> Result<()> {
scale, scale,
time, time,
palette: bd.palette, palette: bd.palette,
shelf: ui.get_shelf_t(), brightness: ui.get_shelf_t(),
light: [angle.cos(), angle.sin()], light: [angle.cos(), angle.sin()],
zoom: 1.0 + 0.35 * ui.get_launch_t() * ui.get_launch_t(), zoom: 1.0 + 0.35 * ui.get_launch_t() * ui.get_launch_t(),
images: &[],
video: None,
rects, rects,
quality: q,
}; };
drop(bd); drop(bd);
// SAFETY: called on the UI thread with the Slint GL context current. // SAFETY: called on the UI thread with the Slint GL context current.
@@ -544,14 +842,19 @@ fn main() -> Result<()> {
} }
} }
slint::RenderingState::AfterRendering => { slint::RenderingState::AfterRendering => {
// The backdrop is animated, so keep frames coming (vsync-limited). // The glass backdrop is animated, so keep frames coming
// (vsync-limited). Material is still: frames only while the
// colours ease; Slint asks for its own animations.
if let Some(ui) = weak.upgrade() { if let Some(ui) = weak.upgrade() {
if let Some(r) = renderer.borrow().as_ref() { if let Some(r) = renderer.borrow().as_ref() {
snapshot.capture_if_due(&ui, r); snapshot.capture_if_due(&ui, r);
} }
let still = matches!(quality.get(), Some((Quality::Material, _)));
if !still || easing.get() || snapshot.pending() {
ui.window().request_redraw(); ui.window().request_redraw();
} }
} }
}
slint::RenderingState::RenderingTeardown => { slint::RenderingState::RenderingTeardown => {
if let Some(mut r) = renderer.borrow_mut().take() { if let Some(mut r) = renderer.borrow_mut().take() {
unsafe { r.destroy() }; unsafe { r.destroy() };

View File

@@ -1,178 +1,24 @@
//! Starts apps. Web apps run in a Chromium-family browser in app/kiosk mode //! Starts apps locally, when no sf-core is running (desktop testing). The
//! with a per-app profile; exec apps are spawned directly. //! command line comes from `sf_ipc::launch`; on the TV sf-core does this.
//!
//! This lives in the launcher for local testing; on the TV it moves into the
//! sf-core daemon (systemd scopes, freeze/thaw).
use std::path::{Path, PathBuf}; use std::process::Child;
use std::process::{Child, Command};
use anyhow::{Context, Result, bail}; use anyhow::{Context, Result};
use sf_ipc::{AppKind, AppManifest, Settings}; use sf_ipc::launch::{LaunchOptions, command};
use sf_ipc::{AppManifest, Settings};
pub struct Browser {
pub exe: PathBuf,
/// Full version, used to build a realistic user agent.
pub version: String,
}
pub fn find_browser() -> Option<Browser> {
let mut candidates: Vec<PathBuf> = 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<String> {
// Windows installs keep a folder named after the version next to the exe.
if cfg!(windows) {
let dir = exe.parent()?;
let mut versions: Vec<String> = 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::<u32>().is_ok()))
.collect();
versions.sort_by_key(|v| v.split('.').map(|p| p.parse::<u32>().unwrap_or(0)).collect::<Vec<_>>());
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> {
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)>,
}
pub fn launch(app: &AppManifest, settings: &Settings, opts: &LaunchOptions) -> Result<Child> { pub fn launch(app: &AppManifest, settings: &Settings, opts: &LaunchOptions) -> Result<Child> {
match app.kind { let mut cmd = command(app, settings, opts)?;
AppKind::Web => launch_web(app, settings, opts), log::info!("{} {:?}", cmd.get_program().to_string_lossy(), cmd.get_args().collect::<Vec<_>>());
AppKind::Exec => { cmd.spawn().with_context(|| format!("starting {}", cmd.get_program().to_string_lossy()))
let cmd = app.exec.as_deref().unwrap_or_default();
let (prog, args) = cmd.split_first().context("empty exec command")?;
Command::new(prog).args(args).spawn().with_context(|| format!("starting {prog}"))
}
AppKind::Builtin => bail!("built-in app has no process"),
}
}
/// 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(())
}
fn launch_web(app: &AppManifest, settings: &Settings, opts: &LaunchOptions) -> Result<Child> {
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 profile = opts.data_dir.join("profiles").join(&app.id);
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 cmd = Command::new(&browser.exe);
cmd.arg(format!("--user-data-dir={}", profile.display()))
.arg(format!("--user-agent={ua}"))
.arg("--no-first-run")
.arg("--no-default-browser-check")
.arg("--disable-session-crashed-bubble")
.arg("--hide-crash-restore-bubble")
.arg("--disable-features=Translate,TranslateUI,MediaRouter")
.arg("--lang=hu")
.arg("--accept-lang=hu-HU,hu,en")
// Dark first paint instead of a white flash before the page draws.
.arg("--force-dark-mode")
.arg("--autoplay-policy=no-user-gesture-required")
.arg("--overscroll-history-navigation=0");
if opts.fullscreen {
cmd.arg("--kiosk").arg(&url);
} else {
cmd.arg(format!("--app={url}"));
match opts.bounds {
Some((x, y, w, h)) => {
cmd.arg(format!("--window-position={x},{y}")).arg(format!("--window-size={w},{h}"));
}
None => {
cmd.arg("--window-size=1600,900");
}
}
}
if cfg!(target_os = "linux") {
// Chromium on Linux picks its UI language from the environment, not --lang.
cmd.env("LANGUAGE", "hu");
cmd.arg("--enable-features=VaapiVideoDecoder,VaapiIgnoreDriverChecks,PlatformHEVCDecoderSupport");
if std::env::var_os("WAYLAND_DISPLAY").is_some() {
cmd.arg("--ozone-platform=wayland");
}
}
for ext in &app.web.extensions {
cmd.arg(format!("--load-extension={}", app.dir.join(ext).display()));
}
// Own process group, so closing the app also ends Chromium's helper processes.
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
cmd.process_group(0);
}
log::info!("{} {:?}", browser.exe.display(), cmd.get_args().collect::<Vec<_>>());
cmd.spawn().with_context(|| format!("starting {}", browser.exe.display()))
} }
/// Stops an app and everything it started. /// Stops an app and everything it started.
pub fn stop(child: &mut Child) { pub fn stop(child: &mut Child) {
#[cfg(unix)] #[cfg(unix)]
{ {
// The app runs in its own process group (see launch_web). use std::process::Command;
// The app runs in its own process group (see sf_ipc::launch::command).
let _ = Command::new("kill").arg("-TERM").arg("--").arg(format!("-{}", child.id())).status(); let _ = Command::new("kill").arg("-TERM").arg("--").arg(format!("-{}", child.id())).status();
for _ in 0..20 { for _ in 0..20 {
if matches!(child.try_wait(), Ok(Some(_))) { if matches!(child.try_wait(), Ok(Some(_))) {

View File

@@ -10,7 +10,7 @@ use std::time::{Duration, Instant};
use slint::{ComponentHandle, ModelRc, SharedString, VecModel}; use slint::{ComponentHandle, ModelRc, SharedString, VecModel};
use crate::system::{self, BtDevice, DeviceInfo, Display, Mode, NetInfo, RemoteDebug, Security, UpdateStatus, Wifi, WifiNetwork}; use crate::system::{self, AudioOutput, BtAudioDevice, BtDevice, DeviceInfo, Display, Mode, NetInfo, RemoteDebug, Security, UpdateStatus, Wifi, WifiNetwork};
use crate::power; use crate::power;
use crate::{App, SettingRow, keyboard}; use crate::{App, SettingRow, keyboard};
@@ -19,9 +19,10 @@ const KEEP_SECS: u64 = 15;
const DISPLAY: i32 = 0; const DISPLAY: i32 = 0;
const DEVICES: i32 = 1; const DEVICES: i32 = 1;
const NETWORK: i32 = 2; const AUDIO: i32 = 2;
const ENERGY: i32 = 3; const NETWORK: i32 = 3;
const SYSTEM: i32 = 4; const ENERGY: i32 = 4;
const SYSTEM: i32 = 5;
#[derive(Clone, PartialEq)] #[derive(Clone, PartialEq)]
enum Action { enum Action {
@@ -42,6 +43,9 @@ enum Action {
Back, Back,
PairRemote, PairRemote,
ReplaceRemote, ReplaceRemote,
AudioOutput(String),
BtAudioScan,
BtAudioConnect(String),
Restart, Restart,
ConfirmRestart, ConfirmRestart,
RemoteDebug, RemoteDebug,
@@ -82,6 +86,10 @@ struct Pending {
enum Loaded { enum Loaded {
Display(Result<Display, String>), Display(Result<Display, String>),
Devices(Result<Vec<BtDevice>, String>), Devices(Result<Vec<BtDevice>, String>),
Audio(Result<Vec<AudioOutput>, String>),
BtAudio(Result<Vec<BtAudioDevice>, String>),
AudioDone(Result<String, String>),
BtAudioScanDone(Result<Vec<BtAudioDevice>, String>),
Net(NetInfo), Net(NetInfo),
Wifi(Result<Option<Wifi>, String>), Wifi(Result<Option<Wifi>, String>),
/// A Wi-Fi action finished: notice text, or the error. `retry` reopens the /// A Wi-Fi action finished: notice text, or the error. `retry` reopens the
@@ -105,6 +113,8 @@ struct State {
parent_row: i32, parent_row: i32,
display: Option<Result<Display, String>>, display: Option<Result<Display, String>>,
devices: Option<Result<Vec<BtDevice>, String>>, devices: Option<Result<Vec<BtDevice>, String>>,
audio: Option<Result<Vec<AudioOutput>, String>>,
bt_audio: Option<Result<Vec<BtAudioDevice>, String>>,
net: Option<NetInfo>, net: Option<NetInfo>,
/// Ok(None) = no Wi-Fi adapter. /// Ok(None) = no Wi-Fi adapter.
wifi: Option<Result<Option<Wifi>, String>>, wifi: Option<Result<Option<Wifi>, String>>,
@@ -187,6 +197,8 @@ impl Screen {
parent_row: 0, parent_row: 0,
display: None, display: None,
devices: None, devices: None,
audio: None,
bt_audio: None,
net: None, net: None,
wifi: None, wifi: None,
wifi_pending: None, wifi_pending: None,
@@ -205,13 +217,27 @@ impl Screen {
SCREEN.with(|s| *s.borrow_mut() = Some(screen.clone())); SCREEN.with(|s| *s.borrow_mut() = Some(screen.clone()));
let s = screen.clone(); let s = screen.clone();
// In store mode (app.slint set-mode) the same pane belongs to store_screen.
let store_mode = |s: &Screen| s.ui.upgrade().is_some_and(|ui| ui.get_set_mode() == "store");
ui.on_settings_opened(move || { ui.on_settings_opened(move || {
if store_mode(&s) {
if let Some(store) = crate::store_screen::current() {
store.opened();
}
return;
}
s.state.borrow_mut().notice.clear(); s.state.borrow_mut().notice.clear();
s.refresh_all(); s.refresh_all();
s.rebuild(None); s.rebuild(None);
}); });
let s = screen.clone(); let s = screen.clone();
ui.on_settings_nav_changed(move |i| { ui.on_settings_nav_changed(move |i| {
if store_mode(&s) {
if let Some(store) = crate::store_screen::current() {
store.nav_changed(i);
}
return;
}
{ {
let mut st = s.state.borrow_mut(); let mut st = s.state.borrow_mut();
st.category = i; st.category = i;
@@ -226,9 +252,15 @@ impl Screen {
s.rebuild(Some(0)); s.rebuild(Some(0));
}); });
let s = screen.clone(); let s = screen.clone();
ui.on_settings_activate(move |i| s.activate(i)); ui.on_settings_activate(move |i| match crate::store_screen::current().filter(|_| store_mode(&s)) {
Some(store) => store.activate(i),
None => s.activate(i),
});
let s = screen.clone(); let s = screen.clone();
ui.on_settings_back(move || s.run(Action::Back)); ui.on_settings_back(move || match crate::store_screen::current().filter(|_| store_mode(&s)) {
Some(store) => store.back(),
None => s.run(Action::Back),
});
// Ticks the confirm countdown and keeps device/network rows fresh. // Ticks the confirm countdown and keeps device/network rows fresh.
let s = Rc::downgrade(&screen); let s = Rc::downgrade(&screen);
@@ -255,12 +287,14 @@ impl Screen {
} }
fn is_open(&self) -> bool { fn is_open(&self) -> bool {
self.ui.upgrade().is_some_and(|ui| ui.get_settings_open()) self.ui.upgrade().is_some_and(|ui| ui.get_settings_open() && ui.get_set_mode() != "store")
} }
fn refresh_all(&self) { fn refresh_all(&self) {
post(|| Loaded::Display(system::display().map_err(|e| format!("{e:#}")))); post(|| Loaded::Display(system::display().map_err(|e| format!("{e:#}"))));
post(|| Loaded::Devices(system::bt_devices().map_err(|e| format!("{e:#}")))); post(|| Loaded::Devices(system::bt_devices().map_err(|e| format!("{e:#}"))));
post(|| Loaded::Audio(system::audio_outputs().map_err(|e| format!("{e:#}"))));
post(|| Loaded::BtAudio(system::bt_audio_devices().map_err(|e| format!("{e:#}"))));
post(|| Loaded::Net(system::network())); post(|| Loaded::Net(system::network()));
post(|| Loaded::Wifi(wifi_result(system::wifi()))); post(|| Loaded::Wifi(wifi_result(system::wifi())));
post(|| Loaded::RemoteDebug(system::remote_debug())); post(|| Loaded::RemoteDebug(system::remote_debug()));
@@ -292,6 +326,10 @@ impl Screen {
} }
match category { match category {
DEVICES => post(|| Loaded::Devices(system::bt_devices().map_err(|e| format!("{e:#}")))), DEVICES => post(|| Loaded::Devices(system::bt_devices().map_err(|e| format!("{e:#}")))),
AUDIO => {
post(|| Loaded::Audio(system::audio_outputs().map_err(|e| format!("{e:#}"))));
post(|| Loaded::BtAudio(system::bt_audio_devices().map_err(|e| format!("{e:#}"))));
}
NETWORK => { NETWORK => {
post(|| Loaded::Net(system::network())); post(|| Loaded::Net(system::network()));
post(|| Loaded::Wifi(wifi_result(system::wifi()))); post(|| Loaded::Wifi(wifi_result(system::wifi())));
@@ -382,6 +420,30 @@ impl Screen {
match loaded { match loaded {
Loaded::Display(d) => self.state.borrow_mut().display = Some(d), Loaded::Display(d) => self.state.borrow_mut().display = Some(d),
Loaded::Devices(d) => self.state.borrow_mut().devices = Some(d), Loaded::Devices(d) => self.state.borrow_mut().devices = Some(d),
Loaded::Audio(d) => self.state.borrow_mut().audio = Some(d),
Loaded::BtAudio(d) => self.state.borrow_mut().bt_audio = Some(d),
Loaded::BtAudioScanDone(result) => {
let mut st = self.state.borrow_mut();
st.busy = false;
match result {
Ok(devices) => {
st.notice = if devices.is_empty() { "Nem található Bluetooth hangeszköz.".into() } else { "Válaszd ki a hangeszközt a csatlakozáshoz.".into() };
st.bt_audio = Some(Ok(devices));
}
Err(e) => st.notice = format!("Keresés sikertelen: {}", short_err(&e)),
}
}
Loaded::AudioDone(result) => {
let mut st = self.state.borrow_mut();
st.busy = false;
st.notice = match result {
Ok(message) => message,
Err(e) => format!("Hangkimenet: {}", short_err(&e)),
};
drop(st);
post(|| Loaded::Audio(system::audio_outputs().map_err(|e| format!("{e:#}"))));
post(|| Loaded::BtAudio(system::bt_audio_devices().map_err(|e| format!("{e:#}"))));
}
Loaded::Net(n) => self.state.borrow_mut().net = Some(n), Loaded::Net(n) => self.state.borrow_mut().net = Some(n),
Loaded::Wifi(w) => { Loaded::Wifi(w) => {
if let Err(e) = &w { if let Err(e) = &w {
@@ -681,6 +743,33 @@ impl Screen {
Loaded::Removed { name, result, then_pair: true } Loaded::Removed { name, result, then_pair: true }
}); });
} }
Action::AudioOutput(name) => {
let label = match &self.state.borrow().audio {
Some(Ok(outputs)) => outputs.iter().find(|o| o.name == name).map(|o| o.label.clone()),
_ => None,
}.unwrap_or_else(|| name.clone());
self.state.borrow_mut().busy = true;
self.rebuild(None);
post(move || Loaded::AudioDone(system::set_audio_output(&name)
.map(|()| format!("Hangkimenet: {label}"))
.map_err(|e| format!("{e:#}"))));
}
Action::BtAudioScan => {
self.state.borrow_mut().busy = true;
self.rebuild(None);
post(|| Loaded::BtAudioScanDone(system::bt_audio_scan().map_err(|e| format!("{e:#}"))));
}
Action::BtAudioConnect(addr) => {
let label = match &self.state.borrow().bt_audio {
Some(Ok(devices)) => devices.iter().find(|d| d.address == addr).map(|d| d.name.clone()),
_ => None,
}.unwrap_or_else(|| addr.clone());
self.state.borrow_mut().busy = true;
self.rebuild(None);
post(move || Loaded::AudioDone(system::bt_audio_connect(&addr)
.map(|()| format!("Hangkimenet: {label}"))
.map_err(|e| format!("{e:#}"))));
}
Action::Restart => self.enter(Sub::Restart, 1), Action::Restart => self.enter(Sub::Restart, 1),
Action::ConfirmRestart => { Action::ConfirmRestart => {
log::info!("restarting the launcher (settings)"); log::info!("restarting the launcher (settings)");
@@ -776,6 +865,10 @@ impl Screen {
/// Pushes the current page to Slint. `row` moves the focus (clamped). /// Pushes the current page to Slint. `row` moves the focus (clamped).
fn rebuild(&self, row: Option<i32>) { fn rebuild(&self, row: Option<i32>) {
let Some(ui) = self.ui.upgrade() else { return }; let Some(ui) = self.ui.upgrade() else { return };
// The pane shows the App Store: its rows are store_screen's.
if ui.get_set_mode() == "store" {
return;
}
let (title, subtitle, rows, actions) = self.page(); let (title, subtitle, rows, actions) = self.page();
let len = rows.len() as i32; let len = rows.len() as i32;
let in_sub = self.state.borrow().sub != Sub::None; let in_sub = self.state.borrow().sub != Sub::None;
@@ -978,13 +1071,39 @@ impl Screen {
notice_or("Párosított eszközök. Válassz ki egyet az eltávolításhoz."), notice_or("Párosított eszközök. Válassz ki egyet az eltávolításhoz."),
) )
} }
(Sub::None, AUDIO) => {
match &st.audio {
None => push(row("Hangkimenetek lekérdezése…", "", "", "info"), Action::None),
Some(Err(e)) => push(row("A hangrendszer nem érhető el", "", short_err(e), "info"), Action::None),
Some(Ok(outputs)) if outputs.is_empty() => push(row("Nincs elérhető hangkimenet", "", "", "info"), Action::None),
Some(Ok(outputs)) => {
for output in outputs {
let kind = if output.bluetooth { "Bluetooth" } else { "Vezetékes / HDMI" };
push(row(output.label.clone(), if output.selected { "✓" } else { "" }, kind, "option"), Action::AudioOutput(output.name.clone()));
}
}
}
match &st.bt_audio {
Some(Ok(devices)) => for device in devices {
let sink_address = device.address.replace(':', "_").to_ascii_uppercase();
let shown_as_output = device.connected && matches!(&st.audio, Some(Ok(outputs)) if outputs.iter().any(|o| o.name.to_ascii_uppercase().contains(&sink_address)));
if shown_as_output { continue; }
let status = if device.connected { "Csatlakozva" } else if device.paired { "Párosítva" } else { "Új eszköz" };
push(row(device.name.clone(), status, "Bluetooth hangeszköz", "device"), Action::BtAudioConnect(device.address.clone()));
},
Some(Err(e)) => push(row("Bluetooth nem érhető el", "", short_err(e), "info"), Action::None),
None => {}
}
push(row(if st.busy { "Folyamatban…" } else { "Bluetooth hangeszközök keresése" }, "", "Kapcsold be az eszköz párosítási módját", "action"), Action::BtAudioScan);
("Hangkimenet".to_string(), notice_or("Válaszd ki, hol szóljon a TV. Bluetooth eszközhöz indíts keresést."))
}
(Sub::None, NETWORK) => { (Sub::None, NETWORK) => {
match &st.net { match &st.net {
None => push(row("Hálózat lekérdezése…", "", "", "info"), Action::None), None => push(row("Hálózat lekérdezése…", "", "", "info"), Action::None),
Some(n) => { Some(n) => {
let conn = match (&n.iface, n.ip.is_some(), n.wireless) { let conn = match (&n.iface, n.ip.is_some(), n.wireless) {
(Some(i), true, true) => format!("Wi-Fi · {i}"), (Some(_), true, true) => "Wi-Fi".to_string(),
(Some(i), true, false) => format!("Vezetékes · {i}"), (Some(_), true, false) => "Vezetékes".to_string(),
_ => "Nincs kapcsolat".to_string(), _ => "Nincs kapcsolat".to_string(),
}; };
push(row("Kapcsolat", conn, "", "info"), Action::None); push(row("Kapcsolat", conn, "", "info"), Action::None);
@@ -1002,7 +1121,8 @@ impl Screen {
(false, true) => "Be", (false, true) => "Be",
(false, false) => "Ki", (false, false) => "Ki",
}; };
push(row("Wi-Fi", value, w.iface.clone(), "action"), Action::WifiPower); let joined = w.networks.iter().find(|n| n.connected).map(|n| format!("Csatlakozva: {}", n.name));
push(row("Wi-Fi", value, joined.unwrap_or_default(), "action"), Action::WifiPower);
if w.powered { if w.powered {
if w.networks.is_empty() { if w.networks.is_empty() {
let text = if w.scanning { "Hálózatok keresése…" } else { "Nincs elérhető hálózat" }; let text = if w.scanning { "Hálózatok keresése…" } else { "Nincs elérhető hálózat" };
@@ -1066,7 +1186,7 @@ impl Screen {
(Sub::None, _) => { (Sub::None, _) => {
let info = st.info.clone().unwrap_or_default(); let info = st.info.clone().unwrap_or_default();
push(row("Eszköz neve", info.hostname, "", "info"), Action::None); push(row("Eszköz neve", info.hostname, "", "info"), Action::None);
push(row("SmartFox", format!("v{}", env!("CARGO_PKG_VERSION")), "", "info"), Action::None); push(row("Fennec OS", format!("v{}", env!("CARGO_PKG_VERSION")), "", "info"), Action::None);
push(row("Operációs rendszer", info.os, "", "info"), Action::None); push(row("Operációs rendszer", info.os, "", "info"), Action::None);
push(row("Kernel", info.kernel, "", "info"), Action::None); push(row("Kernel", info.kernel, "", "info"), Action::None);
let ip = st.net.as_ref().and_then(|n| n.ip.clone()); let ip = st.net.as_ref().and_then(|n| n.ip.clone());
@@ -1096,8 +1216,8 @@ impl Screen {
} }
/// Glass for the settings screen. Mirrors the geometry in ui/settings.slint. /// Glass for the settings screen. Mirrors the geometry in ui/settings.slint.
pub fn glass(ui: &App, scale: f32) -> Vec<crate::glass::Panel> { pub fn glass(ui: &App, scale: f32) -> Vec<sf_ui::render::Panel> {
use crate::glass::Panel; use sf_ui::render::Panel;
use slint::Model; use slint::Model;
let t = ui.get_set_t(); let t = ui.get_set_t();
@@ -1120,51 +1240,63 @@ pub fn glass(ui: &App, scale: f32) -> Vec<crate::glass::Panel> {
tint, tint,
}; };
let white = [1.0, 1.0, 1.0]; let white = [1.0, 1.0, 1.0];
let (sx, sy, sw, sh) = (ui.get_sp_x(), ui.get_sp_y(), ui.get_sp_w(), ui.get_sp_h()); // The on-screen keyboard takes over the screen: categories and rows fade out.
let mut out = vec![panel(sx, sy, sw, sh, 52.0 * u, 0.15 * t, t, 3.6, [0.79, 0.83, 0.88], [0.04, 0.043, 0.063, 0.40])];
// The on-screen keyboard takes over the pane: categories and rows fade out.
let content = t * (1.0 - ui.get_kb_t()); let content = t * (1.0 - ui.get_kb_t());
let mut out = Vec::new();
// Category column: focus glides with nav-pos, the selected one stays lit. // Category column: no glass at rest. The selected category keeps a faint
// pill while the rows are focused; the focused one is a white pill.
let (nx, ny, nw, nh, nstep) = (ui.get_nav_x(), ui.get_nav_y(), ui.get_nav_w(), ui.get_nav_h(), ui.get_nav_step()); let (nx, ny, nw, nh, nstep) = (ui.get_nav_x(), ui.get_nav_y(), ui.get_nav_w(), ui.get_nav_h(), ui.get_nav_step());
let (nav_pos, nav_active) = (ui.get_nav_pos(), ui.get_nav_active()); let (nav_pos, nav_active) = (ui.get_nav_pos(), ui.get_nav_active());
for i in 0..ui.get_set_nav_count() { for i in 0..ui.get_set_nav_count() {
let sel = (1.0 - (nav_pos - i as f32).abs()).max(0.0); let sel = (1.0 - (nav_pos - i as f32).abs()).max(0.0);
let f = sel * nav_active; let f = sel * nav_active;
let amount = 0.10 * sel * (1.0 - nav_active) + 0.86 * f;
if amount <= 0.002 {
continue;
}
let s = 1.0 + 0.03 * f; let s = 1.0 + 0.03 * f;
let (w, h) = (nw * s, nh * s); let (w, h) = (nw * s, nh * s);
let y = ny + i as f32 * nstep; let y = ny + i as f32 * nstep;
out.push(panel(nx - (w - nw) / 2.0, y - (h - nh) / 2.0, w, h, 26.0 * u * s, f, content, -1.0, white, [1.0, 1.0, 1.0, 0.035 + 0.16 * sel + 0.66 * f])); out.push(panel(nx - (w - nw) / 2.0, y - (h - nh) / 2.0, w, h, h / 2.0, f, content, -1.0, white, [1.0, 1.0, 1.0, amount]));
} }
// Back chip.
out.push(panel(nx, sy + sh - 92.0 * u, 300.0 * u, 56.0 * u, 28.0 * u, 0.0, t, -1.0, white, [1.0, 1.0, 1.0, 0.03]));
// Rows, scrolled and faded at the edges of the list area. // One grouped platter behind the visible rows.
let (rx, ry, rw) = (ui.get_rows_x(), ui.get_rows_y(), ui.get_rows_w()); let (rx, ry, rw) = (ui.get_rows_x(), ui.get_rows_y(), ui.get_rows_w());
let (rh, rstep, view, scroll) = (ui.get_set_row_h(), ui.get_set_row_step(), ui.get_rows_view_h(), ui.get_rows_scroll()); let (rh, rstep, view, scroll) = (ui.get_set_row_h(), ui.get_set_row_step(), ui.get_rows_view_h(), ui.get_rows_scroll());
let rows = ui.get_set_rows();
let n = rows.row_count();
if n > 0 {
let visible = (n as f32 * rstep).min(view);
let pad = 8.0 * u;
out.push(panel(rx, ry - pad, rw, visible + 2.0 * pad, 32.0 * u, 0.0, content, 2.2, white, [0.04, 0.045, 0.06, 0.30]));
}
// Focus pill on the focused row (rows are inset by the platter padding).
let inset = 8.0 * u;
let (row_pos, active) = (ui.get_row_pos(), ui.get_content_active()); let (row_pos, active) = (ui.get_row_pos(), ui.get_content_active());
for (j, row) in ui.get_set_rows().iter().enumerate() { for (j, row) in rows.iter().enumerate() {
let top = ry + j as f32 * rstep - scroll; let top = ry + j as f32 * rstep - scroll;
let over = (ry - top).max(top + rh - (ry + view)) / rh; let over = (ry - top).max(top + rh - (ry + view)) / rh;
let vis = (1.0 - over).clamp(0.0, 1.0); let vis = (1.0 - over).clamp(0.0, 1.0);
if vis <= 0.01 { let f = (1.0 - (row_pos - j as f32).abs()).max(0.0) * active;
if vis <= 0.01 || f <= 0.002 {
continue; continue;
} }
let f = (1.0 - (row_pos - j as f32).abs()).max(0.0) * active; let (x0, w0) = (rx + inset, rw - 2.0 * inset);
let s = 1.0 + 0.02 * f; let s = 1.0 + 0.015 * f;
let (w, h) = (rw * s, rh * s); let (w, h) = (w0 * s, rh * s);
let (glow, tint) = if row.kind == "danger" { let (glow, tint) = if row.kind == "danger" {
let red = [1.0, 0.27, 0.23]; ([1.0, 0.27, 0.23], [1.0, 0.27, 0.23, 0.86 * f])
(red, [1.0, 0.27, 0.23, 0.10 + 0.72 * f])
} else { } else {
(white, [1.0, 1.0, 1.0, 0.04 + 0.80 * f]) (white, [1.0, 1.0, 1.0, 0.88 * f])
}; };
out.push(panel(rx - (w - rw) / 2.0, top - (h - rh) / 2.0, w, h, 24.0 * u * s, f, content * vis, -1.0, glow, tint)); out.push(panel(x0 - (w - w0) / 2.0, top - (h - rh) / 2.0, w, h, 24.0 * u * s, f, content * vis, -1.0, glow, tint));
} }
out out
} }
/// Value and detail for the Updates row: "2 frissítés" / "SmartFox felület 0.2.0 · YouTube 1.1.0". /// Value and detail for the Updates row: "2 frissítés" / "Fennec OS felület 0.2.0 · YouTube 1.1.0".
fn update_summary(u: &UpdateStatus) -> (String, String) { fn update_summary(u: &UpdateStatus) -> (String, String) {
let checked = || { let checked = || {
use chrono::TimeZone; use chrono::TimeZone;

View File

@@ -0,0 +1,296 @@
//! Top Shelf content for Netflex on the home screen. Optional: the home screen
//! is complete without it (the shelf then shows the app itself).
//!
//! Sources, first that answers wins:
//! 1. the Netflex server's `/api/home` with `netflex_token` from settings.toml:
//! continue watching, else the first catalog row. Artwork comes through the
//! server's image cache (`/api/img`), like in the Netflex apps;
//! 2. Cinemeta's public "popular movies" list (the catalog Netflex browses).
//!
//! The last good result is kept in `<data_dir>/cache/shelf/` and shown at
//! start, so the shelf survives restarts without a network.
use std::io::Read;
use std::path::{Path, PathBuf};
use std::time::Duration;
use anyhow::{Context, Result, bail};
use serde::{Deserialize, Serialize};
/// Cards the home screen shows.
const MAX_ITEMS: usize = 4;
const REFRESH: Duration = Duration::from_secs(15 * 60);
const CINEMETA_TOP: &str = "https://v3-cinemeta.strem.io/catalog/movie/top.json";
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Item {
pub title: String,
pub detail: String,
/// Artwork file name inside the cache folder.
pub image: Option<String>,
/// 0..1 watched; 0 = no progress bar.
pub progress: f32,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Shelf {
pub title: String,
pub items: Vec<Item>,
}
pub struct Source {
/// Netflex server base URL ("https://netflex.example").
pub server: Option<String>,
pub token: Option<String>,
/// `<data_dir>/cache/shelf`.
pub dir: PathBuf,
}
/// Loads the cached shelf, then refreshes it every 15 minutes on a background
/// thread. `on_update` gets the shelf and the folder its images are in.
pub fn spawn(source: Source, on_update: impl Fn(Shelf, PathBuf) + Send + 'static) {
let spawned = std::thread::Builder::new().name("shelf".into()).spawn(move || {
let cache = source.dir.join("shelf.json");
if let Some(shelf) = std::fs::read_to_string(&cache).ok().and_then(|t| serde_json::from_str::<Shelf>(&t).ok()) {
on_update(shelf, source.dir.clone());
}
let agent: ureq::Agent = ureq::Agent::config_builder()
.timeout_global(Some(Duration::from_secs(20)))
.user_agent(concat!("FennecOS-launcher/", env!("CARGO_PKG_VERSION")))
.build()
.into();
loop {
match fetch(&agent, &source) {
Ok(shelf) if !shelf.items.is_empty() => {
if let Err(e) = std::fs::write(&cache, serde_json::to_string(&shelf).unwrap_or_default()) {
log::warn!("shelf cache: {e}");
}
prune(&source.dir, &shelf);
on_update(shelf, source.dir.clone());
}
Ok(_) => log::info!("shelf: nothing to show"),
Err(e) => log::info!("shelf: {e:#}"),
}
std::thread::sleep(REFRESH);
}
});
if let Err(e) = spawned {
log::warn!("shelf thread: {e}");
}
}
fn fetch(agent: &ureq::Agent, source: &Source) -> Result<Shelf> {
std::fs::create_dir_all(&source.dir).with_context(|| format!("creating {}", source.dir.display()))?;
if let (Some(server), Some(token)) = (&source.server, &source.token) {
match netflex(agent, server.trim_end_matches('/'), token, &source.dir) {
Ok(shelf) if !shelf.items.is_empty() => return Ok(shelf),
Ok(_) => {}
Err(e) => log::info!("shelf: Netflex: {e:#}"),
}
}
cinemeta(agent, &source.dir)
}
// ---- Netflex -----------------------------------------------------------------
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Title {
id: String,
title: String,
backdrop: Option<String>,
year_label: Option<String>,
}
#[derive(Deserialize)]
struct Continue {
title: Title,
season: Option<u32>,
episode: Option<u32>,
position: Option<f64>,
duration: Option<f64>,
}
#[derive(Deserialize)]
struct Row {
title: String,
items: Vec<Title>,
}
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Home {
#[serde(default)]
rows: Vec<Row>,
#[serde(default)]
continue_watching: Vec<Continue>,
}
fn netflex(agent: &ureq::Agent, server: &str, token: &str, dir: &Path) -> Result<Shelf> {
let auth = format!("Bearer {token}");
let resp = agent.get(format!("{server}/api/home")).header("Authorization", &auth).call().context("/api/home")?;
let home: Home = serde_json::from_str(&read_text(resp, 4 << 20)?).context("parsing /api/home")?;
let image = |t: &Title| {
let url = t.backdrop.as_deref()?;
let req = agent.get(format!("{server}/api/img")).query("u", url).header("Authorization", &auth);
download(req, dir, &t.id)
};
if !home.continue_watching.is_empty() {
let items = home
.continue_watching
.iter()
.take(MAX_ITEMS)
.map(|c| {
let (pos, dur) = (c.position.unwrap_or(0.0), c.duration.unwrap_or(0.0));
let left = if dur > pos && pos > 0.0 { Some(((dur - pos) / 60.0).ceil() as u32) } else { None };
let detail = match (c.season, c.episode, left) {
(Some(s), Some(e), Some(m)) => format!("{s}. évad, {e}. rész · még {m} perc"),
(Some(s), Some(e), None) => format!("{s}. évad, {e}. rész"),
(_, _, Some(m)) => format!("Még {m} perc"),
_ => c.title.year_label.clone().unwrap_or_default(),
};
let progress = if dur > 0.0 { (pos / dur).clamp(0.0, 1.0) as f32 } else { 0.0 };
Item { title: c.title.title.clone(), detail, image: image(&c.title), progress }
})
.collect();
return Ok(Shelf { title: "Folytatás".into(), items });
}
let Some(row) = home.rows.into_iter().find(|r| !r.items.is_empty()) else {
return Ok(Shelf::default());
};
let items = row
.items
.iter()
.take(MAX_ITEMS)
.map(|t| Item { title: t.title.clone(), detail: t.year_label.clone().unwrap_or_default(), image: image(t), progress: 0.0 })
.collect();
Ok(Shelf { title: row.title, items })
}
// ---- Cinemeta ------------------------------------------------------------------
#[derive(Deserialize)]
#[serde(rename_all = "camelCase")]
struct Meta {
id: String,
name: String,
background: Option<String>,
release_info: Option<String>,
imdb_rating: Option<String>,
}
#[derive(Deserialize)]
struct Catalog {
metas: Vec<Meta>,
}
fn cinemeta(agent: &ureq::Agent, dir: &Path) -> Result<Shelf> {
let resp = agent.get(CINEMETA_TOP).call().context("Cinemeta")?;
let catalog: Catalog = serde_json::from_str(&read_text(resp, 8 << 20)?).context("parsing Cinemeta")?;
let items = catalog
.metas
.iter()
.filter(|m| m.background.is_some())
.take(MAX_ITEMS)
.map(|m| {
let rating = m.imdb_rating.as_ref().filter(|r| !r.trim().is_empty());
let year = m.release_info.as_ref().filter(|y| !y.trim().is_empty());
let detail = match (year, rating) {
(Some(y), Some(r)) => format!("{y} · IMDb {r}"),
(Some(y), None) => y.clone(),
(None, Some(r)) => format!("IMDb {r}"),
(None, None) => String::new(),
};
let image = m.background.as_deref().and_then(|url| download(agent.get(url), dir, &m.id));
Item { title: m.name.clone(), detail, image, progress: 0.0 }
})
.collect();
Ok(Shelf { title: "Népszerű filmek".into(), items })
}
// ---- files ---------------------------------------------------------------------
fn read_text(resp: ureq::http::Response<ureq::Body>, limit: u64) -> Result<String> {
let mut text = String::new();
resp.into_body().into_reader().take(limit + 1).read_to_string(&mut text)?;
if text.len() as u64 > limit {
bail!("response is too large");
}
Ok(text)
}
const IMAGE_EXTS: [&str; 3] = ["jpg", "png", "webp"];
/// Image type from the first bytes (the decoder picks it by extension).
fn image_ext(bytes: &[u8]) -> Option<&'static str> {
match bytes {
[0xff, 0xd8, ..] => Some("jpg"),
[0x89, b'P', b'N', b'G', ..] => Some("png"),
[b'R', b'I', b'F', b'F', _, _, _, _, b'W', b'E', b'B', b'P', ..] => Some("webp"),
_ => None,
}
}
/// Saves the artwork as `<id>.<ext>`, reusing a file that is already there.
fn download(req: ureq::RequestBuilder<ureq::typestate::WithoutBody>, dir: &Path, id: &str) -> Option<String> {
let stem: String = id.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_').collect();
if stem.is_empty() {
return None;
}
if let Some(name) = IMAGE_EXTS.iter().map(|ext| format!("{stem}.{ext}")).find(|n| dir.join(n).exists()) {
return Some(name);
}
let result = (|| -> Result<String> {
let resp = req.call()?;
let mut bytes = Vec::new();
resp.into_body().into_reader().take(8 << 20).read_to_end(&mut bytes)?;
let ext = image_ext(&bytes).context("not a JPEG, PNG or WebP image")?;
let name = format!("{stem}.{ext}");
let tmp = dir.join(format!("{stem}.part"));
std::fs::write(&tmp, &bytes)?;
std::fs::rename(&tmp, dir.join(&name))?;
Ok(name)
})();
match result {
Ok(name) => Some(name),
Err(e) => {
log::info!("shelf: artwork for {id}: {e:#}");
None
}
}
}
/// Removes artwork the current shelf no longer uses.
fn prune(dir: &Path, shelf: &Shelf) {
let keep: Vec<&str> = shelf.items.iter().filter_map(|i| i.image.as_deref()).collect();
let Ok(entries) = std::fs::read_dir(dir) else { return };
for e in entries.flatten() {
let name = e.file_name().to_string_lossy().to_string();
let artwork = name.rsplit_once('.').is_some_and(|(_, ext)| IMAGE_EXTS.contains(&ext) || ext == "part");
if artwork && !keep.contains(&name.as_str()) {
let _ = std::fs::remove_file(e.path());
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn sniffs_image_types() {
assert_eq!(image_ext(&[0xff, 0xd8, 0xff, 0xe0]), Some("jpg"));
assert_eq!(image_ext(b"\x89PNG\r\n"), Some("png"));
assert_eq!(image_ext(b"RIFF\0\0\0\0WEBPVP8 "), Some("webp"));
assert_eq!(image_ext(b"<html>"), None);
}
#[test]
fn parses_netflex_home() {
let json = r#"{"rows":[{"id":"popular-movie","title":"Népszerű filmek","items":[{"type":"movie","id":"tt1","tmdbId":null,"title":"A","originalTitle":null,"overview":null,"poster":null,"backdrop":"https://x/b.jpg","year":2024,"yearLabel":"2024","rating":7.1,"genres":[]}]}],
"continueWatching":[{"title":{"type":"tv","id":"tt2","title":"B","backdrop":null,"yearLabel":"2021–"},"season":2,"episode":3,"position":600,"duration":2400,"updatedAt":"2026-10-01T10:00:00Z"}]}"#;
let home: Home = serde_json::from_str(json).unwrap();
assert_eq!(home.rows[0].items[0].year_label.as_deref(), Some("2024"));
assert_eq!(home.continue_watching[0].season, Some(2));
}
}

View File

@@ -0,0 +1,70 @@
//! Live TV state for the home screen: network, the Siri Remote's battery and
//! the display mode. The probes shell out (ip, busctl, bluetoothctl,
//! wlr-randr), so they run on a background thread.
use std::time::Duration;
use crate::system;
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Status {
/// "wired" | "wifi" | "none" (icon names in ui/icons.slint).
pub net: &'static str,
/// "Vezetékes hálózat", the Wi-Fi name, or "Nincs hálózat".
pub net_label: String,
pub remote_battery: Option<u8>,
pub remote_connected: bool,
/// "4K UHD · 60 Hz".
pub display: Option<String>,
}
pub fn probe() -> Status {
let info = system::network();
let (net, net_label) = match (&info.iface, info.wireless) {
(None, _) => ("none", "Nincs hálózat".to_string()),
(Some(_), false) => ("wired", "Vezetékes hálózat".to_string()),
(Some(_), true) => {
let name = system::wifi()
.ok()
.flatten()
.and_then(|w| w.networks.into_iter().find(|n| n.connected).map(|n| n.name));
("wifi", name.unwrap_or_else(|| "Wi-Fi".into()))
}
};
let remote = system::bt_devices().ok().and_then(|d| d.into_iter().find(|d| d.remote));
let display = system::display().ok().and_then(|d| {
d.current_mode().map(|m| {
let hz = m.hz.round() as u32;
match m.name() {
"" => format!("{} × {} · {hz} Hz", m.w, m.h),
name => format!("{name} · {hz} Hz"),
}
})
});
Status {
net,
net_label,
remote_battery: remote.as_ref().and_then(|r| r.battery),
remote_connected: remote.as_ref().is_some_and(|r| r.connected),
display,
}
}
/// Probes now and then every 20 s; `on_change` runs (on the probe thread)
/// whenever something changed.
pub fn spawn(on_change: impl Fn(Status) + Send + 'static) {
let spawned = std::thread::Builder::new().name("status".into()).spawn(move || {
let mut last: Option<Status> = None;
loop {
let now = probe();
if last.as_ref() != Some(&now) {
on_change(now.clone());
last = Some(now);
}
std::thread::sleep(Duration::from_secs(20));
}
});
if let Err(e) = spawned {
log::warn!("status thread: {e}");
}
}

View File

@@ -0,0 +1,609 @@
//! The App Store screen (docs/store.md). It reuses the settings pane: the
//! same Slint view and glass, in "store" mode (`set-mode`), with its own
//! categories and rows.
//!
//! The launcher runs as user tv and can't install anything: it writes what
//! the user wants into store.toml and asks sf-update (root) to act on it
//! (`store` request). It reads back what the sources offer from catalog.json
//! and sf-update's progress from status.json.
use std::cell::RefCell;
use std::path::PathBuf;
use std::rc::Rc;
use std::time::Duration;
use sf_ipc::Permission;
use sf_ipc::store::{CATALOG_FILE, Catalog, CatalogApp, SourceInfo, WANTED_FILE, Wanted, WantedApp, missing_permissions};
use slint::{ComponentHandle, ModelRc, SharedString, VecModel};
use crate::system::{self, UpdateStatus};
use crate::{App, SettingRow, keyboard};
// Categories, as in app.slint (set-categories in store mode): Felfedezés,
// Telepítve, Források (anything else).
const DISCOVER: i32 = 0;
const INSTALLED: i32 = 1;
#[derive(Clone, PartialEq)]
enum Action {
None,
App(String),
Install(String),
Approve(String),
Uninstall(String),
UninstallWithData(String),
Source(String),
AddSource,
RemoveSource(String),
Refresh,
Back,
}
#[derive(Clone, PartialEq)]
enum Sub {
None,
App(String),
Source(String),
}
struct State {
category: i32,
sub: Sub,
parent_row: i32,
wanted: Wanted,
catalog: Option<Catalog>,
status: Option<UpdateStatus>,
notice: String,
actions: Vec<Action>,
/// Ids of installed store apps last time we looked; a change reloads the
/// launcher's app list once the store is closed.
installed: Vec<String>,
reload_pending: bool,
}
pub struct Screen {
ui: slint::Weak<App>,
state: RefCell<State>,
on_apps_changed: RefCell<Option<Box<dyn Fn()>>>,
timer: slint::Timer,
}
thread_local! {
static SCREEN: RefCell<Option<Rc<Screen>>> = const { RefCell::new(None) };
/// Demo (Windows / SMARTFOX_DEMO_SYSTEM): store.toml and catalog in memory.
static DEMO: RefCell<Option<(Wanted, Catalog)>> = const { RefCell::new(None) };
}
pub fn current() -> Option<Rc<Screen>> {
SCREEN.with(|s| s.borrow().clone())
}
fn row(title: impl Into<SharedString>, value: impl Into<SharedString>, detail: impl Into<SharedString>, kind: &str) -> SettingRow {
SettingRow { title: title.into(), value: value.into(), detail: detail.into(), kind: kind.into(), level: 0, lock: false }
}
fn short(text: &str, max: usize) -> String {
let line = text.lines().next().unwrap_or(text);
if line.chars().count() > max { format!("{}…", line.chars().take(max).collect::<String>()) } else { line.to_string() }
}
/// "github.com/fox/app" for display.
fn pretty_source(url: &str) -> String {
url.trim_start_matches("https://").to_string()
}
fn permissions_text(perms: &[Permission]) -> String {
if perms.is_empty() {
return "Nem kér külön engedélyt".into();
}
perms.iter().map(|p| p.label()).collect::<Vec<_>>().join(", ")
}
fn wanted_path() -> PathBuf {
std::env::var_os("SMARTFOX_STORE_FILE").map(PathBuf::from).unwrap_or_else(|| WANTED_FILE.into())
}
fn demo_catalog() -> Catalog {
let app = |id: &str, name: &str, cat: &str, desc: &str, perms: Vec<Permission>| CatalogApp {
id: id.into(),
name: name.into(),
version: "1.2.0".into(),
kind: "exec".into(),
category: cat.into(),
description: desc.into(),
author: "Példa Fejlesztő".into(),
homepage: format!("https://github.com/example/{name}"),
license: "MIT".into(),
permissions: perms,
source: format!("https://github.com/example/{}", name.to_lowercase()),
catalog: Some("https://github.com/example/fennec-catalog".into()),
..Default::default()
};
Catalog {
updated_at: 1_792_800_000,
sources: vec![SourceInfo {
url: "https://github.com/example/fennec-catalog".into(),
kind: "catalog".into(),
name: "Példa katalógus".into(),
apps: 3,
error: None,
}],
apps: vec![
app("io.github.example.retro", "RetroArch", "Játékok · Emulátor", "Régi konzolok játékai kontrollerrel.", vec![Permission::Gpu, Permission::Audio, Permission::Gamepad]),
app("io.github.example.radio", "Rádió", "Zene", "Internetes rádióállomások.", vec![Permission::Network, Permission::Audio]),
app("io.github.example.clock", "Óra", "Eszköz", "Nagy óra és időjárás a TV-n.", vec![Permission::Network]),
],
}
}
fn load_wanted() -> Wanted {
if system::demo() {
return DEMO.with(|d| d.borrow().as_ref().map(|(w, _)| w.clone())).unwrap_or_default();
}
Wanted::load(&wanted_path()).unwrap_or_else(|e| {
log::warn!("store: {e:#}");
Wanted::default()
})
}
fn load_catalog() -> Option<Catalog> {
if system::demo() {
return DEMO.with(|d| {
let mut d = d.borrow_mut();
let (_, c) = d.get_or_insert_with(|| (Wanted::default(), demo_catalog()));
Some(c.clone())
});
}
Catalog::load(std::path::Path::new(CATALOG_FILE))
}
impl Screen {
pub fn install(ui: &App) -> Rc<Screen> {
let screen = Rc::new(Screen {
ui: ui.as_weak(),
state: RefCell::new(State {
category: 0,
sub: Sub::None,
parent_row: 0,
wanted: Wanted::default(),
catalog: None,
status: None,
notice: String::new(),
actions: Vec::new(),
installed: Vec::new(),
reload_pending: false,
}),
on_apps_changed: RefCell::new(None),
timer: slint::Timer::default(),
});
SCREEN.with(|s| *s.borrow_mut() = Some(screen.clone()));
screen.state.borrow_mut().installed = installed_ids();
// While open: follow sf-update's progress and the catalog. Once closed
// after apps were installed or removed: reload the app list.
let weak = Rc::downgrade(&screen);
screen.timer.start(slint::TimerMode::Repeated, Duration::from_secs(2), move || {
let Some(s) = weak.upgrade() else { return };
if s.is_open() {
s.reload();
} else if std::mem::take(&mut s.state.borrow_mut().reload_pending) {
if let Some(f) = s.on_apps_changed.borrow().as_ref() {
f();
}
}
});
screen
}
/// Called after the store is closed if store apps were installed or removed.
pub fn on_apps_changed(&self, f: impl Fn() + 'static) {
*self.on_apps_changed.borrow_mut() = Some(Box::new(f));
}
fn is_open(&self) -> bool {
self.ui.upgrade().is_some_and(|ui| ui.get_settings_open() && ui.get_set_mode() == "store")
}
pub fn opened(&self) {
{
let mut st = self.state.borrow_mut();
st.notice.clear();
st.sub = Sub::None;
st.category = 0;
}
self.reload();
self.rebuild(Some(0));
}
pub fn nav_changed(&self, i: i32) {
{
let mut st = self.state.borrow_mut();
st.category = i;
st.sub = Sub::None;
st.notice.clear();
}
self.rebuild(Some(0));
}
pub fn activate(&self, index: i32) {
let action = self.state.borrow().actions.get(index as usize).cloned().unwrap_or(Action::None);
if !matches!(action, Action::None) && self.state.borrow().sub == Sub::None {
self.state.borrow_mut().parent_row = index;
}
self.run(action);
}
pub fn back(&self) {
self.run(Action::Back);
}
/// Re-reads store.toml, catalog.json and status.json.
fn reload(&self) {
let wanted = load_wanted();
let catalog = load_catalog();
let status = system::update_status();
{
let mut st = self.state.borrow_mut();
st.wanted = wanted;
st.catalog = catalog;
st.status = status;
}
let now = installed_ids();
let changed = {
let mut st = self.state.borrow_mut();
let changed = st.installed != now;
st.installed = now;
changed
};
if changed {
self.state.borrow_mut().reload_pending = true;
}
if self.is_open() {
self.rebuild(None);
}
}
fn busy(&self) -> bool {
self.state.borrow().status.as_ref().is_some_and(UpdateStatus::busy)
}
/// Saves store.toml and asks sf-update to act on it.
fn save(&self, notice: &str, f: impl FnOnce(&mut Wanted)) {
let mut wanted = load_wanted();
f(&mut wanted);
let result = if system::demo() {
DEMO.with(|d| {
let mut d = d.borrow_mut();
let (w, c) = d.get_or_insert_with(|| (Wanted::default(), demo_catalog()));
*w = wanted.clone();
for app in &mut c.apps {
app.installed = w.apps.contains_key(&app.id).then(|| app.version.clone());
}
});
Ok(())
} else {
wanted.save(&wanted_path()).and_then(|()| system::request_update("store"))
};
self.state.borrow_mut().notice = match result {
Ok(()) => notice.to_string(),
Err(e) => {
log::warn!("store: {e:#}");
format!("Nem sikerült: {}", short(&format!("{e:#}"), 60))
}
};
self.reload();
}
fn app(&self, id: &str) -> Option<CatalogApp> {
self.state.borrow().catalog.as_ref().and_then(|c| c.app(id).cloned())
}
fn enter(&self, sub: Sub) {
self.state.borrow_mut().sub = sub;
self.rebuild(Some(0));
}
fn leave(&self) {
let parent = {
let mut st = self.state.borrow_mut();
st.sub = Sub::None;
st.parent_row
};
self.rebuild(Some(parent));
}
fn run(&self, action: Action) {
let with_data = matches!(action, Action::UninstallWithData(_));
match action {
Action::None => {}
Action::Back => {
if self.state.borrow().sub != Sub::None {
self.leave();
}
}
Action::App(id) => self.enter(Sub::App(id)),
Action::Source(url) => self.enter(Sub::Source(url)),
Action::Install(id) | Action::Approve(id) => {
let Some(app) = self.app(&id) else { return };
if self.busy() {
return;
}
let notice = format!("{} telepítése…", app.name);
self.save(&notice, |w| {
w.apps.insert(app.id.clone(), WantedApp { source: app.source.clone(), permissions: app.permissions.clone() });
});
}
Action::Uninstall(id) | Action::UninstallWithData(id) => {
let name = self.app(&id).map(|a| a.name).unwrap_or_else(|| id.clone());
self.save(&format!("{name} eltávolítva."), |w| {
w.apps.remove(&id);
});
if with_data && sf_ipc::manifest::is_store_id(&id) {
let dir = sf_ipc::paths::app_data_dir(&id);
if dir.is_dir() {
if let Err(e) = std::fs::remove_dir_all(&dir) {
log::warn!("removing {}: {e}", dir.display());
}
}
}
self.leave();
}
Action::RemoveSource(url) => {
self.save("Forrás eltávolítva. Az innen telepített appok megmaradnak.", |w| {
w.sources.retain(|s| sf_ipc_canonical(s) != url);
});
self.leave();
}
Action::Refresh => {
if self.busy() {
return;
}
self.save("Források frissítése…", |_| {});
}
Action::AddSource => self.ask_source(None),
}
}
/// On-screen keyboard for a repo address.
fn ask_source(&self, error: Option<String>) {
let Some(ui) = self.ui.upgrade() else { return };
keyboard::open(
&ui,
keyboard::Request {
title: "Forrás hozzáadása".into(),
subtitle: "Egy app vagy egy katalógus repója GitHubon, Giteán vagy GitLabon, pl. github.com/valaki/app".into(),
placeholder: "github.com/felhasználó/repó".into(),
secret: false,
submit_label: "Hozzáadás".into(),
min_len: 5,
max_len: 200,
error,
on_submit: Box::new(|text| {
if let Some(s) = current() {
s.add_source(text);
}
}),
},
);
}
fn add_source(&self, text: String) {
let url = sf_ipc_canonical(&text);
if !looks_like_repo(&url) {
self.ask_source(Some("Ez nem egy repó címe (host/tulajdonos/repó).".into()));
return;
}
if load_wanted().sources.iter().any(|s| sf_ipc_canonical(s) == url) {
self.state.borrow_mut().notice = "Ez a forrás már szerepel.".into();
self.rebuild(None);
return;
}
// Kept as typed: a gitlab:/gitea: prefix tells sf-update the forge of a self-hosted server.
let typed = text.trim().trim_end_matches('/').to_string();
self.save(&format!("{} hozzáadva, az appjai hamarosan megjelennek.", pretty_source(&url)), |w| w.sources.push(typed));
}
fn rebuild(&self, row: Option<i32>) {
let Some(ui) = self.ui.upgrade() else { return };
let (title, subtitle, rows, actions) = self.page();
let len = rows.len() as i32;
let in_sub = self.state.borrow().sub != Sub::None;
let focused = self.state.borrow().actions.get(ui.get_set_row().max(0) as usize).cloned();
let same_item = match (row, focused) {
(None, Some(a)) if a != Action::None => actions.iter().position(|b| *b == a).map(|i| i as i32),
_ => None,
};
self.state.borrow_mut().actions = actions;
ui.set_set_title(title.into());
ui.set_set_subtitle(subtitle.into());
ui.set_set_rows(ModelRc::new(VecModel::from(rows)));
ui.set_set_sub(in_sub);
let target = row.or(same_item).unwrap_or_else(|| ui.get_set_row());
ui.set_set_row(target.clamp(0, (len - 1).max(0)));
}
fn page(&self) -> (String, String, Vec<SettingRow>, Vec<Action>) {
let st = self.state.borrow();
let mut rows = Vec::new();
let mut actions = Vec::new();
let mut push = |r: SettingRow, a: Action| {
rows.push(r);
actions.push(a);
};
let busy = st.status.as_ref().is_some_and(UpdateStatus::busy);
let progress = st.status.as_ref().filter(|s| s.busy()).map(|s| match s.state.as_str() {
"checking" => "Források lekérdezése…".to_string(),
"downloading" => format!("Letöltés: {}", s.message),
_ => "Telepítés…".to_string(),
});
let error = st.status.as_ref().filter(|s| s.state == "error").map(|s| format!("Hiba: {}", short(&s.message, 70)));
let notice_or = |text: &str| progress.clone().or_else(|| (!st.notice.is_empty()).then(|| st.notice.clone())).or(error.clone()).unwrap_or_else(|| text.to_string());
let catalog = st.catalog.clone().unwrap_or_default();
let (title, subtitle) = match (&st.sub, st.category) {
(Sub::App(id), _) => match catalog.app(id) {
None => {
push(row("Vissza", "", "", "action"), Action::Back);
(id.clone(), "Ez az app már nem érhető el a forrásaidban.".to_string())
}
Some(app) => {
let want = st.wanted.apps.get(&app.id);
let missing = want.map(|w| missing_permissions(&app.permissions, &w.permissions)).unwrap_or_default();
match (&app.installed, want) {
(None, None) => push(row(if busy { "Folyamatban…" } else { "Telepítés" }, "", "Az engedélyeket lent látod", "action"), Action::Install(app.id.clone())),
(None, Some(_)) => push(row("Telepítés folyamatban…", "", "", "info"), Action::None),
(Some(_), _) if !missing.is_empty() => push(
row("Frissítés jóváhagyása", "", format!("Új engedélyt kér: {}", permissions_text(&missing)), "action"),
Action::Approve(app.id.clone()),
),
_ => {}
}
let version = match &app.installed {
Some(i) if i != &app.version => format!("{i} → {}", app.version),
Some(i) => i.clone(),
None => app.version.clone(),
};
push(row("Verzió", version, "", "info"), Action::None);
for p in &app.permissions {
let value = if p.risky() { "Kockázatos" } else { "" };
push(row(p.label(), value, "Engedély", "info"), Action::None);
}
if app.permissions.is_empty() {
push(row("Engedélyek", "Nem kér", "Csak a saját fájljait és a képernyőt éri el", "info"), Action::None);
}
if !app.author.is_empty() {
push(row("Szerző", app.author.clone(), "", "info"), Action::None);
}
push(row("Forrás", pretty_source(&app.source), app.license.clone(), "info"), Action::None);
if want.is_some() || app.installed.is_some() {
push(row("Eltávolítás", "", "Az adatai megmaradnak", "danger"), Action::Uninstall(app.id.clone()));
push(row("Eltávolítás az adataival együtt", "", "", "danger"), Action::UninstallWithData(app.id.clone()));
}
push(row("Vissza", "", "", "action"), Action::Back);
let what = if app.category.is_empty() { String::new() } else { format!("{} · ", app.category) };
(app.name.clone(), notice_or(&format!("{what}{}", app.description)))
}
},
(Sub::Source(url), _) => {
let info = catalog.sources.iter().find(|s| &s.url == url).cloned();
push(row("Forrás eltávolítása", "", "Az innen telepített appok megmaradnak", "danger"), Action::RemoveSource(url.clone()));
push(row("Vissza", "", "", "action"), Action::Back);
let detail = match info {
Some(i) if i.error.is_some() => format!("Hiba: {}", short(i.error.as_deref().unwrap_or(""), 80)),
Some(i) if i.kind == "catalog" => format!("Katalógus · {} app", i.apps),
Some(_) => "App-repó".to_string(),
None => "Még nincs lekérdezve.".to_string(),
};
(pretty_source(url), detail)
}
(Sub::None, DISCOVER) => {
let offer: Vec<&CatalogApp> = catalog.apps.iter().filter(|a| a.installed.is_none() && !st.wanted.apps.contains_key(&a.id)).collect();
if st.wanted.sources.is_empty() && catalog.apps.is_empty() {
push(row("Forrás hozzáadása", "", "GitHub, Gitea vagy GitLab repó", "action"), Action::AddSource);
} else if offer.is_empty() {
push(row("Nincs több telepíthető app", "", "Adj hozzá forrást a Források alatt", "info"), Action::None);
}
for a in offer {
let detail = if a.category.is_empty() { pretty_source(&a.source) } else { a.category.clone() };
push(row(a.name.clone(), a.version.clone(), detail, "choice"), Action::App(a.id.clone()));
}
("Felfedezés".to_string(), notice_or("Nyílt forrású appok a forrásaidból. Mindegyik a saját sandboxában fut."))
}
(Sub::None, INSTALLED) => {
if st.wanted.apps.is_empty() {
push(row("Még nincs telepített app", "", "", "info"), Action::None);
}
for (id, want) in &st.wanted.apps {
let app = catalog.app(id);
let name = app.map(|a| a.name.clone()).unwrap_or_else(|| id.clone());
let (value, detail) = match app {
None => ("…".to_string(), pretty_source(&want.source)),
Some(a) if a.installed.is_none() => ("Telepítés…".to_string(), a.version.clone()),
Some(a) if a.blocked.as_deref() == Some("permissions") => (a.installed.clone().unwrap_or_default(), "Új engedélyt kér · jóváhagyás".to_string()),
Some(a) if a.installed.as_deref() != Some(a.version.as_str()) => {
(format!("{} → {}", a.installed.clone().unwrap_or_default(), a.version), "Frissítés letöltés alatt".to_string())
}
Some(a) => (a.version.clone(), if a.category.is_empty() { pretty_source(&a.source) } else { a.category.clone() }),
};
push(row(name, value, detail, "choice"), Action::App(id.clone()));
}
("Telepítve".to_string(), notice_or("A store appok a többi csomaggal együtt frissülnek (Beállítások → Rendszer → Frissítések)."))
}
(Sub::None, _) => {
push(row("Forrás hozzáadása", "", "GitHub, Gitea vagy GitLab repó", "action"), Action::AddSource);
for url in &st.wanted.sources {
let url = sf_ipc_canonical(url);
let info = catalog.sources.iter().find(|s| s.url == url);
let (value, detail) = match info {
None => ("…".to_string(), "Lekérdezés…".to_string()),
Some(i) if i.error.is_some() => ("Hiba".to_string(), short(i.error.as_deref().unwrap_or(""), 60)),
Some(i) if i.kind == "catalog" => (format!("{} app", i.apps), if i.name.is_empty() { "Katalógus".into() } else { i.name.clone() }),
Some(i) => ("App".to_string(), i.name.clone()),
};
push(row(pretty_source(&url), value, detail, "choice"), Action::Source(url.clone()));
}
let checked = if catalog.updated_at > 0 {
use chrono::TimeZone;
chrono::Local.timestamp_opt(catalog.updated_at as i64, 0).single().map(|t| t.format("Lekérdezve: %m. %d. %H:%M").to_string()).unwrap_or_default()
} else {
String::new()
};
push(row(if busy { "Folyamatban…" } else { "Frissítés most" }, "", checked, "action"), Action::Refresh);
("Források".to_string(), notice_or("Minden app a saját repójában él. Egy katalógus-repó sok appot hoz egyszerre."))
}
};
drop(push);
(title, subtitle, rows, actions)
}
}
/// Ids of the installed store apps (folders under the store apps dir).
fn installed_ids() -> Vec<String> {
if system::demo() {
return DEMO.with(|d| d.borrow().as_ref().map(|(w, _)| w.apps.keys().cloned().collect()).unwrap_or_default());
}
let mut ids: Vec<String> = std::fs::read_dir(sf_ipc::paths::STORE_APPS)
.map(|d| d.flatten().filter(|e| e.path().join("app.toml").exists()).filter_map(|e| e.file_name().into_string().ok()).collect())
.unwrap_or_default();
ids.sort();
ids
}
/// `https://host/owner/repo` from what was typed: the same form sf-update
/// uses in catalog.json (forge::Repo::url), so sources can be matched up.
fn sf_ipc_canonical(input: &str) -> String {
let s = input.trim();
let (prefix, rest) = match s.split_once(':') {
Some((p @ ("github" | "gitea" | "forgejo" | "gitlab"), r)) => (Some(p), r),
_ => (None, s),
};
let rest = rest.trim_start_matches('/').trim_start_matches("https://").split(['?', '#']).next().unwrap_or("").trim_end_matches('/');
let rest = rest.strip_suffix(".git").unwrap_or(rest);
let (host, path) = rest.split_once('/').unwrap_or((rest, ""));
match prefix {
Some("github") if !host.contains('.') => format!("https://github.com/{rest}"),
_ => format!("https://{}/{path}", host.to_ascii_lowercase()),
}
}
fn looks_like_repo(url: &str) -> bool {
let rest = url.trim_start_matches("https://");
let parts: Vec<&str> = rest.split('/').collect();
parts.len() >= 3 && parts[0].contains('.') && parts.iter().all(|p| !p.is_empty() && !p.contains(' '))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn source_addresses() {
assert_eq!(sf_ipc_canonical("github.com/fox/app.git"), "https://github.com/fox/app");
assert_eq!(sf_ipc_canonical("github:fox/app"), "https://github.com/fox/app");
assert_eq!(sf_ipc_canonical("gitlab:Git.x.org/a/b/"), "https://git.x.org/a/b");
assert!(looks_like_repo("https://github.com/fox/app"));
assert!(looks_like_repo(&sf_ipc_canonical("gitlab:git.x.org/a/b")));
assert!(!looks_like_repo("https://github.com/fox"));
assert!(!looks_like_repo("https://hello"));
}
}

View File

@@ -439,6 +439,174 @@ pub fn bt_remove(addr: &str) -> Result<()> {
Ok(()) Ok(())
} }
// ---- audio ---------------------------------------------------------------
#[derive(Debug, Clone)]
pub struct AudioOutput {
pub name: String,
pub label: String,
pub bluetooth: bool,
pub selected: bool,
}
#[derive(Debug, Clone)]
pub struct BtAudioDevice {
pub address: String,
pub name: String,
pub paired: bool,
pub connected: bool,
}
static DEMO_AUDIO: Mutex<Option<String>> = Mutex::new(None);
pub fn audio_outputs() -> Result<Vec<AudioOutput>> {
if demo() {
let selected = DEMO_AUDIO.lock().unwrap().clone().unwrap_or_else(|| "hdmi".into());
return Ok(vec![
AudioOutput { name: "hdmi".into(), label: "TV · HDMI".into(), bluetooth: false, selected: selected == "hdmi" },
AudioOutput { name: "airpods".into(), label: "AirPods Pro".into(), bluetooth: true, selected: selected == "airpods" },
]);
}
let t = Duration::from_secs(4);
let default = run("pactl", &["get-default-sink"], t)?.trim().to_string();
let json = run("pactl", &["--format=json", "list", "sinks"], t)?;
let sinks: serde_json::Value = serde_json::from_str(&json).context("parsing audio outputs")?;
let sinks = sinks.as_array().context("audio outputs are not a list")?;
let mut outputs = Vec::new();
for sink in sinks {
let Some(name) = sink.get("name").and_then(|v| v.as_str()) else { continue };
if name == "auto_null" { continue; }
let description = sink.get("description").and_then(|v| v.as_str()).unwrap_or(name);
let label = output_label(name, description);
let bluetooth = name.starts_with("bluez_output.");
outputs.push(AudioOutput { name: name.into(), label, bluetooth, selected: name == default });
}
// The selected one, then the TV, Bluetooth, anything else, the jack last.
let rank = |o: &AudioOutput| match () {
_ if o.label.starts_with("TV") => 0,
_ if o.bluetooth => 1,
_ if o.label.starts_with("Jack") => 3,
_ => 2,
};
outputs.sort_by_key(|o| (!o.selected, rank(o), o.label.to_lowercase()));
Ok(outputs)
}
/// A name people recognise for a sound output. ALSA's descriptions
/// ("Built-in Audio Digital Stereo (HDMI)", "Built-in Audio Stereo") look
/// alike; the analog one is the 3.5 mm jack, not the TV.
fn output_label(name: &str, description: &str) -> String {
if name.starts_with("bluez_output.") {
return description.to_string();
}
let n = name.to_ascii_lowercase();
if n.contains("hdmi") {
// Raspberry Pi 4: two HDMI ports (fef00700 = HDMI 0, fef05700 = HDMI 1).
return match () {
_ if n.contains("fef05700") => "TV · HDMI 2".into(),
_ if n.contains("fef00700") => "TV · HDMI 1".into(),
_ => "TV · HDMI".into(),
};
}
if n.starts_with("alsa_output.")
&& (n.contains("analog") || n.contains("stereo-fallback") || n.contains("headphones") || n.contains("mailbox"))
{
return "Jack-kimenet (3,5 mm)".into();
}
description.to_string()
}
pub fn set_audio_output(name: &str) -> Result<()> {
if demo() {
*DEMO_AUDIO.lock().unwrap() = Some(name.into());
return Ok(());
}
// Only accept a sink currently reported by PipeWire.
if !audio_outputs()?.iter().any(|o| o.name == name) {
bail!("A hangkimenet már nem érhető el");
}
run("pactl", &["set-default-sink", name], Duration::from_secs(4))?;
// Move streams that were already playing when the output changed.
if let Ok(streams) = run("pactl", &["list", "short", "sink-inputs"], Duration::from_secs(4)) {
for line in streams.lines() {
if let Some(index) = line.split_whitespace().next().filter(|s| s.parse::<u32>().is_ok()) {
if let Err(e) = run("pactl", &["move-sink-input", index, name], Duration::from_secs(4)) {
log::warn!("moving audio stream {index}: {e:#}");
}
}
}
}
Ok(())
}
fn audio_device_info(addr: &str, fallback: &str, info: &str) -> Option<BtAudioDevice> {
let device = parse_info(addr, fallback, info);
let audio = ["audio-headphones", "audio-headset", "audio-card", "audio-speakers"]
.contains(&device.icon.as_str())
|| info.lines().any(|line| line.contains("Audio Sink") || line.contains("0000110b"));
(audio && !device.remote).then(|| BtAudioDevice {
address: addr.into(), name: device.name,
paired: info.lines().any(|line| line.trim() == "Paired: yes"),
connected: device.connected,
})
}
pub fn bt_audio_devices() -> Result<Vec<BtAudioDevice>> {
if demo() {
return Ok(vec![BtAudioDevice { address: "4C:87:5D:0E:22:9B".into(), name: "AirPods Pro".into(), paired: true, connected: false }]);
}
let t = Duration::from_secs(4);
let list = run("bluetoothctl", &["devices"], t)?;
let mut devices = Vec::new();
for (addr, name) in parse_device_list(&list) {
let info = run("bluetoothctl", &["info", &addr], t).unwrap_or_default();
if let Some(device) = audio_device_info(&addr, &name, &info) {
devices.push(device);
}
}
devices.sort_by_key(|d| (!d.connected, !d.paired, d.name.to_lowercase()));
Ok(devices)
}
pub fn bt_audio_scan() -> Result<Vec<BtAudioDevice>> {
if !demo() {
// Keep scanning long enough for headphones in pairing mode to appear.
let result = run("bluetoothctl", &["--timeout", "8", "scan", "on"], Duration::from_secs(10))?;
if result.contains("Failed") || result.contains("No default controller") {
bail!("{}", result.trim());
}
}
bt_audio_devices()
}
pub fn bt_audio_connect(addr: &str) -> Result<()> {
if demo() {
*DEMO_AUDIO.lock().unwrap() = Some("airpods".into());
return Ok(());
}
if !is_mac(addr) { bail!("Érvénytelen Bluetooth cím"); }
let t = Duration::from_secs(25);
let info = run("bluetoothctl", &["info", addr], Duration::from_secs(4))?;
if !info.lines().any(|line| line.trim() == "Paired: yes") {
let result = run("bluetoothctl", &["pair", addr], t)?;
if result.contains("Failed") { bail!("{}", result.trim()); }
}
let trust = run("bluetoothctl", &["trust", addr], Duration::from_secs(5))?;
if trust.contains("Failed") { bail!("{}", trust.trim()); }
let result = run("bluetoothctl", &["connect", addr], t)?;
if result.contains("Failed") && !result.contains("AlreadyConnected") { bail!("{}", result.trim()); }
let sink_prefix = format!("bluez_output.{}", addr.replace(':', "_")).to_ascii_uppercase();
for _ in 0..20 {
if let Ok(outputs) = audio_outputs() {
if let Some(output) = outputs.iter().find(|o| o.name.to_ascii_uppercase().starts_with(&sink_prefix)) {
return set_audio_output(&output.name);
}
}
std::thread::sleep(Duration::from_millis(500));
}
bail!("A Bluetooth eszköz csatlakozott, de még nem jelent meg hangkimenetként")
}
// ---- network & device info ------------------------------------------------- // ---- network & device info -------------------------------------------------
#[derive(Debug, Clone, Default)] #[derive(Debug, Clone, Default)]
@@ -877,7 +1045,7 @@ pub struct UpdateStatus {
#[derive(Debug, Clone, Default)] #[derive(Debug, Clone, Default)]
pub struct UpdatePackage { pub struct UpdatePackage {
/// Display name ("SmartFox felület", "YouTube"). /// Display name ("Fennec OS felület", "YouTube").
pub title: String, pub title: String,
pub installed: String, pub installed: String,
pub available: Option<String>, pub available: Option<String>,
@@ -906,14 +1074,14 @@ impl UpdateStatus {
} }
} }
/// "sf-shell" -> "SmartFox felület", "sf-app-youtube" -> the app's name. /// "sf-shell" -> "Fennec OS felület", "sf-app-youtube" -> the app's name.
fn package_title(name: &str) -> String { fn package_title(name: &str) -> String {
if name == "sf-shell" { if name == "sf-shell" {
return "SmartFox felület".into(); return "Fennec OS felület".into();
} }
let id = name.strip_prefix("sf-app-").unwrap_or(name); let id = name.strip_prefix("sf-app-").or_else(|| name.strip_prefix(sf_ipc::store::PACKAGE_PREFIX)).unwrap_or(name);
let dirs = [PathBuf::from("/usr/share/smartfox/apps"), PathBuf::from("/var/lib/sf-pkg/apps")]; let dirs = [PathBuf::from("/usr/share/smartfox/apps"), PathBuf::from("/var/lib/sf-pkg/apps")];
sf_ipc::manifest::load_apps_from(&dirs) sf_ipc::manifest::load_all(&dirs, Some(Path::new(sf_ipc::paths::STORE_APPS)))
.ok() .ok()
.and_then(|apps| apps.into_iter().find(|a| a.id == id).map(|a| a.name)) .and_then(|apps| apps.into_iter().find(|a| a.id == id).map(|a| a.name))
.unwrap_or_else(|| id.to_string()) .unwrap_or_else(|| id.to_string())
@@ -930,8 +1098,8 @@ pub fn update_status() -> Option<UpdateStatus> {
staged: None, staged: None,
}; };
let packages = match step { let packages = match step {
0 => vec![pkg("SmartFox felület", "0.1.0", "0.2.0"), pkg("YouTube", "1.0.0", "1.1.0"), pkg("Netflex", "1.0.0", "1.0.0")], 0 => vec![pkg("Fennec OS felület", "0.1.0", "0.2.0"), pkg("YouTube", "1.0.0", "1.1.0"), pkg("Netflex", "1.0.0", "1.0.0")],
_ => vec![pkg("SmartFox felület", "0.2.0", "0.2.0"), pkg("YouTube", "1.1.0", "1.1.0")], _ => vec![pkg("Fennec OS felület", "0.2.0", "0.2.0"), pkg("YouTube", "1.1.0", "1.1.0")],
}; };
return Some(UpdateStatus { state: "idle".into(), message: String::new(), checked_at: 1_792_800_000, packages }); return Some(UpdateStatus { state: "idle".into(), message: String::new(), checked_at: 1_792_800_000, packages });
} }
@@ -993,6 +1161,16 @@ pub fn confirm_shell_trial() {
mod tests { mod tests {
use super::*; use super::*;
#[test]
fn output_labels() {
assert_eq!(output_label("alsa_output.platform-fef00700.hdmi.hdmi-stereo", "Built-in Audio Digital Stereo (HDMI)"), "TV · HDMI 1");
assert_eq!(output_label("alsa_output.platform-fef05700.hdmi.hdmi-stereo", "Built-in Audio Digital Stereo (HDMI)"), "TV · HDMI 2");
assert_eq!(output_label("alsa_output.pci-0000_00_1f.3.hdmi-stereo", "HDA Intel PCH HDMI"), "TV · HDMI");
assert_eq!(output_label("alsa_output.platform-fe00b840.mailbox.stereo-fallback", "Built-in Audio Stereo"), "Jack-kimenet (3,5 mm)");
assert_eq!(output_label("alsa_output.pci-0000_00_1f.3.analog-stereo", "Built-in Audio Analog Stereo"), "Jack-kimenet (3,5 mm)");
assert_eq!(output_label("bluez_output.D8_37_3B_73_C9_45.1", "AirPods Pro"), "AirPods Pro");
}
#[test] #[test]
fn parses_wlr_randr() { fn parses_wlr_randr() {
let text = "HDMI-A-1 \"Samsung Electric Company SAMSUNG (HDMI-A-1)\"\n Enabled: yes\n Modes:\n 3840x2160 px, 30.000000 Hz\n 1920x1080 px, 60.000000 Hz (preferred, current)\n 1920x1080 px, 59.940002 Hz\n 3840x2160 px, 60.000000 Hz\n 720x400 px, 70.082001 Hz\n Position: 0,0\n Transform: normal\n Scale: 1.000000\n"; let text = "HDMI-A-1 \"Samsung Electric Company SAMSUNG (HDMI-A-1)\"\n Enabled: yes\n Modes:\n 3840x2160 px, 30.000000 Hz\n 1920x1080 px, 60.000000 Hz (preferred, current)\n 1920x1080 px, 59.940002 Hz\n 3840x2160 px, 60.000000 Hz\n 720x400 px, 70.082001 Hz\n Position: 0,0\n Transform: normal\n Scale: 1.000000\n";
@@ -1021,6 +1199,16 @@ mod tests {
assert_eq!(d.name, "Nappali távirányító"); assert_eq!(d.name, "Nappali távirányító");
} }
#[test]
fn identifies_only_bluetooth_audio_devices() {
let headphones = "Alias: AirPods Pro\nIcon: audio-headphones\nPaired: yes\nConnected: no\n";
let audio = audio_device_info("4C:87:5D:0E:22:9B", "AirPods", headphones).unwrap();
assert_eq!(audio.name, "AirPods Pro");
assert!(audio.paired && !audio.connected);
let remote = "Icon: input-gaming\nModalias: bluetooth:v004Cp0315d0001\nPaired: yes\n";
assert!(audio_device_info("F0:B3:EC:12:7A:41", "Siri Remote", remote).is_none());
}
#[test] #[test]
fn parses_iwd_objects() { fn parses_iwd_objects() {
let objects: serde_json::Value = serde_json::from_str( let objects: serde_json::Value = serde_json::from_str(

View File

@@ -86,11 +86,12 @@ pub fn reveal_when_ready(pid: u32, not_before: Instant, on_shown: impl FnOnce()
} }
std::thread::sleep(Duration::from_millis(30)); std::thread::sleep(Duration::from_millis(30));
} }
let fade = Duration::from_millis(340); // Same crossfade as sf-compositor on the TV.
let fade = Duration::from_millis(560);
let t0 = Instant::now(); let t0 = Instant::now();
while t0.elapsed() < fade { while t0.elapsed() < fade {
let x = t0.elapsed().as_secs_f32() / fade.as_secs_f32(); let x = t0.elapsed().as_secs_f32() / fade.as_secs_f32();
let eased = 1.0 - (1.0 - x).powi(3); let eased = if x < 0.5 { 4.0 * x * x * x } else { 1.0 - (-2.0 * x + 2.0).powi(3) / 2.0 };
set_alpha(hwnd, (eased * 255.0) as u8); set_alpha(hwnd, (eased * 255.0) as u8);
std::thread::sleep(Duration::from_millis(8)); std::thread::sleep(Duration::from_millis(8));
} }

File diff suppressed because it is too large Load Diff

View File

@@ -1,92 +0,0 @@
Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter)
This Font Software is licensed under the SIL Open Font License, Version 1.1.
This license is copied below, and is also available with a FAQ at:
http://scripts.sil.org/OFL
-----------------------------------------------------------
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
-----------------------------------------------------------
PREAMBLE
The goals of the Open Font License (OFL) are to stimulate worldwide
development of collaborative font projects, to support the font creation
efforts of academic and linguistic communities, and to provide a free and
open framework in which fonts may be shared and improved in partnership
with others.
The OFL allows the licensed fonts to be used, studied, modified and
redistributed freely as long as they are not sold by themselves. The
fonts, including any derivative works, can be bundled, embedded,
redistributed and/or sold with any software provided that any reserved
names are not used by derivative works. The fonts and derivatives,
however, cannot be released under any other type of license. The
requirement for fonts to remain under this license does not apply
to any document created using the fonts or their derivatives.
DEFINITIONS
"Font Software" refers to the set of files released by the Copyright
Holder(s) under this license and clearly marked as such. This may
include source files, build scripts and documentation.
"Reserved Font Name" refers to any names specified as such after the
copyright statement(s).
"Original Version" refers to the collection of Font Software components as
distributed by the Copyright Holder(s).
"Modified Version" refers to any derivative made by adding to, deleting,
or substituting -- in part or in whole -- any of the components of the
Original Version, by changing formats or by porting the Font Software to a
new environment.
"Author" refers to any designer, engineer, programmer, technical
writer or other person who contributed to the Font Software.
PERMISSION AND CONDITIONS
Permission is hereby granted, free of charge, to any person obtaining
a copy of the Font Software, to use, study, copy, merge, embed, modify,
redistribute, and sell modified and unmodified copies of the Font
Software, subject to the following conditions:
1) Neither the Font Software nor any of its individual components,
in Original or Modified Versions, may be sold by itself.
2) Original or Modified Versions of the Font Software may be bundled,
redistributed and/or sold with any software, provided that each copy
contains the above copyright notice and this license. These can be
included either as stand-alone text files, human-readable headers or
in the appropriate machine-readable metadata fields within text or
binary files as long as those fields can be easily viewed by the user.
3) No Modified Version of the Font Software may use the Reserved Font
Name(s) unless explicit written permission is granted by the corresponding
Copyright Holder. This restriction only applies to the primary font name as
presented to the users.
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
Software shall not be used to promote, endorse or advertise any
Modified Version, except to acknowledge the contribution(s) of the
Copyright Holder(s) and the Author(s) or with their explicit written
permission.
5) The Font Software, modified or unmodified, in part or in whole,
must be distributed entirely under this license, and must not be
distributed under any other license. The requirement for fonts to
remain under this license does not apply to any document created
using the Font Software.
TERMINATION
This license becomes null and void if any of the above conditions are
not met.
DISCLAIMER
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
OTHER DEALINGS IN THE FONT SOFTWARE.

View File

@@ -3,47 +3,46 @@
export component AppIcon inherits Rectangle { export component AppIcon inherits Rectangle {
in property <string> icon; in property <string> icon;
in property <color> ink: #ffffff; in property <color> ink: #ffffff;
// Store apps bring their own picture (app.toml: icon = "icon.png").
in property <image> image;
in property <bool> has-image: false;
// No picture and no built-in icon: the app name's first letter.
in property <string> letter;
property <bool> builtin: root.icon == "airplay" || root.icon == "miracast" || root.icon == "settings" || root.icon == "store";
if root.icon == "netflex": Rectangle { if root.has-image: Image {
// Netflex mark: mirrored "N" in three ribbons (from netflex/apps/web/public/favicon.svg). width: 100%;
Path { height: 100%;
width: 100%; height: 100%; source: root.image;
viewbox-width: 32; viewbox-height: 32; image-fit: contain;
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 { if !root.has-image && !root.builtin: Text {
width: 100%;
height: 100%;
horizontal-alignment: center;
vertical-alignment: center;
text: root.letter;
font-size: root.height * 0.72;
font-weight: 700;
color: root.ink;
}
if root.icon == "store": Rectangle {
// App Store: a shopping bag with a handle.
Path { Path {
width: 100%; height: 100%; width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32; 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"; commands: "M6.5 11h19l-1.4 15a2.5 2.5 0 0 1-2.5 2.3H10.4a2.5 2.5 0 0 1-2.5-2.3z";
fill: @linear-gradient(160deg, #ff3b30 0%, #d90d1d 100%); fill: @linear-gradient(180deg, #8cc4ff 0%, #3d7fe0 100%);
} }
Path { Path {
width: 100%; height: 100%; width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32; viewbox-width: 32; viewbox-height: 32;
commands: "M13.2 11.6v8.8l7.6-4.4z"; commands: "M11.5 14V9.5a4.5 4.5 0 0 1 9 0V14";
fill: #ffffff; stroke: root.ink;
stroke-width: 2.4px;
stroke-line-cap: round;
} }
} }
@@ -107,7 +106,7 @@ export component AppIcon inherits Rectangle {
} }
} }
// SmartFox brand mark: a geometric fox head. // Fennec OS brand mark: a geometric fox head.
export component FoxMark inherits Rectangle { export component FoxMark inherits Rectangle {
Path { Path {
width: 100%; height: 100%; width: 100%; height: 100%;
@@ -293,3 +292,273 @@ export component PowerIcon inherits Rectangle {
stroke-line-cap: round; stroke-line-cap: round;
} }
} }
export component AudioIcon inherits Rectangle {
in property <color> ink: #ffffff;
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M5 12h6l7-6v20l-7-6H5zM22 12a6 6 0 0 1 0 8M25 8a11 11 0 0 1 0 16";
stroke: root.ink;
stroke-width: 2.2px;
stroke-line-cap: round;
stroke-line-join: round;
}
}
// Siri Remote, front view (status capsule, facts).
export component RemoteIcon inherits Rectangle {
in property <color> ink: #ffffff;
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M12.5 3h7a3 3 0 0 1 3 3v20a3 3 0 0 1-3 3h-7a3 3 0 0 1-3-3V6a3 3 0 0 1 3-3z";
stroke: root.ink;
stroke-width: 2.2px;
stroke-line-join: round;
}
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M12.6 10.5a3.4 3.4 0 1 0 6.8 0a3.4 3.4 0 1 0-6.8 0zM13.5 18.5a1.3 1.3 0 1 0 2.6 0a1.3 1.3 0 1 0-2.6 0zM15.9 18.5a1.3 1.3 0 1 0 2.6 0a1.3 1.3 0 1 0-2.6 0z";
fill: root.ink;
}
}
// Wired network (ethernet plug).
export component WiredIcon inherits Rectangle {
in property <color> ink: #ffffff;
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M9 6h14a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-3v4h-8v-4H9a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2zM16 23v5M12.5 10.5v3M16 10.5v3M19.5 10.5v3";
stroke: root.ink;
stroke-width: 2.2px;
stroke-line-cap: round;
stroke-line-join: round;
}
}
// Cast from a phone: screen with broadcast arcs in the corner.
export component CastIcon inherits Rectangle {
in property <color> ink: #ffffff;
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M4 11V8.5A2.5 2.5 0 0 1 6.5 6h19A2.5 2.5 0 0 1 28 8.5v15a2.5 2.5 0 0 1-2.5 2.5H17M4 16.5a9.5 9.5 0 0 1 9.5 9.5M4 21.5a4.5 4.5 0 0 1 4.5 4.5";
stroke: root.ink;
stroke-width: 2.2px;
stroke-line-cap: round;
stroke-line-join: round;
}
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M3 26a1.5 1.5 0 1 0 3 0a1.5 1.5 0 1 0-3 0z";
fill: root.ink;
}
}
// Home media server.
export component ServerIcon inherits Rectangle {
in property <color> ink: #ffffff;
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M7 5h18a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2zM7 18h18a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2z";
stroke: root.ink;
stroke-width: 2.2px;
stroke-line-join: round;
}
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M9.5 9.5a1.4 1.4 0 1 0 2.8 0a1.4 1.4 0 1 0-2.8 0zM9.5 22.5a1.4 1.4 0 1 0 2.8 0a1.4 1.4 0 1 0-2.8 0z";
fill: root.ink;
}
}
export component CheckIcon inherits Rectangle {
in property <color> ink: #ffffff;
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M7 16.5l6 6L25.5 10";
stroke: root.ink;
stroke-width: 3px;
stroke-line-cap: round;
stroke-line-join: round;
}
}
export component AlertIcon inherits Rectangle {
in property <color> ink: #ffffff;
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M16 8v10";
stroke: root.ink;
stroke-width: 3px;
stroke-line-cap: round;
}
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M14.2 24a1.8 1.8 0 1 0 3.6 0a1.8 1.8 0 1 0-3.6 0z";
fill: root.ink;
}
}
export component ChevronIcon inherits Rectangle {
in property <color> ink: #ffffff;
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M12 7l9 9-9 9";
stroke: root.ink;
stroke-width: 2.6px;
stroke-line-cap: round;
stroke-line-join: round;
}
}
// Remote buttons in the pairing drawing.
export component BackGlyph inherits Rectangle {
in property <color> ink: #ffffff;
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M19 8l-8 8 8 8";
stroke: root.ink;
stroke-width: 3px;
stroke-line-cap: round;
stroke-line-join: round;
}
}
export component TvGlyph inherits Rectangle {
in property <color> ink: #ffffff;
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M7.5 8h17a1.5 1.5 0 0 1 1.5 1.5v11a1.5 1.5 0 0 1-1.5 1.5h-17A1.5 1.5 0 0 1 6 20.5v-11A1.5 1.5 0 0 1 7.5 8zM12 25.5h8";
stroke: root.ink;
stroke-width: 2.6px;
stroke-line-cap: round;
stroke-line-join: round;
}
}
export component PlayPauseGlyph inherits Rectangle {
in property <color> ink: #ffffff;
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M6 9.5v13l9-6.5z";
fill: root.ink;
}
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M19.5 10v12M25 10v12";
stroke: root.ink;
stroke-width: 2.8px;
stroke-line-cap: round;
}
}
export component MuteGlyph inherits Rectangle {
in property <color> ink: #ffffff;
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M5 12.5h4.5L16 7v18l-6.5-5.5H5z";
fill: root.ink;
}
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M20.5 12.5l7 7M27.5 12.5l-7 7";
stroke: root.ink;
stroke-width: 2.6px;
stroke-line-cap: round;
}
}
export component PlusGlyph inherits Rectangle {
in property <color> ink: #ffffff;
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M16 8v16M8 16h16";
stroke: root.ink;
stroke-width: 3px;
stroke-line-cap: round;
}
}
export component MinusGlyph inherits Rectangle {
in property <color> ink: #ffffff;
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M8 16h16";
stroke: root.ink;
stroke-width: 3px;
stroke-line-cap: round;
}
}
export component PowerGlyph inherits Rectangle {
in property <color> ink: #ffffff;
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M10.3 9.6a9 9 0 1 0 11.4 0M16 5.5v10";
stroke: root.ink;
stroke-width: 3px;
stroke-line-cap: round;
}
}
// One icon by name, for data-driven rows (home screen facts).
export component NamedIcon inherits Rectangle {
in property <string> name;
in property <color> ink: #ffffff;
if root.name == "remote": RemoteIcon { width: 100%; height: 100%; ink: root.ink; }
if root.name == "wifi": WifiIcon { width: 100%; height: 100%; ink: root.ink; }
if root.name == "wired": WiredIcon { width: 100%; height: 100%; ink: root.ink; }
if root.name == "display": DisplayIcon { width: 100%; height: 100%; ink: root.ink; }
if root.name == "cast": CastIcon { width: 100%; height: 100%; ink: root.ink; }
if root.name == "server": ServerIcon { width: 100%; height: 100%; ink: root.ink; }
if root.name == "check": CheckIcon { width: 100%; height: 100%; ink: root.ink; }
if root.name == "alert": AlertIcon { width: 100%; height: 100%; ink: root.ink; }
if root.name == "bluetooth": BluetoothIcon { width: 100%; height: 100%; ink: root.ink; }
}
// Store screen categories (settings.slint NavIcon 5..7).
export component StoreIcon inherits Rectangle {
in property <color> ink: #ffffff;
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M6.5 11h19l-1.4 15a2.5 2.5 0 0 1-2.5 2.3H10.4a2.5 2.5 0 0 1-2.5-2.3zM11.5 14V9.5a4.5 4.5 0 0 1 9 0V14";
stroke: root.ink;
stroke-width: 2.2px;
stroke-line-cap: round;
stroke-line-join: round;
}
}
export component LinkIcon inherits Rectangle {
in property <color> ink: #ffffff;
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M14 18a5 5 0 0 0 7.1 0l4-4a5 5 0 0 0-7.1-7.1l-1.5 1.5M18 14a5 5 0 0 0-7.1 0l-4 4a5 5 0 0 0 7.1 7.1l1.5-1.5";
stroke: root.ink;
stroke-width: 2.4px;
stroke-line-cap: round;
stroke-line-join: round;
}
}

View File

@@ -1,7 +1,7 @@
// On-screen keyboard in the tvOS style: one horizontal row of characters, // On-screen keyboard in the tvOS style: one horizontal row of characters,
// the text field above it and the mode chips below. // the text field above it and the mode chips below.
// //
// Drawn inside the settings pane, which stays; the settings content fades out. // Opens in place of the settings content, which fades out.
// Only text and icons are drawn here. The glass (field, key track, focus lens, // Only text and icons are drawn here. The glass (field, key track, focus lens,
// chips) comes from `keyboard::glass` in Rust, which mirrors the geometry the // chips) comes from `keyboard::glass` in Rust, which mirrors the geometry the
// App exports (kb-* properties): keep the two in sync. // App exports (kb-* properties): keep the two in sync.
@@ -16,7 +16,6 @@ export component KeyboardView inherits Rectangle {
in property <length> pane-y; in property <length> pane-y;
in property <length> pane-w; in property <length> pane-w;
in property <length> pane-h; in property <length> pane-h;
in property <length> back-x;
in property <length> field-x; in property <length> field-x;
in property <length> field-y; in property <length> field-y;
in property <length> field-w; in property <length> field-w;
@@ -50,24 +49,23 @@ export component KeyboardView inherits Rectangle {
// ---- heading ---------------------------------------------------------- // ---- heading ----------------------------------------------------------
Text { Text {
x: root.pane-x; x: root.pane-x;
y: root.pane-y + 58 * root.u; y: root.pane-y + 88 * root.u;
width: root.pane-w; width: root.pane-w;
horizontal-alignment: center; horizontal-alignment: center;
text: root.title; text: root.title;
font-family: "Inter Display"; font-weight: 700;
font-weight: 800; font-size: 48 * root.u;
font-size: 46 * root.u; letter-spacing: -0.8 * root.u;
letter-spacing: -1.2 * root.u;
color: #ffffff; color: #ffffff;
overflow: elide; overflow: elide;
} }
Text { Text {
x: root.pane-x + 80 * root.u; x: root.pane-x + 80 * root.u;
y: root.pane-y + 128 * root.u; y: root.pane-y + 160 * root.u;
width: root.pane-w - 160 * root.u; width: root.pane-w - 160 * root.u;
horizontal-alignment: center; horizontal-alignment: center;
text: root.subtitle; text: root.subtitle;
font-size: 23 * root.u; font-size: 24 * root.u;
color: #ffffffa8; color: #ffffffa8;
overflow: elide; overflow: elide;
} }
@@ -114,12 +112,12 @@ export component KeyboardView inherits Rectangle {
} }
Text { Text {
x: root.field-x; x: root.field-x;
y: root.field-y + root.field-h + 18 * root.u; y: root.field-y + root.field-h + 20 * root.u;
width: root.field-w; width: root.field-w;
horizontal-alignment: center; horizontal-alignment: center;
text: root.hint; text: root.hint;
font-size: 21 * root.u; font-size: 22 * root.u;
color: root.hint-error ? #ff8278 : #ffffff8c; color: root.hint-error ? #ff8278 : #ffffff99;
} }
// ---- key row --------------------------------------------------------------- // ---- key row ---------------------------------------------------------------
@@ -175,16 +173,4 @@ export component KeyboardView inherits Rectangle {
: self.f > 0.5 ? #121317 : self.selected ? #ff9a5c : #ffffffc8; : self.f > 0.5 ? #121317 : self.selected ? #ff9a5c : #ffffffc8;
} }
Text {
x: root.back-x;
y: root.pane-y + root.pane-h - 92 * root.u;
width: 300 * root.u;
height: 56 * root.u;
horizontal-alignment: center;
vertical-alignment: center;
text: "‹ Mégse · Vissza";
font-size: 21 * root.u;
font-weight: 500;
color: #ffffffc0;
}
} }

View File

@@ -1,6 +1,8 @@
// First-run pairing guide for the Apple Siri Remote. The frosted pane behind // First-run pairing guide for the Apple Siri Remote. The frosted pane behind
// it is drawn by the glass layer (see `glass-over` in app.slint). // it is drawn by the glass layer (see `glass-over` in app.slint).
import { BackGlyph, TvGlyph, PlayPauseGlyph, MuteGlyph, PlusGlyph, MinusGlyph, PowerGlyph, CheckIcon, AlertIcon } from "icons.slint";
// Pulsing ring that draws the eye to a button. // Pulsing ring that draws the eye to a button.
component Pulse inherits Rectangle { component Pulse inherits Rectangle {
in property <length> size; in property <length> size;
@@ -17,9 +19,12 @@ component Pulse inherits Rectangle {
component RemoteButton inherits Rectangle { component RemoteButton inherits Rectangle {
in property <length> u; in property <length> u;
// back | tv | playpause | mute | plus
in property <string> glyph; in property <string> glyph;
in property <bool> hot; in property <bool> hot;
in property <color> accent; in property <color> accent;
property <color> ink: self.hot ? self.accent.brighter(0.5) : #e8e8ea;
property <length> g: 26 * self.u;
width: 52 * self.u; width: 52 * self.u;
height: self.width; height: self.width;
border-radius: self.width / 2; border-radius: self.width / 2;
@@ -40,14 +45,11 @@ component RemoteButton inherits Rectangle {
x: (parent.width - self.width) / 2; x: (parent.width - self.width) / 2;
y: (parent.height - self.height) / 2; y: (parent.height - self.height) / 2;
} }
Text { if root.glyph == "back": BackGlyph { x: (parent.width - self.width) / 2; y: (parent.height - self.height) / 2; width: root.g; height: root.g; ink: root.ink; }
text: root.glyph; if root.glyph == "tv": TvGlyph { x: (parent.width - self.width) / 2; y: (parent.height - self.height) / 2; width: root.g; height: root.g; ink: root.ink; }
color: root.hot ? root.accent.brighter(0.5) : #e8e8ea; if root.glyph == "playpause": PlayPauseGlyph { x: (parent.width - self.width) / 2; y: (parent.height - self.height) / 2; width: root.g; height: root.g; ink: root.ink; }
font-size: 24 * root.u; if root.glyph == "mute": MuteGlyph { x: (parent.width - self.width) / 2; y: (parent.height - self.height) / 2; width: root.g; height: root.g; ink: root.ink; }
font-weight: 600; if root.glyph == "plus": PlusGlyph { x: (parent.width - self.width) / 2; y: (parent.height - self.height) / 2; width: root.g; height: root.g; ink: root.ink; }
horizontal-alignment: center;
vertical-alignment: center;
}
} }
// Apple Siri Remote (2nd gen, aluminium), drawn front-on. // Apple Siri Remote (2nd gen, aluminium), drawn front-on.
@@ -57,7 +59,9 @@ export component SiriRemote inherits Rectangle {
width: 150 * self.u; width: 150 * self.u;
height: 560 * self.u; height: 560 * self.u;
border-radius: 44 * self.u; border-radius: 44 * self.u;
background: @linear-gradient(90deg, #8d929a 0%, #d9dde2 22%, #f1f3f5 45%, #c6cad0 75%, #959aa2 100%); background: #c4c8ce;
border-width: 2px;
border-color: #ffffff40;
drop-shadow-blur: 30 * self.u; drop-shadow-blur: 30 * self.u;
drop-shadow-color: #000000a0; drop-shadow-color: #000000a0;
drop-shadow-offset-y: 16 * self.u; drop-shadow-offset-y: 16 * self.u;
@@ -79,12 +83,12 @@ export component SiriRemote inherits Rectangle {
height: 18 * root.u; height: 18 * root.u;
border-radius: self.width / 2; border-radius: self.width / 2;
background: #1b1b1d; background: #1b1b1d;
Text { PowerGlyph {
text: "⏻"; x: (parent.width - self.width) / 2;
color: #d0d0d4; y: (parent.height - self.height) / 2;
font-size: 11 * root.u; width: 12 * root.u;
horizontal-alignment: center; height: 12 * root.u;
vertical-alignment: center; ink: #d0d0d4;
} }
} }
// Clickpad: outer touch ring and center. // Clickpad: outer touch ring and center.
@@ -118,10 +122,10 @@ export component SiriRemote inherits Rectangle {
// Button grid below the clickpad. // Button grid below the clickpad.
property <length> col1: 18 * root.u; property <length> col1: 18 * root.u;
property <length> col2: root.width - 18 * root.u - 52 * root.u; property <length> col2: root.width - 18 * root.u - 52 * root.u;
RemoteButton { u: root.u; accent: root.accent; x: root.col1; y: 200 * root.u; glyph: "‹"; hot: true; } RemoteButton { u: root.u; accent: root.accent; x: root.col1; y: 200 * root.u; glyph: "back"; hot: true; }
RemoteButton { u: root.u; accent: root.accent; x: root.col2; y: 200 * root.u; glyph: "▭"; } RemoteButton { u: root.u; accent: root.accent; x: root.col2; y: 200 * root.u; glyph: "tv"; }
RemoteButton { u: root.u; accent: root.accent; x: root.col1; y: 268 * root.u; glyph: "⏯"; } RemoteButton { u: root.u; accent: root.accent; x: root.col1; y: 268 * root.u; glyph: "playpause"; }
RemoteButton { u: root.u; accent: root.accent; x: root.col1; y: 336 * root.u; glyph: "🔇"; } RemoteButton { u: root.u; accent: root.accent; x: root.col1; y: 336 * root.u; glyph: "mute"; }
// Volume rocker: + is the one to hold. // Volume rocker: + is the one to hold.
Rectangle { Rectangle {
x: root.col2; x: root.col2;
@@ -135,19 +139,16 @@ export component SiriRemote inherits Rectangle {
accent: root.accent; accent: root.accent;
x: 0; x: 0;
y: 0; y: 0;
glyph: "+"; glyph: "plus";
hot: true; hot: true;
background: transparent; background: transparent;
} }
Text { MinusGlyph {
y: parent.height - 52 * root.u; x: (parent.width - self.width) / 2;
width: parent.width; y: parent.height - 52 * root.u + (52 * root.u - self.height) / 2;
height: 52 * root.u; width: 26 * root.u;
text: "−"; height: 26 * root.u;
color: #e8e8ea; ink: #e8e8ea;
font-size: 24 * root.u;
horizontal-alignment: center;
vertical-alignment: center;
} }
} }
} }
@@ -157,81 +158,76 @@ component Step inherits Rectangle {
in property <int> n; in property <int> n;
in property <string> label; in property <string> label;
in property <color> accent; in property <color> accent;
height: 70 * self.u; // The glass bead behind the number is drawn by the glass layer (app.slint),
Rectangle { // on the same 48 px square.
x: 0;
y: 4 * root.u;
width: 40 * root.u;
height: self.width;
// The glass bead behind the number is drawn by the glass layer (app.slint).
Text { Text {
x: 0;
y: 0;
width: 48 * root.u;
height: 48 * root.u;
text: root.n; text: root.n;
color: root.accent.brighter(0.6); color: root.accent.brighter(0.6);
font-size: 20 * root.u; font-size: 22 * root.u;
font-weight: 700; font-weight: 700;
horizontal-alignment: center; horizontal-alignment: center;
vertical-alignment: center; vertical-alignment: center;
} }
}
Text { Text {
x: 60 * root.u; x: 72 * root.u;
y: 10 * root.u; y: 6 * root.u;
width: parent.width - 60 * root.u; width: parent.width - 72 * root.u;
text: root.label; text: root.label;
wrap: word-wrap; wrap: word-wrap;
font-size: 24 * root.u; font-size: 26 * root.u;
color: #ffffffd8; color: #ffffffe0;
} }
} }
// Pane content; `state` is the remote status from sf-remote. // Pane content; `state` is the remote status from sf-remote. The text column
// starts at (content-x, content-y); `steps` and `pill-y` are offsets from
// there, shared with the glass beads and pills in app.slint.
export component PairingGuide inherits Rectangle { export component PairingGuide inherits Rectangle {
in property <length> u; in property <length> u;
in property <string> state; in property <string> state;
in property <color> accent: #ff7a35; in property <color> accent: #ff7a35;
in property <length> content-x;
in property <length> content-y;
in property <[length]> steps;
in property <length> pill-y;
property <bool> ok: self.state == "paired" || self.state == "connected"; property <bool> ok: self.state == "paired" || self.state == "connected";
property <bool> broken: self.state == "no-adapter"; property <bool> broken: self.state == "no-adapter";
SiriRemote { SiriRemote {
u: root.u; u: root.u;
accent: root.accent; accent: root.accent;
x: 120 * root.u; x: (root.content-x - self.width) / 2;
y: (parent.height - self.height) / 2; y: (parent.height - self.height) / 2;
} }
Rectangle { Rectangle {
x: 420 * root.u; x: root.content-x;
y: 70 * root.u; y: root.content-y;
width: parent.width - 420 * root.u - 80 * root.u; width: parent.width - root.content-x - 88 * root.u;
height: parent.height - 140 * root.u; height: parent.height - root.content-y;
Text { Text {
x: 0; x: 0;
y: 0; y: 0;
text: "ELSŐ LÉPÉS";
font-size: 20 * root.u;
font-weight: 600;
letter-spacing: 3 * root.u;
color: root.accent.brighter(0.3);
}
Text {
x: 0;
y: 34 * root.u;
width: parent.width; width: parent.width;
text: "Párosítsd a Siri Remote-ot"; text: "Párosítsd a Siri Remote-ot";
wrap: word-wrap; font-weight: 700;
font-family: "Inter Display"; font-size: 52 * root.u;
font-weight: 800; letter-spacing: -1 * root.u;
font-size: 58 * root.u;
letter-spacing: -1.6 * root.u;
color: #ffffff; color: #ffffff;
overflow: elide;
} }
Step { Step {
u: root.u; u: root.u;
accent: root.accent; accent: root.accent;
x: 0; x: 0;
y: 150 * root.u; y: root.steps[0];
width: parent.width; width: parent.width;
height: 64 * root.u;
n: 1; n: 1;
label: "Vidd a távirányítót a TV közelébe."; label: "Vidd a távirányítót a TV közelébe.";
} }
@@ -239,33 +235,34 @@ export component PairingGuide inherits Rectangle {
u: root.u; u: root.u;
accent: root.accent; accent: root.accent;
x: 0; x: 0;
y: 226 * root.u; y: root.steps[1];
width: parent.width; width: parent.width;
height: 100 * root.u;
n: 2; n: 2;
label: "Tartsd nyomva egyszerre a Vissza (‹) és a Hangerő + gombot kb. 5 másodpercig."; label: "Tartsd nyomva egyszerre a Vissza és a Hangerő + gombot, kb. 5 másodpercig.";
} }
Step { Step {
u: root.u; u: root.u;
accent: root.accent; accent: root.accent;
x: 0; x: 0;
y: 330 * root.u; y: root.steps[2];
width: parent.width; width: parent.width;
height: 64 * root.u;
n: 3; n: 3;
label: "Engedd el. A TV magától megtalálja és párosítja."; label: "Engedd el. A TV magától megtalálja és párosítja.";
} }
// Live status. // Live status, on the glass pill drawn by app.slint (520 x 64).
Rectangle { Rectangle {
x: 0; x: 0;
y: parent.height - 70 * root.u; y: root.pill-y;
width: 520 * root.u; width: 520 * root.u;
height: 64 * root.u; height: 64 * root.u;
// Glass pill (tinted by state) is drawn by the glass layer (app.slint).
// Searching: three breathing dots. Done: check mark. Error: "!". // Searching: three breathing dots. Done: check mark. Error: alert.
if !root.ok && !root.broken: HorizontalLayout { if !root.ok && !root.broken: HorizontalLayout {
x: 26 * root.u; x: 0;
width: 60 * root.u; width: 56 * root.u;
spacing: 8 * root.u; spacing: 8 * root.u;
alignment: start; alignment: start;
for i in 3: Rectangle { for i in 3: Rectangle {
@@ -278,41 +275,47 @@ export component PairingGuide inherits Rectangle {
opacity: 0.25 + 0.75 * abs(sin(self.p * 180deg)); opacity: 0.25 + 0.75 * abs(sin(self.p * 180deg));
} }
} }
if root.ok || root.broken: Text { if root.ok: CheckIcon {
x: 26 * root.u; x: 24 * root.u;
width: 40 * root.u; y: (parent.height - self.height) / 2;
height: parent.height; width: 32 * root.u;
text: root.ok ? "✓" : "!"; height: 32 * root.u;
color: root.ok ? #34c759 : #ff9f0a; ink: #34c759;
font-size: 30 * root.u; }
font-weight: 800; if root.broken: AlertIcon {
vertical-alignment: center; x: 24 * root.u;
y: (parent.height - self.height) / 2;
width: 32 * root.u;
height: 32 * root.u;
ink: #ff9f0a;
} }
Text { Text {
x: 92 * root.u; x: root.ok || root.broken ? 72 * root.u : 64 * root.u;
width: parent.width - 110 * root.u; width: parent.width - 96 * root.u;
height: parent.height; height: parent.height;
vertical-alignment: center; vertical-alignment: center;
font-size: 24 * root.u; font-size: 24 * root.u;
font-weight: 500; font-weight: 500;
color: #ffffff; color: #ffffff;
text: root.ok ? "Sikeres párosítás!" overflow: elide;
text: root.ok ? "Sikeres párosítás"
: root.broken ? "Nem található Bluetooth adapter" : root.broken ? "Nem található Bluetooth adapter"
: root.state == "pairing" ? "Párosítás…" : root.state == "pairing" ? "Párosítás…"
: "Távirányító keresése…"; : "Távirányító keresése…";
} }
} }
// Skip chip (glass in app.slint, 200 x 64).
Text { Text {
x: 556 * root.u; x: 544 * root.u;
y: parent.height - 68 * root.u; y: root.pill-y;
width: 204 * root.u; width: 200 * root.u;
height: 60 * root.u; height: 64 * root.u;
horizontal-alignment: center; horizontal-alignment: center;
vertical-alignment: center; vertical-alignment: center;
text: "Kihagyás · Esc"; text: "Kihagyás";
font-size: 21 * root.u; font-size: 24 * root.u;
font-weight: 500; font-weight: 600;
color: #ffffffc0; color: #ffffffd0;
} }
} }
} }

View File

@@ -1,10 +1,11 @@
// Settings screen: categories on the left, rows on the right. // Settings screen: categories on the left, the selected page's rows on one
// grouped platter on the right.
// //
// Only text and icons are drawn here. The glass (pane, rows, chips) comes from // Only text and icons are drawn here. The glass (platter, focus pills) comes
// `settings_screen::glass` in Rust, which mirrors the geometry below: keep the // from `settings_screen::glass` in Rust, which mirrors the geometry below: keep
// row/nav formulas (position, focus `f`, visibility `vis`) in sync with it. // the row/nav formulas (position, focus `f`, visibility `vis`) in sync with it.
import { WifiIcon, BluetoothIcon, InfoIcon, DisplayIcon, PowerIcon, SignalIcon, LockIcon } from "icons.slint"; import { WifiIcon, BluetoothIcon, InfoIcon, DisplayIcon, AudioIcon, PowerIcon, SignalIcon, LockIcon, ChevronIcon, StoreIcon, CheckIcon, LinkIcon } from "icons.slint";
export struct SettingRow { export struct SettingRow {
title: string, title: string,
@@ -22,9 +23,14 @@ component NavIcon inherits Rectangle {
in property <color> ink; in property <color> ink;
if root.index == 0: DisplayIcon { width: 100%; height: 100%; ink: root.ink; } if root.index == 0: DisplayIcon { width: 100%; height: 100%; ink: root.ink; }
if root.index == 1: BluetoothIcon { width: 100%; height: 100%; ink: root.ink; } if root.index == 1: BluetoothIcon { width: 100%; height: 100%; ink: root.ink; }
if root.index == 2: WifiIcon { width: 100%; height: 100%; ink: root.ink; } if root.index == 2: AudioIcon { width: 100%; height: 100%; ink: root.ink; }
if root.index == 3: PowerIcon { width: 100%; height: 100%; ink: root.ink; } if root.index == 3: WifiIcon { width: 100%; height: 100%; ink: root.ink; }
if root.index == 4: InfoIcon { width: 100%; height: 100%; ink: root.ink; } if root.index == 4: PowerIcon { width: 100%; height: 100%; ink: root.ink; }
if root.index == 5: InfoIcon { width: 100%; height: 100%; ink: root.ink; }
// App Store mode: Felfedezés, Telepítve, Források.
if root.index == 6: StoreIcon { width: 100%; height: 100%; ink: root.ink; }
if root.index == 7: CheckIcon { width: 100%; height: 100%; ink: root.ink; }
if root.index == 8: LinkIcon { width: 100%; height: 100%; ink: root.ink; }
} }
export component SettingsView inherits Rectangle { export component SettingsView inherits Rectangle {
@@ -52,38 +58,47 @@ export component SettingsView inherits Rectangle {
in property <string> subtitle; in property <string> subtitle;
in property <[SettingRow]> rows; in property <[SettingRow]> rows;
in property <[string]> categories; in property <[string]> categories;
// The same pane serves the App Store (app.slint set-mode).
in property <string> heading: "Beállítások";
in property <int> icon-base: 0;
// Row text is inset from the platter edge by the focus pill's margin.
property <length> inset: 8 * root.u;
property <length> pad: 28 * root.u;
// ---- left column ---------------------------------------------------- // ---- left column ----------------------------------------------------
Text { Text {
x: root.nav-x + 8 * root.u; x: root.nav-x;
y: root.pane-y + 50 * root.u; y: root.pane-y;
text: "Beállítások"; width: root.nav-w;
font-family: "Inter Display"; height: 88 * root.u;
font-weight: 800; vertical-alignment: center;
font-size: 50 * root.u; text: root.heading;
letter-spacing: -1.5 * root.u; font-weight: 700;
font-size: 56 * root.u;
letter-spacing: -1 * root.u;
color: #ffffff; color: #ffffff;
} }
for name[i] in root.categories: Rectangle { for name[i] in root.categories: Rectangle {
property <float> f: max(0, 1 - abs(root.nav-pos - i)) * root.nav-active; property <float> f: max(0, 1 - abs(root.nav-pos - i)) * root.nav-active;
property <float> sel: max(0, 1 - abs(root.nav-pos - i)); property <float> sel: max(0, 1 - abs(root.nav-pos - i));
property <color> ink: self.f > 0.5 ? #121317 : #ffffff.with-alpha(0.72 + 0.28 * self.sel); property <color> ink: self.f > 0.5 ? #121317 : #ffffff.with-alpha(0.62 + 0.38 * self.sel);
x: root.nav-x; x: root.nav-x;
y: root.nav-y + i * root.nav-step; y: root.nav-y + i * root.nav-step;
width: root.nav-w; width: root.nav-w;
height: root.nav-h; height: root.nav-h;
NavIcon { NavIcon {
x: 28 * root.u; x: 24 * root.u;
y: (parent.height - self.height) / 2; y: (parent.height - self.height) / 2;
width: 34 * root.u; width: 32 * root.u;
height: 34 * root.u; height: 32 * root.u;
index: i; index: i + root.icon-base;
ink: parent.ink; ink: parent.ink;
} }
Text { Text {
x: 82 * root.u; x: 76 * root.u;
width: parent.width - 100 * root.u; width: parent.width - 96 * root.u;
height: parent.height; height: parent.height;
vertical-alignment: center; vertical-alignment: center;
text: name; text: name;
@@ -94,46 +109,35 @@ export component SettingsView inherits Rectangle {
} }
} }
Text {
x: root.nav-x;
y: root.pane-y + root.pane-h - 92 * root.u;
width: 300 * root.u;
height: 56 * root.u;
horizontal-alignment: center;
vertical-alignment: center;
text: "‹ Vissza · Esc";
font-size: 21 * root.u;
font-weight: 500;
color: #ffffffc0;
}
// ---- right column --------------------------------------------------- // ---- right column ---------------------------------------------------
Text { Text {
x: root.rows-x + 8 * root.u; x: root.rows-x + root.inset + root.pad;
y: root.pane-y + 44 * root.u; y: root.nav-y;
width: root.rows-w - 16 * root.u; width: root.rows-w - 2 * (root.inset + root.pad);
height: root.nav-h;
vertical-alignment: center;
text: root.title; text: root.title;
font-family: "Inter Display"; font-weight: 700;
font-weight: 800;
font-size: 40 * root.u; font-size: 40 * root.u;
letter-spacing: -1 * root.u;
color: #ffffff; color: #ffffff;
overflow: elide; overflow: elide;
} }
Text { Text {
x: root.rows-x + 8 * root.u; x: root.rows-x + root.inset + root.pad;
y: root.pane-y + 102 * root.u; y: root.nav-y + root.nav-h;
width: root.rows-w - 16 * root.u; width: root.rows-w - 2 * (root.inset + root.pad);
height: 64 * root.u; height: root.rows-y - root.nav-y - root.nav-h - 24 * root.u;
text: root.subtitle; text: root.subtitle;
wrap: word-wrap; wrap: word-wrap;
overflow: elide; overflow: elide;
font-size: 21 * root.u; font-size: 24 * root.u;
color: #ffffffa8; color: #ffffffa8;
} }
for row[j] in root.rows: r := Rectangle { for row[j] in root.rows: r := Rectangle {
property <float> f: max(0, 1 - abs(root.row-pos - j)) * root.content-active; property <float> f: max(0, 1 - abs(root.row-pos - j)) * root.content-active;
// Focus on this row or the one above hides the hairline between them.
property <float> f-above: max(0, 1 - abs(root.row-pos - (j - 1))) * root.content-active;
property <length> top: root.rows-y + j * root.row-step - root.rows-scroll; property <length> top: root.rows-y + j * root.row-step - root.rows-scroll;
property <float> over: max(root.rows-y - self.top, self.top + root.row-h - (root.rows-y + root.rows-view-h)) / root.row-h; property <float> over: max(root.rows-y - self.top, self.top + root.row-h - (root.rows-y + root.rows-view-h)) / root.row-h;
property <float> vis: clamp(1 - self.over, 0, 1); property <float> vis: clamp(1 - self.over, 0, 1);
@@ -143,17 +147,25 @@ export component SettingsView inherits Rectangle {
property <color> ink-dim: self.hot ? (self.danger ? #ffffffd0 : #121317b0) : #ffffff99; property <color> ink-dim: self.hot ? (self.danger ? #ffffffd0 : #121317b0) : #ffffff99;
property <bool> chevron: row.kind == "choice" || row.kind == "device"; property <bool> chevron: row.kind == "choice" || row.kind == "device";
property <bool> network: row.kind == "network"; property <bool> network: row.kind == "network";
x: root.rows-x; x: root.rows-x + root.inset;
y: self.top; y: self.top;
width: root.rows-w; width: root.rows-w - 2 * root.inset;
height: root.row-h; height: root.row-h;
opacity: self.vis; opacity: self.vis;
visible: self.vis > 0.01; visible: self.vis > 0.01;
if j > 0: Rectangle {
x: root.pad;
y: 0;
width: parent.width - 2 * root.pad;
height: 1.5 * root.u;
background: #ffffff1f;
opacity: 1 - clamp(max(r.f, r.f-above) * 2, 0, 1);
}
Text { Text {
x: 30 * root.u; x: root.pad;
y: row.detail == "" ? (parent.height - self.height) / 2 : 15 * root.u; y: row.detail == "" ? (parent.height - self.height) / 2 : 14 * root.u;
width: parent.width * 0.55; width: parent.width * 0.56;
text: row.title; text: row.title;
font-size: 26 * root.u; font-size: 26 * root.u;
font-weight: 600; font-weight: 600;
@@ -161,45 +173,43 @@ export component SettingsView inherits Rectangle {
overflow: elide; overflow: elide;
} }
if row.detail != "": Text { if row.detail != "": Text {
x: 30 * root.u; x: root.pad;
y: 51 * root.u; y: 50 * root.u;
width: parent.width * 0.55; width: parent.width * 0.56;
text: row.detail; text: row.detail;
font-size: 19 * root.u; font-size: 21 * root.u;
color: r.ink-dim; color: r.ink-dim;
overflow: elide; overflow: elide;
} }
Text { Text {
x: parent.width * 0.4; x: parent.width * 0.4;
width: parent.width * 0.6 - (r.network ? 124 : r.chevron ? 64 : 32) * root.u; width: parent.width * 0.6 - (r.network ? 120 : r.chevron ? 64 : root.pad / root.u) * root.u;
height: parent.height; height: parent.height;
horizontal-alignment: right; horizontal-alignment: right;
vertical-alignment: center; vertical-alignment: center;
text: row.value; text: row.value;
font-size: row.kind == "option" ? 30 * root.u : 23 * root.u; font-size: row.kind == "option" ? 28 * root.u : 24 * root.u;
font-weight: row.kind == "option" ? 700 : 400; font-weight: row.kind == "option" ? 700 : 400;
color: row.kind == "option" ? (r.hot ? #121317 : #ff9a5c) : r.ink-dim; color: row.kind == "option" ? (r.hot ? #121317 : #ff9a5c) : r.ink-dim;
overflow: elide; overflow: elide;
} }
if r.chevron: Text { if r.chevron: ChevronIcon {
x: parent.width - 50 * root.u; x: parent.width - root.pad - self.width + 4 * root.u;
y: (parent.height - self.height) / 2;
width: 24 * root.u; width: 24 * root.u;
height: parent.height; height: 24 * root.u;
vertical-alignment: center; ink: r.ink-dim;
text: "›";
font-size: 36 * root.u;
color: r.ink-dim;
} }
// Wi-Fi network: lock (protected) and signal strength on the right. // Wi-Fi network: lock (protected) and signal strength on the right.
if r.network && row.lock: LockIcon { if r.network && row.lock: LockIcon {
x: parent.width - 104 * root.u; x: parent.width - root.pad - 34 * root.u - 16 * root.u - self.width;
y: (parent.height - self.height) / 2; y: (parent.height - self.height) / 2;
width: 24 * root.u; width: 24 * root.u;
height: 24 * root.u; height: 24 * root.u;
ink: r.ink-dim; ink: r.ink-dim;
} }
if r.network: SignalIcon { if r.network: SignalIcon {
x: parent.width - 66 * root.u; x: parent.width - root.pad - self.width;
y: (parent.height - self.height) / 2; y: (parent.height - self.height) / 2;
width: 34 * root.u; width: 34 * root.u;
height: 34 * root.u; height: 34 * root.u;

View File

@@ -0,0 +1,16 @@
[package]
name = "sf-miracast"
description = "Experimental Miracast (Wi-Fi Display) sink for Fennec OS: iwd P2P + WFD RTSP + GStreamer"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
anyhow.workspace = true
log.workspace = true
env_logger.workspace = true
[target.'cfg(target_os = "linux")'.dependencies]
tokio = { version = "1", features = ["rt", "net", "time", "io-util", "macros", "process", "signal", "sync"] }
libc = "0.2"
zbus = { version = "5", default-features = false, features = ["tokio"] }

View File

@@ -0,0 +1,301 @@
//! iwd P2P control, the RTSP session loop and the GStreamer player.
use std::collections::{HashMap, HashSet};
use std::io::Write;
use std::process::Stdio;
use std::time::{Duration, Instant};
use anyhow::{Context, Result, bail};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpStream;
use zbus::Connection;
use zbus::zvariant::{OwnedObjectPath, OwnedValue, Value};
use crate::rtsp::{Event, Message, SOURCE_PORT, Sink};
const IWD: &str = "net.connman.iwd";
const P2P_DEVICE: &str = "net.connman.iwd.p2p.Device";
const P2P_PEER: &str = "net.connman.iwd.p2p.Peer";
const P2P_DISPLAY: &str = "net.connman.iwd.p2p.Display";
const SERVICE_MANAGER: &str = "net.connman.iwd.p2p.ServiceManager";
const RTP_PORT: u16 = 1028;
/// A source peer must be visible this long before we connect to it.
const SETTLE: Duration = Duration::from_secs(2);
type Props = HashMap<String, OwnedValue>;
type Objects = HashMap<OwnedObjectPath, HashMap<String, Props>>;
fn event(text: &str) {
let mut out = std::io::stdout().lock();
let _ = writeln!(out, "SF-EVENT {text}");
let _ = out.flush();
}
fn get_bool(p: &Props, k: &str) -> Option<bool> {
p.get(k).and_then(|v| bool::try_from(v.try_clone().ok()?).ok())
}
fn get_str(p: &Props, k: &str) -> Option<String> {
p.get(k).and_then(|v| String::try_from(v.try_clone().ok()?).ok())
}
fn get_u16(p: &Props, k: &str) -> Option<u16> {
p.get(k).and_then(|v| u16::try_from(v.try_clone().ok()?).ok())
}
async fn objects(conn: &Connection) -> Result<Objects> {
let om = zbus::fdo::ObjectManagerProxy::builder(conn).destination(IWD)?.path("/")?.build().await?;
let raw = om.get_managed_objects().await?;
Ok(raw
.into_iter()
.map(|(path, ifaces)| (path, ifaces.into_iter().map(|(k, v)| (k.to_string(), v)).collect()))
.collect())
}
async fn proxy<'a>(conn: &Connection, path: &'a str, iface: &'a str) -> Result<zbus::Proxy<'a>> {
Ok(zbus::Proxy::new(conn, IWD, path, iface).await?)
}
#[derive(Debug, Clone)]
struct Peer {
path: String,
name: String,
connected: bool,
ip: Option<String>,
source: bool,
port: u16,
}
fn peers(objs: &Objects) -> Vec<Peer> {
objs.iter()
.filter_map(|(path, ifaces)| {
let p = ifaces.get(P2P_PEER)?;
let display = ifaces.get(P2P_DISPLAY);
Some(Peer {
path: path.to_string(),
name: get_str(p, "Name").unwrap_or_else(|| "telefon".into()),
connected: get_bool(p, "Connected").unwrap_or(false),
ip: get_str(p, "ConnectedIP"),
source: display.and_then(|d| get_bool(d, "Source")).unwrap_or(false),
port: display.and_then(|d| get_u16(d, "Port")).filter(|p| *p != 0).unwrap_or(SOURCE_PORT),
})
})
.collect()
}
pub fn run(name: String) -> Result<()> {
let rt = tokio::runtime::Builder::new_current_thread().enable_all().build()?;
rt.block_on(main_loop(name))
}
async fn main_loop(name: String) -> Result<()> {
let conn = Connection::system().await.context("system D-Bus")?;
let mut setup_for: Option<String> = None;
let mut warned = false;
let mut first_seen: HashMap<String, Instant> = HashMap::new();
let mut backoff: HashMap<String, Instant> = HashMap::new();
loop {
tokio::time::sleep(Duration::from_secs(1)).await;
let objs = match objects(&conn).await {
Ok(o) => o,
Err(e) => {
if !warned {
log::warn!("iwd: {e:#}");
warned = true;
}
tokio::time::sleep(Duration::from_secs(9)).await;
continue;
}
};
let Some(device) = objs.iter().find(|(_, i)| i.contains_key(P2P_DEVICE)).map(|(p, _)| p.to_string()) else {
if !warned {
log::warn!("no Wi-Fi Direct (P2P) capable Wi-Fi device; Miracast is unavailable");
warned = true;
}
setup_for = None;
tokio::time::sleep(Duration::from_secs(9)).await;
continue;
};
warned = false;
if setup_for.as_deref() != Some(device.as_str()) {
match setup(&conn, &device, &name).await {
Ok(()) => {
log::info!("Wi-Fi Display sink \"{name}\" ready on {device}");
setup_for = Some(device.clone());
}
Err(e) => {
log::error!("p2p setup: {e:#}");
tokio::time::sleep(Duration::from_secs(10)).await;
continue;
}
}
}
let now = Instant::now();
backoff.retain(|_, until| *until > now);
let list = peers(&objs);
let visible: HashSet<String> = list.iter().map(|p| p.path.clone()).collect();
first_seen.retain(|k, _| visible.contains(k));
// Already connected (e.g. we connected in an earlier round).
let target = match list.iter().find(|p| p.connected) {
Some(p) => Some(p.clone()),
None => {
let candidate = list.iter().find(|p| p.source && !backoff.contains_key(&p.path)).cloned();
match candidate {
Some(p) if now.duration_since(*first_seen.entry(p.path.clone()).or_insert(now)) >= SETTLE => {
log::info!("connecting to {} ({})", p.name, p.path);
match proxy(&conn, &p.path, P2P_PEER).await?.call_method("Connect", &()).await {
Ok(_) => Some(p),
Err(e) => {
log::warn!("connect {}: {e}", p.name);
backoff.insert(p.path.clone(), now + Duration::from_secs(60));
None
}
}
}
_ => None,
}
}
};
let Some(peer) = target else { continue };
// Wait for the peer's IP (DHCP on the P2P link).
let mut ip = peer.ip.clone();
for _ in 0..30 {
if ip.is_some() {
break;
}
tokio::time::sleep(Duration::from_millis(500)).await;
ip = objects(&conn).await.ok().and_then(|o| peers(&o).into_iter().find(|p| p.path == peer.path)?.ip);
}
match ip {
Some(ip) => {
if let Err(e) = session(&ip, peer.port, &peer.name).await {
log::warn!("session with {}: {e:#}", peer.name);
}
}
None => log::warn!("{}: no IP address on the P2P link", peer.name),
}
event("ended");
if let Ok(p) = proxy(&conn, &peer.path, P2P_PEER).await {
let _ = p.call_method("Disconnect", &()).await;
}
backoff.insert(peer.path.clone(), Instant::now() + Duration::from_secs(10));
// iwd stops discovery while connected; ask again.
if let Ok(d) = proxy(&conn, &device, P2P_DEVICE).await {
let _ = d.call_method("RequestDiscovery", &()).await;
}
}
}
async fn setup(conn: &Connection, device: &str, name: &str) -> Result<()> {
let dev = proxy(conn, device, P2P_DEVICE).await?;
dev.set_property("Name", name).await.context("setting the P2P name")?;
dev.set_property("Enabled", true).await.context("enabling P2P")?;
let mut props: HashMap<&str, Value> = HashMap::new();
props.insert("Source", Value::from(false));
props.insert("Sink", Value::from(true));
props.insert("Port", Value::from(SOURCE_PORT));
props.insert("HasAudio", Value::from(true));
let sm = proxy(conn, "/net/connman/iwd", SERVICE_MANAGER).await?;
if let Err(e) = sm.call_method("RegisterDisplayService", &(props,)).await {
// Already registered by an earlier run of this connection is fine.
if !e.to_string().contains("AlreadyExists") {
bail!("RegisterDisplayService: {e}");
}
}
// Discovery also keeps us visible to phones.
dev.call_method("RequestDiscovery", &()).await.context("RequestDiscovery")?;
Ok(())
}
/// One WFD session: RTSP with the phone, the player while streaming.
async fn session(ip: &str, port: u16, name: &str) -> Result<()> {
log::info!("rtsp: connecting to {ip}:{port}");
let mut stream = None;
for _ in 0..20 {
match TcpStream::connect((ip, port)).await {
Ok(s) => {
stream = Some(s);
break;
}
Err(_) => tokio::time::sleep(Duration::from_millis(500)).await,
}
}
let mut stream = stream.context("the phone's RTSP server did not answer")?;
let mut sink = Sink::new(RTP_PORT);
let mut player: Option<tokio::process::Child> = None;
let mut buf: Vec<u8> = Vec::new();
let result = loop {
let mut chunk = [0u8; 4096];
let read = tokio::select! {
r = tokio::time::timeout(Duration::from_secs(75), stream.read(&mut chunk)) => r,
status = async { match player.as_mut() { Some(p) => p.wait().await, None => std::future::pending().await } } => {
log::warn!("player exited: {status:?}");
break Ok(());
}
};
let n = match read {
Ok(Ok(0)) => break Ok(()),
Ok(Ok(n)) => n,
Ok(Err(e)) => break Err(e.into()),
Err(_) => break Err(anyhow::anyhow!("no keep-alive from the phone")),
};
buf.extend_from_slice(&chunk[..n]);
let mut teardown = false;
while let Some((msg, used)) = Message::parse(&buf) {
buf.drain(..used);
log::debug!("rtsp <- {:?}", msg.start);
let (out, events) = sink.handle(&msg);
for m in out {
log::debug!("rtsp -> {:?}", m.start);
stream.write_all(&m.to_bytes()).await?;
}
for ev in events {
match ev {
Event::Playing if player.is_none() => {
player = Some(start_player()?);
event(&format!("connected {name}"));
}
Event::Teardown => teardown = true,
_ => {}
}
}
}
if teardown {
break Ok(());
}
};
if let Some(mut p) = player {
let _ = p.kill().await;
}
result
}
/// MPEG-TS over RTP on RTP_PORT, decoded by whatever GStreamer finds best
/// (VA-API on the N100), full screen on Wayland.
fn start_player() -> Result<tokio::process::Child> {
let caps = "application/x-rtp,media=video,clock-rate=90000,encoding-name=MP2T";
let pipeline = format!(
"udpsrc port={RTP_PORT} caps=\"{caps}\" ! rtpjitterbuffer latency=120 ! rtpmp2tdepay ! decodebin3 name=d \
d. ! queue ! waylandsink fullscreen=true sync=false \
d. ! queue ! audioconvert ! audioresample ! autoaudiosink sync=false"
);
log::info!("player: gst-launch-1.0 {pipeline}");
let mut std_cmd = std::process::Command::new("sh");
std_cmd.arg("-c").arg(format!("exec gst-launch-1.0 -q {pipeline}"));
// Dies with us, so no stray player keeps the RTP port.
// SAFETY: prctl is async-signal-safe.
unsafe {
use std::os::unix::process::CommandExt;
std_cmd.pre_exec(|| {
libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM);
Ok(())
});
}
let mut cmd = tokio::process::Command::from(std_cmd);
cmd.stdin(Stdio::null()).stdout(Stdio::null()).kill_on_drop(true);
cmd.spawn().context("starting gst-launch-1.0 (gstreamer1.0-tools)")
}

View File

@@ -0,0 +1,42 @@
#![cfg_attr(not(target_os = "linux"), allow(dead_code))]
//! sf-miracast: experimental Miracast (Wi-Fi Display) sink.
//!
//! 1. Registers the TV as a Wi-Fi Display sink with iwd and keeps P2P
//! discovery on, so phones list "Fennec OS" under Smart View / Cast screen.
//! 2. iwd doesn't accept incoming P2P connections; it answers "try later"
//! and the phone waits for us to connect. So when a phone that is looking
//! for a screen (a WFD source peer) shows up, we connect to it.
//! 3. Over the P2P link we talk WFD RTSP with the phone (`rtsp`) and play
//! the MPEG-TS/RTP stream with GStreamer (`gst-launch-1.0`, VA-API).
//!
//! sf-core reads `SF-EVENT connected <name>` / `SF-EVENT ended` from stdout.
mod rtsp;
#[cfg(target_os = "linux")]
mod linux;
fn main() -> anyhow::Result<()> {
// zbus logs every D-Bus handshake at info level; keep that out of the session log.
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info"))
.filter_module("zbus", log::LevelFilter::Warn)
.filter_module("tracing", log::LevelFilter::Warn)
.init();
let mut name = "Fennec OS".to_string();
let mut args = std::env::args().skip(1);
while let Some(a) = args.next() {
match a.as_str() {
"--name" => name = args.next().unwrap_or(name),
other => log::warn!("unknown argument {other}"),
}
}
#[cfg(target_os = "linux")]
{
linux::run(name)
}
#[cfg(not(target_os = "linux"))]
{
let _ = name;
anyhow::bail!("sf-miracast needs Linux (iwd + GStreamer)")
}
}

View File

@@ -0,0 +1,296 @@
//! Wi-Fi Display (Miracast) RTSP, sink side. The phone (source) runs the
//! RTSP server; we connect and answer its capability questions (M1–M4), it
//! triggers SETUP/PLAY (M5–M7), keeps the session alive (M16) and finally
//! asks for TEARDOWN. The stream itself is MPEG-TS over RTP to `rtp_port`.
use std::collections::HashMap;
/// Default WFD RTSP port of the source.
pub const SOURCE_PORT: u16 = 7236;
#[derive(Debug, Clone, PartialEq)]
pub enum Start {
Request { method: String, uri: String },
Response { status: u16 },
}
#[derive(Debug, Clone, PartialEq)]
pub struct Message {
pub start: Start,
pub headers: Vec<(String, String)>,
pub body: String,
}
impl Message {
pub fn request(method: &str, uri: &str, cseq: u32) -> Self {
Message {
start: Start::Request { method: method.into(), uri: uri.into() },
headers: vec![("CSeq".into(), cseq.to_string())],
body: String::new(),
}
}
pub fn response(status: u16, cseq: &str) -> Self {
Message { start: Start::Response { status }, headers: vec![("CSeq".into(), cseq.into())], body: String::new() }
}
pub fn header(&self, name: &str) -> Option<&str> {
self.headers.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str())
}
fn with(mut self, k: &str, v: impl Into<String>) -> Self {
self.headers.push((k.into(), v.into()));
self
}
fn with_body(mut self, body: String) -> Self {
self.body = body;
self
}
pub fn to_bytes(&self) -> Vec<u8> {
let mut out = match &self.start {
Start::Request { method, uri } => format!("{method} {uri} RTSP/1.0\r\n"),
Start::Response { status } => format!("RTSP/1.0 {status} {}\r\n", if *status == 200 { "OK" } else { "Error" }),
};
for (k, v) in &self.headers {
out.push_str(&format!("{k}: {v}\r\n"));
}
if !self.body.is_empty() {
out.push_str("Content-Type: text/parameters\r\n");
out.push_str(&format!("Content-Length: {}\r\n", self.body.len()));
}
out.push_str("\r\n");
out.push_str(&self.body);
out.into_bytes()
}
/// Parses one message from the front of `buf`; returns it and the bytes used.
pub fn parse(buf: &[u8]) -> Option<(Message, usize)> {
let head_end = buf.windows(4).position(|w| w == b"\r\n\r\n")?;
let head = std::str::from_utf8(&buf[..head_end]).ok()?;
let mut lines = head.split("\r\n");
let first = lines.next()?;
let start = if let Some(rest) = first.strip_prefix("RTSP/1.0 ") {
Start::Response { status: rest.split(' ').next()?.parse().ok()? }
} else {
let mut p = first.split(' ');
Start::Request { method: p.next()?.to_string(), uri: p.next()?.to_string() }
};
let headers: Vec<(String, String)> = lines
.filter_map(|l| l.split_once(':'))
.map(|(k, v)| (k.trim().to_string(), v.trim().to_string()))
.collect();
let len: usize = headers
.iter()
.find(|(k, _)| k.eq_ignore_ascii_case("content-length"))
.and_then(|(_, v)| v.parse().ok())
.unwrap_or(0);
let total = head_end + 4 + len;
if buf.len() < total {
return None;
}
let body = String::from_utf8_lossy(&buf[head_end + 4..total]).into_owned();
Some((Message { start, headers, body }, total))
}
}
/// `name: value` lines of a text/parameters body.
pub fn parse_params(body: &str) -> Vec<(String, String)> {
body.lines()
.filter_map(|l| {
let l = l.trim();
if l.is_empty() {
return None;
}
Some(match l.split_once(':') {
Some((k, v)) => (k.trim().to_string(), v.trim().to_string()),
None => (l.to_string(), String::new()),
})
})
.collect()
}
#[derive(Debug, Clone, PartialEq)]
pub enum Event {
/// PLAY accepted: the stream is coming.
Playing,
Paused,
/// The source ended the session.
Teardown,
}
/// The sink's side of one WFD session.
pub struct Sink {
cseq: u32,
pending: HashMap<u32, String>,
rtp_port: u16,
presentation_url: Option<String>,
session: Option<String>,
}
impl Sink {
pub fn new(rtp_port: u16) -> Self {
Sink { cseq: 0, pending: HashMap::new(), rtp_port, presentation_url: None, session: None }
}
fn next_request(&mut self, method: &str, uri: &str) -> Message {
self.cseq += 1;
self.pending.insert(self.cseq, method.to_string());
let mut m = Message::request(method, uri, self.cseq);
if let Some(s) = &self.session {
m = m.with("Session", s.clone());
}
m
}
/// What we can play. H.264 CBP/CHP up to 1080p (VA-API decodes it), AAC and LPCM audio.
fn capability(&self, name: &str) -> String {
match name {
"wfd_video_formats" => "00 00 03 10 0001ffff 1fffffff 00001fff 00 0000 0000 00 none none".into(),
"wfd_audio_codecs" => "LPCM 00000003 00, AAC 00000007 00".into(),
"wfd_client_rtp_ports" => format!("RTP/AVP/UDP;unicast {} 0 mode=play", self.rtp_port),
"wfd_content_protection" | "wfd_display_edid" | "wfd_coupled_sink" | "wfd_uibc_capability" => "none".into(),
"wfd_connector_type" => "05".into(),
"wfd_standby_resume_capability" => "none".into(),
_ => "none".into(),
}
}
fn url(&self) -> String {
self.presentation_url.clone().unwrap_or_else(|| "rtsp://localhost/wfd1.0/streamid=0".into())
}
/// Handles one message from the source; returns what to send back and
/// what happened.
pub fn handle(&mut self, msg: &Message) -> (Vec<Message>, Vec<Event>) {
let mut out = vec![];
let mut events = vec![];
let cseq = msg.header("CSeq").unwrap_or("0").to_string();
match &msg.start {
Start::Request { method, .. } => match method.as_str() {
// M1: the source asks what we support; then we ask it (M2).
"OPTIONS" => {
out.push(Message::response(200, &cseq).with("Public", "org.wfa.wfd1.0, GET_PARAMETER, SET_PARAMETER"));
out.push(self.next_request("OPTIONS", "*").with("Require", "org.wfa.wfd1.0"));
}
// M3 (capabilities) or M16 (keep-alive, empty body).
"GET_PARAMETER" => {
let body: String = parse_params(&msg.body)
.into_iter()
.map(|(k, _)| format!("{k}: {}\r\n", self.capability(&k)))
.collect();
out.push(Message::response(200, &cseq).with_body(body));
}
// M4 (chosen formats, presentation URL) or M5 (trigger).
"SET_PARAMETER" => {
out.push(Message::response(200, &cseq));
for (k, v) in parse_params(&msg.body) {
match k.as_str() {
"wfd_presentation_URL" => {
self.presentation_url = v.split_whitespace().next().map(str::to_string);
}
"wfd_trigger_method" => match v.as_str() {
"SETUP" => {
let req = self.next_request("SETUP", &self.url()).with(
"Transport",
format!("RTP/AVP/UDP;unicast;client_port={}", self.rtp_port),
);
out.push(req);
}
"PLAY" => out.push(self.next_request("PLAY", &self.url())),
"PAUSE" => out.push(self.next_request("PAUSE", &self.url())),
"TEARDOWN" => {
out.push(self.next_request("TEARDOWN", &self.url()));
events.push(Event::Teardown);
}
_ => {}
},
_ => {}
}
}
}
_ => out.push(Message::response(501, &cseq)),
},
Start::Response { status } => {
let method = msg.header("CSeq").and_then(|c| c.parse().ok()).and_then(|c: u32| self.pending.remove(&c));
match (method.as_deref(), *status) {
(Some("SETUP"), 200) => {
self.session = msg.header("Session").map(|s| s.split(';').next().unwrap_or(s).trim().to_string());
out.push(self.next_request("PLAY", &self.url()));
}
(Some("PLAY"), 200) => events.push(Event::Playing),
(Some("PAUSE"), 200) => events.push(Event::Paused),
(Some(m), s) if s != 200 => log::warn!("rtsp: {m} failed with {s}"),
_ => {}
}
}
}
(out, events)
}
}
#[cfg(test)]
mod tests {
use super::*;
fn req(text: &str) -> Message {
Message::parse(text.as_bytes()).unwrap().0
}
#[test]
fn parses_with_body() {
let raw = b"GET_PARAMETER rtsp://localhost/wfd1.0 RTSP/1.0\r\nCSeq: 2\r\nContent-Length: 19\r\n\r\nwfd_video_formats\r\nextra";
let (m, used) = Message::parse(raw).unwrap();
assert_eq!(m.body, "wfd_video_formats\r\n");
assert_eq!(used, raw.len() - 5);
assert!(Message::parse(b"OPTIONS * RTSP/1.0\r\nCSeq: 1\r\n").is_none());
}
#[test]
fn full_session() {
let mut sink = Sink::new(1028);
// M1 -> 200 + our M2
let (out, _) = sink.handle(&req("OPTIONS * RTSP/1.0\r\nCSeq: 1\r\nRequire: org.wfa.wfd1.0\r\n\r\n"));
assert_eq!(out.len(), 2);
assert!(matches!(out[1].start, Start::Request { ref method, .. } if method == "OPTIONS"));
// M3
let body = "wfd_video_formats\r\nwfd_client_rtp_ports\r\nwfd_audio_codecs\r\n";
let (out, _) = sink.handle(&req(&format!(
"GET_PARAMETER rtsp://localhost/wfd1.0 RTSP/1.0\r\nCSeq: 2\r\nContent-Length: {}\r\n\r\n{body}",
body.len()
)));
assert!(out[0].body.contains("wfd_client_rtp_ports: RTP/AVP/UDP;unicast 1028 0 mode=play\r\n"));
// M4
let body = "wfd_presentation_URL: rtsp://192.168.49.1/wfd1.0/streamid=0 none\r\n";
sink.handle(&req(&format!(
"SET_PARAMETER rtsp://localhost/wfd1.0 RTSP/1.0\r\nCSeq: 3\r\nContent-Length: {}\r\n\r\n{body}",
body.len()
)));
// M5 SETUP trigger -> our M6
let body = "wfd_trigger_method: SETUP\r\n";
let (out, _) = sink.handle(&req(&format!(
"SET_PARAMETER rtsp://localhost/wfd1.0 RTSP/1.0\r\nCSeq: 4\r\nContent-Length: {}\r\n\r\n{body}",
body.len()
)));
let setup = &out[1];
assert_eq!(setup.start, Start::Request { method: "SETUP".into(), uri: "rtsp://192.168.49.1/wfd1.0/streamid=0".into() });
let setup_cseq = setup.header("CSeq").unwrap().to_string();
// SETUP reply -> PLAY with session
let (out, _) = sink.handle(&req(&format!("RTSP/1.0 200 OK\r\nCSeq: {setup_cseq}\r\nSession: 6B8B4567;timeout=30\r\n\r\n")));
assert_eq!(out[0].header("Session"), Some("6B8B4567"));
let play_cseq = out[0].header("CSeq").unwrap().to_string();
let (_, ev) = sink.handle(&req(&format!("RTSP/1.0 200 OK\r\nCSeq: {play_cseq}\r\nSession: 6B8B4567\r\n\r\n")));
assert_eq!(ev, vec![Event::Playing]);
// M16 keep-alive
let (out, _) = sink.handle(&req("GET_PARAMETER rtsp://localhost/wfd1.0 RTSP/1.0\r\nCSeq: 9\r\n\r\n"));
assert_eq!(out[0].start, Start::Response { status: 200 });
// Teardown trigger
let body = "wfd_trigger_method: TEARDOWN\r\n";
let (_, ev) = sink.handle(&req(&format!(
"SET_PARAMETER rtsp://localhost/wfd1.0 RTSP/1.0\r\nCSeq: 10\r\nContent-Length: {}\r\n\r\n{body}",
body.len()
)));
assert_eq!(ev, vec![Event::Teardown]);
}
}

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "sf-remote" name = "sf-remote"
description = "SmartFox Apple Siri Remote driver: BLE GATT -> uinput keys + touch gestures" description = "Fennec OS Apple Siri Remote driver: BLE GATT -> uinput keys + touch gestures"
version.workspace = true version.workspace = true
edition.workspace = true edition.workspace = true
license.workspace = true license.workspace = true

View File

@@ -13,7 +13,7 @@ use evdev::{EventType, KeyCode};
use crate::link::Link; use crate::link::Link;
const ESC_HOLD: Duration = Duration::from_millis(800); const ESC_HOLD: Duration = Duration::from_millis(800);
const OWN_DEVICE: &str = "SmartFox Siri Remote"; const OWN_DEVICE: &str = "Fennec OS Siri Remote";
pub fn spawn(link: Link) { pub fn spawn(link: Link) {
std::thread::spawn(move || { std::thread::spawn(move || {

View File

@@ -99,7 +99,7 @@ impl Keys {
keys.insert(KeyCode::KEY_PAUSECD); keys.insert(KeyCode::KEY_PAUSECD);
let dev = VirtualDevice::builder() let dev = VirtualDevice::builder()
.context("opening /dev/uinput (is the user in the smartfox group?)")? .context("opening /dev/uinput (is the user in the smartfox group?)")?
.name("SmartFox Siri Remote") .name("Fennec OS Siri Remote")
.with_keys(&keys)? .with_keys(&keys)?
.build()?; .build()?;
Ok(Self { dev: Some(dev) }) Ok(Self { dev: Some(dev) })
@@ -244,6 +244,9 @@ async fn wake_target(adapter: &Adapter, dev: &Device) -> Option<wake::Target> {
/// Handles one connection until the remote disconnects. /// Handles one connection until the remote disconnects.
async fn serve(dev: &Device, keys: &mut Keys, step: i32, link: &Link) -> Result<()> { async fn serve(dev: &Device, keys: &mut Keys, step: i32, link: &Link) -> Result<()> {
use bluer::{DeviceEvent, DeviceProperty};
let mut events = dev.events().await?;
let mut reports = futures::stream::select_all(subscribe(dev).await?); let mut reports = futures::stream::select_all(subscribe(dev).await?);
let mut gestures = Gestures::new(step); let mut gestures = Gestures::new(step);
let mut held: u16 = 0; let mut held: u16 = 0;
@@ -253,9 +256,20 @@ async fn serve(dev: &Device, keys: &mut Keys, step: i32, link: &Link) -> Result<
let mut held_since = Instant::now(); let mut held_since = Instant::now();
let mut last_repeat = Instant::now(); let mut last_repeat = Instant::now();
let mut tick = tokio::time::interval(Duration::from_millis(20)); let mut tick = tokio::time::interval(Duration::from_millis(20));
let mut connection_check = tokio::time::interval(Duration::from_secs(2));
loop { loop {
tokio::select! { tokio::select! {
event = events.next() => match event {
Some(DeviceEvent::PropertyChanged(DeviceProperty::Connected(false))) | None => return Ok(()),
Some(_) => {}
},
_ = connection_check.tick() => {
// Notification streams can stay open after the GATT link goes away.
if !dev.is_connected().await.unwrap_or(false) {
return Ok(());
}
}
item = reports.next() => { item = reports.next() => {
let Some(data) = item else { return Ok(()) }; let Some(data) = item else { return Ok(()) };
match protocol::parse(&data) { match protocol::parse(&data) {
@@ -319,13 +333,16 @@ async fn serve(dev: &Device, keys: &mut Keys, step: i32, link: &Link) -> Result<
} }
} }
/// The remote advertises with a rotating private address. The controller's /// The remote advertises with a rotating private address. Keep discovery
/// accept list only knows its identity address, so BlueZ's passive /// active while connecting so BlueZ can resolve that address with the bonded
/// auto-connect never sees it. An active scan lets the kernel resolve the /// IRK. Also retry without an RSSI event: some controllers do not report one
/// address with the bonded IRK; we connect as soon as an advert arrives. /// for an already known device after the remote restarts.
async fn wait_for_advert(adapter: &Adapter, dev: &Device) -> Result<()> { async fn connect(adapter: &Adapter, dev: &Device) -> Result<bool> {
use bluer::{DeviceEvent, DeviceProperty, DiscoveryFilter, DiscoveryTransport}; use bluer::{DeviceEvent, DeviceProperty, DiscoveryFilter, DiscoveryTransport};
if dev.is_connected().await.unwrap_or(false) {
return Ok(true);
}
adapter adapter
.set_discovery_filter(DiscoveryFilter { .set_discovery_filter(DiscoveryFilter {
transport: DiscoveryTransport::Le, transport: DiscoveryTransport::Le,
@@ -335,30 +352,48 @@ async fn wait_for_advert(adapter: &Adapter, dev: &Device) -> Result<()> {
.await?; .await?;
let mut discovery = adapter.discover_devices_with_changes().await?; let mut discovery = adapter.discover_devices_with_changes().await?;
let mut events = dev.events().await?; let mut events = dev.events().await?;
let mut recheck = tokio::time::interval(Duration::from_secs(2)); let mut retry = tokio::time::interval(Duration::from_secs(5));
retry.reset();
loop { loop {
tokio::select! { let should_connect = tokio::select! {
// A connection may come up between our checks (e.g. a pending Connect()). _ = retry.tick() => true,
_ = recheck.tick() => { ev = events.next() => match ev {
Some(DeviceEvent::PropertyChanged(DeviceProperty::Rssi(rssi))) => {
log::info!("remote advertising (rssi {rssi}), connecting");
true
}
Some(DeviceEvent::PropertyChanged(DeviceProperty::Connected(true))) => return Ok(true),
Some(_) => false,
None => anyhow::bail!("device event stream ended"),
},
// Keep the discovery session alive and drained.
event = discovery.next() => {
if event.is_none() {
anyhow::bail!("discovery ended");
}
false
}
};
if !should_connect {
continue;
}
if dev.is_connected().await.unwrap_or(false) { if dev.is_connected().await.unwrap_or(false) {
return Ok(()); return Ok(true);
} }
// Removed in the launcher's settings: go back to pairing. // Removed in the launcher's settings: go back to pairing.
if !dev.is_paired().await.unwrap_or(false) { if !dev.is_paired().await.unwrap_or(false) {
anyhow::bail!("remote {} was unpaired", dev.address()); anyhow::bail!("remote {} was unpaired", dev.address());
} }
match tokio::time::timeout(Duration::from_secs(10), dev.connect()).await {
Ok(Ok(())) => return Ok(true),
Ok(Err(e)) if e.kind == bluer::ErrorKind::InProgress => {
tokio::time::sleep(Duration::from_secs(2)).await;
} }
ev = events.next() => match ev { Ok(Err(e)) => log::debug!("connect: {e}"),
Some(DeviceEvent::PropertyChanged(DeviceProperty::Rssi(rssi))) => { Err(_) => log::debug!("connect timed out"),
log::info!("remote advertising (rssi {rssi}), connecting");
return Ok(());
} }
Some(DeviceEvent::PropertyChanged(DeviceProperty::Connected(true))) => return Ok(()), if dev.is_connected().await.unwrap_or(false) {
Some(_) => {} return Ok(true);
None => anyhow::bail!("device event stream ended"),
},
// Keep the discovery session alive and drained.
_ = discovery.next() => {}
} }
} }
} }
@@ -426,31 +461,6 @@ async fn pair_new(adapter: &Adapter, link: &Link) -> Result<Device> {
} }
} }
async fn connect(adapter: &Adapter, dev: &Device) -> Result<bool> {
if dev.is_connected().await.unwrap_or(false) {
return Ok(true);
}
wait_for_advert(adapter, dev).await?;
if dev.is_connected().await.unwrap_or(false) {
return Ok(true);
}
match tokio::time::timeout(Duration::from_secs(10), dev.connect()).await {
Ok(Ok(())) => Ok(true),
Ok(Err(e)) if e.kind == bluer::ErrorKind::InProgress => {
tokio::time::sleep(Duration::from_secs(2)).await;
Ok(false)
}
Ok(Err(e)) => {
log::debug!("connect: {e}");
Ok(false)
}
Err(_) => {
log::debug!("connect timed out");
Ok(false)
}
}
}
pub fn run() -> Result<()> { pub fn run() -> Result<()> {
let opts = parse_args(); let opts = parse_args();
let link = Link::new(opts.home_socket.clone()); let link = Link::new(opts.home_socket.clone());

View File

@@ -1,6 +1,6 @@
#![cfg_attr(not(target_os = "linux"), allow(dead_code))] #![cfg_attr(not(target_os = "linux"), allow(dead_code))]
//! sf-remote: Apple Siri Remote driver for SmartFox. //! sf-remote: Apple Siri Remote driver for Fennec OS.
//! //!
//! Subscribes to the remote's HID report characteristics over BlueZ D-Bus //! Subscribes to the remote's HID report characteristics over BlueZ D-Bus
//! (BlueZ's own HID plugin must be disabled, it drops these reports) and //! (BlueZ's own HID plugin must be disabled, it drops these reports) and

View File

@@ -5,7 +5,7 @@
//! on its USB device and the ports above it. //! on its USB device and the ports above it.
//! 2. The kernel keeps scanning for the remote while suspended. It does that //! 2. The kernel keeps scanning for the remote while suspended. It does that
//! for devices on its connect list that carry the "remote wakeup" flag. //! for devices on its connect list that carry the "remote wakeup" flag.
//! BlueZ sets both only through its HID plugins, which SmartFox disables //! BlueZ sets both only through its HID plugins, which Fennec OS disables
//! (they drop the Siri Remote's reports), so we send the two management //! (they drop the Siri Remote's reports), so we send the two management
//! commands ourselves: Add Device (auto-connect) and Set Device Flags. //! commands ourselves: Add Device (auto-connect) and Set Device Flags.
//! //!

View File

@@ -1,6 +1,6 @@
[package] [package]
name = "sf-update" name = "sf-update"
description = "SmartFox package updater: signed shell and app packages from the Gitea package registry" description = "Fennec OS package updater: signed shell and app packages from the Gitea package registry"
version.workspace = true version.workspace = true
edition.workspace = true edition.workspace = true
license.workspace = true license.workspace = true
@@ -18,3 +18,6 @@ ed25519-dalek = "2"
base64 = "0.22" base64 = "0.22"
tar = "0.4" tar = "0.4"
ruzstd = "0.8" ruzstd = "0.8"
[target.'cfg(unix)'.dependencies]
libc = "0.2"

View File

@@ -0,0 +1,289 @@
//! The app store side of sf-update (docs/store.md): reads what the user wants
//! (store.toml, written by the launcher), asks the sources what they offer
//! (catalog.json) and works out which store apps to install, update or
//! remove. Downloading, checking and unpacking reuse the package store.
use std::collections::BTreeMap;
use std::path::Path;
use std::time::{SystemTime, UNIX_EPOCH};
use anyhow::{Context, Result};
use sf_ipc::manifest::{AppManifest, version_cmp};
use sf_ipc::store::{Catalog, CatalogApp, INDEX_FILE, Index, MAX_WANTED, PACKAGE_PREFIX, SourceInfo, Wanted, missing_permissions};
use crate::forge::{self, Repo};
use crate::store::Store;
/// Apps one catalog may list.
const MAX_CATALOG_APPS: usize = 200;
/// A store package to download.
#[derive(Debug, Clone)]
pub struct StoreDownload {
pub id: String,
pub package_url: String,
pub approved: Vec<sf_ipc::Permission>,
pub source: String,
}
/// Reads store.toml. The launcher (user tv) writes it, so it is read
/// carefully: no symlinks, a regular file, a size limit.
pub fn read_wanted(path: &Path) -> Result<Wanted> {
let mut opts = std::fs::OpenOptions::new();
opts.read(true);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
opts.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK);
}
let file = match opts.open(path) {
Ok(f) => f,
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Wanted::default()),
Err(e) => return Err(e).with_context(|| format!("opening {}", path.display())),
};
let meta = file.metadata()?;
anyhow::ensure!(meta.is_file(), "{} is not a regular file", path.display());
anyhow::ensure!(meta.len() <= MAX_WANTED, "{} is too large", path.display());
let mut text = String::new();
use std::io::Read;
file.take(MAX_WANTED).read_to_string(&mut text)?;
Wanted::parse(&text)
}
fn now() -> u64 {
SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
}
/// The canonical address of a source, or the input if it doesn't parse.
pub fn canonical(source: &str) -> String {
Repo::parse(source).map(|r| r.url()).unwrap_or_else(|_| source.trim().to_string())
}
/// Asks every source what it offers.
pub fn refresh_catalog(wanted: &Wanted) -> Catalog {
let agent = forge::agent();
let mut sources: Vec<String> = Vec::new();
for s in wanted.sources.iter().chain(wanted.apps.values().map(|a| &a.source)) {
let c = canonical(s);
if !sources.contains(&c) {
sources.push(c);
}
}
let mut catalog = Catalog { updated_at: now(), ..Default::default() };
for url in sources {
let mut info = SourceInfo { url: url.clone(), ..Default::default() };
match Repo::parse(&url).and_then(|r| forge::detect(&agent, &r)) {
Err(e) => info.error = Some(format!("{e:#}")),
Ok(repo) => match forge::raw_file(&agent, &repo, INDEX_FILE) {
Ok(Some(text)) => {
info.kind = "catalog".into();
match toml::from_str::<Index>(&text) {
Err(e) => info.error = Some(format!("{INDEX_FILE}: {e}")),
Ok(index) => {
info.name = index.name.clone();
let mut errors = Vec::new();
for app_url in index.apps.iter().take(MAX_CATALOG_APPS) {
match Repo::parse(app_url).and_then(|r| forge::detect(&agent, &r)).and_then(|r| app_entry(&agent, &r)) {
Ok(Some(mut app)) => {
app.catalog = Some(url.clone());
catalog.apps.push(app);
info.apps += 1;
}
Ok(None) => {}
Err(e) => errors.push(format!("{app_url}: {e:#}")),
}
}
for e in &errors {
log::warn!("store: {e}");
}
if info.apps == 0 && !errors.is_empty() {
info.error = errors.into_iter().next();
}
}
}
}
Ok(None) | Err(_) => {
info.kind = "app".into();
match app_entry(&agent, &repo) {
Ok(Some(app)) => {
info.name = app.name.clone();
info.apps = 1;
catalog.apps.push(app);
}
Ok(None) => info.error = Some("no release with an app.toml yet".into()),
Err(e) => info.error = Some(format!("{e:#}")),
}
}
},
}
if let Some(e) = &info.error {
log::warn!("store source {url}: {e}");
}
catalog.sources.push(info);
}
// One entry per id: the source the app is installed from wins, else the first.
let mut seen: BTreeMap<String, usize> = BTreeMap::new();
let mut apps: Vec<CatalogApp> = Vec::new();
for app in catalog.apps.drain(..) {
let pinned = wanted.apps.get(&app.id).map(|w| canonical(&w.source));
match seen.get(&app.id) {
Some(&i) => {
if pinned.as_deref() == Some(app.source.as_str()) && apps[i].source != app.source {
apps[i] = app;
}
}
None => {
seen.insert(app.id.clone(), apps.len());
apps.push(app);
}
}
}
catalog.apps = apps;
catalog
}
/// The newest release of one app repo.
fn app_entry(agent: &ureq::Agent, repo: &Repo) -> Result<Option<CatalogApp>> {
let Some(release) = forge::latest_release(agent, repo)? else { return Ok(None) };
let manifest_asset = release.asset("app.toml").context("app.toml")?;
let app: AppManifest = toml::from_str(&forge::asset_text(agent, manifest_asset)?).context("app.toml")?;
app.check_store_rules()?;
anyhow::ensure!(crate::registry::is_release(&app.version), "version {} is not a release version (1.2.3)", app.version);
let package = package_asset(&release, &app)?;
Ok(Some(CatalogApp {
id: app.id.clone(),
name: app.name.clone(),
version: app.version.clone(),
kind: format!("{:?}", app.kind).to_lowercase(),
category: app.category.clone(),
description: app.description.clone(),
author: app.author.clone().unwrap_or_default(),
homepage: app.homepage.clone().unwrap_or_else(|| repo.url()),
license: app.license.clone().unwrap_or_default(),
accent: app.accent.clone(),
permissions: app.permissions(),
source: repo.url(),
catalog: None,
package_url: package.url.clone(),
installed: None,
blocked: None,
}))
}
/// The release's package for this TV (docs/store.md): `<id>-<version>.tar.zst`
/// on x86-64, `<id>-<version>-aarch64.tar.zst` on ARM. A web app is the same
/// everywhere, so its plain package is fine on any architecture; an exec app's
/// plain package is an x86-64 build.
fn package_asset<'a>(release: &'a forge::Release, app: &AppManifest) -> Result<&'a forge::Asset> {
let plain = format!("{}-{}.tar.zst", app.id, app.version);
let native = crate::arch::file_name(&app.id, &app.version);
if let Some(a) = release.asset(&native) {
return Ok(a);
}
if !crate::arch::IS_DEFAULT && app.kind == sf_ipc::manifest::AppKind::Web {
if let Some(a) = release.asset(&plain) {
return Ok(a);
}
}
anyhow::bail!("release {} has no {native}", release.tag)
}
/// Marks what's installed and what's held back, and returns the store
/// packages to download (new installs and updates).
pub fn plan(store: &Store, wanted: &Wanted, catalog: &mut Catalog) -> BTreeMap<String, (String, StoreDownload)> {
let mut out = BTreeMap::new();
for app in &mut catalog.apps {
let name = format!("{PACKAGE_PREFIX}{}", app.id);
app.installed = store.installed(&name);
app.blocked = None;
let Some(want) = wanted.apps.get(&app.id) else { continue };
if canonical(&want.source) != app.source {
continue;
}
if !missing_permissions(&app.permissions, &want.permissions).is_empty() {
app.blocked = Some("permissions".into());
continue;
}
let newer = app.installed.as_deref().is_none_or(|i| version_cmp(&app.version, i).is_gt());
if newer && !store.bad(&name).contains(&app.version) {
out.insert(
name,
(
app.version.clone(),
StoreDownload {
id: app.id.clone(),
package_url: app.package_url.clone(),
approved: want.permissions.clone(),
source: app.source.clone(),
},
),
);
}
}
out
}
/// Removes store apps the user no longer wants.
pub fn remove_unwanted(store: &Store, wanted: &Wanted) -> bool {
let mut changed = false;
for id in store.store_apps() {
if !wanted.apps.contains_key(&id) {
match store.remove_store_app(&id) {
Ok(()) => changed = true,
Err(e) => log::error!("removing {id}: {e:#}"),
}
}
}
changed
}
pub fn write_catalog(path: &Path, catalog: &Catalog) {
let ok = (|| -> Result<()> {
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)?;
}
let tmp = path.with_extension("json.tmp");
std::fs::write(&tmp, serde_json::to_vec_pretty(catalog)?)?;
std::fs::rename(&tmp, path)?;
Ok(())
})();
if let Err(e) = ok {
log::warn!("writing {}: {e:#}", path.display());
}
}
/// Downloads a store package into `dir`.
pub fn download(d: &StoreDownload, version: &str, dir: &Path) -> Result<std::path::PathBuf> {
let agent = forge::agent();
let file = dir.join(format!("{}-{version}.tar.zst", d.id));
let n = forge::download(&agent, &d.package_url, &file, crate::registry::MAX_PACKAGE)?;
log::info!("downloaded {} {version} ({n} bytes)", d.id);
Ok(file)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn canonical_sources() {
assert_eq!(canonical("github.com/Fox/App.git"), "https://github.com/Fox/App");
assert_eq!(canonical(" not a url "), "not a url");
}
#[cfg(unix)]
#[test]
fn wanted_file_is_read_carefully() {
let dir = std::env::temp_dir().join(format!("sf-store-test-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let real = dir.join("real.toml");
std::fs::write(&real, "sources = ['github.com/a/b']\n").unwrap();
assert_eq!(read_wanted(&real).unwrap().sources, ["github.com/a/b"]);
let link = dir.join("link.toml");
let _ = std::fs::remove_file(&link);
std::os::unix::fs::symlink(&real, &link).unwrap();
assert!(read_wanted(&link).is_err());
assert!(read_wanted(&dir.join("missing.toml")).unwrap().apps.is_empty());
std::fs::remove_dir_all(&dir).unwrap();
}
}

View File

@@ -0,0 +1,45 @@
//! The CPU architecture of this TV, and how packages built for it are named
//! (docs/updates.md, "Architektúrák").
//!
//! Fennec OS started on x86-64: its package files carry no architecture
//! (`sf-shell-1.2.0.tar.zst`). Packages for any other architecture have a
//! suffix (`sf-shell-1.2.0-aarch64.tar.zst`).
/// This build's architecture, as in Rust's `std::env::consts::ARCH`.
pub const NAME: &str = std::env::consts::ARCH;
/// Whether this is the original architecture (unsuffixed package files).
pub const IS_DEFAULT: bool = cfg!(target_arch = "x86_64");
/// `name-version.tar.zst` for this architecture.
pub fn file_name(name: &str, version: &str) -> String {
if IS_DEFAULT { format!("{name}-{version}.tar.zst") } else { format!("{name}-{version}-{NAME}.tar.zst") }
}
/// Whether a package that says it was built for `arch` (pkg.toml; missing =
/// an old package, built for x86-64) runs here.
pub fn runs_here(arch: Option<&str>) -> bool {
match arch {
Some(a) => a == NAME,
None => IS_DEFAULT,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn names() {
if IS_DEFAULT {
assert_eq!(file_name("sf-shell", "1.2.0"), "sf-shell-1.2.0.tar.zst");
assert!(runs_here(None));
assert!(!runs_here(Some("aarch64")));
} else {
assert_eq!(file_name("sf-shell", "1.2.0"), format!("sf-shell-1.2.0-{NAME}.tar.zst"));
assert!(!runs_here(None));
assert!(!runs_here(Some("x86_64")));
}
assert!(runs_here(Some(NAME)));
}
}

View File

@@ -21,6 +21,7 @@ struct File {
root: Option<PathBuf>, root: Option<PathBuf>,
requests: Option<PathBuf>, requests: Option<PathBuf>,
factory: Option<PathBuf>, factory: Option<PathBuf>,
store_wanted: Option<PathBuf>,
} }
impl File { impl File {
@@ -38,6 +39,7 @@ impl File {
root: o.root.or(self.root), root: o.root.or(self.root),
requests: o.requests.or(self.requests), requests: o.requests.or(self.requests),
factory: o.factory.or(self.factory), factory: o.factory.or(self.factory),
store_wanted: o.store_wanted.or(self.store_wanted),
} }
} }
} }
@@ -57,6 +59,10 @@ pub struct Config {
pub requests: PathBuf, pub requests: PathBuf,
/// Versions of the copies built into the image. /// Versions of the copies built into the image.
pub factory: PathBuf, pub factory: PathBuf,
/// What the user wants from the store (written by the launcher).
pub store_wanted: PathBuf,
/// What the store sources offer (written here).
pub catalog: PathBuf,
} }
impl Config { impl Config {
@@ -84,12 +90,15 @@ impl Config {
} }
None => None, None => None,
}; };
let root = file.root.unwrap_or_else(|| "/var/lib/sf-pkg".into());
Ok(Config { Ok(Config {
catalog: root.join("store").join("catalog.json"),
store_wanted: file.store_wanted.unwrap_or_else(|| sf_ipc::store::WANTED_FILE.into()),
server: server.trim_end_matches('/').to_string(), server: server.trim_end_matches('/').to_string(),
owner, owner,
auth, auth,
public_key, public_key,
root: file.root.unwrap_or_else(|| "/var/lib/sf-pkg".into()), root,
requests: file.requests.unwrap_or_else(|| "/var/lib/smartfox/update-requests".into()), requests: file.requests.unwrap_or_else(|| "/var/lib/smartfox/update-requests".into()),
factory: file.factory.unwrap_or_else(|| "/usr/share/smartfox/factory-versions.toml".into()), factory: file.factory.unwrap_or_else(|| "/usr/share/smartfox/factory-versions.toml".into()),
}) })

View File

@@ -0,0 +1,326 @@
//! Store sources: app repos on GitHub, Gitea/Forgejo (Codeberg too) and
//! GitLab. An app is published as a release with two assets (docs/store.md):
//!
//! app.toml the manifest (name, permissions)
//! <id>-<version>.tar.zst the package
//!
//! A catalog repo lists many app repos in `smartfox-store.toml` on its
//! default branch.
//!
//! Requests go without our registry login (it must never reach third-party
//! servers), HTTPS only, with size limits on everything.
use std::io::Read;
use std::time::Duration;
use anyhow::{Context, Result, bail};
use serde::Deserialize;
const MAX_JSON: u64 = 4 * 1024 * 1024;
const MAX_TEXT: u64 = 256 * 1024;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Forge {
GitHub,
Gitea,
GitLab,
}
/// A repository on a forge.
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Repo {
/// None: not known yet (self-hosted), found out by `detect`.
pub forge: Option<Forge>,
/// https://host
pub base: String,
/// owner/repo (GitLab: group/subgroup/project)
pub path: String,
}
impl Repo {
/// What the user typed: `https://github.com/o/r(.git)`, `github.com/o/r`,
/// or with an explicit forge: `gitea:git.example.org/o/r`,
/// `gitlab:gitlab.example.org/group/project`, `github:o/r`.
pub fn parse(input: &str) -> Result<Repo> {
let input = input.trim();
let (forge, rest) = match input.split_once(':') {
Some(("github", r)) => (Some(Forge::GitHub), r),
Some(("gitea" | "forgejo", r)) => (Some(Forge::Gitea), r),
Some(("gitlab", r)) => (Some(Forge::GitLab), r),
_ => (None, input),
};
let rest = rest.trim_start_matches('/');
let rest = if let Some(r) = rest.strip_prefix("https://") {
r
} else if rest.starts_with("http://") {
bail!("only https:// sources are allowed");
} else {
rest
};
let rest = rest.split(['?', '#']).next().unwrap_or("").trim_end_matches('/');
let rest = rest.strip_suffix(".git").unwrap_or(rest);
let (host, path) = match (forge, rest.split_once('/')) {
(Some(Forge::GitHub), Some((h, p))) if !h.contains('.') => ("github.com", format!("{h}/{p}")),
(_, Some((h, p))) => (h, p.to_string()),
_ => bail!("not a repository address: {input}"),
};
let host = host.to_ascii_lowercase();
let valid_host = !host.is_empty() && host.contains('.') && host.bytes().all(|b| b.is_ascii_alphanumeric() || b"-.:".contains(&b));
if !valid_host {
bail!("bad host in {input}");
}
let parts: Vec<&str> = path.split('/').collect();
let valid_part = |p: &&str| !p.is_empty() && *p != "." && *p != ".." && p.bytes().all(|b| b.is_ascii_alphanumeric() || b"-._".contains(&b));
if parts.len() < 2 || !parts.iter().all(valid_part) {
bail!("expected owner/repository in {input}");
}
let forge = forge.or(match host.as_str() {
"github.com" => Some(Forge::GitHub),
"gitlab.com" | "framagit.org" => Some(Forge::GitLab),
"codeberg.org" => Some(Forge::Gitea),
_ => None,
});
if matches!(forge, Some(Forge::GitHub | Forge::Gitea)) && parts.len() != 2 {
bail!("expected owner/repository in {input}");
}
Ok(Repo { forge, base: format!("https://{host}"), path })
}
/// Canonical form, stored in store.toml and catalog.json.
pub fn url(&self) -> String {
format!("{}/{}", self.base, self.path)
}
fn encoded_path(&self) -> String {
self.path.replace('/', "%2F")
}
}
#[derive(Debug, Clone)]
pub struct Asset {
pub name: String,
pub url: String,
}
#[derive(Debug, Clone)]
pub struct Release {
pub tag: String,
pub assets: Vec<Asset>,
}
impl Release {
pub fn asset(&self, name: &str) -> Option<&Asset> {
self.assets.iter().find(|a| a.name == name)
}
}
pub fn agent() -> ureq::Agent {
ureq::Agent::config_builder()
.timeout_connect(Some(Duration::from_secs(15)))
.timeout_recv_response(Some(Duration::from_secs(60)))
.timeout_recv_body(Some(Duration::from_secs(1800)))
.https_only(true)
.user_agent(concat!("FennecOS-store/", env!("CARGO_PKG_VERSION")))
.build()
.into()
}
/// GET returning None on 404.
fn get_text(agent: &ureq::Agent, url: &str, limit: u64) -> Result<Option<String>> {
match agent.get(url).header("Accept", "application/json, text/plain, */*").call() {
Ok(resp) => {
let mut body = String::new();
resp.into_body().into_reader().take(limit + 1).read_to_string(&mut body).with_context(|| format!("reading {url}"))?;
if body.len() as u64 > limit {
bail!("{url}: response is too large");
}
Ok(Some(body))
}
Err(ureq::Error::StatusCode(404)) => Ok(None),
Err(ureq::Error::StatusCode(403 | 429)) if url.contains("api.github.com") => {
bail!("GitHub rate limit reached, try again later")
}
Err(e) => Err(e).with_context(|| format!("GET {url}")),
}
}
/// Works out the forge of a self-hosted repo.
pub fn detect(agent: &ureq::Agent, repo: &Repo) -> Result<Repo> {
if repo.forge.is_some() {
return Ok(repo.clone());
}
let gitea = format!("{}/api/v1/repos/{}", repo.base, repo.path);
if repo.path.matches('/').count() == 1 && get_text(agent, &gitea, MAX_JSON).ok().flatten().is_some() {
return Ok(Repo { forge: Some(Forge::Gitea), ..repo.clone() });
}
let gitlab = format!("{}/api/v4/projects/{}", repo.base, repo.encoded_path());
if get_text(agent, &gitlab, MAX_JSON).ok().flatten().is_some() {
return Ok(Repo { forge: Some(Forge::GitLab), ..repo.clone() });
}
bail!("{}: no public GitHub, Gitea or GitLab repository found", repo.url())
}
#[derive(Deserialize)]
struct GhRelease {
tag_name: String,
#[serde(default)]
draft: bool,
#[serde(default)]
prerelease: bool,
#[serde(default)]
assets: Vec<GhAsset>,
}
#[derive(Deserialize)]
struct GhAsset {
name: String,
browser_download_url: String,
}
#[derive(Deserialize)]
struct GlRelease {
tag_name: String,
#[serde(default)]
upcoming_release: bool,
#[serde(default)]
assets: GlAssets,
}
#[derive(Deserialize, Default)]
struct GlAssets {
#[serde(default)]
links: Vec<GlLink>,
}
#[derive(Deserialize)]
struct GlLink {
name: String,
url: String,
#[serde(default)]
direct_asset_url: Option<String>,
}
/// The newest published (not draft, not pre-release) release that carries
/// an `app.toml`.
pub fn latest_release(agent: &ureq::Agent, repo: &Repo) -> Result<Option<Release>> {
let releases: Vec<Release> = match repo.forge.context("unknown forge")? {
Forge::GitHub => {
let url = format!("https://api.github.com/repos/{}/releases?per_page=20", repo.path);
let Some(text) = get_text(agent, &url, MAX_JSON)? else { return Ok(None) };
let list: Vec<GhRelease> = serde_json::from_str(&text).context("GitHub releases")?;
list.into_iter().filter(|r| !r.draft && !r.prerelease).map(gh_release).collect()
}
Forge::Gitea => {
let url = format!("{}/api/v1/repos/{}/releases?limit=20", repo.base, repo.path);
let Some(text) = get_text(agent, &url, MAX_JSON)? else { return Ok(None) };
let list: Vec<GhRelease> = serde_json::from_str(&text).context("Gitea releases")?;
list.into_iter().filter(|r| !r.draft && !r.prerelease).map(gh_release).collect()
}
Forge::GitLab => {
let url = format!("{}/api/v4/projects/{}/releases?per_page=20", repo.base, repo.encoded_path());
let Some(text) = get_text(agent, &url, MAX_JSON)? else { return Ok(None) };
let list: Vec<GlRelease> = serde_json::from_str(&text).context("GitLab releases")?;
list.into_iter()
.filter(|r| !r.upcoming_release)
.map(|r| Release {
tag: r.tag_name,
assets: r.assets.links.into_iter().map(|l| Asset { url: l.direct_asset_url.unwrap_or(l.url), name: l.name }).collect(),
})
.collect()
}
};
Ok(releases.into_iter().find(|r| r.asset("app.toml").is_some()))
}
fn gh_release(r: GhRelease) -> Release {
Release { tag: r.tag_name, assets: r.assets.into_iter().map(|a| Asset { name: a.name, url: a.browser_download_url }).collect() }
}
/// A file from the default branch (catalogs: `smartfox-store.toml`).
pub fn raw_file(agent: &ureq::Agent, repo: &Repo, file: &str) -> Result<Option<String>> {
let url = match repo.forge.context("unknown forge")? {
Forge::GitHub => format!("https://raw.githubusercontent.com/{}/HEAD/{file}", repo.path),
Forge::Gitea => format!("{}/api/v1/repos/{}/raw/{file}", repo.base, repo.path),
Forge::GitLab => format!("{}/api/v4/projects/{}/repository/files/{}/raw?ref=HEAD", repo.base, repo.encoded_path(), file.replace('/', "%2F")),
};
get_text(agent, &url, MAX_TEXT)
}
/// A small text asset (the release's app.toml).
pub fn asset_text(agent: &ureq::Agent, asset: &Asset) -> Result<String> {
get_text(agent, &asset.url, MAX_TEXT)?.with_context(|| format!("{} is missing", asset.name))
}
/// Downloads an asset into `path`, at most `limit` bytes.
pub fn download(agent: &ureq::Agent, url: &str, path: &std::path::Path, limit: u64) -> Result<u64> {
let resp = agent.get(url).call().with_context(|| format!("GET {url}"))?;
let mut out = std::fs::File::create(path).with_context(|| format!("creating {}", path.display()))?;
let mut body = resp.into_body().into_reader().take(limit + 1);
let n = std::io::copy(&mut body, &mut out).with_context(|| format!("downloading {url}"))?;
if n > limit {
bail!("{url} is larger than {limit} bytes");
}
out.sync_all()?;
Ok(n)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_repo_addresses() {
let r = Repo::parse("https://github.com/Fox/hello-app.git").unwrap();
assert_eq!((r.forge, r.url()), (Some(Forge::GitHub), "https://github.com/Fox/hello-app".to_string()));
assert_eq!(Repo::parse("github.com/fox/x/").unwrap().url(), "https://github.com/fox/x");
assert_eq!(Repo::parse("github:fox/x").unwrap().url(), "https://github.com/fox/x");
let r = Repo::parse("gitlab.com/group/sub/proj").unwrap();
assert_eq!((r.forge, r.path.as_str()), (Some(Forge::GitLab), "group/sub/proj"));
let r = Repo::parse("gitea:git.example.org/o/r").unwrap();
assert_eq!((r.forge, r.base.as_str()), (Some(Forge::Gitea), "https://git.example.org"));
let r = Repo::parse("https://gitea.bluefox.support/bluefox/store").unwrap();
assert_eq!(r.forge, None);
assert!(Repo::parse("http://github.com/a/b").is_err());
assert!(Repo::parse("github.com/a").is_err());
assert!(Repo::parse("github.com/a/b/c").is_err());
assert!(Repo::parse("github.com/../b").is_err());
assert!(Repo::parse("exa mple.org/a/b").is_err());
}
#[test]
fn parses_releases() {
let gh: Vec<GhRelease> = serde_json::from_str(
r#"[{"tag_name":"v2","draft":true,"assets":[]},{"tag_name":"v1","prerelease":false,"assets":[{"name":"app.toml","browser_download_url":"https://x/app.toml","size":3}]}]"#,
)
.unwrap();
let rel: Vec<Release> = gh.into_iter().filter(|r| !r.draft).map(gh_release).collect();
assert_eq!(rel[0].tag, "v1");
assert_eq!(rel[0].asset("app.toml").unwrap().url, "https://x/app.toml");
let gl: Vec<GlRelease> = serde_json::from_str(r#"[{"tag_name":"1.0","assets":{"links":[{"name":"app.toml","url":"https://a","direct_asset_url":"https://b"}]}}]"#).unwrap();
assert_eq!(gl[0].assets.links[0].direct_asset_url.as_deref(), Some("https://b"));
}
}
/// Talks to the real forges: `cargo test -p sf-update -- --ignored live`.
#[cfg(test)]
mod live {
use super::*;
#[test]
#[ignore]
fn live_forges() {
let agent = agent();
for (url, file) in [
("github.com/BurntSushi/ripgrep", "README.md"),
("codeberg.org/forgejo/forgejo", "README.md"),
("gitlab.com/gitlab-org/cli", "README.md"),
("gitea:gitea.com/gitea/tea", "README.md"),
] {
let repo = detect(&agent, &Repo::parse(url).unwrap()).unwrap();
let release = latest_release(&agent, &repo).unwrap();
let readme = raw_file(&agent, &repo, file).unwrap();
println!("{url}: {:?}, release with app.toml: {}, readme: {} bytes", repo.forge, release.is_some(), readme.map(|r| r.len()).unwrap_or(0));
assert!(raw_file(&agent, &repo, "no-such-file.toml").unwrap().is_none());
}
}
}

View File

@@ -1,27 +1,34 @@
//! sf-update: installs signed SmartFox packages (the shell and the apps) from //! sf-update: installs signed Fennec OS packages (the shell and the apps) from
//! the Gitea package registry onto the writable data partition. The root //! the Gitea package registry, and store apps from their own GitHub, Gitea or
//! file system stays read-only and keeps the factory copies as a fallback. //! GitLab repos, onto the writable data partition. The root file system stays
//! read-only and keeps the factory copies as a fallback.
//! //!
//! Protocol and layout: docs/updates.md. //! Protocol and layout: docs/updates.md, docs/store.md.
//! //!
//! sf-update check ask the server what's new (status.json) //! sf-update check ask the servers what's new (status.json, catalog.json)
//! sf-update auto check, then download and stage what's new (timer) //! sf-update auto check, then download and stage what's new (timer)
//! sf-update apply switch staged packages live (at boot) //! sf-update apply switch staged packages live (at boot)
//! sf-update install check, download, apply now and restart the UI //! sf-update install check, download, apply now and restart the UI
//! sf-update store install / remove store apps as store.toml says, now
//! sf-update requests handle the launcher's request files (path unit) //! sf-update requests handle the launcher's request files (path unit)
//! sf-update status print status.json //! sf-update status print status.json
mod appstore;
mod arch;
mod config; mod config;
mod forge;
mod migrate;
mod registry; mod registry;
mod store; mod store;
use std::collections::BTreeMap;
use std::path::Path; use std::path::Path;
use std::time::Duration; use std::time::Duration;
use anyhow::{Context, Result, bail}; use anyhow::{Context, Result, bail};
use crate::config::Config; use crate::config::Config;
use crate::store::Store; use crate::store::{Expect, Store};
fn main() { fn main() {
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init(); env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
@@ -34,14 +41,14 @@ fn main() {
fn run(cmd: &str) -> Result<()> { fn run(cmd: &str) -> Result<()> {
let cfg = Config::load()?; let cfg = Config::load()?;
let store = Store::open(&cfg)?; let store = Store::open(&cfg.root, &cfg.factory)?;
match cmd { match cmd {
"status" => { "status" => {
println!("{}", serde_json::to_string_pretty(&store.read_status())?); println!("{}", serde_json::to_string_pretty(&store.read_status())?);
return Ok(()); return Ok(());
} }
"check" | "auto" | "apply" | "install" | "requests" => {} "check" | "auto" | "apply" | "install" | "store" | "requests" => {}
_ => bail!("usage: sf-update check|auto|apply|install|requests|status"), _ => bail!("usage: sf-update check|auto|apply|install|store|requests|status"),
} }
// One run at a time (timer, boot and launcher requests can overlap). // One run at a time (timer, boot and launcher requests can overlap).
let _lock = store.lock(Duration::from_secs(600))?; let _lock = store.lock(Duration::from_secs(600))?;
@@ -50,28 +57,81 @@ fn run(cmd: &str) -> Result<()> {
"auto" => auto(&cfg, &store), "auto" => auto(&cfg, &store),
"apply" => apply(&store).map(drop), "apply" => apply(&store).map(drop),
"install" => install(&cfg, &store), "install" => install(&cfg, &store),
"store" => store_sync(&cfg, &store),
"requests" => requests(&cfg, &store), "requests" => requests(&cfg, &store),
_ => unreachable!(), _ => unreachable!(),
} }
} }
/// Asks the registry for the newest version of every package and records /// The store's plan: newest versions of the wanted store apps that may be
/// which ones are newer than what's installed. /// installed, with where to get them. None if store.toml can't be read
/// (then nothing is installed or removed).
fn store_plan(cfg: &Config, store: &Store) -> Option<(sf_ipc::store::Wanted, BTreeMap<String, (String, appstore::StoreDownload)>)> {
if let Err(e) = migrate::adopt_retired(&cfg.store_wanted, store) {
log::warn!("store: adding the replacements of the old factory apps: {e:#}");
}
let wanted = match appstore::read_wanted(&cfg.store_wanted) {
Ok(w) => w,
Err(e) => {
log::error!("store: {e:#}");
return None;
}
};
if wanted.sources.is_empty() && wanted.apps.is_empty() {
appstore::write_catalog(&cfg.catalog, &Default::default());
return Some((wanted, BTreeMap::new()));
}
let mut catalog = appstore::refresh_catalog(&wanted);
let plan = appstore::plan(store, &wanted, &mut catalog);
appstore::write_catalog(&cfg.catalog, &catalog);
Some((wanted, plan))
}
/// Asks the registry and the store sources for the newest version of every
/// package and records which ones are newer than what's installed.
fn check(cfg: &Config, store: &Store) -> Result<Vec<store::Pending>> { fn check(cfg: &Config, store: &Store) -> Result<Vec<store::Pending>> {
store.set_state("checking", ""); store.set_state("checking", "");
let latest = match registry::latest_versions(cfg) { let official = registry::latest_versions(cfg);
Ok(l) => l, let mut latest = official.as_ref().cloned().unwrap_or_default();
Err(e) => { let mut downloads = BTreeMap::new();
if let Some((_, plan)) = store_plan(cfg, store) {
for (name, (version, d)) in plan {
latest.insert(name.clone(), version);
downloads.insert(name, d);
}
}
let mut pending = store.refresh(&latest);
for p in &mut pending {
p.store = downloads.remove(&p.name);
}
// A store app without download info (shouldn't happen) is skipped.
pending.retain(|p| registry::store_id(&p.name).is_none() || p.store.is_some());
if let Err(e) = official {
store.set_state("error", &format!("{e:#}")); store.set_state("error", &format!("{e:#}"));
return Err(e); return Err(e);
} }
};
let pending = store.refresh(&latest);
store.set_state("idle", ""); store.set_state("idle", "");
log::info!("{} update(s) available", pending.len()); log::info!("{} update(s) available", pending.len());
Ok(pending) Ok(pending)
} }
/// Downloads, checks and stages one package.
fn fetch(cfg: &Config, store: &Store, p: &store::Pending) -> Result<()> {
let dir = store.download_dir()?;
match &p.store {
None => {
let (pkg, sig) = registry::download(cfg, &p.name, &p.version, &dir)?;
store.verify_and_unpack(&cfg.public_key, &p.name, &p.version, &pkg, &sig, &Expect::Official)?;
}
Some(d) => {
let pkg = appstore::download(d, &p.version, &dir)?;
let expect = Expect::Store { id: &d.id, approved: &d.approved, source: &d.source };
store.unpack_store(&p.name, &p.version, &pkg, &expect)?;
}
}
store.stage(&p.name, &p.version)
}
/// Downloads and stages each pending package. Failures of one package don't /// Downloads and stages each pending package. Failures of one package don't
/// stop the others; the first error is reported. /// stop the others; the first error is reported.
fn download(cfg: &Config, store: &Store, pending: &[store::Pending]) -> Result<usize> { fn download(cfg: &Config, store: &Store, pending: &[store::Pending]) -> Result<usize> {
@@ -83,12 +143,7 @@ fn download(cfg: &Config, store: &Store, pending: &[store::Pending]) -> Result<u
continue; continue;
} }
store.set_state("downloading", &format!("{} {}", p.name, p.version)); store.set_state("downloading", &format!("{} {}", p.name, p.version));
let result = (|| -> Result<()> { let result = fetch(cfg, store, p);
let dir = store.download_dir()?;
let (pkg, sig) = registry::download(cfg, &p.name, &p.version, &dir)?;
store.verify_and_unpack(cfg, &p.name, &p.version, &pkg, &sig)?;
store.stage(&p.name, &p.version)
})();
let _ = std::fs::remove_dir_all(store.download_dir_path()); let _ = std::fs::remove_dir_all(store.download_dir_path());
match result { match result {
Ok(()) => { Ok(()) => {
@@ -123,7 +178,7 @@ fn auto(cfg: &Config, store: &Store) -> Result<()> {
/// Switches staged packages live. Returns which kinds changed. /// Switches staged packages live. Returns which kinds changed.
fn apply(store: &Store) -> Result<store::Applied> { fn apply(store: &Store) -> Result<store::Applied> {
let applied = store.apply_staged()?; let applied = store.apply_staged(|_| true)?;
store.gc(); store.gc();
store.write_status(|_| {}); store.write_status(|_| {});
Ok(applied) Ok(applied)
@@ -139,13 +194,45 @@ fn install(cfg: &Config, store: &Store) -> Result<()> {
result.map(drop) result.map(drop)
} }
/// The store screen changed store.toml: install new apps and approved
/// updates, remove the ones the user uninstalled, all right away. The
/// launcher picks the new app list up by itself; nothing restarts.
fn store_sync(cfg: &Config, store: &Store) -> Result<()> {
store.set_state("checking", "");
let Some((wanted, plan)) = store_plan(cfg, store) else {
store.set_state("error", "store.toml can't be read");
bail!("store.toml can't be read");
};
appstore::remove_unwanted(store, &wanted);
let pending: Vec<store::Pending> = plan
.into_iter()
.map(|(name, (version, d))| store::Pending { name, version, store: Some(d) })
.collect();
let result = download(cfg, store, &pending);
store.apply_staged(|name| registry::store_id(name).is_some())?;
store.link_apps()?;
store.gc();
// The catalog's "installed" marks are now stale; refresh them from disk.
if let Some(mut catalog) = sf_ipc::store::Catalog::load(&cfg.catalog) {
for app in &mut catalog.apps {
app.installed = store.installed(&format!("{}{}", sf_ipc::store::PACKAGE_PREFIX, app.id));
}
appstore::write_catalog(&cfg.catalog, &catalog);
}
store.write_status(|_| {});
if result.is_ok() {
store.set_state("idle", "");
}
result.map(drop)
}
/// Restarts what an update touched: the remote driver for a new shell, the /// Restarts what an update touched: the remote driver for a new shell, the
/// TV session (cage + launcher) for a new shell or new apps. /// TV session (cage + launcher) for a new shell or new apps.
fn restart(applied: &store::Applied) { fn restart(applied: &store::Applied) {
if applied.shell { if applied.shell {
systemctl(&["restart", "sf-remote.service"]); systemctl(&["restart", "sf-remote.service"]);
} }
if applied.shell || applied.apps { if applied.shell || applied.apps || applied.store {
restart_ui(); restart_ui();
} }
} }
@@ -164,9 +251,10 @@ fn systemctl(args: &[&str]) {
/// The launcher (user tv) can't run anything as root; it drops empty files /// The launcher (user tv) can't run anything as root; it drops empty files
/// named after a request into the requests folder, sf-update-requests.path /// named after a request into the requests folder, sf-update-requests.path
/// starts this. Only the file names are used, never their contents. /// starts this. Only the file names are used, never their contents (the
/// store request reads store.toml, carefully).
fn requests(cfg: &Config, store: &Store) -> Result<()> { fn requests(cfg: &Config, store: &Store) -> Result<()> {
const ORDER: [&str; 4] = ["rollback", "confirm", "install", "check"]; const ORDER: [&str; 5] = ["rollback", "confirm", "store", "install", "check"];
let dir = &cfg.requests; let dir = &cfg.requests;
let mut result = Ok(()); let mut result = Ok(());
for _ in 0..10 { for _ in 0..10 {
@@ -178,6 +266,7 @@ fn requests(cfg: &Config, store: &Store) -> Result<()> {
let r = match name { let r = match name {
"rollback" => rollback(store), "rollback" => rollback(store),
"confirm" => store.confirm_shell(), "confirm" => store.confirm_shell(),
"store" => store_sync(cfg, store),
"install" => install(cfg, store), "install" => install(cfg, store),
_ => check(cfg, store).map(drop), _ => check(cfg, store).map(drop),
}; };
@@ -213,4 +302,3 @@ fn rollback(store: &Store) -> Result<()> {
} }
Ok(()) Ok(())
} }

View File

@@ -0,0 +1,99 @@
//! Official apps that became store apps (`sf_ipc::manifest::RETIRED`): on a
//! TV that has the old app, its store replacement is added to store.toml
//! once, with the permissions the old app already had, and the Fennec
//! catalog as a source. The launcher keeps showing the old app until the
//! replacement is installed, so nothing disappears in between.
//!
//! Done ids are remembered in `<root>/store/retired-adopted`: an app the user
//! uninstalls later is not added again.
use std::collections::BTreeSet;
use std::fs;
use std::io::Write;
use std::path::Path;
use anyhow::{Context, Result};
use sf_ipc::manifest::{FENNEC_CATALOG, RETIRED};
use sf_ipc::store::{Wanted, WantedApp};
use crate::appstore;
use crate::store::Store;
const DONE_FILE: &str = "retired-adopted";
pub fn adopt_retired(wanted_path: &Path, store: &Store) -> Result<()> {
let done_path = store.store_dir().join(DONE_FILE);
let mut done: BTreeSet<String> = fs::read_to_string(&done_path).unwrap_or_default().lines().map(str::to_string).collect();
let todo: Vec<_> = RETIRED.iter().filter(|r| !done.contains(r.id)).collect();
if todo.is_empty() {
return Ok(());
}
let mut wanted = appstore::read_wanted(wanted_path)?;
let changed = plan(&mut wanted, &todo, |id| store.installed(&format!("sf-app-{id}")).is_some());
if changed {
write_wanted(wanted_path, &wanted)?;
log::info!("store.toml: added the store apps that replace the old factory apps");
}
done.extend(todo.iter().map(|r| r.id.to_string()));
fs::create_dir_all(store.store_dir())?;
fs::write(&done_path, done.into_iter().map(|id| id + "\n").collect::<String>())?;
Ok(())
}
/// Adds the replacements of the retired apps the TV has. True if `wanted`
/// changed.
fn plan(wanted: &mut Wanted, todo: &[&sf_ipc::manifest::Retired], has_old: impl Fn(&str) -> bool) -> bool {
let mut changed = false;
for r in todo.iter().filter(|r| has_old(r.id)) {
if !wanted.apps.contains_key(r.replacement) {
wanted.apps.insert(r.replacement.to_string(), WantedApp { source: r.source.to_string(), permissions: r.permissions.to_vec() });
changed = true;
}
if !wanted.sources.iter().any(|s| appstore::canonical(s) == FENNEC_CATALOG) {
wanted.sources.push(FENNEC_CATALOG.to_string());
changed = true;
}
}
changed
}
/// Root writes into the TV user's folder: a new file (never through an
/// existing name, which the user could have made a symlink), renamed over
/// store.toml, owned like its folder.
fn write_wanted(path: &Path, wanted: &Wanted) -> Result<()> {
let dir = path.parent().context("store.toml has no folder")?;
let tmp = dir.join(format!(".store.toml.sf-update-{}", std::process::id()));
let _ = fs::remove_file(&tmp);
let mut f = fs::OpenOptions::new().write(true).create_new(true).open(&tmp).with_context(|| format!("creating {}", tmp.display()))?;
f.write_all(toml::to_string_pretty(wanted)?.as_bytes())?;
f.sync_all()?;
drop(f);
#[cfg(unix)]
{
use std::os::unix::fs::{MetadataExt, PermissionsExt};
let meta = fs::metadata(dir)?;
std::os::unix::fs::chown(&tmp, Some(meta.uid()), Some(meta.gid()))?;
fs::set_permissions(&tmp, fs::Permissions::from_mode(0o644))?;
}
fs::rename(&tmp, path).with_context(|| format!("writing {}", path.display()))?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn adds_replacements_of_old_apps_only() {
let todo: Vec<_> = RETIRED.iter().collect();
let mut w = Wanted::default();
assert!(plan(&mut w, &todo, |id| id == "youtube"));
assert_eq!(w.sources, [FENNEC_CATALOG]);
assert_eq!(w.apps.keys().collect::<Vec<_>>(), ["support.bluefox.youtube"]);
assert!(w.apps["support.bluefox.youtube"].permissions.contains(&sf_ipc::Permission::Dial));
// A new TV: store.toml has it all already.
assert!(!plan(&mut w, &todo, |id| id == "youtube"));
// No old apps: nothing to do.
assert!(!plan(&mut Wanted::default(), &todo, |_| false));
}
}

View File

@@ -2,6 +2,11 @@
//! //!
//! list: GET {server}/api/v1/packages/{owner}?type=generic&q=sf- //! list: GET {server}/api/v1/packages/{owner}?type=generic&q=sf-
//! download: GET {server}/api/packages/{owner}/generic/{name}/{version}/{name}-{version}.tar.zst (+ .sig) //! download: GET {server}/api/packages/{owner}/generic/{name}/{version}/{name}-{version}.tar.zst (+ .sig)
//! files: GET {server}/api/v1/packages/{owner}/generic/{name}/{version}/files
//!
//! The shell is native code: on any architecture but x86-64 its file has a
//! suffix (`sf-shell-1.2.0-aarch64.tar.zst`, crate::arch). App packages are
//! manifests only and are the same everywhere.
use std::collections::BTreeMap; use std::collections::BTreeMap;
use std::io::Read; use std::io::Read;
@@ -14,18 +19,34 @@ use serde::Deserialize;
use sf_ipc::manifest::version_cmp; use sf_ipc::manifest::version_cmp;
/// Largest package we'll download. /// Largest package we'll download.
const MAX_PACKAGE: u64 = 1024 * 1024 * 1024; pub const MAX_PACKAGE: u64 = 1024 * 1024 * 1024;
use crate::config::Config; use crate::config::Config;
/// Package names this updater handles. /// Official package names (from our registry). Apps that became store apps
pub fn is_ours(name: &str) -> bool { /// (`sf_ipc::manifest::RETIRED`) are no longer official packages: old
name == "sf-shell" || name.strip_prefix("sf-app-").is_some_and(|id| !id.is_empty() && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')) /// versions in the registry are not installed.
pub fn is_official(name: &str) -> bool {
name == "sf-shell"
|| name.strip_prefix("sf-app-").is_some_and(|id| {
!id.is_empty() && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_') && !sf_ipc::manifest::is_retired(id)
})
} }
/// Release versions only: digits and dots (prereleases like 1.2.0-rc1 are skipped). /// Store app id of a package name (`store-<id>`).
pub fn store_id(name: &str) -> Option<&str> {
name.strip_prefix(sf_ipc::store::PACKAGE_PREFIX).filter(|id| sf_ipc::manifest::is_store_id(id))
}
/// Package names this updater handles: official ones and store apps.
pub fn is_ours(name: &str) -> bool {
is_official(name) || store_id(name).is_some()
}
/// Release versions only: digits and dots, up to four parts (prereleases
/// like 1.2.0-rc1 are skipped).
pub fn is_release(version: &str) -> bool { pub fn is_release(version: &str) -> bool {
!version.is_empty() && version.split('.').all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit())) && version.split('.').count() <= 3 !version.is_empty() && version.split('.').all(|p| !p.is_empty() && p.len() <= 9 && p.bytes().all(|b| b.is_ascii_digit())) && version.split('.').count() <= 4
} }
fn agent() -> ureq::Agent { fn agent() -> ureq::Agent {
@@ -57,10 +78,12 @@ struct PackageVersion {
version: String, version: String,
} }
/// Newest release version of every package on the server. /// Newest release version of every package on the server. A shell version
/// without a file for this architecture doesn't count.
pub fn latest_versions(cfg: &Config) -> Result<BTreeMap<String, String>> { pub fn latest_versions(cfg: &Config) -> Result<BTreeMap<String, String>> {
let agent = agent(); let agent = agent();
let mut latest: BTreeMap<String, String> = BTreeMap::new(); let mut latest: BTreeMap<String, String> = BTreeMap::new();
let mut shells: Vec<String> = Vec::new();
for page in 1..=100 { for page in 1..=100 {
let url = format!("{}/api/v1/packages/{}?type=generic&q=sf-&limit=50&page={page}", cfg.server, cfg.owner); let url = format!("{}/api/v1/packages/{}?type=generic&q=sf-&limit=50&page={page}", cfg.server, cfg.owner);
let text = get(cfg, &agent, &url)?.body_mut().read_to_string()?; let text = get(cfg, &agent, &url)?.body_mut().read_to_string()?;
@@ -69,7 +92,11 @@ pub fn latest_versions(cfg: &Config) -> Result<BTreeMap<String, String>> {
break; break;
} }
for p in list { for p in list {
if !is_ours(&p.name) || !is_release(&p.version) { if !is_official(&p.name) || !is_release(&p.version) {
continue;
}
if p.name == SHELL && !crate::arch::IS_DEFAULT {
shells.push(p.version);
continue; continue;
} }
match latest.get(&p.name) { match latest.get(&p.name) {
@@ -80,17 +107,51 @@ pub fn latest_versions(cfg: &Config) -> Result<BTreeMap<String, String>> {
} }
} }
} }
if !shells.is_empty() {
shells.sort_by(|a, b| version_cmp(b, a));
shells.dedup();
// Newest first; a few tries are enough (CI builds every architecture together).
for v in shells.iter().take(5) {
match has_file(cfg, &agent, SHELL, v) {
Ok(true) => {
latest.insert(SHELL.into(), v.clone());
break;
}
Ok(false) => log::info!("{SHELL} {v}: no {} build", crate::arch::NAME),
Err(e) => {
log::warn!("{SHELL} {v}: {e:#}");
break;
}
}
}
}
Ok(latest) Ok(latest)
} }
const SHELL: &str = "sf-shell";
#[derive(Deserialize)]
struct PackageFile {
name: String,
}
/// Whether a package version has its file for this architecture.
fn has_file(cfg: &Config, agent: &ureq::Agent, name: &str, version: &str) -> Result<bool> {
let url = format!("{}/api/v1/packages/{}/generic/{name}/{version}/files", cfg.server, cfg.owner);
let text = get(cfg, agent, &url)?.body_mut().read_to_string()?;
let files: Vec<PackageFile> = serde_json::from_str(&text).context("package files")?;
let want = file_name(name, version);
Ok(files.iter().any(|f| f.name == want))
}
/// File name of a package in the registry. /// File name of a package in the registry.
pub fn file_name(name: &str, version: &str) -> String { pub fn file_name(name: &str, version: &str) -> String {
format!("{name}-{version}.tar.zst") if name == SHELL { crate::arch::file_name(name, version) } else { format!("{name}-{version}.tar.zst") }
} }
/// Downloads a package and its signature into `dir`. /// Downloads a package and its signature into `dir`.
pub fn download(cfg: &Config, name: &str, version: &str, dir: &Path) -> Result<(PathBuf, Vec<u8>)> { pub fn download(cfg: &Config, name: &str, version: &str, dir: &Path) -> Result<(PathBuf, Vec<u8>)> {
if !is_ours(name) || !is_release(version) { if !is_official(name) || !is_release(version) {
bail!("refusing package {name} {version}"); bail!("refusing package {name} {version}");
} }
let agent = agent(); let agent = agent();
@@ -120,11 +181,18 @@ mod tests {
#[test] #[test]
fn names_and_versions() { fn names_and_versions() {
assert!(is_ours("sf-shell")); assert!(is_ours("sf-shell"));
assert!(is_ours("sf-app-youtube")); assert!(is_ours("sf-app-airplay"));
assert!(!is_ours("sf-app-youtube"));
assert!(!is_ours("sf-app-")); assert!(!is_ours("sf-app-"));
assert!(!is_ours("sf-app-../x")); assert!(!is_ours("sf-app-../x"));
assert!(!is_ours("other")); assert!(!is_ours("other"));
assert!(is_ours("store-io.github.fox.hello"));
assert!(!is_official("store-io.github.fox.hello"));
assert!(!is_ours("store-youtube"));
assert!(!is_ours("store-io.x/../y"));
assert!(is_release("1.2.3")); assert!(is_release("1.2.3"));
assert!(is_release("1.0.0.87"));
assert!(!is_release("1.0.0.0.1"));
assert!(!is_release("1.2.3-rc1")); assert!(!is_release("1.2.3-rc1"));
assert!(!is_release("1..2")); assert!(!is_release("1..2"));
assert!(!is_release("../1")); assert!(!is_release("../1"));

View File

@@ -7,6 +7,9 @@
//! <name>/bad versions that failed, never installed again //! <name>/bad versions that failed, never installed again
//! sf-shell/trial a new shell that hasn't confirmed a good start yet //! sf-shell/trial a new shell that hasn't confirmed a good start yet
//! apps/<id> -> ../sf-app-<id>/current (the launcher reads this folder) //! apps/<id> -> ../sf-app-<id>/current (the launcher reads this folder)
//! store-<id>/ a store app (docs/store.md), same layout plus:
//! source the repo it was installed from
//! store/apps/<id> -> ../../store-<id>/current
//! status.json for the launcher's Updates row //! status.json for the launcher's Updates row
use std::collections::{BTreeMap, BTreeSet}; use std::collections::{BTreeMap, BTreeSet};
@@ -17,9 +20,9 @@ use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
use anyhow::{Context, Result, bail}; use anyhow::{Context, Result, bail};
use ed25519_dalek::{Signature, VerifyingKey}; use ed25519_dalek::{Signature, VerifyingKey};
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use sf_ipc::manifest::version_cmp; use sf_ipc::Permission;
use sf_ipc::manifest::{AppManifest, version_cmp};
use crate::config::Config;
use crate::registry; use crate::registry;
pub const SHELL: &str = "sf-shell"; pub const SHELL: &str = "sf-shell";
@@ -50,18 +53,37 @@ pub struct PackageStatus {
pub struct Pending { pub struct Pending {
pub name: String, pub name: String,
pub version: String, pub version: String,
/// Store apps: where to get it and what it must be.
pub store: Option<crate::appstore::StoreDownload>,
} }
#[derive(Debug, Default)] #[derive(Debug, Default)]
pub struct Applied { pub struct Applied {
pub shell: bool, pub shell: bool,
pub apps: bool, pub apps: bool,
pub store: bool,
} }
/// What a package must be to be installed.
pub enum Expect<'a> {
/// Ours: signed with the Fennec OS key.
Official,
/// A store app: its manifest must follow the store rules and stay within
/// the approved permissions.
Store { id: &'a str, approved: &'a [Permission], source: &'a str },
}
/// Largest unpacked store package and file count.
const MAX_STORE_UNPACKED: u64 = 8 * 1024 * 1024 * 1024;
const MAX_STORE_FILES: usize = 200_000;
#[derive(Deserialize)] #[derive(Deserialize)]
struct PkgInfo { struct PkgInfo {
name: String, name: String,
version: String, version: String,
/// Native packages (the shell): the architecture they were built for.
#[serde(default)]
arch: Option<String>,
} }
#[cfg(unix)] #[cfg(unix)]
@@ -83,13 +105,18 @@ pub struct Store {
pub struct Lock(#[allow(dead_code)] fs::File); pub struct Lock(#[allow(dead_code)] fs::File);
impl Store { impl Store {
pub fn open(cfg: &Config) -> Result<Self> { pub fn open(root: &Path, factory: &Path) -> Result<Self> {
fs::create_dir_all(&cfg.root).with_context(|| format!("creating {}", cfg.root.display()))?; fs::create_dir_all(root).with_context(|| format!("creating {}", root.display()))?;
let factory = match fs::read_to_string(&cfg.factory) { let factory = match fs::read_to_string(factory) {
Ok(t) => toml::from_str(&t).with_context(|| format!("parsing {}", cfg.factory.display()))?, Ok(t) => toml::from_str(&t).with_context(|| format!("parsing {}", factory.display()))?,
Err(_) => BTreeMap::new(), Err(_) => BTreeMap::new(),
}; };
Ok(Store { root: cfg.root.clone(), factory }) Ok(Store { root: root.to_path_buf(), factory })
}
/// Store app folders: `store/` under the root.
pub fn store_dir(&self) -> PathBuf {
self.root.join("store")
} }
pub fn lock(&self, wait: Duration) -> Result<Lock> { pub fn lock(&self, wait: Duration) -> Result<Lock> {
@@ -134,7 +161,7 @@ impl Store {
} }
/// The version running now: installed package or factory copy, the newer one. /// The version running now: installed package or factory copy, the newer one.
fn installed(&self, name: &str) -> Option<String> { pub fn installed(&self, name: &str) -> Option<String> {
let current = self.link(name, "current"); let current = self.link(name, "current");
let factory = self.factory.get(name).cloned(); let factory = self.factory.get(name).cloned();
match (current, factory) { match (current, factory) {
@@ -143,7 +170,7 @@ impl Store {
} }
} }
fn bad(&self, name: &str) -> BTreeSet<String> { pub fn bad(&self, name: &str) -> BTreeSet<String> {
fs::read_to_string(self.dir(name).join("bad")).unwrap_or_default().lines().map(str::to_string).collect() fs::read_to_string(self.dir(name).join("bad")).unwrap_or_default().lines().map(str::to_string).collect()
} }
@@ -164,7 +191,7 @@ impl Store {
let Some(v) = latest.get(&name) else { continue }; let Some(v) = latest.get(&name) else { continue };
let newer = self.installed(&name).is_none_or(|i| version_cmp(v, &i).is_gt()); let newer = self.installed(&name).is_none_or(|i| version_cmp(v, &i).is_gt());
if newer && !self.bad(&name).contains(v) { if newer && !self.bad(&name).contains(v) {
pending.push(Pending { name: name.clone(), version: v.clone() }); pending.push(Pending { name: name.clone(), version: v.clone(), store: None });
} }
} }
let now = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0); let now = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
@@ -190,13 +217,24 @@ impl Store {
Ok(d) Ok(d)
} }
/// Checks the signature and unpacks into `<name>/<version>/`. /// Checks the signature with `key` and unpacks into `<name>/<version>/`.
pub fn verify_and_unpack(&self, cfg: &Config, name: &str, version: &str, pkg: &Path, sig: &[u8]) -> Result<()> { pub fn verify_and_unpack(&self, key: &[u8; 32], name: &str, version: &str, pkg: &Path, sig: &[u8], expect: &Expect) -> Result<()> {
anyhow::ensure!(matches!(expect, Expect::Official), "signed install is for official packages");
let data = fs::read(pkg)?; let data = fs::read(pkg)?;
let key = VerifyingKey::from_bytes(&cfg.public_key).context("public key")?; let key = VerifyingKey::from_bytes(key).context("public key")?;
let sig = Signature::from_slice(sig).context("signature: not 64 bytes")?; let sig = Signature::from_slice(sig).context("signature: not 64 bytes")?;
key.verify_strict(&data, &sig).context("bad signature")?; key.verify_strict(&data, &sig).context("bad signature")?;
self.unpack(name, version, &data, expect)
}
/// Store packages come from the selected source and need no signature.
pub fn unpack_store(&self, name: &str, version: &str, pkg: &Path, expect: &Expect) -> Result<()> {
anyhow::ensure!(matches!(expect, Expect::Store { .. }), "unsigned install is for store apps");
let data = fs::read(pkg)?;
self.unpack(name, version, &data, expect)
}
fn unpack(&self, name: &str, version: &str, data: &[u8], expect: &Expect) -> Result<()> {
let dir = self.dir(name); let dir = self.dir(name);
fs::create_dir_all(&dir)?; fs::create_dir_all(&dir)?;
let dest = dir.join(version); let dest = dir.join(version);
@@ -209,18 +247,63 @@ impl Store {
let tmp = dir.join(format!(".tmp-{version}")); let tmp = dir.join(format!(".tmp-{version}"));
let _ = fs::remove_dir_all(&tmp); let _ = fs::remove_dir_all(&tmp);
fs::create_dir_all(&tmp)?; fs::create_dir_all(&tmp)?;
let result = (|| -> Result<()> {
let decoder = ruzstd::decoding::StreamingDecoder::new(&data[..]).map_err(|e| anyhow::anyhow!("zstd: {e}"))?; let decoder = ruzstd::decoding::StreamingDecoder::new(&data[..]).map_err(|e| anyhow::anyhow!("zstd: {e}"))?;
let mut archive = tar::Archive::new(decoder); let mut archive = tar::Archive::new(decoder);
archive.set_preserve_permissions(true);
archive.set_preserve_ownerships(false); archive.set_preserve_ownerships(false);
match expect {
Expect::Official => {
archive.set_preserve_permissions(true);
archive.unpack(&tmp).context("unpacking")?; archive.unpack(&tmp).context("unpacking")?;
}
Expect::Store { .. } => unpack_untrusted(&mut archive, &tmp)?,
}
let info: PkgInfo = toml::from_str(&fs::read_to_string(tmp.join("pkg.toml")).context("pkg.toml missing")?).context("pkg.toml")?; let info: PkgInfo = toml::from_str(&fs::read_to_string(tmp.join("pkg.toml")).context("pkg.toml missing")?).context("pkg.toml")?;
if info.name != name || info.version != version { let expected_name = match expect {
Expect::Official => name,
Expect::Store { id, .. } => id,
};
if info.name != expected_name || info.version != version {
bail!("package says it is {} {}, expected {expected_name} {version}", info.name, info.version);
}
if name == "sf-shell" && !crate::arch::runs_here(info.arch.as_deref()) {
bail!("{name} {version} is built for {}, this TV is {}", info.arch.as_deref().unwrap_or("x86_64"), crate::arch::NAME);
}
if let Expect::Store { id, approved, .. } = expect {
check_store_manifest(&tmp, id, version, approved)?;
}
Ok(())
})();
if let Err(e) = result {
let _ = fs::remove_dir_all(&tmp); let _ = fs::remove_dir_all(&tmp);
bail!("package says it is {} {}, expected {name} {version}", info.name, info.version); return Err(e);
} }
fs::rename(&tmp, &dest)?; fs::rename(&tmp, &dest)?;
if let Expect::Store { source, .. } = expect {
fs::write(dir.join("source"), format!("{source}\n"))?;
}
Ok(())
}
/// Ids of the store apps on disk.
pub fn store_apps(&self) -> Vec<String> {
let Ok(entries) = fs::read_dir(&self.root) else { return Vec::new() };
entries
.flatten()
.filter_map(|e| e.file_name().into_string().ok())
.filter_map(|n| registry::store_id(&n).map(str::to_string))
.collect()
}
/// Uninstalls a store app (its files; the user's data stays in their home).
pub fn remove_store_app(&self, id: &str) -> Result<()> {
let name = format!("{}{id}", sf_ipc::store::PACKAGE_PREFIX);
anyhow::ensure!(registry::store_id(&name).is_some(), "bad store app id {id}");
let _ = fs::remove_file(self.store_dir().join("apps").join(id));
if self.dir(&name).exists() {
fs::remove_dir_all(self.dir(&name)).with_context(|| format!("removing {name}"))?;
log::info!("removed store app {id}");
}
Ok(()) Ok(())
} }
@@ -228,12 +311,12 @@ impl Store {
self.set_link(name, "staged", version) self.set_link(name, "staged", version)
} }
/// Makes every staged package live. /// Makes every staged package live for which `which(name)` says so.
pub fn apply_staged(&self) -> Result<Applied> { pub fn apply_staged(&self, which: impl Fn(&str) -> bool) -> Result<Applied> {
let mut applied = Applied::default(); let mut applied = Applied::default();
let Ok(entries) = fs::read_dir(&self.root) else { return Ok(applied) }; let Ok(entries) = fs::read_dir(&self.root) else { return Ok(applied) };
for e in entries.flatten() { for e in entries.flatten() {
let Some(name) = e.file_name().into_string().ok().filter(|n| registry::is_ours(n)) else { continue }; let Some(name) = e.file_name().into_string().ok().filter(|n| registry::is_ours(n) && which(n)) else { continue };
let Some(v) = self.staged(&name) else { continue }; let Some(v) = self.staged(&name) else { continue };
if self.link(&name, "current").as_deref() != Some(v.as_str()) { if self.link(&name, "current").as_deref() != Some(v.as_str()) {
if let Some(cur) = self.link(&name, "current") { if let Some(cur) = self.link(&name, "current") {
@@ -244,6 +327,8 @@ impl Store {
if name == SHELL { if name == SHELL {
fs::write(self.dir(&name).join("trial"), &v)?; fs::write(self.dir(&name).join("trial"), &v)?;
applied.shell = true; applied.shell = true;
} else if registry::store_id(&name).is_some() {
applied.store = true;
} else { } else {
applied.apps = true; applied.apps = true;
} }
@@ -254,17 +339,33 @@ impl Store {
Ok(applied) Ok(applied)
} }
/// apps/<id> -> ../sf-app-<id>/current for every installed app. /// apps/<id> -> ../sf-app-<id>/current for every installed app, and
fn link_apps(&self) -> Result<()> { /// store/apps/<id> -> ../../store-<id>/current for store apps.
pub fn link_apps(&self) -> Result<()> {
let apps = self.root.join("apps"); let apps = self.root.join("apps");
let store_apps = self.store_dir().join("apps");
fs::create_dir_all(&apps)?; fs::create_dir_all(&apps)?;
fs::create_dir_all(&store_apps)?;
let Ok(entries) = fs::read_dir(&self.root) else { return Ok(()) }; let Ok(entries) = fs::read_dir(&self.root) else { return Ok(()) };
for e in entries.flatten() { for e in entries.flatten() {
let Some(name) = e.file_name().into_string().ok() else { continue }; let Some(name) = e.file_name().into_string().ok() else { continue };
let Some(id) = name.strip_prefix("sf-app-").filter(|_| registry::is_ours(&name)) else { continue }; let (link, target) = if let Some(id) = name.strip_prefix("sf-app-").filter(|_| registry::is_official(&name)) {
let link = apps.join(id); (apps.join(id), format!("../{name}/current"))
} else if let Some(id) = registry::store_id(&name) {
(store_apps.join(id), format!("../../{name}/current"))
} else {
continue;
};
if self.link(&name, "current").is_some() && fs::symlink_metadata(&link).is_err() { if self.link(&name, "current").is_some() && fs::symlink_metadata(&link).is_err() {
symlink(format!("../{name}/current"), &link)?; symlink(target, &link)?;
}
}
// Links of removed store apps.
if let Ok(entries) = fs::read_dir(&store_apps) {
for e in entries.flatten() {
if !e.path().join("app.toml").exists() {
let _ = fs::remove_file(e.path());
}
} }
} }
Ok(()) Ok(())
@@ -341,7 +442,8 @@ impl Store {
.into_iter() .into_iter()
.map(|name| PackageStatus { .map(|name| PackageStatus {
installed: self.installed(&name).unwrap_or_default(), installed: self.installed(&name).unwrap_or_default(),
available: old.get(&name).cloned().flatten(), // A version that failed here isn't offered again.
available: old.get(&name).cloned().flatten().filter(|v| !self.bad(&name).contains(v)),
staged: self.staged(&name), staged: self.staged(&name),
name, name,
}) })
@@ -361,3 +463,213 @@ impl Store {
}); });
} }
} }
/// Unpacks a package from a third party: only plain files, folders and
/// symlinks that stay inside, no setuid/setgid bits, nothing writable by
/// others, within size limits.
fn unpack_untrusted<R: std::io::Read>(archive: &mut tar::Archive<R>, dest: &Path) -> Result<()> {
use std::path::Component;
archive.set_preserve_permissions(false);
let mut total = 0u64;
let mut files = 0usize;
for entry in archive.entries().context("reading the package")? {
let mut entry = entry.context("reading the package")?;
let path = entry.path().context("bad path")?.into_owned();
if !path.components().all(|c| matches!(c, Component::Normal(_) | Component::CurDir)) {
bail!("package path {} leaves the package", path.display());
}
match entry.header().entry_type() {
tar::EntryType::Regular | tar::EntryType::Directory => {}
tar::EntryType::Symlink => {
let target = entry.link_name().ok().flatten().context("symlink without target")?;
// Depth of the folder the link is in; ".." may not climb above the package.
let mut level = path.components().filter(|c| matches!(c, Component::Normal(_))).count() as i64 - 1;
for c in target.components() {
match c {
Component::Normal(_) => level += 1,
Component::ParentDir => level -= 1,
Component::CurDir => {}
_ => bail!("symlink {} points outside the package", path.display()),
}
if level < 0 {
bail!("symlink {} points outside the package", path.display());
}
}
}
other => bail!("{}: {other:?} entries are not allowed", path.display()),
}
total += entry.header().size().unwrap_or(0);
files += 1;
if total > MAX_STORE_UNPACKED || files > MAX_STORE_FILES {
bail!("the package is too large");
}
if !entry.unpack_in(dest).with_context(|| format!("unpacking {}", path.display()))? {
bail!("package path {} leaves the package", path.display());
}
}
strip_modes(dest)
}
/// No setuid/setgid/sticky and no group/other write anywhere in `dir`.
#[cfg(unix)]
fn strip_modes(dir: &Path) -> Result<()> {
use std::os::unix::fs::PermissionsExt;
for e in fs::read_dir(dir)?.flatten() {
let meta = fs::symlink_metadata(e.path())?;
if meta.file_type().is_symlink() {
continue;
}
let mode = meta.permissions().mode() & 0o755;
fs::set_permissions(e.path(), fs::Permissions::from_mode(mode))?;
if meta.is_dir() {
strip_modes(&e.path())?;
}
}
Ok(())
}
#[cfg(not(unix))]
fn strip_modes(_dir: &Path) -> Result<()> {
Ok(())
}
/// The manifest inside a store package must match what was offered.
fn check_store_manifest(dir: &Path, id: &str, version: &str, approved: &[Permission]) -> Result<()> {
let text = fs::read_to_string(dir.join("app.toml")).context("app.toml missing")?;
let app: AppManifest = toml::from_str(&text).context("app.toml")?;
anyhow::ensure!(app.id == id, "app.toml says id {}, expected {id}", app.id);
anyhow::ensure!(app.version == version, "app.toml says version {}, expected {version}", app.version);
app.check_store_rules()?;
let missing = sf_ipc::store::missing_permissions(&app.permissions(), approved);
anyhow::ensure!(missing.is_empty(), "the package asks for permissions that were not approved: {missing:?}");
Ok(())
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
const ID: &str = "io.github.fox.hello";
struct Pkg {
tar: tar::Builder<Vec<u8>>,
}
impl Pkg {
fn new(version: &str, perms: &str) -> Pkg {
let mut p = Pkg { tar: tar::Builder::new(Vec::new()) };
p.file("pkg.toml", &format!("name = \"{ID}\"\nversion = \"{version}\"\n"), 0o644);
p.file(
"app.toml",
&format!("id = \"{ID}\"\nname = \"Hello\"\nversion = \"{version}\"\nkind = \"exec\"\nexec = [\"bin/hello\"]\n[sandbox]\npermissions = [{perms}]\n"),
0o644,
);
p.file("bin/hello", "#!/bin/sh\n", 0o755);
p
}
fn file(&mut self, path: &str, body: &str, mode: u32) {
let mut h = tar::Header::new_gnu();
h.set_size(body.len() as u64);
h.set_mode(mode);
self.tar.append_data(&mut h, path, body.as_bytes()).unwrap();
}
fn link(&mut self, path: &str, target: &str) {
let mut h = tar::Header::new_gnu();
h.set_entry_type(tar::EntryType::Symlink);
h.set_size(0);
self.tar.append_link(&mut h, path, target).unwrap();
}
fn write(self, dir: &Path) -> PathBuf {
let tar = self.tar.into_inner().unwrap();
let zst = ruzstd::encoding::compress_to_vec(&tar[..], ruzstd::encoding::CompressionLevel::Fastest);
let path = dir.join("pkg.tar.zst");
fs::write(&path, &zst).unwrap();
path
}
}
fn setup(name: &str) -> (PathBuf, Store) {
let root = std::env::temp_dir().join(format!("sf-update-{name}-{}", std::process::id()));
let _ = fs::remove_dir_all(&root);
let store = Store::open(&root, &root.join("none.toml")).unwrap();
(root, store)
}
#[test]
fn installs_a_store_app_and_refuses_bad_ones() {
let (root, store) = setup("store");
let name = format!("store-{ID}");
let approved = [Permission::Network];
let expect = Expect::Store { id: ID, approved: &approved, source: "https://github.com/fox/hello" };
// A good package, with a setuid bit that must be stripped.
let mut p = Pkg::new("1.0.0", "\"network\"");
p.file("bin/suid", "x", 0o4777);
p.link("bin/alias", "hello");
let pkg = p.write(&root);
store.unpack_store(&name, "1.0.0", &pkg, &expect).unwrap();
store.stage(&name, "1.0.0").unwrap();
let applied = store.apply_staged(|_| true).unwrap();
assert!(applied.store && !applied.apps);
assert!(root.join("store/apps").join(ID).join("app.toml").is_file());
assert_eq!(store.installed(&name).as_deref(), Some("1.0.0"));
assert_eq!(fs::read_to_string(root.join(&name).join("source")).unwrap().trim(), "https://github.com/fox/hello");
use std::os::unix::fs::PermissionsExt;
let mode = fs::metadata(root.join(&name).join("1.0.0/bin/suid")).unwrap().permissions().mode() & 0o7777;
assert_eq!(mode, 0o755);
// An unsigned update installs from the selected source.
let pkg = Pkg::new("1.1.0", "\"network\"").write(&root);
store.unpack_store(&name, "1.1.0", &pkg, &expect).unwrap();
// More permissions than approved.
let pkg = Pkg::new("1.1.0", "\"network\", \"devices\"").write(&root);
let err = store.unpack_store(&name, "1.1.0", &pkg, &expect).unwrap_err();
assert!(format!("{err:#}").contains("not approved"), "{err:#}");
// A symlink out of the package.
let mut p = Pkg::new("1.1.0", "\"network\"");
p.link("bin/evil", "../../../../etc/shadow");
let pkg = p.write(&root);
assert!(store.unpack_store(&name, "1.1.0", &pkg, &expect).is_err());
let mut p = Pkg::new("1.1.0", "\"network\"");
p.link("evil", "/etc/shadow");
let pkg = p.write(&root);
assert!(store.unpack_store(&name, "1.1.0", &pkg, &expect).is_err());
// Nothing half-unpacked is left behind.
assert!(!root.join(&name).join("1.1.0").exists());
assert!(!root.join(&name).join(".tmp-1.1.0").exists());
// Uninstall.
store.remove_store_app(ID).unwrap();
assert!(!root.join(&name).exists());
assert!(fs::symlink_metadata(root.join("store/apps").join(ID)).is_err());
fs::remove_dir_all(&root).unwrap();
}
#[test]
fn plan_holds_back_new_permissions() {
use sf_ipc::store::{Catalog, CatalogApp, Wanted, WantedApp};
let (root, store) = setup("plan");
let app = |perms: Vec<Permission>| CatalogApp {
id: ID.into(),
name: "Hello".into(),
version: "2.0.0".into(),
permissions: perms,
source: "https://github.com/fox/hello".into(),
..Default::default()
};
let mut wanted = Wanted::default();
wanted.apps.insert(ID.into(), WantedApp { source: "github.com/fox/hello".into(), permissions: vec![Permission::Network] });
let mut cat = Catalog { apps: vec![app(vec![Permission::Network])], ..Default::default() };
assert_eq!(crate::appstore::plan(&store, &wanted, &mut cat).len(), 1);
let mut cat = Catalog { apps: vec![app(vec![Permission::Network, Permission::Gpu])], ..Default::default() };
assert!(crate::appstore::plan(&store, &wanted, &mut cat).is_empty());
assert_eq!(cat.apps[0].blocked.as_deref(), Some("permissions"));
// Not wanted: nothing to do.
let mut cat = Catalog { apps: vec![app(vec![])], ..Default::default() };
assert!(crate::appstore::plan(&store, &Wanted::default(), &mut cat).is_empty());
fs::remove_dir_all(&root).unwrap();
}
}

150
docs/store.md Normal file
View File

@@ -0,0 +1,150 @@
# App Store és sandbox
A Fennec OS appjai két helyről jönnek:
- **Hivatalos appok:** a rendszer saját appjai (Beállítások, App Store, AirPlay, Miracast) az image-ben, és azok csomagjai (`sf-app-<id>`, a Fennec OS kulcsával aláírva, a Gitea registryből). Lásd: [updates.md](updates.md).
- **Store appok:** minden más. Mindegyik a saját GitHub-, Gitea/Forgejo- (pl. Codeberg) vagy GitLab-repójában él, és a release-eiből települ. A Bluefox appjai (Netflex, YouTube, Steam) is ilyenek: a [Fennec katalógusból](https://gitea.bluefox.support/fennec/store) jönnek.
Minden app **sandboxban** fut (bubblewrap, a Flatpak építőköve). Kivételek, mert ezek rendszer-szolgáltatások: az AirPlay és a Miracast vevő. Ezek gyári appok, és az `app.toml`-jukban `[sandbox] enabled = false` áll. Store app ezt nem teheti meg.
## A sandbox
Amit egy app lát (`crates/sf-ipc/src/sandbox.rs`):
| Mit | Hogyan |
|---|---|
| A rendszer | `/usr`, `/etc` csak olvasva |
| Az app saját fájljai | `/app`, csak olvasva (`$SMARTFOX_APP_DIR`) |
| Az app adatai | `$HOME` = a TV-n `~/.local/share/smartfox/apps/<id>`; csak ez írható tartósan |
| Kép | a Wayland socket |
| Ideiglenes | saját `/tmp`, `/run`, `/var`; saját PID-, IPC- és UTS-névtér |
| Ami nincs | más appok és a felhasználó fájljai, a launcher / sf-core / kompozitor socketje, hálózat, hang, eszközök, D-Bus (engedély nélkül) |
**Engedélyek** (`[sandbox] permissions`): ezeket a TV telepítés előtt megmutatja.
| Engedély | Mit nyit meg |
|---|---|
| `network` | internet és helyi hálózat (DNS is) |
| `gpu` | `/dev/dri`, `/sys`: hardveres grafika és videódekódolás |
| `audio` | PipeWire / PulseAudio socket |
| `gamepad` | `/dev/input`, `/dev/hidraw*`, `/dev/uinput`, udev: játékvezérlők |
| `dbus-session` | a munkamenet D-Bus-a (szűretlen, **kockázatos**) |
| `dbus-system` | a rendszer D-Bus-a (szűretlen, **kockázatos**) |
| `devices` | minden eszköz `/dev` alatt (**kockázatos**) |
| `dial` | telefonról castolva is indulhat (DIAL); a `[dial]` szakasz kéri |
A web appok (Chromium) mindig megkapják a `network`, `gpu` és `audio` engedélyt. A Chromium profilja is a sandboxba költözik (`<adat>/chromium`). A régi profil (`~/.config/smartfox/profiles/<id>`) az első indításkor átköltözik, így a bejelentkezések megmaradnak.
**Hibakeresés:** a `SMARTFOX_SANDBOX=off` (a `/var/lib/smartfox/session.env` fájlban) a hivatalos appokat sandbox nélkül indítja. A store appokra nem hat: azok bubblewrap nélkül el sem indulnak.
**Korlátok:**
- nincs seccomp-szűrő és D-Bus-proxy (a Flatpak mindkettőt használja). A D-Bus engedélyek ezért teljes hozzáférést adnak.
- `/etc` egésze olvasható; a titkos fájlok (`shadow`, kulcsok) amúgy is csak a rootnak olvashatók.
## Store források
A Store app (a launcherben) → **Források** → „Forrás hozzáadása”. Egy forrás kétféle lehet:
- **App-repó:** egyetlen app, pl. `github.com/valaki/app`.
- **Katalógus-repó:** sok app listája. Az alapértelmezett ágon egy `smartfox-store.toml` fájl:
```toml
name = "Családi katalógus"
apps = [
"https://github.com/valaki/app",
"https://codeberg.org/masvalaki/jatek",
"gitlab.com/csoport/alcsoport/projekt",
]
```
**Elfogadott címek:**
- `https://github.com/o/r`, `github.com/o/r`, `github:o/r`;
- `gitlab.com/csoport/projekt` (alcsoportokkal is);
- `codeberg.org/o/r`;
- saját szerver: `https://git.pelda.hu/o/r` (a TV kitalálja, Gitea-e vagy GitLab), vagy kifejezetten `gitea:git.pelda.hu/o/r`, `gitlab:git.pelda.hu/csoport/projekt`.
Csak `https://` engedett. A repónak nyilvánosnak kell lennie: a TV bejelentkezés nélkül tölt, és a Fennec OS registry-tokenje sosem megy külső szerverre.
**Egy release** a legújabb nem-draft, nem-prerelease kiadás, amelyben van `app.toml`. Két fájl (asset) kell bele:
| Fájl | Mi |
|---|---|
| `app.toml` | a manifest: név, leírás, engedélyek |
| `<id>-<verzió>.tar.zst` | a csomag |
| `<id>-<verzió>-aarch64.tar.zst` | opcionális: a csomag ARM-ra (Raspberry Pi) |
**ARM-on** (`aarch64`) a TV az `-aarch64` csomagot keresi. Ha nincs, egy `web` app a sima csomagot is megkapja (az minden gépen ugyanaz). Egy `exec` app sima csomagja x86-64-es: ARM-on az ilyen app nem jelenik meg a store-ban.
## Biztonság
- **Az app azonosítója** fordított domain név legalább egy ponttal (`io.github.valaki.app`). A hivatalos appok azonosítójában nincs pont, így store app sosem léphet egy hivatalos app helyére. Két forrás ugyanazzal az azonosítóval: az nyer, ahonnan telepítve van.
- **Forrás:** a TV a felhasználó által kiválasztott repó release-eiből frissít. A repó tulajdonosában és tartalmában a felhasználó bízik meg.
- **Engedélyek:** csak a jóváhagyott engedélyekkel települ. Ha egy frissítés többet kér, vár, amíg a Store-ban jóvá nem hagyod. A TV a letöltött csomagban lévő `app.toml`-t is ellenőrzi, nem csak a release-ét.
- **Kibontás:** csak sima fájl, mappa és csomagon belül maradó symlink lehet benne. Setuid/setgid bitek és mások által írható fájlok nincsenek; méret- és fájlszám-korlát van.
- **Szabályok** (`check_store_rules`, az SDK `sf-app` crate-jében): store app nem lehet `builtin` vagy háttérszolgáltatás, és nem kapcsolhatja ki a sandboxot; web app csak `https://` címmel.
- **DIAL:** store app is regisztrálhat (`[dial] name = "YouTube"`), ehhez a `dial` engedélyt kell jóváhagyni. Ha egy gyári app is ugyanazt a nevet használja, az nyer (`crates/sf-core/src/dial.rs`).
- **Ikon:** a launcher beépített ikonjai (`icon = "settings"`) csak a gyári appoké; store app saját képet hoz (`icon.png`, `icon.svg`), különben a neve kezdőbetűje látszik.
## A TV-n
```
/var/lib/smartfox/store.toml amit a felhasználó kért (a launcher írja, tv)
/var/lib/sf-pkg/store/catalog.json amit a források kínálnak (sf-update, root)
/var/lib/sf-pkg/store-<id>/ a telepített verziók, mint bármely csomagnál
<verzió>/ current previous staged bad
source a repó, ahonnan jött
/var/lib/sf-pkg/store/apps/<id> -> ../../store-<id>/current (ezt olvassa a launcher és az sf-core)
~/.local/share/smartfox/apps/<id>/ az app adatai ($HOME a sandboxban)
```
**`store.toml`:**
```toml
sources = ["https://github.com/valaki/katalogus"]
[apps."io.github.valaki.app"]
source = "https://github.com/valaki/app"
permissions = ["network", "audio"] # amit jóváhagytál
```
**Folyamat:**
1. A Store képernyő átírja a `store.toml`-t, és `store` kérést tesz az `update-requests` mappába.
2. Az `sf-update store` (root) lekérdezi a forrásokat, és megírja a `catalog.json`-t.
3. Ezután letölti, ellenőrzi és azonnal élesíti az új vagy jóváhagyott appokat, a kivetteket pedig eltávolítja.
4. Amikor kilépsz a Store-ból, a launcher újraindítja magát ugyanabban a folyamatban, és így megjelenik az új csempe. A futó appok és az sf-core közben futnak tovább.
A `store.toml`-t a root óvatosan olvassa: symlinket nem követ, csak sima fájlt fogad el, méretkorláttal.
**Frissítés:** pontosan úgy, mint a hivatalos csomagoknál.
- A 6 óránkénti `sf-update auto` a store appok új verzióit is letölti, és a következő induláskor élesednek.
- A Beállítások → Rendszer → Frissítések „Telepítés most” gombja azonnal telepít.
**Eltávolítás:** az app fájljai törlődnek. Az adatai csak akkor, ha a Store-ban azt választod.
## Gyári store appok
Egy új TV `store.toml`-ja az image-ből jön (`image/mkosi.extra/usr/share/smartfox/factory-store.toml`): forrásként a Fennec katalógus, telepítve a Netflex, a YouTube és a Steam, jóváhagyott engedélyekkel.
- Az image építésekor a `mkosi.postinst.chroot` lefuttatja az `sf-update store` parancsot, így a csomagok már a gyári `/var`-ban vannak, és a TV hálózat nélkül is indítja őket.
- Ha az építéskor nem érhetők el (például nem nyilvánosak a repók), az image figyelmeztetéssel elkészül, és a TV az első `sf-update auto` futáskor telepíti őket. Ezek a következő induláskor élesednek.
**Régi TV-k:** a régebbi image-ekben a Netflex web app, a YouTube és a Steam még gyári app volt (`RETIRED`, `crates/sf-ipc/src/manifest.rs`). Az átállás magától megy:
1. Az `sf-update` az első futásakor felveszi a `store.toml`-ba a Fennec katalógust és a régi appok utódjait, a régi engedélyekkel (`crates/sf-update/src/migrate.rs`). Ezt TV-nként egyszer teszi meg (`/var/lib/sf-pkg/store/retired-adopted`), így amit utána eltávolítasz, az nem jön vissza.
2. A régi app addig látszik, amíg az utódja nincs telepítve. Utána a launcher és az sf-core kihagyja.
3. A YouTube és a Steam adatmappája (a bejelentkezések, a Chromium-profil) átköltözik az új azonosítóra.
A régi `sf-app-<id>` csomagokat az `sf-update` már nem tölti le.
## App készítése
A [Fennec SDK](https://gitea.bluefox.support/fennec/sdk) mindent tartalmaz: a teljes, önálló útmutatót (`docs/store-app-guide.md`), az `sf-ui` UI-készletet, az `sf-pack` csomagolót és egy Rust app-sablont release pipeline-okkal. Az OS forráskódja nem kell hozzá.
1. **Csomagoló:**
```sh
cargo install --locked --git https://gitea.bluefox.support/fennec/sdk --tag v0.1.0 sf-pack
```
2. **Kipróbálás a sandboxban,** Linuxon, bubblewrappel: `sf-pack run <app-mappa>`. Ugyanúgy indítja, mint a TV: ugyanaz a sandbox, ugyanazok az engedélyek.
3. **Csomag:** `sf-pack build <app-mappa> dist`. A `dist/` mappába kerül a két release-fájl; ellenőrzés: `sf-pack verify dist`.
4. **Kiadás:** tag (`v1.2.3`) → a CI megépíti, és release-t csinál a két fájllal.
5. **A TV-n:** Store → Források → a repó címe → az app megjelenik a Felfedezés alatt.
## Steam
A Steam store app: [`fennec/steam`](https://gitea.bluefox.support/fennec/steam), a Valve hivatalos `steam-launcher` csomagjából. A csomagolás, az ellenőrzés és a futtatás leírása ott van.
Az OS adja a rendszerszintű részt (az image-ben):
- a `gamescope`-ot;
- a 32 bites könyvtárakat (`steam-libs-i386`) a Valve aláírt apt-repójából (`mkosi.postinst.chroot`, a kulcs: `image/mkosi.extra/usr/share/keyrings/valve-archive-keyring.gpg`);
- a kontrollerek udev-szabályait a Valve `steam-launcher` csomagjából (csak a szabályokat, a launchert nem);
- a kompozitorban azokat a Wayland-protokollokat, amelyek nélkül a beágyazott `gamescope` el sem indul: `wp_presentation` (valódi képkocka-visszajelzéssel), `zwp_relative_pointer_manager_v1`, `zwp_pointer_constraints_v1` (és a meglévő dmabuf, viewporter).
A `gamescope`-nak hardveres Vulkan is kell (`VK_EXT_physical_device_drm`). A QEMU-s teszt-VM-ben csak szoftveres Vulkan (llvmpipe) van, ott a `gamescope` emiatt áll le; a Steam teljes útját valódi gépen kell kipróbálni.

View File

@@ -1,16 +1,19 @@
# Frissítések (csomagok) # Frissítések (csomagok)
A TV nem image-et frissít, hanem csomagokat: A TV nem image-et frissít, hanem csomagokat:
- `sf-shell`: a felület (`sf-launcher`, `sf-remote`, `sf-pair`); - `sf-shell`: a felület és a frissítő (`sf-launcher`, `sf-remote`, `sf-update`, `sf-pair`);
- `sf-app-<id>`: egy-egy app (`apps/<id>/` tartalma). - `sf-app-<id>`: a rendszer egy-egy saját appja (`apps/<id>/` tartalma);
- `store-<id>`: store appok a saját repójukból, aláírás nélkül. Ugyanez a rendszer frissíti őket; lásd [store.md](store.md).
Az image (rendszer, scriptek, unitok, `sf-update`) csak újratelepítéssel változik. A gyári shell és a gyári appok az image-ben maradnak, és tartalékként mindig elérhetők. Az image rendszere, scriptjei és unitjai csak újratelepítéssel változnak. Az új `sf-update` a shell csomaggal érkezik az új rendszerképet használó TV-kre; a gyári példány tartalékként marad meg.
## Kiadás ## Kiadás
Egy csomag akkor jelenik meg, ha a verziója még nincs fent a registryben. Kiadáshoz emeld a verziót, és pushold a `main` ágat: Egy csomag akkor jelenik meg, ha a verziója még nincs fent a registryben. Kiadáshoz emeld a verziót, és pushold a `main` ágat:
- shell: `Cargo.toml` → `[workspace.package] version`; - shell: `Cargo.toml` → `[workspace.package] version`;
- app: `apps/<id>/app.toml` → `version`. - app: `apps/<id>/app.toml` → `version`.
A store appok (Netflex, YouTube, Steam...) a saját repójukból jönnek ki, lásd [store.md](store.md).
A `.gitea/workflows/packages.yml` workflow a `build` runneren lefordítja, aláírja és feltölti a csomagot (`tools/pkg/packages.sh --upload`). Ugyanez kézzel, a WSL-ből: A `.gitea/workflows/packages.yml` workflow a `build` runneren lefordítja, aláírja és feltölti a csomagot (`tools/pkg/packages.sh --upload`). Ugyanez kézzel, a WSL-ből:
```sh ```sh
SF_SIGNING_KEY_FILE=~/.smartfox/signing-key.pem SF_PACKAGE_TOKEN=<token> bash tools/pkg/packages.sh --upload shell app:youtube SF_SIGNING_KEY_FILE=~/.smartfox/signing-key.pem SF_PACKAGE_TOKEN=<token> bash tools/pkg/packages.sh --upload shell app:youtube
@@ -40,7 +43,13 @@ Registry: Gitea generic packages, `https://gitea.bluefox.support`, tulajdonos: `
- A privát kulcs: a `SF_SIGNING_KEY` CI-secret (a PEM fájl base64-ben, egy sorban, így a CI-napló maszkolja), és egy példány a fejlesztő gépén (`%USERPROFILE%\.smartfox\signing-key.pem`). - A privát kulcs: a `SF_SIGNING_KEY` CI-secret (a PEM fájl base64-ben, egy sorban, így a CI-napló maszkolja), és egy példány a fejlesztő gépén (`%USERPROFILE%\.smartfox\signing-key.pem`).
- Aláírás nélküli vagy hibásan aláírt csomagot a TV nem telepít. Azt sem, amelyiknek a `pkg.toml`-ja más nevet vagy verziót mond. - Aláírás nélküli vagy hibásan aláírt csomagot a TV nem telepít. Azt sem, amelyiknek a `pkg.toml`-ja más nevet vagy verziót mond.
**Csak release verzió települ** (`1.2.3`), előzetes verzió (`1.2.3-rc1`) nem. A TV csak a meglévőnél (a gyári és a telepített közül a nagyobbnál) újabbat tölt le. **Architektúrák:** a Fennec OS x86-64-en indult, ezért ott a fájlnévben nincs architektúra. Más architektúrán az `sf-shell` fájl végződést kap: `sf-shell-1.2.0-aarch64.tar.zst`, ugyanabban a csomagverzióban. A `pkg.toml` `arch` mezője is megmondja, mire készült.
- A TV csak a saját architektúrájára épült shellt telepíti. Ha a legújabb verzióban nincs ilyen fájl, a shell nem frissül.
- `arch` nélküli shell x86-64-es (régi csomag).
- Az `sf-app-<id>` csomagok csak manifestek, minden architektúrán ugyanazok.
- Építés: `SF_TARGET=aarch64-unknown-linux-gnu tools/pkg/packages.sh shell` (keresztfordítás, Debian multiarch; a függőségeket az `image/pi/build.sh` telepíti).
**Csak release verzió települ** (`1.2.3`, legfeljebb négy tag: a Steam `1.0.0.87`), előzetes verzió (`1.2.3-rc1`) nem. A TV csak a meglévőnél (a gyári és a telepített közül a nagyobbnál) újabbat tölt le.
**Belépés:** a `fox-tv` felhasználó tokenje, csak `read:package` joggal. Az image építésekor az `image/secrets/update-token` fájlból kerül a `/usr/share/smartfox/update-token` fájlba (`fox-tv:<token>`; a fájl nincs a gitben). Egy adott TV-n felülírható a `/var/lib/sf-pkg/update.toml` fájllal (`token_file`, `server` stb.). **Belépés:** a `fox-tv` felhasználó tokenje, csak `read:package` joggal. Az image építésekor az `image/secrets/update-token` fájlból kerül a `/usr/share/smartfox/update-token` fájlba (`fox-tv:<token>`; a fájl nincs a gitben). Egy adott TV-n felülírható a `/var/lib/sf-pkg/update.toml` fájllal (`token_file`, `server` stb.).

View File

@@ -1,5 +1,5 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# Builds the SmartFox installer ISO (UEFI, x86-64) for a USB stick. # Builds the Fennec OS installer ISO (UEFI, x86-64) for a USB stick.
# Run as root inside WSL Debian: # Run as root inside WSL Debian:
# sudo bash /mnt/g/source/smartfox/image/build-iso.sh # sudo bash /mnt/g/source/smartfox/image/build-iso.sh
# Writes image/out/smartfox-installer.iso (in the source tree, so Rufus on # Writes image/out/smartfox-installer.iso (in the source tree, so Rufus on
@@ -7,7 +7,7 @@
# Raw writers (Etcher, dd) work too: the ISO carries a GPT with an ESP holding # Raw writers (Etcher, dd) work too: the ISO carries a GPT with an ESP holding
# the UKI, so UEFI firmware sees the stick as bootable. # the UKI, so UEFI firmware sees the stick as bootable.
# #
# SKIP_BUILD=1 reuses the last SmartFox image instead of running build.sh. # SKIP_BUILD=1 reuses the last Fennec OS image instead of running build.sh.
# Don't do that after booting it in run-qemu.sh: the VM writes into that file. # Don't do that after booting it in run-qemu.sh: the VM writes into that file.
set -euo pipefail set -euo pipefail
@@ -43,7 +43,7 @@ rm -rf "$STAGE"
mkdir -p "$STAGE/tree/EFI/BOOT" "$STAGE/tree/smartfox" mkdir -p "$STAGE/tree/EFI/BOOT" "$STAGE/tree/smartfox"
cp "$UKI" "$STAGE/tree/EFI/BOOT/BOOTX64.EFI" cp "$UKI" "$STAGE/tree/EFI/BOOT/BOOTX64.EFI"
stat -c %s "$RAW" >"$STAGE/tree/smartfox/smartfox.size" stat -c %s "$RAW" >"$STAGE/tree/smartfox/smartfox.size"
echo "SmartFox $(grep -m1 '^version' "$WORK/Cargo.toml" | cut -d'"' -f2) · $(date +%Y-%m-%d)" >"$STAGE/tree/smartfox/version" echo "Fennec OS $(grep -m1 '^version' "$WORK/Cargo.toml" | cut -d'"' -f2) · $(date +%Y-%m-%d)" >"$STAGE/tree/smartfox/version"
zstd -T0 -10 -q "$RAW" -o "$STAGE/tree/smartfox/smartfox.raw.zst" zstd -T0 -10 -q "$RAW" -o "$STAGE/tree/smartfox/smartfox.raw.zst"
# Rufus puts the files on FAT32: no single file may reach 4 GiB. # Rufus puts the files on FAT32: no single file may reach 4 GiB.
[ "$(stat -c %s "$STAGE/tree/smartfox/smartfox.raw.zst")" -lt 4294967296 ] || { echo "payload too big for FAT32"; exit 1; } [ "$(stat -c %s "$STAGE/tree/smartfox/smartfox.raw.zst")" -lt 4294967296 ] || { echo "payload too big for FAT32"; exit 1; }
@@ -59,7 +59,7 @@ echo "== iso"
ISO="$STAGE/smartfox-installer.iso" ISO="$STAGE/smartfox-installer.iso"
xorriso -as mkisofs \ xorriso -as mkisofs \
-iso-level 3 -full-iso9660-filenames -joliet -joliet-long -rational-rock \ -iso-level 3 -full-iso9660-filenames -joliet -joliet-long -rational-rock \
-volid SMARTFOX -appid "SmartFox installer" \ -volid FENNEC_OS -appid "Fennec OS installer" \
-partition_offset 16 \ -partition_offset 16 \
-append_partition 2 C12A7328-F81F-11D2-BA4B-00A0C93EC93B "$EFI_IMG" -appended_part_as_gpt \ -append_partition 2 C12A7328-F81F-11D2-BA4B-00A0C93EC93B "$EFI_IMG" -appended_part_as_gpt \
-e --interval:appended_partition_2:all:: -no-emul-boot \ -e --interval:appended_partition_2:all:: -no-emul-boot \

View File

@@ -1,5 +1,5 @@
#!/usr/bin/env bash #!/usr/bin/env bash
# Builds the SmartFox binaries and the OS disk image. # Builds the Fennec OS binaries and the OS disk image.
# Run as root inside WSL Debian (or any Debian/Ubuntu host): # Run as root inside WSL Debian (or any Debian/Ubuntu host):
# sudo bash /mnt/g/source/smartfox/image/build.sh # sudo bash /mnt/g/source/smartfox/image/build.sh
set -euo pipefail set -euo pipefail
@@ -11,7 +11,7 @@ echo "== sync $SRC -> $WORK"
mkdir -p "$WORK" mkdir -p "$WORK"
# Files on NTFS show up as 0777; normalize, the image must not get world-writable files. # Files on NTFS show up as 0777; normalize, the image must not get world-writable files.
rsync -a --delete --chmod=Du=rwx,Dgo=rx,Fu=rw,Fgo=r \ rsync -a --delete --chmod=Du=rwx,Dgo=rx,Fu=rw,Fgo=r \
--exclude /target --exclude /image/mkosi.output --exclude /image/mkosi.cache --exclude /image/stage --exclude /image/ovmf-vars.fd \ --exclude /target --exclude '*/target' --exclude /image/mkosi.output --exclude /image/mkosi.cache --exclude /image/stage --exclude /image/ovmf-vars.fd \
--exclude /image/installer/mkosi.output --exclude /image/installer/mkosi.cache --exclude /image/iso --exclude /image/out \ --exclude /image/installer/mkosi.output --exclude /image/installer/mkosi.cache --exclude /image/iso --exclude /image/out \
"$SRC/" "$WORK/" "$SRC/" "$WORK/"
cd "$WORK" cd "$WORK"
@@ -21,7 +21,7 @@ if ! command -v cargo >/dev/null; then
[ -x "$HOME/.cargo/bin/cargo" ] || curl -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal [ -x "$HOME/.cargo/bin/cargo" ] || curl -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal
export PATH="$HOME/.cargo/bin:$PATH" export PATH="$HOME/.cargo/bin:$PATH"
fi fi
cargo build --release -p sf-launcher -p sf-remote -p sf-update cargo build --release -p sf-launcher -p sf-remote -p sf-update -p sf-core -p sf-miracast -p sf-compositor
echo "== stage" echo "== stage"
STAGE="$WORK/image/stage" STAGE="$WORK/image/stage"
@@ -30,6 +30,9 @@ install -Dm755 target/release/sf-launcher "$STAGE/usr/bin/sf-launcher"
install -Dm755 target/release/sf-remote "$STAGE/usr/bin/sf-remote" install -Dm755 target/release/sf-remote "$STAGE/usr/bin/sf-remote"
install -Dm755 tools/siri-remote/fastpair.py "$STAGE/usr/bin/sf-pair" install -Dm755 tools/siri-remote/fastpair.py "$STAGE/usr/bin/sf-pair"
install -Dm755 target/release/sf-update "$STAGE/usr/bin/sf-update" install -Dm755 target/release/sf-update "$STAGE/usr/bin/sf-update"
for b in sf-core sf-miracast sf-compositor; do
install -Dm755 "target/release/$b" "$STAGE/usr/bin/$b"
done
# Registry login for sf-update (read:package only). Kept out of git; without it # Registry login for sf-update (read:package only). Kept out of git; without it
# the TV can only update if the registry allows anonymous downloads. # the TV can only update if the registry allows anonymous downloads.
if [ -f image/secrets/update-token ]; then if [ -f image/secrets/update-token ]; then
@@ -38,17 +41,25 @@ else
echo "warning: image/secrets/update-token is missing, sf-update will log in anonymously" echo "warning: image/secrets/update-token is missing, sf-update will log in anonymously"
fi fi
mkdir -p "$STAGE/usr/share/smartfox" mkdir -p "$STAGE/usr/share/smartfox"
cp -r apps "$STAGE/usr/share/smartfox/apps" # Official apps only. A folder with its own .git is a store app checked out
# here for development (e.g. apps/netflex-tv): not part of the image. Store
# apps come from their own repos (factory-store.toml, mkosi.postinst.chroot).
mkdir -p "$STAGE/usr/share/smartfox/apps"
for d in apps/*/; do
[ -e "$d/.git" ] && continue
cp -r "$d" "$STAGE/usr/share/smartfox/apps/"
done
chmod -R a+x "$STAGE"/usr/share/smartfox/apps/*/bin 2>/dev/null || true
# Versions of the factory copies: sf-update only installs newer packages. # Versions of the factory copies: sf-update only installs newer packages.
{ {
echo "sf-shell = \"$(sed -n '/^\[workspace.package\]/,/^\[/ s/^version *= *"\(.*\)"/\1/p' Cargo.toml)\"" echo "sf-shell = \"$(sed -n '/^\[workspace.package\]/,/^\[/ s/^version *= *"\(.*\)"/\1/p' Cargo.toml)\""
for d in apps/*/; do for d in "$STAGE"/usr/share/smartfox/apps/*/; do
v=$(sed -n 's/^version *= *"\(.*\)".*/\1/p' "$d/app.toml" | head -1) v=$(sed -n 's/^version *= *"\(.*\)".*/\1/p' "$d/app.toml" | head -1)
[ -n "$v" ] && echo "sf-app-$(basename "$d") = \"$v\"" [ -n "$v" ] && echo "sf-app-$(basename "$d") = \"$v\""
done done
} >"$STAGE/usr/share/smartfox/factory-versions.toml" } >"$STAGE/usr/share/smartfox/factory-versions.toml"
mkdir -p "$STAGE/usr/share/doc/smartfox" mkdir -p "$STAGE/usr/share/doc/smartfox"
cp docs/updates.md "$STAGE/usr/share/doc/smartfox/updates.md" cp docs/updates.md docs/store.md "$STAGE/usr/share/doc/smartfox/"
chmod +x image/mkosi.postinst.chroot image/mkosi.extra/usr/bin/sf-session image/mkosi.extra/usr/bin/sf-launcher-start image/mkosi.extra/usr/bin/sf-remote-debug image/mkosi.extra/usr/bin/sf-diag image/mkosi.extra/usr/bin/sf-shell-exec image/*.sh tools/vm/*.sh tools/siri-remote/*.sh tools/siri-remote/*.py chmod +x image/mkosi.postinst.chroot image/mkosi.extra/usr/bin/sf-session image/mkosi.extra/usr/bin/sf-launcher-start image/mkosi.extra/usr/bin/sf-remote-debug image/mkosi.extra/usr/bin/sf-diag image/mkosi.extra/usr/bin/sf-shell-exec image/*.sh tools/vm/*.sh tools/siri-remote/*.sh tools/siri-remote/*.py
echo "== mkosi" echo "== mkosi"

View File

@@ -1,5 +1,5 @@
# SmartFox installer: a tiny Debian that runs entirely from RAM (packed as a # Fennec OS installer: a tiny Debian that runs entirely from RAM (packed as a
# UKI) and writes the SmartFox disk image from the install stick to a disk. # UKI) and writes the Fennec OS disk image from the install stick to a disk.
# Built by ../build-iso.sh; not meant to be built on its own. # Built by ../build-iso.sh; not meant to be built on its own.
[Distribution] [Distribution]

Some files were not shown because too many files have changed in this diff Show More