Add Store support and unsigned app releases

This commit is contained in:
Tamas Csikel
2026-10-25 14:11:49 +01:00
parent 4975784491
commit d7e9fe4568
157 changed files with 22985 additions and 944 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).
# #
@@ -19,6 +19,10 @@ on:
- "tools/siri-remote/fastpair.py" - "tools/siri-remote/fastpair.py"
- ".gitea/workflows/packages.yml" - ".gitea/workflows/packages.yml"
workflow_dispatch: workflow_dispatch:
# Steam follows Valve's official steam-launcher package (tools/pkg/steam):
# look for a new one every Monday; nothing is built if it's published already.
schedule:
- cron: "17 4 * * 1"
jobs: jobs:
packages: packages:
@@ -43,8 +47,9 @@ jobs:
run: | run: |
export DEBIAN_FRONTEND=noninteractive export DEBIAN_FRONTEND=noninteractive
apt-get update -qq apt-get update -qq
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 gpgv dpkg \
libfontconfig1-dev libfreetype-dev libxkbcommon-dev libdbus-1-dev libudev-dev >/dev/null libfontconfig1-dev libfreetype-dev libxkbcommon-dev libdbus-1-dev libudev-dev \
libinput-dev libgbm-dev libseat-dev libdrm-dev libegl-dev >/dev/null
rm -rf /var/lib/apt/lists/* 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
/tmp/sf-build/cargo/bin/rustc --version /tmp/sf-build/cargo/bin/rustc --version

2
.gitignore vendored
View File

@@ -6,3 +6,5 @@
/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/

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

1357
Cargo.lock generated

File diff suppressed because it is too large Load Diff

View File

@@ -1,14 +1,15 @@
[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-pack", "crates/sf-ui", "crates/sf-ui/gallery", "crates/sf-launcher", "crates/sf-remote", "crates/sf-dial", "crates/sf-core", "crates/sf-update", "crates/sf-miracast", "crates/sf-compositor"]
[workspace.package] [workspace.package]
version = "0.1.0" version = "0.2.1"
edition = "2024" edition = "2024"
license = "MIT" license = "MIT"
[workspace.dependencies] [workspace.dependencies]
sf-ipc = { path = "crates/sf-ipc" } sf-ipc = { path = "crates/sf-ipc" }
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.

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, Home-ra fagyasztás, memóriafigyelés; 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.
@@ -49,8 +50,15 @@ A Netflex szerver a Netflex app beállítása (a Részletek lapon látszik), a c
```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 webapp 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/ manifestek, beállítások, IPC üzenetek (közös a daemonokkal)
@@ -59,7 +67,14 @@ tools/siri-remote/ párosítás (fastpair.py), nyers HID/btmon elemzők, host
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 appok: kind = "web" | "exec" | "builtin"
crates/sf-update/ csomag-frissítő (root): aláírt shell- és app-csomagok a Gitea registryből crates/sf-update/ csomag-frissítő (root): aláírt shell- és app-csomagok a Gitea registryből
és store appok a GitHub/Gitea/GitLab release-ekből
crates/sf-pack/ app-csomagoló fejlesztőknek: kulcs, csomag, aláírás, futtatás sandboxban
templates/rust-app/ sablon egy store apphoz Rustban, release pipeline-okkal
tools/pkg/ csomagok építése, aláírása, feltöltése (a CI is ezt futtatja) 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)
``` ```
**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/`).
@@ -74,7 +89,7 @@ tools/pkg/ csomagok építése, aláírása, feltöltése (a CI is ez
- 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.
@@ -96,7 +111,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.
@@ -158,6 +173,27 @@ Az image (a rendszer) csak újratelepítéssel változik. A részletek és a pro
- `image/secrets/update-token`: a TV-k csak olvasható registry-belépése (`fox-tv:<token>`); - `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. - a csomag-aláíró kulcs: `%USERPROFILE%\.smartfox\signing-key.pem` és a `SF_SIGNING_KEY` CI-secret.
## App Store és sandbox
**Store appok:** nyílt forrású, külső appok, mindegyik a saját GitHub-, Gitea/Forgejo- vagy GitLab-repójában. A release-eikből települnek, a szerzőjük kulcsával aláírva. A gyári appok maradnak ebben a repóban.
- **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.
- **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:** a Valve hivatalos `steam-launcher` csomagjából jön, előtelepítve.
- `gamescope`-ban fut, a kontrolleres felületével.
- `sf-app-steam` csomagként frissül: a CI hetente megnézi, van-e új hivatalos verzió.
**Rust (vagy bármilyen natív) app készítése:** [`templates/rust-app`](templates/rust-app).
- Az `sf-pack` eszköz kulcsot generál, csomagol és aláír.
- `sf-pack run <app-mappa>`: ugyanabban a sandboxban futtatja az appot, mint a TV.
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:
@@ -186,6 +222,50 @@ 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>`).
- **Home:** a kompozitor a launchert hozza elő, az app 0,6 mp múlva megfagy (`systemctl --user freeze`). Újra megnyitva azonnal folytatódik (`thaw`).
- **Memória:** legfeljebb 2 app vár a háttérben, a legrégebbi bezárul. Ha 400 MB alá esik a szabad memória, a legrégebbi háttérapp bezárul (értesítés jelenik meg).
- **cage alatt** (tartalék kompozitor) nem lehet ablakot váltani, ott Home bezárja az appot.
- **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 megfagy, a launcher értesítést mutat.
- A tükrözés végén minden visszaáll arra, ami előtte látszott.
**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. A többi app ablaka rejtve, lefagyva vár.
- 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.
## 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

@@ -12,4 +12,4 @@ order = 10
[web] [web]
# "SMART-TV" turns on the Netflex 10-foot UI (see packages/client/src/remote.ts → isTv). # "SMART-TV" turns on the Netflex 10-foot UI (see packages/client/src/remote.ts → isTv).
user_agent_suffix = "SMART-TV SmartFox/0.1" user_agent_suffix = "SMART-TV FennecOS/0.1"

21
apps/steam/app.toml Normal file
View File

@@ -0,0 +1,21 @@
id = "steam"
name = "Steam"
# Set by tools/pkg/steam/package.sh to the official steam-launcher version:
# the package (sf-app-steam) is rebuilt whenever Valve releases a new one.
version = "0.0.0"
kind = "exec"
category = "Játékok"
description = "A hivatalos Steam kliens, kontrollerrel kezelhető Big Picture felülettel. Az első indításkor letölti magát, ez néhány percig tart."
# gamescope (Valve's own compositor, as on the Steam Deck) hosts the X11
# Steam client and the games, and scales them to the TV.
exec = ["bin/smartfox-steam"]
icon = "steam"
accent = "#66C0F4"
palette = ["#66c0f4", "#1b4f7a", "#060b12"]
order = 25
[sandbox]
# Steam runs its games in its own container (pressure-vessel), nested in
# this sandbox. Its data, games included, are in the app's data folder
# (~/.local/share/smartfox/apps/steam).
permissions = ["network", "gpu", "audio", "gamepad", "dbus-session"]

View File

@@ -0,0 +1,24 @@
#!/bin/sh
# Starts the official Steam client (steam/, from Valve's steam-launcher
# package) in its gamepad UI, inside gamescope: the client and the games are
# X11 programs, gamescope gives them an X server and shows them as one
# Wayland window on the TV.
#
# Output: the TV's current mode. Games render at most at 1080p (an N100 can't
# do 4K) and gamescope scales them up.
APP="${SMARTFOX_APP_DIR:-$(cd "$(dirname "$0")/.." && pwd)}"
mode=$(wlr-randr 2>/dev/null | awk '/current/ {print $1; exit}')
W=${mode%x*}
H=${mode#*x}
case "$W:$H" in
*[!0-9:]* | :* | *:) W=1920 H=1080 ;;
esac
GW=$W GH=$H
if [ "$H" -gt 1080 ]; then
GW=$((W * 1080 / H))
GH=1080
fi
GAMESCOPE=$(command -v gamescope || echo /usr/games/gamescope)
exec "$GAMESCOPE" -e -f -W "$W" -H "$H" -w "$GW" -h "$GH" -- "$APP/steam/steam" -gamepadui "$@"

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

@@ -12,7 +12,7 @@ order = 20
[web] [web]
# A Cobalt (TV) user agent makes YouTube serve its leanback UI. # 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)" user_agent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0 Safari/537.36 Cobalt/25.lts.30.1034943-gold (unlike Gecko), Unknown_TV_Unknown_0/Unknown (Fennec OS, SF1, Wired)"
[dial] [dial]
name = "YouTube" name = "YouTube"

View File

@@ -0,0 +1,26 @@
[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]
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,112 @@
//! 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 output_mgmt;
#[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,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,962 @@
//! Compositor state: Wayland protocol handlers, which window is visible,
//! the switch animation, the volume OSD and the render element list.
use std::ffi::OsString;
use std::io::Write;
use std::sync::Arc;
use std::time::{Duration, Instant};
use smithay::backend::input::{Event, InputBackend, InputEvent, KeyState, KeyboardKeyEvent};
use smithay::backend::renderer::element::Kind;
use smithay::backend::renderer::element::solid::{SolidColorBuffer, SolidColorRenderElement};
use smithay::backend::renderer::element::surface::WaylandSurfaceRenderElement;
use smithay::backend::renderer::element::utils::RescaleRenderElement;
use smithay::backend::renderer::element::AsRenderElements;
use smithay::backend::renderer::gles::GlesRenderer;
use smithay::backend::renderer::utils::on_commit_buffer_handler;
use smithay::backend::session::Session;
use smithay::backend::session::libseat::LibSeatSession;
use smithay::desktop::{PopupKind, PopupManager, Space, Window, find_popup_root_surface, get_popup_toplevel_coords};
use smithay::input::keyboard::{FilterResult, XkbConfig, keysyms};
use smithay::input::{Seat, SeatHandler, SeatState};
use smithay::output::Output;
use smithay::reexports::calloop::generic::Generic;
use smithay::reexports::calloop::timer::{TimeoutAction, Timer};
use smithay::reexports::calloop::{EventLoop, Interest, LoopHandle, LoopSignal, Mode, PostAction};
use smithay::reexports::wayland_protocols::xdg::decoration::zv1::server::zxdg_toplevel_decoration_v1;
use smithay::reexports::wayland_protocols::xdg::shell::server::xdg_toplevel;
use smithay::reexports::wayland_server::backend::{ClientData, ClientId, DisconnectReason};
use smithay::reexports::wayland_server::protocol::{wl_buffer, wl_output, wl_seat, wl_surface::WlSurface};
use smithay::reexports::wayland_server::{Client, Display, DisplayHandle, Resource};
use smithay::utils::{IsAlive, Logical, Physical, Point, Rectangle, SERIAL_COUNTER, Scale, Serial, Size};
use smithay::wayland::buffer::BufferHandler;
use smithay::wayland::compositor::{
CompositorClientState, CompositorHandler, CompositorState, get_parent, is_sync_subsurface, with_states,
};
use smithay::wayland::dmabuf::{DmabufGlobal, DmabufHandler, DmabufState, ImportNotifier};
use smithay::wayland::output::{OutputHandler, OutputManagerState};
use smithay::wayland::selection::SelectionHandler;
use smithay::wayland::selection::data_device::{
ClientDndGrabHandler, DataDeviceHandler, DataDeviceState, ServerDndGrabHandler, set_data_device_focus,
};
use smithay::wayland::shell::xdg::decoration::{XdgDecorationHandler, XdgDecorationState};
use smithay::wayland::shell::xdg::{
PopupSurface, PositionerState, ToplevelSurface, XdgShellHandler, XdgShellState, XdgToplevelSurfaceData,
};
use smithay::wayland::shm::{ShmHandler, ShmState};
use smithay::wayland::socket::ListeningSocketSource;
use smithay::wayland::viewporter::ViewporterState;
use smithay::{
delegate_compositor, delegate_data_device, delegate_dmabuf, delegate_output, delegate_seat, delegate_shm,
delegate_viewporter, delegate_xdg_decoration, delegate_xdg_shell,
};
use crate::output_mgmt::{OutputMgmtState, PendingConfig};
/// App <-> launcher switch: the app fades in (growing a little) over the
/// launcher's splash, or fades out (shrinking) over the home screen.
const ENTER: Duration = Duration::from_millis(560);
const LEAVE: Duration = Duration::from_millis(420);
/// The launcher's launch morph (app.slint `launch-t`). An app coming up over
/// the launcher waits until the morph has nearly settled.
const MORPH: Duration = Duration::from_millis(720);
/// A new window's first frames are often blank; give it a moment.
const SETTLE: Duration = Duration::from_millis(250);
/// Longest wait for a browser window to finish loading its page.
const LOAD_TIMEOUT: Duration = Duration::from_secs(4);
/// How often a held-back app window is checked again.
const HOLD_POLL: Duration = Duration::from_millis(30);
const OSD_TIME: Duration = Duration::from_millis(1600);
/// evdev key codes + 8 (xkb keycodes).
const KEY_MUTE: u32 = 113 + 8;
const KEY_VOLUMEDOWN: u32 = 114 + 8;
const KEY_VOLUMEUP: u32 = 115 + 8;
const KEY_HOMEPAGE: u32 = 172 + 8;
smithay::backend::renderer::element::render_elements! {
pub SfElement<=GlesRenderer>;
Surface=WaylandSurfaceRenderElement<GlesRenderer>,
Scaled=RescaleRenderElement<WaylandSurfaceRenderElement<GlesRenderer>>,
Solid=SolidColorRenderElement,
}
/// The event loop data: protocol state plus the display backend.
pub struct App {
pub state: State,
pub backend: Backend,
}
pub enum Backend {
Winit(crate::winit::WinitData),
Udev(crate::udev::UdevData),
}
impl App {
/// Runs after every event loop dispatch.
pub fn after_dispatch(&mut self) {
// Output configuration requests (wlr-randr) need the backend.
for cfg in std::mem::take(&mut self.state.pending_configs) {
let result = match &mut self.backend {
Backend::Winit(w) => w.apply_config(&mut self.state, &cfg),
Backend::Udev(u) => u.apply_config(&mut self.state, &cfg),
};
match result {
Ok(()) => {
cfg.succeeded();
self.state.output_mgmt_refresh();
}
Err(e) => {
tracing::warn!("output configuration failed: {e:#}");
cfg.failed();
}
}
}
if let Backend::Udev(u) = &mut self.backend {
u.kick(&mut self.state);
}
self.state.space.refresh();
self.state.popups.cleanup();
let _ = self.state.dh.flush_clients();
}
}
/// What sf-core wants on screen.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Target {
Launcher,
App(String),
}
pub struct Win {
pub window: Window,
/// The app the client belongs to; None for the launcher (system UI).
pub app: Option<String>,
pub pid: Option<i32>,
/// Has a buffer, can be shown.
pub mapped: bool,
pub mapped_at: Option<Instant>,
pub serial: u64,
}
/// `over` zooms/fades in on top of `under` (entering) or out of it (leaving).
pub struct Transition {
pub over: Window,
pub under: Option<Window>,
pub start: Instant,
pub duration: Duration,
pub entering: bool,
}
pub struct Osd {
pub level: f32,
pub muted: bool,
pub until: Instant,
}
pub struct State {
pub dh: DisplayHandle,
pub handle: LoopHandle<'static, App>,
pub loop_signal: LoopSignal,
pub socket_name: OsString,
pub start: Instant,
pub compositor_state: CompositorState,
pub xdg_shell_state: XdgShellState,
pub shm_state: ShmState,
// Kept for their globals.
#[allow(dead_code)]
pub output_manager_state: OutputManagerState,
pub seat_state: SeatState<State>,
pub data_device_state: DataDeviceState,
pub dmabuf_state: DmabufState,
pub dmabuf_global: Option<DmabufGlobal>,
#[allow(dead_code)]
pub viewporter_state: ViewporterState,
#[allow(dead_code)]
pub decoration_state: XdgDecorationState,
pub output_mgmt: OutputMgmtState,
pub pending_configs: Vec<PendingConfig>,
pub popups: PopupManager,
pub seat: Seat<State>,
pub space: Space<Window>,
pub session: Option<LibSeatSession>,
pub output: Option<Output>,
pub wins: Vec<Win>,
/// Process groups of apps, from sf-core (`register`).
pub registered: std::collections::HashMap<i32, String>,
serial: u64,
pub target: Target,
/// When `target` last changed (the launcher starts its morph then).
target_at: Instant,
/// An app window that could be shown but waits for the launcher's
/// morph and for its own first real frame.
held: Option<Window>,
hold_poll: bool,
pub visible: Option<Window>,
pub transition: Option<Transition>,
pub osd: Option<Osd>,
osd_bg: SolidColorBuffer,
osd_track: SolidColorBuffer,
osd_fill: SolidColorBuffer,
/// False while the screen is turned off (wlr-randr --off / standby).
pub screen_on: bool,
}
#[derive(Default)]
pub struct ClientState {
pub compositor_state: CompositorClientState,
}
impl ClientData for ClientState {
fn initialized(&self, _client_id: ClientId) {}
fn disconnected(&self, _client_id: ClientId, _reason: DisconnectReason) {}
}
/// Process group of a pid (field 5 of /proc/<pid>/stat).
fn pgid_of(pid: i32) -> Option<i32> {
let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
// The command name may contain spaces; fields start after the last ')'.
let rest = &stat[stat.rfind(')')? + 1..];
rest.split_whitespace().nth(2)?.parse().ok()
}
/// The app a client process belongs to:
/// 1. its process group, as registered by sf-core (`register <pgid> <app>`);
/// 2. its systemd scope (`sf-app-<id>-<n>.scope`);
/// 3. `SMARTFOX_APP` in its environment (Chromium overwrites that area, so
/// this only works for simple programs like UxPlay).
fn app_of_pid(pid: i32, registered: &std::collections::HashMap<i32, String>) -> Option<String> {
if let Some(app) = pgid_of(pid).and_then(|g| registered.get(&g)) {
return Some(app.clone());
}
if let Ok(cg) = std::fs::read_to_string(format!("/proc/{pid}/cgroup")) {
for unit in cg.split(['/', '\n']) {
if let Some(rest) = unit.strip_prefix("sf-app-").and_then(|u| u.strip_suffix(".scope")) {
if let Some((id, _serial)) = rest.rsplit_once('-') {
return Some(id.to_string());
}
}
}
}
let env = std::fs::read(format!("/proc/{pid}/environ")).ok()?;
let key = format!("{}=", sf_ipc::launch::APP_ENV);
env.split(|b| *b == 0)
.find_map(|kv| kv.strip_prefix(key.as_bytes()))
.map(|v| String::from_utf8_lossy(v).into_owned())
.filter(|v| !v.is_empty())
}
fn ease_out(t: f32) -> f32 {
1.0 - (1.0 - t.clamp(0.0, 1.0)).powi(3)
}
/// Slow start and end: a crossfade you can see, not a cut.
fn ease_in_out(t: f32) -> f32 {
let t = t.clamp(0.0, 1.0);
if t < 0.5 { 4.0 * t * t * t } else { 1.0 - (-2.0 * t + 2.0).powi(3) / 2.0 }
}
/// Whether a window has something worth showing. Browsers show the URL as
/// their title until the page has loaded and set its own.
fn page_loaded(window: &Window) -> bool {
let Some(toplevel) = window.toplevel() else { return true };
let (title, app_id) = with_states(toplevel.wl_surface(), |states| {
states
.data_map
.get::<XdgToplevelSurfaceData>()
.map(|d| {
let d = d.lock().unwrap();
(d.title.clone().unwrap_or_default(), d.app_id.clone().unwrap_or_default().to_lowercase())
})
.unwrap_or_default()
});
let browser = app_id.contains("chrom") || app_id.contains("edge");
let url_like = !title.contains(' ') && (title.contains('/') || title.contains('.') || title.contains(':'));
!browser || !(title.is_empty() || title.contains("about:blank") || url_like)
}
impl State {
pub fn new(event_loop: &mut EventLoop<'static, App>, display: Display<State>) -> anyhow::Result<Self> {
let dh = display.handle();
let compositor_state = CompositorState::new::<Self>(&dh);
let xdg_shell_state = XdgShellState::new::<Self>(&dh);
let shm_state = ShmState::new::<Self>(&dh, vec![]);
let output_manager_state = OutputManagerState::new_with_xdg_output::<Self>(&dh);
let mut seat_state = SeatState::new();
let data_device_state = DataDeviceState::new::<Self>(&dh);
let viewporter_state = ViewporterState::new::<Self>(&dh);
let decoration_state = XdgDecorationState::new::<Self>(&dh);
let output_mgmt = OutputMgmtState::new(&dh);
let mut seat: Seat<Self> = seat_state.new_wl_seat(&dh, "seat0");
// Same repeat as cage/wlroots: 600 ms delay, 25 per second.
seat.add_keyboard(XkbConfig::default(), 600, 25)
.map_err(|e| anyhow::anyhow!("keyboard: {e:?}"))?;
let socket = ListeningSocketSource::new_auto()?;
let socket_name = socket.socket_name().to_os_string();
let handle = event_loop.handle();
handle
.insert_source(socket, |stream, _, app: &mut App| {
if let Err(e) = app.state.dh.insert_client(stream, Arc::new(ClientState::default())) {
tracing::warn!("client: {e}");
}
})
.map_err(|e| anyhow::anyhow!("socket source: {e}"))?;
handle
.insert_source(Generic::new(display, Interest::READ, Mode::Level), |_, display, app: &mut App| {
// SAFETY: the display is not dropped while the source lives.
unsafe {
display.get_mut().dispatch_clients(&mut app.state).ok();
}
Ok(PostAction::Continue)
})
.map_err(|e| anyhow::anyhow!("display source: {e}"))?;
Ok(State {
dh,
handle,
loop_signal: event_loop.get_signal(),
socket_name,
start: Instant::now(),
compositor_state,
xdg_shell_state,
shm_state,
output_manager_state,
seat_state,
data_device_state,
dmabuf_state: DmabufState::new(),
dmabuf_global: None,
viewporter_state,
decoration_state,
output_mgmt,
pending_configs: vec![],
popups: PopupManager::default(),
seat,
space: Space::default(),
session: None,
output: None,
wins: vec![],
registered: Default::default(),
serial: 0,
target: Target::Launcher,
target_at: Instant::now(),
held: None,
hold_poll: false,
visible: None,
transition: None,
osd: None,
osd_bg: SolidColorBuffer::default(),
osd_track: SolidColorBuffer::default(),
osd_fill: SolidColorBuffer::default(),
screen_on: true,
})
}
pub fn output_size(&self) -> Size<i32, Physical> {
self.output
.as_ref()
.and_then(|o| o.current_mode())
.map(|m| m.size)
.unwrap_or_else(|| (1920, 1080).into())
}
/// A new or changed output: everyone gets its size.
pub fn set_output(&mut self, output: Option<Output>) {
if let Some(old) = self.output.take() {
self.space.unmap_output(&old);
}
if let Some(o) = &output {
self.space.map_output(o, (0, 0));
}
self.output = output;
self.reconfigure_all();
self.output_mgmt_refresh();
}
pub fn reconfigure_all(&mut self) {
let wins: Vec<Window> = self.wins.iter().map(|w| w.window.clone()).collect();
for w in wins {
self.configure(&w);
}
}
/// Full screen at the output size; activated if visible.
fn configure(&self, window: &Window) {
let Some(toplevel) = window.toplevel() else { return };
let size = self.output_size();
let active = self.visible.as_ref() == Some(window);
toplevel.with_pending_state(|s| {
s.size = Some((size.w, size.h).into());
s.states.set(xdg_toplevel::State::Fullscreen);
if active {
s.states.set(xdg_toplevel::State::Activated);
} else {
s.states.unset(xdg_toplevel::State::Activated);
}
s.decoration_mode = Some(zxdg_toplevel_decoration_v1::Mode::ServerSide);
});
if toplevel.is_initial_configure_sent() {
toplevel.send_pending_configure();
}
}
fn win_of(&self, window: &Window) -> Option<&Win> {
self.wins.iter().find(|w| &w.window == window)
}
pub fn app_of_window(&self, window: &Window) -> Option<String> {
self.win_of(window).and_then(|w| w.app.clone())
}
fn find_visible(&self) -> Option<Window> {
let pick = |pred: &dyn Fn(&Win) -> bool| {
self.wins.iter().filter(|w| w.mapped && pred(w)).max_by_key(|w| w.serial).map(|w| w.window.clone())
};
let launcher = || pick(&|w| w.app.is_none());
match &self.target {
Target::App(id) => pick(&|w| w.app.as_deref() == Some(id.as_str())).or_else(launcher),
Target::Launcher => launcher(),
}
.or_else(|| pick(&|_| true))
}
/// sf-core started an app in process group `pgid`. Windows that showed
/// up before this arrived are reassigned.
pub fn register(&mut self, pgid: i32, app: String) {
self.registered.retain(|g, _| std::path::Path::new(&format!("/proc/{g}")).exists());
self.registered.insert(pgid, app.clone());
let mut changed = false;
for w in self.wins.iter_mut() {
if w.app.is_none() && w.pid.and_then(pgid_of) == Some(pgid) {
tracing::info!("window of pid {:?} belongs to {app}", w.pid);
w.app = Some(app.clone());
changed = true;
}
}
if changed {
self.update_visible();
}
}
pub fn set_target(&mut self, target: Target) {
tracing::info!("focus {target:?}");
if target != self.target {
self.target_at = Instant::now();
}
self.target = target;
self.update_visible();
}
/// Recomputes the visible window; animates the change.
pub fn update_visible(&mut self) {
let new = self.find_visible();
if self.held.is_some() && self.held != new {
self.held = None;
}
if new == self.visible {
return;
}
if let Some(wait) = new.as_ref().and_then(|n| self.reveal_wait(n)) {
// Not yet: the launcher's splash stays up (and keeps the focus,
// so Back still cancels). The app gets frame callbacks meanwhile.
self.held = new;
self.poll_held(wait.min(HOLD_POLL));
return;
}
self.held = None;
let old = self.visible.take();
let to_launcher = new.as_ref().is_some_and(|w| self.app_of_window(w).is_none());
let from_app = old.as_ref().is_some_and(|w| self.app_of_window(w).is_some());
self.transition = match (&old, &new) {
// Home: the app shrinks away, revealing the launcher.
(Some(o), Some(n)) if to_launcher && from_app && o.alive() => Some(Transition {
over: o.clone(),
under: Some(n.clone()),
start: Instant::now(),
duration: LEAVE,
entering: false,
}),
(o, Some(n)) => Some(Transition {
over: n.clone(),
under: o.clone().filter(|w| w.alive()),
start: Instant::now(),
duration: ENTER,
entering: true,
}),
_ => None,
};
self.visible = new.clone();
tracing::info!(
"visible: {}",
match &new {
Some(w) => self.app_of_window(w).unwrap_or_else(|| "launcher".into()),
None => "nothing".into(),
}
);
let serial = SERIAL_COUNTER.next_serial();
let focus = new.as_ref().and_then(|w| w.toplevel()).map(|t| t.wl_surface().clone());
if let Some(kb) = self.seat.get_keyboard() {
kb.set_focus(self, focus, serial);
}
for w in [old, new].into_iter().flatten() {
w.set_activated(self.visible.as_ref() == Some(&w));
self.configure(&w);
}
}
/// How long an app window should stay hidden: until the launcher's morph
/// is done (when it comes up over the launcher), it has drawn for a
/// moment, and its page has loaded (or that timed out).
fn reveal_wait(&self, window: &Window) -> Option<Duration> {
let win = self.win_of(window)?;
win.app.as_ref()?;
let mapped_at = win.mapped_at?;
let over_launcher = self.visible.as_ref().is_some_and(|v| self.app_of_window(v).is_none());
let mut ready_at = mapped_at + SETTLE;
if over_launcher {
ready_at = ready_at.max(self.target_at + MORPH);
}
if !page_loaded(window) {
ready_at = ready_at.max(mapped_at + LOAD_TIMEOUT);
}
let now = Instant::now();
(ready_at > now).then(|| ready_at - now)
}
fn poll_held(&mut self, after: Duration) {
if self.hold_poll {
return;
}
self.hold_poll = true;
let _ = self.handle.insert_source(Timer::from_duration(after), |_, _, app: &mut App| {
app.state.hold_poll = false;
if app.state.held.is_some() {
app.state.update_visible();
}
TimeoutAction::Drop
});
}
fn surface_window(&self, surface: &WlSurface) -> Option<Window> {
self.wins.iter().find(|w| w.window.toplevel().is_some_and(|t| t.wl_surface() == surface)).map(|w| w.window.clone())
}
// ---- input ----------------------------------------------------------
pub fn handle_input<B: InputBackend>(&mut self, event: InputEvent<B>) {
let InputEvent::Keyboard { event } = event else { return };
let serial = SERIAL_COUNTER.next_serial();
let time = Event::time_msec(&event);
let pressed = event.state() == KeyState::Pressed;
let Some(kb) = self.seat.get_keyboard() else { return };
enum Action {
Home,
Volume(i32),
Mute,
Vt(i32),
Quit,
/// Release or repeat of a key we handle: keep it from the app.
Swallow,
}
let action = kb.input::<Action, _>(self, event.key_code(), event.state(), serial, time, |_, mods, key| {
let code = key.raw_code().raw();
let sym = key.modified_sym().raw();
let hit = match code {
KEY_HOMEPAGE => Some(Action::Home),
KEY_VOLUMEUP => Some(Action::Volume(5)),
KEY_VOLUMEDOWN => Some(Action::Volume(-5)),
KEY_MUTE => Some(Action::Mute),
_ if (keysyms::KEY_XF86Switch_VT_1..=keysyms::KEY_XF86Switch_VT_12).contains(&sym) => {
Some(Action::Vt((sym - keysyms::KEY_XF86Switch_VT_1 + 1) as i32))
}
_ if mods.ctrl && mods.alt && sym == keysyms::KEY_BackSpace => Some(Action::Quit),
_ => None,
};
match hit {
Some(a) if pressed => FilterResult::Intercept(a),
// Swallow the release (and repeats) of keys we handle.
Some(_) => FilterResult::Intercept(Action::Swallow),
None => FilterResult::Forward,
}
});
match action {
Some(Action::Home) => send_home(),
Some(Action::Volume(d)) => self.change_volume(Some(d)),
Some(Action::Mute) => self.change_volume(None),
Some(Action::Vt(n)) => {
if let Some(s) = self.session.as_mut() {
if let Err(e) = s.change_vt(n) {
tracing::warn!("change vt {n}: {e}");
}
}
}
Some(Action::Quit) => {
tracing::info!("ctrl+alt+backspace: quitting");
self.loop_signal.stop();
}
Some(Action::Swallow) | None => {}
}
}
/// Volume up/down by `delta` percent, or toggle mute (`None`), then show the OSD.
fn change_volume(&mut self, delta: Option<i32>) {
let (tx, rx) = smithay::reexports::calloop::channel::channel::<(f32, bool)>();
std::thread::spawn(move || {
let sink = "@DEFAULT_AUDIO_SINK@";
let _ = match delta {
Some(d) => {
let arg = format!("{}%{}", d.abs(), if d > 0 { "+" } else { "-" });
std::process::Command::new("wpctl").args(["set-mute", sink, "0"]).status().ok();
std::process::Command::new("wpctl").args(["set-volume", "-l", "1.0", sink, &arg]).status()
}
None => std::process::Command::new("wpctl").args(["set-mute", sink, "toggle"]).status(),
};
let out = std::process::Command::new("wpctl").args(["get-volume", sink]).output();
let text = out.map(|o| String::from_utf8_lossy(&o.stdout).into_owned()).unwrap_or_default();
// "Volume: 0.45" or "Volume: 0.45 [MUTED]"
let level = text.split_whitespace().nth(1).and_then(|v| v.parse::<f32>().ok()).unwrap_or(0.0);
let _ = tx.send((level, text.contains("MUTED")));
});
let _ = self.handle.insert_source(rx, |ev, _, app: &mut App| {
if let smithay::reexports::calloop::channel::Event::Msg((level, muted)) = ev {
app.state.osd = Some(Osd { level, muted, until: Instant::now() + OSD_TIME });
}
});
}
// ---- rendering ------------------------------------------------------
fn window_elements(&self, renderer: &mut GlesRenderer, window: &Window, alpha: f32) -> Vec<WaylandSurfaceRenderElement<GlesRenderer>> {
let origin: Point<i32, Logical> = (0, 0).into();
let loc: Point<i32, Physical> = (origin - window.geometry().loc).to_physical_precise_round(1.0);
window.render_elements(renderer, loc, Scale::from(1.0), alpha)
}
/// Render elements, front to back.
pub fn elements(&mut self, renderer: &mut GlesRenderer) -> Vec<SfElement> {
let mut out: Vec<SfElement> = vec![];
if !self.screen_on {
return out;
}
let size = self.output_size();
let now = Instant::now();
// Volume OSD: a pill near the bottom with a level bar.
if let Some(osd) = &self.osd {
if now < osd.until {
let fade = ((osd.until - now).as_secs_f32() / 0.3).min(1.0);
let (w, h) = (size.w as f32, size.h as f32);
let bar_w = (w * 0.26) as i32;
let bar_h = (h * 0.010).max(8.0) as i32;
let pad = (h * 0.022) as i32;
let x = (size.w - bar_w) / 2;
let y = (h * 0.86) as i32;
let fill_w = ((bar_w as f32) * osd.level.clamp(0.0, 1.0)) as i32;
let fill = if osd.muted { [1.0, 0.42, 0.42, 0.95] } else { [1.0, 1.0, 1.0, 0.95] };
self.osd_fill.update((fill_w.max(1), bar_h), fill);
self.osd_track.update((bar_w, bar_h), [1.0, 1.0, 1.0, 0.22]);
self.osd_bg.update((bar_w + 2 * pad, bar_h + 2 * pad), [0.04, 0.05, 0.08, 0.72]);
out.push(SolidColorRenderElement::from_buffer(&self.osd_fill, (x, y), 1.0, fade, Kind::Unspecified).into());
out.push(SolidColorRenderElement::from_buffer(&self.osd_track, (x, y), 1.0, fade, Kind::Unspecified).into());
out.push(SolidColorRenderElement::from_buffer(&self.osd_bg, (x - pad, y - pad), 1.0, fade, Kind::Unspecified).into());
} else {
self.osd = None;
}
}
let done = self.transition.as_ref().is_some_and(|t| now - t.start >= t.duration || !t.over.alive());
if done {
self.transition = None;
}
let center: Point<i32, Physical> = (size.w / 2, size.h / 2).into();
match &self.transition {
Some(t) => {
let x = (now - t.start).as_secs_f32() / t.duration.as_secs_f32();
let (fade, grow) = (ease_in_out(x), ease_out(x));
let (alpha, scale) = if t.entering { (fade, 0.965 + 0.035 * grow) } else { (1.0 - fade, 1.0 - 0.05 * grow) };
let over = t.over.clone();
let under = t.under.clone();
for el in self.window_elements(renderer, &over, alpha) {
out.push(RescaleRenderElement::from_element(el, center, scale as f64).into());
}
if let Some(u) = under.filter(|u| u.alive()) {
out.extend(self.window_elements(renderer, &u, 1.0).into_iter().map(SfElement::from));
}
}
None => {
if let Some(v) = self.visible.clone() {
out.extend(self.window_elements(renderer, &v, 1.0).into_iter().map(SfElement::from));
}
}
}
out
}
/// Frame callbacks for what is on screen (hidden apps get none, so they idle).
pub fn send_frames(&self) {
let Some(output) = self.output.as_ref() else { return };
let time = self.start.elapsed();
// The held-back app draws too, so its page is ready when it shows.
let mut shown: Vec<&Window> = self.visible.iter().chain(self.held.iter()).collect();
if let Some(t) = &self.transition {
shown.push(&t.over);
shown.extend(t.under.iter());
}
for w in shown {
w.send_frame(output, time, Some(Duration::ZERO), |_, _| Some(output.clone()));
}
}
pub fn output_mgmt_refresh(&mut self) {
let info = crate::output_mgmt::HeadInfo::from_state(self);
self.output_mgmt.update(&self.dh, info);
}
fn unconstrain_popup(&self, popup: &PopupSurface) {
let Ok(root) = find_popup_root_surface(&PopupKind::Xdg(popup.clone())) else { return };
let Some(window) = self.surface_window(&root) else { return };
let size = self.output_size();
let mut target = Rectangle::new((0, 0).into(), (size.w, size.h).into());
target.loc -= get_popup_toplevel_coords(&PopupKind::Xdg(popup.clone()));
target.loc += window.geometry().loc;
popup.with_pending_state(|state| {
state.geometry = state.positioner.get_unconstrained_geometry(target);
});
}
}
/// The launcher decides what Home means (it tells sf-core).
pub fn send_home() {
std::thread::spawn(|| {
let path = sf_ipc::paths::launcher_socket();
match std::os::unix::net::UnixStream::connect(&path) {
Ok(mut s) => {
let _ = s.write_all(b"home\n");
}
Err(e) => tracing::warn!("home: {}: {e}", path.display()),
}
});
}
// ---- protocol handlers ------------------------------------------------------
impl CompositorHandler for State {
fn compositor_state(&mut self) -> &mut CompositorState {
&mut self.compositor_state
}
fn client_compositor_state<'a>(&self, client: &'a Client) -> &'a CompositorClientState {
&client.get_data::<ClientState>().unwrap().compositor_state
}
fn commit(&mut self, surface: &WlSurface) {
on_commit_buffer_handler::<Self>(surface);
if !is_sync_subsurface(surface) {
let mut root = surface.clone();
while let Some(parent) = get_parent(&root) {
root = parent;
}
if let Some(window) = self.surface_window(&root) {
window.on_commit();
}
}
// Toplevels: initial configure, then "mapped" once a buffer arrives.
if let Some(window) = self.surface_window(surface) {
let toplevel = window.toplevel().unwrap();
let initial_sent = with_states(surface, |states| {
states
.data_map
.get::<XdgToplevelSurfaceData>()
.map(|d| d.lock().unwrap().initial_configure_sent)
.unwrap_or(true)
});
if !initial_sent {
self.configure(&window);
toplevel.send_configure();
}
let has_buffer = window.bbox().size.w > 0;
let newly_mapped = match self.wins.iter_mut().find(|w| w.window == window) {
Some(w) if !w.mapped && has_buffer => {
w.mapped = true;
w.mapped_at = Some(Instant::now());
Some(w.app.clone())
}
_ => None,
};
if let Some(app) = newly_mapped {
tracing::info!("mapped: {}", app.as_deref().unwrap_or("launcher"));
match app {
// A new app window comes to the front (like cage).
Some(id) => self.set_target(Target::App(id)),
None => self.update_visible(),
}
}
}
self.popups.commit(surface);
if let Some(PopupKind::Xdg(xdg)) = self.popups.find_popup(surface) {
if !xdg.is_initial_configure_sent() {
let _ = xdg.send_configure();
}
}
}
}
impl BufferHandler for State {
fn buffer_destroyed(&mut self, _buffer: &wl_buffer::WlBuffer) {}
}
impl ShmHandler for State {
fn shm_state(&self) -> &ShmState {
&self.shm_state
}
}
impl XdgShellHandler for State {
fn xdg_shell_state(&mut self) -> &mut XdgShellState {
&mut self.xdg_shell_state
}
fn new_toplevel(&mut self, surface: ToplevelSurface) {
let pid = surface.wl_surface().client().and_then(|c| c.get_credentials(&self.dh).ok()).map(|c| c.pid);
let app = pid.and_then(|p| app_of_pid(p, &self.registered));
tracing::info!("new window: pid {pid:?}, app {}", app.as_deref().unwrap_or("launcher"));
let window = Window::new_wayland_window(surface);
self.space.map_element(window.clone(), (0, 0), false);
self.serial += 1;
self.wins.push(Win { window: window.clone(), app, pid, mapped: false, mapped_at: None, serial: self.serial });
self.configure(&window);
}
fn toplevel_destroyed(&mut self, surface: ToplevelSurface) {
let Some(window) = self.surface_window(surface.wl_surface()) else { return };
tracing::info!("window closed: {}", self.app_of_window(&window).unwrap_or_else(|| "launcher".into()));
self.space.unmap_elem(&window);
self.wins.retain(|w| w.window != window);
if self.transition.as_ref().is_some_and(|t| t.over == window || t.under.as_ref() == Some(&window)) {
self.transition = None;
}
if self.held.as_ref() == Some(&window) {
self.held = None;
}
if self.visible.as_ref() == Some(&window) {
self.visible = None;
// The app is gone: back to the launcher unless sf-core says otherwise.
if let Target::App(id) = &self.target {
if !self.wins.iter().any(|w| w.mapped && w.app.as_deref() == Some(id.as_str())) {
self.target = Target::Launcher;
}
}
self.update_visible();
}
}
fn new_popup(&mut self, surface: PopupSurface, _positioner: PositionerState) {
self.unconstrain_popup(&surface);
let _ = self.popups.track_popup(PopupKind::Xdg(surface));
}
fn reposition_request(&mut self, surface: PopupSurface, positioner: PositionerState, token: u32) {
surface.with_pending_state(|state| {
state.geometry = positioner.get_geometry();
state.positioner = positioner;
});
self.unconstrain_popup(&surface);
surface.send_repositioned(token);
}
fn grab(&mut self, _surface: PopupSurface, _seat: wl_seat::WlSeat, _serial: Serial) {}
fn fullscreen_request(&mut self, surface: ToplevelSurface, _output: Option<wl_output::WlOutput>) {
if let Some(w) = self.surface_window(surface.wl_surface()) {
self.configure(&w);
}
}
fn unfullscreen_request(&mut self, surface: ToplevelSurface) {
if let Some(w) = self.surface_window(surface.wl_surface()) {
self.configure(&w);
}
}
fn maximize_request(&mut self, surface: ToplevelSurface) {
if let Some(w) = self.surface_window(surface.wl_surface()) {
self.configure(&w);
}
}
}
impl XdgDecorationHandler for State {
fn new_decoration(&mut self, toplevel: ToplevelSurface) {
toplevel.with_pending_state(|s| s.decoration_mode = Some(zxdg_toplevel_decoration_v1::Mode::ServerSide));
}
fn request_mode(&mut self, toplevel: ToplevelSurface, _mode: zxdg_toplevel_decoration_v1::Mode) {
toplevel.with_pending_state(|s| s.decoration_mode = Some(zxdg_toplevel_decoration_v1::Mode::ServerSide));
if toplevel.is_initial_configure_sent() {
toplevel.send_pending_configure();
}
}
fn unset_mode(&mut self, toplevel: ToplevelSurface) {
self.request_mode(toplevel, zxdg_toplevel_decoration_v1::Mode::ServerSide);
}
}
impl SeatHandler for State {
type KeyboardFocus = WlSurface;
type PointerFocus = WlSurface;
type TouchFocus = WlSurface;
fn seat_state(&mut self) -> &mut SeatState<State> {
&mut self.seat_state
}
fn focus_changed(&mut self, seat: &Seat<Self>, focused: Option<&WlSurface>) {
let client = focused.and_then(|s| self.dh.get_client(s.id()).ok());
set_data_device_focus(&self.dh, seat, client);
}
}
impl SelectionHandler for State {
type SelectionUserData = ();
}
impl DataDeviceHandler for State {
fn data_device_state(&self) -> &DataDeviceState {
&self.data_device_state
}
}
impl ClientDndGrabHandler for State {}
impl ServerDndGrabHandler for State {}
impl OutputHandler for State {}
impl DmabufHandler for State {
fn dmabuf_state(&mut self) -> &mut DmabufState {
&mut self.dmabuf_state
}
fn dmabuf_imported(
&mut self,
_global: &DmabufGlobal,
_dmabuf: smithay::backend::allocator::dmabuf::Dmabuf,
notifier: ImportNotifier,
) {
// Formats come from the renderer; a bad buffer shows up when drawn.
let _ = notifier.successful::<State>();
}
}
delegate_compositor!(State);
delegate_shm!(State);
delegate_xdg_shell!(State);
delegate_xdg_decoration!(State);
delegate_seat!(State);
delegate_data_device!(State);
delegate_output!(State);
delegate_dmabuf!(State);
delegate_viewporter!(State);

View File

@@ -0,0 +1,391 @@
//! 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, 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::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_server::backend::GlobalId;
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>;
const FORMATS: &[Fourcc] = &[Fourcc::Argb8888, Fourcc::Abgr8888, Fourcc::Xrgb8888];
struct Out {
drm_output: DrmOutput<Allocator, Exporter, (), 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, (), DrmDeviceFd>,
renderer: GlesRenderer,
out: Option<Out>,
active: bool,
/// A render is queued on a timer (no damage last time).
retry_scheduled: bool,
}
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 = primary_gpu(&seat)?
.or_else(|| all_gpus(&seat).ok()?.into_iter().next())
.context("no GPU found")?;
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();
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, _, app: &mut App| match event {
DrmEvent::VBlank(_crtc) => {
if let Backend::Udev(u) = &mut app.backend {
u.frame_done(&mut app.state);
}
}
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) {
let Some(out) = self.out.as_mut() else { return };
if let Err(e) = out.drm_output.frame_submitted() {
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 rendered {
match out.drm_output.queue_frame(()) {
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,110 @@
//! 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::utils::Transform;
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 = match w.backend.bind() {
Ok((renderer, mut fb)) => {
let elements = app.state.elements(renderer);
match w.damage.render_output(renderer, &mut fb, age, &elements, [0.0, 0.0, 0.0, 1.0]) {
Ok(r) => r.damage.cloned(),
Err(e) => {
tracing::warn!("render: {e:?}");
None
}
}
}
Err(e) => {
tracing::warn!("bind: {e:?}");
None
}
};
if let Some(damage) = damage {
if let Err(e) = w.backend.submit(Some(&damage)) {
tracing::warn!("submit: {e:?}");
}
}
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(())
}
}

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

@@ -0,0 +1,18 @@
[package]
name = "sf-core"
description = "Fennec OS core daemon: app lifecycle (systemd scopes, freeze/thaw), 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"

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

@@ -0,0 +1,493 @@
//! App lifecycle: start, bring to front, send to the background (freeze),
//! close. One app is in the foreground; with sf-compositor the others wait
//! frozen in the background, under cage they are closed.
use std::os::unix::process::CommandExt;
use std::path::PathBuf;
use std::process::Command as StdCommand;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use anyhow::{Context, Result, bail};
use sf_ipc::launch::{LaunchOptions, command};
use sf_ipc::{AppKind, AppManifest, CoreEvent, Settings};
use tokio::sync::broadcast;
use crate::wm;
/// Frozen apps kept in the background; the oldest beyond this is closed.
const MAX_BACKGROUND: usize = 2;
/// Below this much available memory the oldest frozen app is closed.
const LOW_MEMORY_KB: u64 = 400 * 1024;
/// Freeze only after the compositor's switch animation has finished.
const FREEZE_DELAY: Duration = Duration::from_millis(600);
struct Running {
id: String,
pid: u32,
/// systemd scope (`sf-app-<id>-<n>.scope`), if scopes are used.
unit: Option<String>,
frozen: bool,
last_used: Instant,
serial: u64,
}
#[derive(Default)]
struct State {
apps: Vec<AppManifest>,
running: Vec<Running>,
foreground: Option<String>,
serial: u64,
/// While a cast window is up: what to show when it ends (None: launcher).
cast_return: Option<Option<String>>,
}
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(())
}
fn mem_available_kb() -> Option<u64> {
let text = std::fs::read_to_string("/proc/meminfo").ok()?;
let line = text.lines().find(|l| l.starts_with("MemAvailable:"))?;
line.split_whitespace().nth(1)?.parse().ok()
}
impl Core {
pub fn new(apps_dirs: Vec<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;
}
let switching = wm::available();
// Already running: thaw and show it.
let existing = {
let st = self.state.lock().unwrap();
st.running.iter().find(|r| r.id == id).map(|r| (r.unit.clone(), r.pid, r.frozen))
};
if let Some((unit, pid, frozen)) = existing {
if frozen {
self.thaw(id, unit.as_deref(), pid).await;
}
let prev = self.set_foreground(Some(id));
self.leave_foreground(prev, switching);
wm::focus(Some(id));
self.emit(CoreEvent::AppStarted { app_id: id.to_string(), cast });
return Ok(());
}
let prev = self.set_foreground(None);
self.leave_foreground(prev, switching);
if !switching {
// Under cage only the newest window shows; don't leave others running.
let others: Vec<String> = self.state.lock().unwrap().running.iter().map(|r| r.id.clone()).collect();
for other in others {
self.stop(&other);
}
}
self.spawn(&app, query.as_deref())?;
self.set_foreground(Some(id));
wm::focus(Some(id));
self.emit(CoreEvent::AppStarted { app_id: id.to_string(), cast });
self.enforce_background_limit();
Ok(())
}
fn set_foreground(&self, id: Option<&str>) -> Option<String> {
let mut st = self.state.lock().unwrap();
if let Some(id) = id {
if let Some(r) = st.running.iter_mut().find(|r| r.id == id) {
r.last_used = Instant::now();
}
}
let prev = std::mem::replace(&mut st.foreground, id.map(str::to_string));
prev.filter(|p| Some(p.as_str()) != id)
}
/// The previous foreground app goes to the background (or is closed
/// when the compositor can't keep it there).
fn leave_foreground(self: &Arc<Self>, prev: Option<String>, switching: bool) {
let Some(prev) = prev else { return };
if switching {
self.freeze_later(prev);
} else {
self.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,
frozen: false,
last_used: Instant::now(),
serial,
});
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;
}
if let Some(Some(ret)) = &st.cast_return {
if ret == id {
st.cast_return = Some(None);
}
}
fg
};
if was_foreground {
wm::focus(None);
}
self.emit(CoreEvent::AppStopped { app_id: id.to_string() });
}
/// Home: show the launcher; the foreground app waits frozen (or closes).
pub fn go_home(self: &Arc<Self>) {
let prev = self.set_foreground(None);
let switching = wm::available();
wm::focus(None);
self.leave_foreground(prev, switching);
self.enforce_background_limit();
}
fn freeze_later(self: &Arc<Self>, id: String) {
let core = self.clone();
tokio::spawn(async move {
tokio::time::sleep(FREEZE_DELAY).await;
let target = {
let st = core.state.lock().unwrap();
if st.foreground.as_deref() == Some(id.as_str()) {
return; // came back in the meantime
}
st.running.iter().find(|r| r.id == id && !r.frozen).map(|r| (r.unit.clone(), r.pid))
};
let Some((unit, pid)) = target else { return };
let ok = match &unit {
Some(u) => systemctl("freeze", u).await.map_err(|e| log::warn!("{e:#}")).is_ok(),
None => kill_group(pid, libc::SIGSTOP),
};
if ok {
// It may have been brought back while we were freezing it.
let back = {
let mut st = core.state.lock().unwrap();
if let Some(r) = st.running.iter_mut().find(|r| r.id == id) {
r.frozen = true;
}
st.foreground.as_deref() == Some(id.as_str())
};
if back {
core.thaw(&id, unit.as_deref(), pid).await;
} else {
log::info!("{id} frozen");
}
}
});
}
async fn thaw(&self, id: &str, unit: Option<&str>, pid: u32) {
match unit {
Some(u) => {
if let Err(e) = systemctl("thaw", u).await {
log::warn!("{e:#}");
}
}
None => {
kill_group(pid, libc::SIGCONT);
}
}
if let Some(r) = self.state.lock().unwrap().running.iter_mut().find(|r| r.id == id) {
r.frozen = false;
}
log::info!("{id} thawed");
}
/// Closes the app (asynchronously); false if it wasn't running.
pub fn stop(self: &Arc<Self>, id: &str) -> bool {
let target = {
let st = self.state.lock().unwrap();
st.running.iter().find(|r| r.id == id).map(|r| (r.unit.clone(), r.pid))
};
let Some((unit, pid)) = target else { return false };
log::info!("stopping {id}");
tokio::spawn(async move {
match unit {
// Stops every process of the scope, thawing it first.
Some(u) => {
let _ = systemctl("thaw", &u).await;
if let Err(e) = systemctl("stop", &u).await {
log::warn!("{e:#}");
kill_group(pid, libc::SIGKILL);
}
}
None => {
kill_group(pid, libc::SIGCONT);
kill_group(pid, libc::SIGTERM);
tokio::time::sleep(Duration::from_secs(3)).await;
kill_group(pid, libc::SIGKILL);
}
}
});
true
}
async fn stop_and_wait(self: &Arc<Self>, id: &str) {
if !self.stop(id) {
return;
}
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");
}
/// The oldest frozen app, if any.
fn oldest_background(&self) -> Option<String> {
let st = self.state.lock().unwrap();
st.running
.iter()
.filter(|r| st.foreground.as_deref() != Some(r.id.as_str()))
.min_by_key(|r| r.last_used)
.map(|r| r.id.clone())
}
fn background_count(&self) -> usize {
let st = self.state.lock().unwrap();
st.running.iter().filter(|r| st.foreground.as_deref() != Some(r.id.as_str())).count()
}
fn enforce_background_limit(self: &Arc<Self>) {
while self.background_count() > MAX_BACKGROUND {
let Some(id) = self.oldest_background() else { break };
log::info!("too many apps in the background, closing {id}");
if !self.stop(&id) {
break;
}
// Don't pick it again while it shuts down.
self.state.lock().unwrap().running.retain(|r| r.id != id);
self.emit(CoreEvent::AppStopped { app_id: id });
}
}
/// A receiver (AirPlay/Miracast) got a connection: its window goes on
/// top, the foreground app pauses in the background.
pub fn cast_connected(self: &Arc<Self>, app_id: &str, device: &str) {
let switching = wm::available();
let prev = {
let mut st = self.state.lock().unwrap();
if st.cast_return.is_none() {
st.cast_return = Some(st.foreground.clone());
}
if switching { st.foreground.take() } else { None }
};
if let Some(prev) = prev {
self.freeze_later(prev);
}
wm::focus(Some(app_id));
self.emit(CoreEvent::CastConnected { app_id: app_id.to_string(), device: device.to_string() });
}
/// The cast ended: back to what was on screen before.
pub fn cast_ended(self: &Arc<Self>, app_id: &str) {
let ret = self.state.lock().unwrap().cast_return.take();
self.emit(CoreEvent::CastEnded { app_id: app_id.to_string() });
let Some(ret) = ret else { return };
if !wm::available() {
return;
}
match ret.filter(|id| self.is_running(id)) {
Some(id) => {
let core = self.clone();
tokio::spawn(async move {
if let Err(e) = core.launch(&id, None, false).await {
log::warn!("back to {id}: {e:#}");
}
});
}
None => wm::focus(None),
}
}
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", "thaw", &u]).status();
let _ = StdCommand::new("systemctl").args(["--user", "stop", "--no-block", &u]).status();
}
kill_group(pid, libc::SIGCONT);
kill_group(pid, libc::SIGTERM);
}
}
}
/// Closes the oldest frozen app when memory runs low.
pub async fn watch_memory(core: Arc<Core>) {
let mut tick = tokio::time::interval(Duration::from_secs(5));
loop {
tick.tick().await;
let Some(avail) = mem_available_kb() else { continue };
if avail >= LOW_MEMORY_KB {
continue;
}
let Some(id) = core.oldest_background() else { continue };
let name = core.apps().into_iter().find(|a| a.id == id).map(|a| a.name).unwrap_or(id.clone());
log::warn!("low memory ({} MB available), closing {id}", avail / 1024);
if core.stop(&id) {
core.state.lock().unwrap().running.retain(|r| r.id != id);
core.emit(CoreEvent::AppStopped { app_id: id });
core.emit(CoreEvent::Toast { text: format!("Kevés a memória: {name} bezárva") });
}
}
}

View File

@@ -0,0 +1,57 @@
//! DIAL glue: apps with a `[dial]` section in their manifest (YouTube) can be
//! started from a phone.
use std::sync::Arc;
use anyhow::{Context, Result};
use sf_dial::{AppState, Config, Handler, LaunchParams};
use crate::apps::Core;
struct Dial(Arc<Core>);
impl Dial {
fn app_for(&self, dial_name: &str) -> Option<String> {
self.0.apps().into_iter().find(|a| a.dial.as_ref().is_some_and(|d| d.name == dial_name)).map(|a| a.id)
}
}
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
}

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

@@ -0,0 +1,128 @@
//! sf-core: the Fennec OS core daemon.
//!
//! - Starts apps for the launcher, each in its own systemd user scope.
//! Home freezes the foreground app (`systemctl --user freeze`) so it comes
//! back instantly; under memory pressure the oldest frozen app is closed.
//! - 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()
);
tokio::spawn(apps::watch_memory(core.clone()));
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,6 +1,6 @@
[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: app manifests, settings and IPC messages"
version.workspace = true version.workspace = true
edition.workspace = true edition.workspace = true
license.workspace = true license.workspace = true

283
crates/sf-ipc/src/launch.rs Normal file
View File

@@ -0,0 +1,283 @@
//! How apps are started: the command line for a web app (Chromium in kiosk or
//! app mode with its own profile) or an exec app. Shared by the launcher
//! (local testing on a desktop) and sf-core (the TV).
use std::path::{Path, PathBuf};
use std::process::Command;
use anyhow::{Context, Result, bail};
use crate::{AppKind, AppManifest, Settings, paths, sandbox};
/// Environment variable carrying the app id into the app's processes. The
/// compositor reads it from `/proc/<pid>/environ` to tell windows apart.
pub const APP_ENV: &str = "SMARTFOX_APP";
pub struct Browser {
pub exe: PathBuf,
/// Full version, used to build a realistic user agent.
pub version: String,
}
pub fn find_browser() -> Option<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> {
/// Per-app browser profiles live in `<data_dir>/profiles/<id>`.
pub data_dir: &'a Path,
pub fullscreen: bool,
/// Windowed mode: open the app exactly over the launcher (x, y, w, h).
pub bounds: Option<(i32, i32, u32, u32)>,
/// Extra query string for the start URL (DIAL launch parameters).
pub query: Option<&'a str>,
}
/// A program with its arguments and environment, before it is (maybe) put
/// into the sandbox.
struct Inner {
program: String,
args: Vec<String>,
env: Vec<(String, String)>,
}
/// The bwrap binary if `app` runs sandboxed (`sandbox` module). Store apps
/// never run without it. Official apps run unsandboxed when bwrap is missing
/// (an older image under a newer shell) or with `SMARTFOX_SANDBOX=off`
/// (debugging), with a warning.
fn sandbox_for(app: &AppManifest) -> Result<Option<PathBuf>> {
if app.origin == crate::Origin::Store {
anyhow::ensure!(cfg!(target_os = "linux"), "store apps only run on the TV (Linux)");
return sandbox::bwrap_path().context("bubblewrap (bwrap) is not installed, and store apps only run sandboxed").map(Some);
}
if !cfg!(target_os = "linux") || !app.sandboxed() {
return Ok(None);
}
if std::env::var("SMARTFOX_SANDBOX").is_ok_and(|v| v == "off") {
log::warn!("{}: SMARTFOX_SANDBOX=off, running without a sandbox", app.id);
return Ok(None);
}
let bwrap = sandbox::bwrap_path();
if bwrap.is_none() {
log::warn!("{}: bubblewrap is not installed, running without a sandbox", app.id);
}
Ok(bwrap)
}
/// The command that starts `app`. Not spawned yet, so callers can wrap it
/// (sf-core runs it inside a systemd scope).
pub fn command(app: &AppManifest, settings: &Settings, opts: &LaunchOptions) -> Result<Command> {
let bwrap = sandbox_for(app)?;
// Where the app's files are, as the app sees them.
let root = if bwrap.is_some() { PathBuf::from(sandbox::APP_DIR) } else { app.dir.clone() };
let data = paths::app_data_dir(&app.id);
let inner = match app.kind {
AppKind::Web => web_command(app, settings, opts, &root, bwrap.is_some().then_some(data.as_path()))?,
AppKind::Exec => {
let line = app.resolved_exec(&root);
let (prog, args) = line.split_first().context("empty exec command")?;
Inner { program: prog.clone(), args: args.to_vec(), env: Vec::new() }
}
AppKind::Builtin => bail!("built-in app has no process"),
};
let mut env = inner.env;
env.extend(app.env.iter().map(|(k, v)| (k.clone(), settings.expand(v))));
let mut cmd = match bwrap {
Some(bwrap) => {
std::fs::create_dir_all(&data).with_context(|| format!("creating {}", data.display()))?;
// Store apps sit behind symlinks (store/apps/<id> -> ../store-<id>/current).
let app_dir = std::fs::canonicalize(&app.dir).unwrap_or_else(|_| app.dir.clone());
let permissions = app.permissions();
let spec = sandbox::Spec {
app_id: &app.id,
app_dir: &app_dir,
data_dir: &data,
extra_rw: Vec::new(),
permissions: &permissions,
env,
program: inner.program,
args: inner.args,
};
let cmd = sandbox::command(&bwrap, &spec, &sandbox::Host::current());
log::info!("{}: sandboxed, permissions: {:?}", app.id, permissions.iter().map(|p| p.key()).collect::<Vec<_>>());
cmd
}
None => {
let mut cmd = Command::new(&inner.program);
cmd.args(&inner.args).envs(env).env("SMARTFOX_APP_DIR", &app.dir);
cmd
}
};
cmd.env(APP_ENV, &app.id);
// Own process group, so stopping the app also ends its helper processes.
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
cmd.process_group(0);
}
Ok(cmd)
}
/// Adds `query` to `url`, before any `#fragment`.
pub fn with_query(url: &str, query: Option<&str>) -> String {
let Some(q) = query.map(|q| q.trim_start_matches(['?', '&'])).filter(|q| !q.is_empty()) else {
return url.to_string();
};
let (base, frag) = match url.find('#') {
Some(i) => (&url[..i], &url[i..]),
None => (url, ""),
};
let sep = if base.contains('?') { '&' } else { '?' };
format!("{base}{sep}{q}{frag}")
}
/// First-run preferences for an app profile: no translate prompt, Hungarian
/// content language. Existing profiles are left alone.
fn seed_profile(profile: &Path) -> Result<()> {
let prefs = profile.join("Default").join("Preferences");
if prefs.exists() {
return Ok(());
}
std::fs::create_dir_all(prefs.parent().unwrap())?;
std::fs::write(
&prefs,
r#"{"translate":{"enabled":false},"intl":{"accept_languages":"hu-HU,hu,en"},"browser":{"has_seen_welcome_page":true}}"#,
)?;
Ok(())
}
/// The browser command for a web app. `sandbox_home`: the app's data folder
/// when it runs sandboxed; its Chromium profile then lives in there.
fn web_command(app: &AppManifest, settings: &Settings, opts: &LaunchOptions, root: &Path, sandbox_home: Option<&Path>) -> Result<Inner> {
let browser = find_browser().context("no Chromium/Chrome/Edge found (set SMARTFOX_BROWSER)")?;
let url = app.resolved_url(settings).filter(|u| !u.is_empty()).context("app has no URL")?;
if url.starts_with('/') {
bail!("URL is not set (check settings: {url})");
}
let url = with_query(&url, opts.query);
let old_profile = opts.data_dir.join("profiles").join(&app.id);
let profile = match sandbox_home {
Some(home) => {
let profile = home.join("chromium");
// Profiles from before the sandbox (logins, settings) move along.
if old_profile.is_dir() && !profile.exists() {
std::fs::create_dir_all(home)?;
if let Err(e) = std::fs::rename(&old_profile, &profile) {
log::warn!("{}: moving the browser profile: {e}", app.id);
}
}
profile
}
None => old_profile,
};
seed_profile(&profile)?;
let ua = match (&app.web.user_agent, &app.web.user_agent_suffix) {
(Some(ua), _) => ua.clone(),
(None, Some(suffix)) => format!("{} {suffix}", default_user_agent(&browser.version)),
(None, None) => default_user_agent(&browser.version),
};
let mut args: Vec<String> = vec![
format!("--user-data-dir={}", profile.display()),
format!("--user-agent={ua}"),
"--no-first-run".into(),
"--no-default-browser-check".into(),
"--disable-session-crashed-bubble".into(),
"--hide-crash-restore-bubble".into(),
"--disable-features=Translate,TranslateUI,MediaRouter,LocalNetworkAccessChecks".into(),
"--lang=hu".into(),
"--accept-lang=hu-HU,hu,en".into(),
// Dark first paint instead of a white flash before the page draws.
"--force-dark-mode".into(),
"--autoplay-policy=no-user-gesture-required".into(),
"--overscroll-history-navigation=0".into(),
];
if opts.fullscreen {
args.extend(["--kiosk".into(), url]);
} else {
args.push(format!("--app={url}"));
match opts.bounds {
Some((x, y, w, h)) => args.extend([format!("--window-position={x},{y}"), format!("--window-size={w},{h}")]),
None => args.push("--window-size=1600,900".into()),
}
}
let mut env = Vec::new();
if cfg!(target_os = "linux") {
// Chromium on Linux picks its UI language from the environment, not --lang.
env.push(("LANGUAGE".to_string(), "hu".to_string()));
args.push("--enable-features=VaapiVideoDecoder,VaapiIgnoreDriverChecks,PlatformHEVCDecoderSupport".into());
if std::env::var_os("WAYLAND_DISPLAY").is_some() {
args.push("--ozone-platform=wayland".into());
}
}
for ext in &app.web.extensions {
args.push(format!("--load-extension={}", root.join(ext).display()));
}
Ok(Inner { program: browser.exe.to_string_lossy().into_owned(), args, env })
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn adds_query() {
assert_eq!(with_query("https://www.youtube.com/tv", Some("a=1&b=2")), "https://www.youtube.com/tv?a=1&b=2");
assert_eq!(with_query("https://x/tv?x=1#f", Some("?a=1")), "https://x/tv?x=1&a=1#f");
assert_eq!(with_query("https://x/", None), "https://x/");
assert_eq!(with_query("https://x/", Some("")), "https://x/");
}
}

View File

@@ -1,9 +1,14 @@
//! Shared types for SmartFox components (launcher, core daemon, remote daemon). //! Shared types for Fennec OS components (launcher, core daemon, remote daemon,
//! compositor).
pub mod launch;
pub mod manifest; pub mod manifest;
pub mod message; pub mod message;
pub mod paths;
pub mod sandbox;
pub mod settings; pub mod settings;
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,5 +1,13 @@
//! App manifests: one `app.toml` per folder under the apps directory. //! App manifests: one `app.toml` per folder under the apps directory.
//!
//! Apps come from two places:
//! - factory apps (the image) and official packages (`sf-app-<id>`, signed
//! with the Fennec OS key);
//! - the store: third-party apps from their own GitHub/Gitea/GitLab repos,
//! published in their own repo (docs/store.md). These always run sandboxed and
//! can never replace an official app.
use std::collections::BTreeMap;
use std::path::{Path, PathBuf}; use std::path::{Path, PathBuf};
use anyhow::{Context, Result}; use anyhow::{Context, Result};
@@ -18,6 +26,101 @@ pub enum AppKind {
Builtin, Builtin,
} }
/// Where an app was loaded from.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Origin {
/// The image or an official package.
#[default]
Official,
/// A store package from a third-party repo: always sandboxed.
Store,
}
/// What a sandboxed app may reach besides its own files and the screen
/// (the Wayland socket). Shown to the user before installing.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum Permission {
/// Internet and the local network.
Network,
/// Hardware graphics and video decoding (/dev/dri).
Gpu,
/// Sound output (PipeWire / PulseAudio socket).
Audio,
/// Game controllers: /dev/input, /dev/hidraw*, /dev/uinput.
Gamepad,
/// The user's D-Bus session bus (unfiltered).
DbusSession,
/// The system D-Bus (unfiltered).
DbusSystem,
/// Every device in /dev.
Devices,
}
impl Permission {
pub const ALL: [Permission; 7] = [
Permission::Network,
Permission::Gpu,
Permission::Audio,
Permission::Gamepad,
Permission::DbusSession,
Permission::DbusSystem,
Permission::Devices,
];
/// Name used in app.toml and store.toml.
pub fn key(self) -> &'static str {
match self {
Permission::Network => "network",
Permission::Gpu => "gpu",
Permission::Audio => "audio",
Permission::Gamepad => "gamepad",
Permission::DbusSession => "dbus-session",
Permission::DbusSystem => "dbus-system",
Permission::Devices => "devices",
}
}
pub fn from_key(key: &str) -> Option<Permission> {
Permission::ALL.into_iter().find(|p| p.key() == key)
}
/// Hungarian label for the store screen.
pub fn label(self) -> &'static str {
match self {
Permission::Network => "Internet és helyi hálózat",
Permission::Gpu => "Grafikus gyorsítás",
Permission::Audio => "Hang",
Permission::Gamepad => "Játékvezérlők",
Permission::DbusSession => "Munkamenet D-Bus",
Permission::DbusSystem => "Rendszer D-Bus",
Permission::Devices => "Minden eszköz (/dev)",
}
}
/// Worth a warning: the app can reach far outside its sandbox.
pub fn risky(self) -> bool {
matches!(self, Permission::DbusSession | Permission::DbusSystem | Permission::Devices)
}
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SandboxOptions {
/// Run in a bubblewrap sandbox. Only official apps may turn it off
/// (system receivers like AirPlay); store apps are always sandboxed.
/// Unset: on, except for official background services.
#[serde(default)]
pub enabled: Option<bool>,
#[serde(default)]
pub permissions: Vec<Permission>,
}
impl Default for SandboxOptions {
fn default() -> Self {
SandboxOptions { enabled: None, permissions: Vec::new() }
}
}
#[derive(Debug, Clone, Serialize, Deserialize)] #[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AppManifest { pub struct AppManifest {
pub id: String, pub id: String,
@@ -59,9 +162,26 @@ pub struct AppManifest {
/// launcher tile only opens the details sheet. /// launcher tile only opens the details sheet.
#[serde(default)] #[serde(default)]
pub service: bool, pub service: bool,
#[serde(default)]
pub sandbox: SandboxOptions,
/// Extra environment for the app's process.
#[serde(default)]
pub env: BTreeMap<String, String>,
/// Legacy store manifest field. Older signed releases may still contain it.
#[serde(default)]
pub public_key: Option<String>,
/// Store apps: source code / home page, shown on the store screen.
#[serde(default)]
pub homepage: Option<String>,
#[serde(default)]
pub author: Option<String>,
#[serde(default)]
pub license: Option<String>,
/// Folder the manifest was loaded from (not serialized). /// Folder the manifest was loaded from (not serialized).
#[serde(skip)] #[serde(skip)]
pub dir: PathBuf, pub dir: PathBuf,
#[serde(skip)]
pub origin: Origin,
} }
#[derive(Debug, Clone, Default, Serialize, Deserialize)] #[derive(Debug, Clone, Default, Serialize, Deserialize)]
@@ -96,6 +216,79 @@ impl AppManifest {
pub fn resolved_url(&self, settings: &Settings) -> Option<String> { pub fn resolved_url(&self, settings: &Settings) -> Option<String> {
self.url.as_ref().map(|u| settings.expand(u)) self.url.as_ref().map(|u| settings.expand(u))
} }
/// The command line with `${app}` replaced by `app_root` (where the app's
/// files are: its folder, or /app inside the sandbox). A relative program
/// path with a slash (`bin/hello`) is inside the app folder too; a bare
/// name (`uxplay`) is looked up in PATH.
pub fn resolved_exec(&self, app_root: &Path) -> Vec<String> {
let root = app_root.to_string_lossy();
let mut line: Vec<String> = self.exec.iter().flatten().map(|a| a.replace("${app}", &root)).collect();
if let Some(first) = line.first_mut() {
if first.contains('/') && !first.starts_with('/') {
*first = format!("{}/{}", root.trim_end_matches('/'), first.trim_start_matches("./"));
}
}
line
}
/// What the app may reach from its sandbox. Web apps always get what a
/// browser needs.
pub fn permissions(&self) -> Vec<Permission> {
let mut p = self.sandbox.permissions.clone();
if self.kind == AppKind::Web {
p.extend([Permission::Network, Permission::Gpu, Permission::Audio]);
}
p.sort();
p.dedup();
p
}
/// Store apps always run sandboxed; official ones unless they opt out.
pub fn sandboxed(&self) -> bool {
self.origin == Origin::Store || self.sandbox.enabled.unwrap_or(!self.service)
}
/// An image file shipped with the app (`icon = "icon.png"`), if `icon`
/// isn't one of the launcher's built-in icon names.
pub fn icon_file(&self) -> Option<PathBuf> {
let lower = self.icon.to_ascii_lowercase();
if ![".png", ".svg", ".jpg", ".jpeg"].iter().any(|ext| lower.ends_with(ext)) {
return None;
}
if self.icon.contains("..") || Path::new(&self.icon).is_absolute() {
return None;
}
let path = self.dir.join(&self.icon);
path.is_file().then_some(path)
}
/// Rules a store app must follow (checked by sf-update before installing
/// and by the launcher when loading).
pub fn check_store_rules(&self) -> Result<()> {
anyhow::ensure!(is_store_id(&self.id), "store app id {:?} must be a reverse domain name (io.github.user.app)", self.id);
anyhow::ensure!(self.kind != AppKind::Builtin, "store apps can't be built-in");
anyhow::ensure!(!self.service, "store apps can't be background services");
anyhow::ensure!(self.dial.is_none(), "store apps can't register for DIAL");
anyhow::ensure!(self.sandbox.enabled != Some(false), "store apps can't turn off the sandbox");
match self.kind {
AppKind::Exec => anyhow::ensure!(!self.resolved_exec(Path::new("/app")).is_empty(), "exec is missing"),
AppKind::Web => anyhow::ensure!(self.url.as_deref().is_some_and(|u| u.starts_with("https://")), "web apps need an https:// url"),
AppKind::Builtin => {}
}
Ok(())
}
}
/// Store app ids are reverse domain names with at least one dot
/// (`io.github.user.app`). Official app ids never have a dot, so a store app
/// can't take the place of one.
pub fn is_store_id(id: &str) -> bool {
let parts: Vec<&str> = id.split('.').collect();
id.len() <= 128
&& parts.len() >= 2
&& parts.iter().all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_'))
&& parts[0].bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
} }
/// Loads every `*/app.toml` under `dir`, sorted by `order` then name. /// Loads every `*/app.toml` under `dir`, sorted by `order` then name.
@@ -128,6 +321,12 @@ pub fn load_apps_from(dirs: &[PathBuf]) -> Result<Vec<AppManifest>> {
} }
found = true; found = true;
for app in load_apps(dir)? { for app in load_apps(dir)? {
// Official ids have no dot; a store app here (developed inside
// the apps folder) belongs to the store, not the factory set.
if is_store_id(&app.id) {
log::info!("skipping {}: a store app id in an official apps folder", app.id);
continue;
}
match apps.iter_mut().find(|a| a.id == app.id) { match apps.iter_mut().find(|a| a.id == app.id) {
Some(old) if version_cmp(&app.version, &old.version).is_ge() => *old = app, Some(old) if version_cmp(&app.version, &old.version).is_ge() => *old = app,
Some(_) => {} Some(_) => {}
@@ -140,16 +339,37 @@ pub fn load_apps_from(dirs: &[PathBuf]) -> Result<Vec<AppManifest>> {
Ok(apps) Ok(apps)
} }
/// Official apps from `dirs` (see `load_apps_from`), plus store apps from
/// `store`. A store app is skipped if it breaks the store rules or has the id
/// of an official app.
pub fn load_all(dirs: &[PathBuf], store: Option<&Path>) -> Result<Vec<AppManifest>> {
let mut apps = load_apps_from(dirs)?;
if let Some(store) = store.filter(|d| d.is_dir()) {
for mut app in load_apps(store)? {
app.origin = Origin::Store;
if let Err(e) = app.check_store_rules() {
log::warn!("skipping store app {}: {e:#}", app.dir.display());
} else if apps.iter().any(|a| a.id == app.id) {
log::warn!("skipping store app {}: an app with this id is already installed", app.id);
} else {
apps.push(app);
}
}
sort_apps(&mut apps);
}
Ok(apps)
}
fn sort_apps(apps: &mut [AppManifest]) { fn sort_apps(apps: &mut [AppManifest]) {
apps.sort_by(|a, b| a.order.cmp(&b.order).then_with(|| a.name.cmp(&b.name))); 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 /// Compares dotted numeric versions ("1.10.0" > "1.9.2"), up to four parts
/// isn't a number compares as 0. /// (the Steam launcher is 1.0.0.87); anything that isn't a number compares as 0.
pub fn version_cmp(a: &str, b: &str) -> std::cmp::Ordering { 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 parts = |v: &str| -> Vec<u64> { v.split(['.', '-', '+']).take(4).map(|p| p.parse().unwrap_or(0)).collect() };
let (a, b) = (parts(a), parts(b)); 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) (0..4).map(|i| a.get(i).unwrap_or(&0).cmp(b.get(i).unwrap_or(&0))).find(|o| o.is_ne()).unwrap_or(std::cmp::Ordering::Equal)
} }
fn load_one(path: &Path) -> Result<AppManifest> { fn load_one(path: &Path) -> Result<AppManifest> {
@@ -174,7 +394,7 @@ mod tests {
accent = "#E50914" accent = "#E50914"
palette = ["#ff3b3b", "#7a0a10", "#0c0203"] palette = ["#ff3b3b", "#7a0a10", "#0c0203"]
[web] [web]
user_agent_suffix = "SMART-TV SmartFox/0.1" user_agent_suffix = "SMART-TV FennecOS/0.1"
"##, "##,
) )
.unwrap(); .unwrap();
@@ -191,5 +411,49 @@ mod tests {
assert_eq!(version_cmp("1.10.0", "1.9.2"), Greater); assert_eq!(version_cmp("1.10.0", "1.9.2"), Greater);
assert_eq!(version_cmp("0.2", "0.2.0"), Equal); assert_eq!(version_cmp("0.2", "0.2.0"), Equal);
assert_eq!(version_cmp("0.1.9", "0.2.0"), Less); assert_eq!(version_cmp("0.1.9", "0.2.0"), Less);
assert_eq!(version_cmp("1.0.0.87", "1.0.0.9"), Greater);
assert_eq!(version_cmp("1.0.0", "1.0.0.0"), Equal);
}
#[test]
fn store_ids() {
assert!(is_store_id("io.github.user.app"));
assert!(is_store_id("org.example.My_App-2"));
assert!(!is_store_id("youtube"));
assert!(!is_store_id("IO.github.x"));
assert!(!is_store_id("io..x"));
assert!(!is_store_id("io.x/../y"));
assert!(!is_store_id(".io.x"));
}
#[test]
fn exec_and_permissions() {
let app: AppManifest = toml::from_str(
r#"
id = "io.github.fox.hello"
name = "Hello"
kind = "exec"
exec = ["bin/hello", "--data", "${app}/share"]
[sandbox]
permissions = ["network", "gamepad"]
"#,
)
.unwrap();
assert_eq!(app.resolved_exec(Path::new("/app")), ["/app/bin/hello", "--data", "/app/share"]);
assert_eq!(app.permissions(), [Permission::Network, Permission::Gamepad]);
assert!(app.sandboxed());
app.check_store_rules().unwrap();
let mut bad = app.clone();
bad.sandbox.enabled = Some(false);
assert!(bad.check_store_rules().is_err());
bad = app.clone();
bad.id = "youtube".into();
assert!(bad.check_store_rules().is_err());
let web: AppManifest = toml::from_str("id = 'a'\nname = 'A'\nkind = 'web'\nurl = 'https://x'\n").unwrap();
assert_eq!(web.permissions(), [Permission::Network, Permission::Gpu, Permission::Audio]);
let path: AppManifest = toml::from_str("id = 'a'\nname = 'A'\nkind = 'exec'\nexec = ['uxplay', '-n']\n").unwrap();
assert_eq!(path.resolved_exec(Path::new("/x")), ["uxplay", "-n"]);
} }
} }

View File

@@ -1,23 +1,82 @@
//! 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, or bring it back if it waits in the background.
/// 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 foreground app is frozen in the background if
/// the compositor can switch windows, otherwise it is closed.
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 apps are kept (frozen) in the background on Home.
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,78 @@
//! Where the Fennec OS sockets and files live.
use std::path::{Path, PathBuf};
/// `$XDG_RUNTIME_DIR`, or the temp dir.
pub fn runtime_dir() -> PathBuf {
std::env::var_os("XDG_RUNTIME_DIR").map(PathBuf::from).unwrap_or_else(std::env::temp_dir)
}
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")
}
/// The settings file: `$SMARTFOX_SETTINGS`, else `<config>/smartfox/settings.toml`.
pub fn settings_file() -> PathBuf {
if let Ok(p) = std::env::var("SMARTFOX_SETTINGS") {
return p.into();
}
let base = std::env::var_os("XDG_CONFIG_HOME")
.map(PathBuf::from)
.or_else(|| std::env::var_os("APPDATA").map(PathBuf::from))
.or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")))
.unwrap_or_else(|| PathBuf::from("."));
base.join("smartfox").join("settings.toml")
}
/// An app's private data folder; its `$HOME` inside the sandbox:
/// `$XDG_DATA_HOME/smartfox/apps/<id>` (default `~/.local/share/...`).
pub fn app_data_dir(id: &str) -> PathBuf {
let base = std::env::var_os("XDG_DATA_HOME")
.map(PathBuf::from)
.or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".local").join("share")))
.or_else(|| std::env::var_os("LOCALAPPDATA").map(PathBuf::from))
.unwrap_or_else(|| PathBuf::from("."));
base.join("smartfox").join("apps").join(id)
}
/// Installed store apps (`/var/lib/sf-pkg/store/apps/<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("netflex").is_dir() {
return candidate;
}
}
}
PathBuf::from("/usr/share/smartfox/apps")
}

View File

@@ -0,0 +1,350 @@
//! App sandbox: every app runs in its own bubblewrap (`bwrap`) container,
//! the same building block Flatpak uses.
//!
//! Inside the sandbox an app sees:
//! - the system read-only (`/usr`, `/etc`), no other user's or app's files;
//! - its own files read-only at `/app`;
//! - its own data folder as `$HOME` (on the host:
//! `~/.local/share/smartfox/apps/<id>`), the only writable place that lasts;
//! - the Wayland socket (it can show a window), nothing else from
//! `$XDG_RUNTIME_DIR` (no launcher, sf-core or compositor sockets);
//! - fresh /tmp, /run, /var and its own PID, IPC and UTS namespaces;
//! - and only what its permissions allow (`Permission`): network, GPU,
//! sound, game controllers, D-Bus, devices.
use std::path::{Path, PathBuf};
use std::process::Command;
use crate::manifest::Permission;
/// Where the app's own files are inside the sandbox.
pub const APP_DIR: &str = "/app";
/// Environment variables passed through from the session when set.
const PASS_ENV: [&str; 7] = ["LANG", "LANGUAGE", "LC_ALL", "TZ", "XCURSOR_THEME", "XCURSOR_SIZE", "RUST_LOG"];
/// What a host path is, for building the mount list (a function so tests
/// can fake the file system).
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Entry {
Missing,
Dir,
Other,
Symlink(PathBuf),
/// There, but we may not read it (bwrap's `--*-bind-try` fails on that).
Denied,
}
pub fn probe(path: &Path) -> Entry {
if let Err(e) = std::fs::metadata(path) {
if e.kind() == std::io::ErrorKind::PermissionDenied {
return Entry::Denied;
}
}
match std::fs::symlink_metadata(path) {
Err(_) => Entry::Missing,
Ok(m) if m.file_type().is_symlink() => std::fs::read_link(path).map(Entry::Symlink).unwrap_or(Entry::Missing),
Ok(m) if m.is_dir() => Entry::Dir,
Ok(_) => Entry::Other,
}
}
/// The session the app is started from.
#[derive(Debug, Clone)]
pub struct Host {
pub uid: u32,
pub user: String,
pub home: PathBuf,
pub runtime_dir: PathBuf,
pub wayland_display: Option<String>,
pub hostname: Option<String>,
/// Allowed variables from the session (`PASS_ENV`).
pub env: Vec<(String, String)>,
/// /dev/hidraw* (controllers that talk raw HID, like DualSense).
pub hidraw: Vec<PathBuf>,
}
impl Host {
pub fn current() -> Host {
let var = |k: &str| std::env::var(k).ok().filter(|v| !v.is_empty());
let home = var("HOME").map(PathBuf::from).unwrap_or_else(|| PathBuf::from("/tmp"));
let hidraw = std::fs::read_dir("/dev")
.map(|d| d.flatten().map(|e| e.path()).filter(|p| p.file_name().is_some_and(|n| n.to_string_lossy().starts_with("hidraw"))).collect())
.unwrap_or_default();
Host {
uid: current_uid(),
user: var("USER").unwrap_or_else(|| "tv".into()),
home,
runtime_dir: crate::paths::runtime_dir(),
wayland_display: var("WAYLAND_DISPLAY"),
hostname: std::fs::read_to_string("/etc/hostname").ok().map(|h| h.trim().to_string()).filter(|h| !h.is_empty()),
env: PASS_ENV.iter().filter_map(|k| var(k).map(|v| (k.to_string(), v))).collect(),
hidraw,
}
}
}
#[cfg(unix)]
fn current_uid() -> u32 {
use std::os::unix::fs::MetadataExt;
// The owner of our own /proc entry is our uid (no libc needed).
std::fs::metadata("/proc/self").map(|m| m.uid()).unwrap_or(1000)
}
#[cfg(not(unix))]
fn current_uid() -> u32 {
1000
}
/// One sandboxed process.
#[derive(Debug, Clone)]
pub struct Spec<'a> {
pub app_id: &'a str,
/// The app's files (host path), read-only at `/app`.
pub app_dir: &'a Path,
/// The app's private data (host path), mounted as `$HOME`.
pub data_dir: &'a Path,
/// More writable folders, at the same path inside (a browser profile).
pub extra_rw: Vec<PathBuf>,
pub permissions: &'a [Permission],
/// Extra environment for the app.
pub env: Vec<(String, String)>,
pub program: String,
pub args: Vec<String>,
}
pub fn bwrap_path() -> Option<PathBuf> {
if let Ok(p) = std::env::var("SMARTFOX_BWRAP") {
return Some(p.into());
}
["/usr/bin/bwrap", "/usr/local/bin/bwrap"].iter().map(PathBuf::from).find(|p| p.is_file())
}
/// The bwrap command for `spec`.
pub fn command(bwrap: &Path, spec: &Spec, host: &Host) -> Command {
let mut cmd = Command::new(bwrap);
cmd.args(args(spec, host, &probe));
cmd
}
/// The bwrap arguments. Mount order matters: later mounts go on top.
pub fn args(spec: &Spec, host: &Host, fs: &dyn Fn(&Path) -> Entry) -> Vec<String> {
let has = |p: Permission| spec.permissions.contains(&p);
let mut a: Vec<String> = Vec::new();
let mut push = |items: &[&str]| a.extend(items.iter().map(|s| s.to_string()));
push(&["--die-with-parent", "--unshare-all"]);
if has(Permission::Network) {
push(&["--share-net"]);
}
if host.uid == 0 {
// Unprivileged bwrap drops every capability by itself; as root
// (development) do it explicitly.
push(&["--cap-drop", "ALL"]);
}
if let Some(h) = &host.hostname {
push(&["--hostname", h]);
}
// The system, read-only. /bin, /lib... are symlinks into /usr on Debian.
push(&["--ro-bind", "/usr", "/usr"]);
for top in ["/bin", "/sbin", "/lib", "/lib32", "/lib64", "/libx32"] {
match fs(Path::new(top)) {
Entry::Symlink(t) => push(&["--symlink", &t.to_string_lossy(), top]),
Entry::Dir => push(&["--ro-bind", top, top]),
_ => {}
}
}
push(&["--ro-bind", "/etc", "/etc", "--proc", "/proc"]);
// Devices.
if has(Permission::Devices) {
push(&["--dev-bind", "/dev", "/dev"]);
} else {
push(&["--dev", "/dev", "--tmpfs", "/dev/shm"]);
if has(Permission::Gpu) {
push(&["--dev-bind-try", "/dev/dri", "/dev/dri"]);
}
if has(Permission::Gamepad) {
push(&["--dev-bind-try", "/dev/input", "/dev/input", "--dev-bind-try", "/dev/uinput", "/dev/uinput"]);
for h in &host.hidraw {
let h = h.to_string_lossy();
push(&["--dev-bind-try", &h, &h]);
}
}
}
if has(Permission::Gpu) || has(Permission::Gamepad) || has(Permission::Devices) {
push(&["--ro-bind", "/sys", "/sys"]);
}
// Fresh writable scratch space.
push(&["--tmpfs", "/tmp", "--tmpfs", "/var", "--tmpfs", "/run", "--dir", "/var/tmp", "--symlink", "../run", "/var/run"]);
push(&["--ro-bind-try", "/var/cache/fontconfig", "/var/cache/fontconfig"]);
if has(Permission::Gamepad) || has(Permission::Devices) {
// Hotplug of controllers (SDL, Steam) goes through udev.
push(&["--ro-bind-try", "/run/udev", "/run/udev"]);
}
if has(Permission::Network) {
// /etc/resolv.conf points at systemd-resolved's stub file on the TV;
// elsewhere (WSL: /mnt/wsl/resolv.conf) bind whatever it points at.
push(&["--ro-bind-try", "/run/systemd/resolve", "/run/systemd/resolve"]);
if let Entry::Symlink(t) = fs(Path::new("/etc/resolv.conf")) {
let target = Path::new("/etc").join(t);
let target = target.to_string_lossy();
if !target.starts_with("/run/systemd/resolve/") && !target.starts_with("/etc/") && !target.starts_with("/usr/") {
push(&["--ro-bind-try", &target, &target]);
}
}
}
if has(Permission::DbusSystem) {
push(&["--ro-bind-try", "/run/dbus/system_bus_socket", "/run/dbus/system_bus_socket"]);
}
// The session's runtime dir: only the sockets the app may use.
let rt = host.runtime_dir.to_string_lossy().to_string();
push(&["--perms", "0700", "--dir", &rt]);
let mut socket = |name: &str| {
let p = format!("{rt}/{name}");
if fs(Path::new(&p)) != Entry::Denied {
push(&["--ro-bind-try", &p, &p]);
}
};
if let Some(wl) = &host.wayland_display {
socket(wl);
}
if has(Permission::Audio) {
socket("pipewire-0");
socket("pulse/native");
}
if has(Permission::DbusSession) {
socket("bus");
}
// $HOME is the app's own data folder (at the real home path, so programs
// that remember absolute paths keep working).
let home = host.home.to_string_lossy().to_string();
if let Entry::Symlink(t) = fs(Path::new("/home")) {
push(&["--symlink", &t.to_string_lossy(), "/home"]);
}
push(&["--bind", &spec.data_dir.to_string_lossy(), &home]);
for p in &spec.extra_rw {
let p = p.to_string_lossy();
push(&["--bind", &p, &p]);
}
push(&["--ro-bind", &spec.app_dir.to_string_lossy(), APP_DIR, "--chdir", &home]);
// A clean environment.
push(&["--clearenv"]);
let mut env: Vec<(String, String)> = vec![
("PATH".into(), "/usr/local/bin:/usr/bin:/bin:/usr/games".into()),
("HOME".into(), home.clone()),
("USER".into(), host.user.clone()),
("LOGNAME".into(), host.user.clone()),
("SHELL".into(), "/bin/sh".into()),
("XDG_RUNTIME_DIR".into(), rt.clone()),
("XDG_SESSION_TYPE".into(), "wayland".into()),
("SMARTFOX_APP".into(), spec.app_id.into()),
("SMARTFOX_APP_DIR".into(), APP_DIR.into()),
];
if let Some(wl) = &host.wayland_display {
env.push(("WAYLAND_DISPLAY".into(), wl.clone()));
}
if has(Permission::DbusSession) {
env.push(("DBUS_SESSION_BUS_ADDRESS".into(), format!("unix:path={rt}/bus")));
}
env.extend(host.env.iter().cloned());
env.extend(spec.env.iter().cloned());
for (k, v) in env {
push(&["--setenv", &k, &v]);
}
push(&["--", &spec.program]);
a.extend(spec.args.iter().cloned());
a
}
#[cfg(test)]
mod tests {
use super::*;
fn host() -> Host {
Host {
uid: 1000,
user: "tv".into(),
home: "/var/home/tv".into(),
runtime_dir: "/run/user/1000".into(),
wayland_display: Some("wayland-1".into()),
hostname: Some("smartfox".into()),
env: vec![("LANG".into(), "C.UTF-8".into())],
hidraw: vec!["/dev/hidraw0".into()],
}
}
fn fake_fs(p: &Path) -> Entry {
match p.to_str().unwrap() {
"/bin" => Entry::Symlink("usr/bin".into()),
"/lib" => Entry::Symlink("usr/lib".into()),
"/lib64" => Entry::Symlink("usr/lib64".into()),
"/home" => Entry::Symlink("var/home".into()),
_ => Entry::Missing,
}
}
fn has_seq(args: &[String], seq: &[&str]) -> bool {
args.windows(seq.len()).any(|w| w.iter().zip(seq).all(|(a, b)| a == b))
}
#[test]
fn minimal_sandbox() {
let spec = Spec {
app_id: "io.github.fox.hello",
app_dir: Path::new("/var/lib/sf-pkg/store-io.github.fox.hello/1.0.0"),
data_dir: Path::new("/var/home/tv/.local/share/smartfox/apps/io.github.fox.hello"),
extra_rw: vec![],
permissions: &[],
env: vec![("FOO".into(), "bar".into())],
program: "/app/bin/hello".into(),
args: vec!["--x".into()],
};
let a = args(&spec, &host(), &fake_fs);
assert!(has_seq(&a, &["--unshare-all"]));
assert!(!a.contains(&"--share-net".to_string()));
assert!(!a.iter().any(|s| s == "/dev/dri" || s == "/sys"));
assert!(!a.iter().any(|s| s.contains("pipewire") || s.ends_with("/bus")));
assert!(has_seq(&a, &["--symlink", "usr/bin", "/bin"]));
assert!(has_seq(&a, &["--ro-bind-try", "/run/user/1000/wayland-1", "/run/user/1000/wayland-1"]));
assert!(has_seq(&a, &["--bind", "/var/home/tv/.local/share/smartfox/apps/io.github.fox.hello", "/var/home/tv"]));
assert!(has_seq(&a, &["--ro-bind", "/var/lib/sf-pkg/store-io.github.fox.hello/1.0.0", "/app"]));
assert!(has_seq(&a, &["--setenv", "SMARTFOX_APP", "io.github.fox.hello"]));
assert!(has_seq(&a, &["--setenv", "FOO", "bar"]));
assert!(has_seq(&a, &["--", "/app/bin/hello", "--x"]));
assert_eq!(a.last().unwrap(), "--x");
// /run must be fresh before the runtime dir and sockets go in.
let run = a.iter().position(|s| s == "/run").unwrap();
let sock = a.iter().position(|s| s == "/run/user/1000/wayland-1").unwrap();
assert!(run < sock);
}
#[test]
fn permissions_open_doors() {
let perms = [Permission::Network, Permission::Gpu, Permission::Audio, Permission::Gamepad, Permission::DbusSession];
let spec = Spec {
app_id: "steam",
app_dir: Path::new("/usr/share/smartfox/apps/steam"),
data_dir: Path::new("/d"),
extra_rw: vec!["/var/home/tv/.config/smartfox/profiles/steam".into()],
permissions: &perms,
env: vec![],
program: "/app/x".into(),
args: vec![],
};
let a = args(&spec, &host(), &fake_fs);
assert!(a.contains(&"--share-net".to_string()));
assert!(has_seq(&a, &["--dev-bind-try", "/dev/dri", "/dev/dri"]));
assert!(has_seq(&a, &["--dev-bind-try", "/dev/hidraw0", "/dev/hidraw0"]));
assert!(has_seq(&a, &["--ro-bind", "/sys", "/sys"]));
assert!(has_seq(&a, &["--ro-bind-try", "/run/user/1000/pipewire-0", "/run/user/1000/pipewire-0"]));
assert!(has_seq(&a, &["--setenv", "DBUS_SESSION_BUS_ADDRESS", "unix:path=/run/user/1000/bus"]));
assert!(has_seq(&a, &["--bind", "/var/home/tv/.config/smartfox/profiles/steam", "/var/home/tv/.config/smartfox/profiles/steam"]));
}
}

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 = { path = "../sf-ui", 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, freezes 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>,

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,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};
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,
} }
@@ -114,12 +122,20 @@ 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 };
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(),
@@ -130,9 +146,132 @@ fn entry_of(app: &AppManifest, settings: &Settings) -> AppEntry {
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(),
} }
} }
/// 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() {
"youtube" => {
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 +314,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 +324,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 +364,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 +439,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 +526,18 @@ 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);
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 +563,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 keeps them frozen in the
// background 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 +606,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 +635,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 +652,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 goes to the
// background (sf-core) or 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);
@@ -527,10 +796,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: Default::default(),
}; };
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.

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,142 @@ 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 label = sink.get("description").and_then(|v| v.as_str()).unwrap_or(name).to_string();
let bluetooth = name.starts_with("bluez_output.");
outputs.push(AudioOutput { name: name.into(), label, bluetooth, selected: name == default });
}
outputs.sort_by_key(|o| (!o.selected, o.bluetooth, o.label.to_lowercase()));
Ok(outputs)
}
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 +1013,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 +1042,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 +1066,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 });
} }
@@ -1021,6 +1157,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

@@ -3,6 +3,59 @@
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 == "netflex" || root.icon == "youtube" || root.icon == "airplay" || root.icon == "miracast" || root.icon == "settings" || root.icon == "store" || root.icon == "steam";
if root.has-image: Image {
width: 100%;
height: 100%;
source: root.image;
image-fit: contain;
}
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 {
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.3z";
fill: @linear-gradient(180deg, #8cc4ff 0%, #3d7fe0 100%);
}
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M11.5 14V9.5a4.5 4.5 0 0 1 9 0V14";
stroke: root.ink;
stroke-width: 2.4px;
stroke-line-cap: round;
}
}
if root.icon == "steam": Rectangle {
// Steam mark: the piston and valve in a disc (Simple Icons, CC0).
Path {
width: 100%; height: 100%;
viewbox-x: -3; viewbox-y: -3;
viewbox-width: 30; viewbox-height: 30;
commands: "M11.979 0C5.678 0 .511 4.86.022 11.037l6.432 2.658c.545-.371 1.203-.59 1.912-.59.063 0 .125.004.188.006l2.861-4.142V8.91c0-2.495 2.028-4.524 4.524-4.524 2.494 0 4.524 2.031 4.524 4.527s-2.03 4.525-4.524 4.525h-.105l-4.076 2.911c0 .052.004.105.004.159 0 1.875-1.515 3.396-3.39 3.396-1.635 0-3.016-1.173-3.331-2.727L.436 15.27C1.862 20.307 6.486 24 11.979 24c6.627 0 11.999-5.373 11.999-12S18.605 0 11.979 0zM7.54 18.21l-1.473-.61c.262.543.714.999 1.314 1.25 1.297.539 2.793-.076 3.332-1.375.263-.63.264-1.319.005-1.949s-.75-1.121-1.377-1.383c-.624-.26-1.29-.249-1.878-.03l1.523.63c.956.4 1.409 1.5 1.009 2.455-.397.957-1.497 1.41-2.454 1.012H7.54zm11.415-9.303c0-1.662-1.353-3.015-3.015-3.015-1.665 0-3.015 1.353-3.015 3.015 0 1.665 1.35 3.015 3.015 3.015 1.663 0 3.015-1.35 3.015-3.015zm-5.273-.005c0-1.252 1.013-2.266 2.265-2.266 1.249 0 2.266 1.014 2.266 2.266 0 1.251-1.017 2.265-2.266 2.265-1.253 0-2.265-1.014-2.265-2.265z";
fill: @linear-gradient(160deg, #ffffff 0%, #c7e4f8 100%);
}
}
if root.icon == "netflex": Rectangle { if root.icon == "netflex": Rectangle {
// Netflex mark: mirrored "N" in three ribbons (from netflex/apps/web/public/favicon.svg). // Netflex mark: mirrored "N" in three ribbons (from netflex/apps/web/public/favicon.svg).
@@ -107,7 +160,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 +346,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.
Text {
x: 0; x: 0;
y: 4 * root.u; y: 0;
width: 40 * root.u; width: 48 * root.u;
height: self.width; height: 48 * root.u;
// The glass bead behind the number is drawn by the glass layer (app.slint). text: root.n;
Text { color: root.accent.brighter(0.6);
text: root.n; font-size: 22 * root.u;
color: root.accent.brighter(0.6); font-weight: 700;
font-size: 20 * root.u; horizontal-alignment: center;
font-weight: 700; vertical-alignment: center;
horizontal-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]);
}
}

14
crates/sf-pack/Cargo.toml Normal file
View File

@@ -0,0 +1,14 @@
[package]
name = "sf-pack"
description = "Fennec OS store app packaging (docs/store.md)"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
sf-ipc.workspace = true
anyhow.workspace = true
serde.workspace = true
toml.workspace = true
tar = "0.4"
ruzstd = "0.8"

220
crates/sf-pack/src/main.rs Normal file
View File

@@ -0,0 +1,220 @@
//! sf-pack: builds Fennec OS store packages (docs/store.md).
//!
//! sf-pack build <app-dir> [out-dir] app.toml + <id>-<version>.tar.zst
//! sf-pack verify <out-dir> checks what `build` made
//! sf-pack run <app-dir> runs the app the way the TV does: in the
//! store sandbox (Linux, needs bwrap)
//!
//! The two files in out-dir are the release assets: upload them to a
//! release of the app's repo (GitHub, Gitea or GitLab).
use std::io::Read;
use std::path::{Path, PathBuf};
use anyhow::{Context, Result, bail};
use sf_ipc::AppManifest;
fn main() {
let args: Vec<String> = std::env::args().skip(1).collect();
if let Err(e) = run(&args) {
eprintln!("sf-pack: {e:#}");
std::process::exit(1);
}
}
fn run(args: &[String]) -> Result<()> {
let arg = |i: usize| args.get(i).map(String::as_str);
match arg(0) {
Some("build") => {
let dir = arg(1).context("usage: sf-pack build <app-dir> [out-dir]")?;
build(Path::new(dir), Path::new(arg(2).unwrap_or("dist")))
}
Some("verify") => verify(Path::new(arg(1).unwrap_or("dist"))),
Some("run") => run_app(Path::new(arg(1).context("usage: sf-pack run <app-dir>")?)),
_ => bail!("usage: sf-pack build <app-dir> [out-dir] | verify [out-dir] | run <app-dir>"),
}
}
fn read_manifest(dir: &Path) -> Result<AppManifest> {
let path = dir.join("app.toml");
let text = std::fs::read_to_string(&path).with_context(|| format!("reading {}", path.display()))?;
let mut app: AppManifest = toml::from_str(&text).with_context(|| format!("parsing {}", path.display()))?;
app.dir = dir.to_path_buf();
Ok(app)
}
fn is_release(v: &str) -> bool {
!v.is_empty() && v.split('.').count() <= 4 && v.split('.').all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()))
}
fn build(dir: &Path, out: &Path) -> Result<()> {
let app = read_manifest(dir)?;
app.check_store_rules().context("app.toml")?;
if !is_release(&app.version) {
bail!("version {:?} must be a release version like 1.2.3", app.version);
}
if app.icon.contains('.') && app.icon_file().is_none() {
bail!("icon {} is missing from {}", app.icon, dir.display());
}
if let Some(exe) = app.resolved_exec(Path::new("/app")).first().and_then(|p| p.strip_prefix("/app/")) {
let path = dir.join(exe);
if !path.is_file() {
bail!("exec {} is missing from {}", exe, dir.display());
}
check_executable(&path)?;
}
std::fs::create_dir_all(out)?;
let file = format!("{}-{}.tar.zst", app.id, app.version);
let tar = pack_tar(dir, &app)?;
let zst = ruzstd::encoding::compress_to_vec(&tar[..], ruzstd::encoding::CompressionLevel::Fastest);
std::fs::write(out.join(&file), &zst)?;
std::fs::copy(dir.join("app.toml"), out.join("app.toml"))?;
println!("{}: {} ({} KiB)", app.id, out.join(&file).display(), zst.len() / 1024);
println!("Release assets: app.toml, {file}");
Ok(())
}
#[cfg(unix)]
fn check_executable(path: &Path) -> Result<()> {
use std::os::unix::fs::PermissionsExt;
if std::fs::metadata(path)?.permissions().mode() & 0o111 == 0 {
bail!("{} is not executable (chmod +x)", path.display());
}
Ok(())
}
#[cfg(not(unix))]
fn check_executable(_path: &Path) -> Result<()> {
Ok(())
}
/// The package: the app folder plus pkg.toml, reproducible (sorted, no
/// owners, fixed time).
fn pack_tar(dir: &Path, app: &AppManifest) -> Result<Vec<u8>> {
let mut files = Vec::new();
collect(dir, Path::new(""), &mut files)?;
files.sort();
let mut b = tar::Builder::new(Vec::new());
b.follow_symlinks(false);
let pkg = format!("name = \"{}\"\nversion = \"{}\"\n", app.id, app.version);
let mut h = header(tar::EntryType::Regular, 0o644, pkg.len() as u64);
b.append_data(&mut h, "pkg.toml", pkg.as_bytes())?;
for rel in files {
let path = dir.join(&rel);
let meta = std::fs::symlink_metadata(&path)?;
let mode = file_mode(&meta);
if meta.file_type().is_symlink() {
let mut h = header(tar::EntryType::Symlink, 0o777, 0);
b.append_link(&mut h, &rel, std::fs::read_link(&path)?)?;
} else if meta.is_dir() {
let mut h = header(tar::EntryType::Directory, 0o755, 0);
b.append_data(&mut h, &rel, std::io::empty())?;
} else {
// Windows has no x bit: whatever is under bin/ is executable.
let exec = mode & 0o111 != 0 || rel.starts_with("bin");
let mut h = header(tar::EntryType::Regular, if exec { 0o755 } else { 0o644 }, meta.len());
b.append_data(&mut h, &rel, std::fs::File::open(&path)?)?;
}
}
Ok(b.into_inner()?)
}
fn header(kind: tar::EntryType, mode: u32, size: u64) -> tar::Header {
let mut h = tar::Header::new_gnu();
h.set_entry_type(kind);
h.set_mode(mode);
h.set_size(size);
h.set_mtime(0);
h.set_uid(0);
h.set_gid(0);
h
}
#[cfg(unix)]
fn file_mode(meta: &std::fs::Metadata) -> u32 {
use std::os::unix::fs::PermissionsExt;
meta.permissions().mode()
}
/// On Windows nothing is executable; binaries under bin/ are.
#[cfg(not(unix))]
fn file_mode(_meta: &std::fs::Metadata) -> u32 {
0o644
}
fn collect(root: &Path, rel: &Path, out: &mut Vec<PathBuf>) -> Result<()> {
for e in std::fs::read_dir(root.join(rel))? {
let e = e?;
let name = e.file_name();
if name == "pkg.toml" && rel.as_os_str().is_empty() {
continue;
}
let r = rel.join(&name);
out.push(r.clone());
if e.file_type()?.is_dir() {
collect(root, &r, out)?;
}
}
Ok(())
}
fn verify(out: &Path) -> Result<()> {
let app = read_manifest(out)?;
app.check_store_rules()?;
let file = out.join(format!("{}-{}.tar.zst", app.id, app.version));
let data = std::fs::read(&file).with_context(|| format!("reading {}", file.display()))?;
let mut tar = Vec::new();
ruzstd::decoding::StreamingDecoder::new(&data[..]).map_err(|e| anyhow::anyhow!("zstd: {e}"))?.read_to_end(&mut tar)?;
let mut archive = tar::Archive::new(&tar[..]);
let names: Vec<String> = archive.entries()?.filter_map(|e| e.ok()?.path().ok().map(|p| p.to_string_lossy().into_owned())).collect();
if !names.iter().any(|n| n == "pkg.toml") || !names.iter().any(|n| n == "app.toml") {
bail!("pkg.toml or app.toml missing from the package");
}
println!("{} {}: package OK, {} files", app.id, app.version, names.len());
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn builds_and_verifies() {
let tmp = std::env::temp_dir().join(format!("sf-pack-test-{}", std::process::id()));
let app = tmp.join("app");
std::fs::create_dir_all(app.join("bin")).unwrap();
std::fs::write(
app.join("app.toml"),
"id = \"io.github.fox.hello\"\nname = \"Hello\"\nversion = \"1.2.3\"\nkind = \"exec\"\nexec = [\"bin/hello\"]\n",
)
.unwrap();
std::fs::write(app.join("bin/hello"), "#!/bin/sh\necho hi\n").unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(app.join("bin/hello"), std::fs::Permissions::from_mode(0o755)).unwrap();
}
let out = tmp.join("dist");
build(&app, &out).unwrap();
verify(&out).unwrap();
std::fs::remove_dir_all(&tmp).unwrap();
}
}
/// Runs an app folder as a store app: same sandbox, same permissions.
fn run_app(dir: &Path) -> Result<()> {
let mut app = read_manifest(dir)?;
app.check_store_rules().context("app.toml")?;
app.origin = sf_ipc::Origin::Store;
let settings = sf_ipc::Settings::default();
let data = std::env::temp_dir().join("sf-pack-run");
let opts = sf_ipc::launch::LaunchOptions { data_dir: &data, fullscreen: false, bounds: None, query: None };
let mut cmd = sf_ipc::launch::command(&app, &settings, &opts)?;
eprintln!("data folder ($HOME inside): {}", sf_ipc::paths::app_data_dir(&app.id).display());
if std::env::var_os("SF_PACK_SHOW").is_some() {
eprintln!("{} {}", cmd.get_program().to_string_lossy(), cmd.get_args().map(|a| a.to_string_lossy()).collect::<Vec<_>>().join(" "));
}
let status = cmd.status().context("starting the app")?;
std::process::exit(status.code().unwrap_or(1));
}

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() => {
if dev.is_connected().await.unwrap_or(false) {
return Ok(());
}
// Removed in the launcher's settings: go back to pairing.
if !dev.is_paired().await.unwrap_or(false) {
anyhow::bail!("remote {} was unpaired", dev.address());
}
}
ev = events.next() => match ev { ev = events.next() => match ev {
Some(DeviceEvent::PropertyChanged(DeviceProperty::Rssi(rssi))) => { Some(DeviceEvent::PropertyChanged(DeviceProperty::Rssi(rssi))) => {
log::info!("remote advertising (rssi {rssi}), connecting"); log::info!("remote advertising (rssi {rssi}), connecting");
return Ok(()); true
} }
Some(DeviceEvent::PropertyChanged(DeviceProperty::Connected(true))) => return Ok(()), Some(DeviceEvent::PropertyChanged(DeviceProperty::Connected(true))) => return Ok(true),
Some(_) => {} Some(_) => false,
None => anyhow::bail!("device event stream ended"), None => anyhow::bail!("device event stream ended"),
}, },
// Keep the discovery session alive and drained. // Keep the discovery session alive and drained.
_ = discovery.next() => {} event = discovery.next() => {
if event.is_none() {
anyhow::bail!("discovery ended");
}
false
}
};
if !should_connect {
continue;
}
if dev.is_connected().await.unwrap_or(false) {
return Ok(true);
}
// Removed in the launcher's settings: go back to pairing.
if !dev.is_paired().await.unwrap_or(false) {
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;
}
Ok(Err(e)) => log::debug!("connect: {e}"),
Err(_) => log::debug!("connect timed out"),
}
if dev.is_connected().await.unwrap_or(false) {
return Ok(true);
} }
} }
} }
@@ -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.
//! //!

30
crates/sf-ui/Cargo.toml Normal file
View File

@@ -0,0 +1,30 @@
[package]
name = "sf-ui"
description = "SmartFox TV UI kit: Liquid Glass for Slint apps, TV components, artwork loading, video playback"
version.workspace = true
edition.workspace = true
# Slint is used under GPL-3.0 (its royalty-free license does not cover embedded
# devices like a TV box), so apps built on sf-ui are GPL-3.0 too.
license = "GPL-3.0-only"
# Lets the build script of an app read DEP_SF_UI_UI_DIR (the Slint library).
links = "sf_ui"
build = "build.rs"
[features]
default = ["images"]
# Artwork over HTTP(S), decoded and scaled off the UI thread (images::Images).
images = ["dep:ureq", "dep:image"]
# Video playback with GStreamer (video::Player). Linux; needs GStreamer 1.22+.
video = ["dep:gstreamer", "dep:gstreamer-app", "dep:gstreamer-video"]
[dependencies]
anyhow.workspace = true
log.workspace = true
slint = { version = "1.18", default-features = false, features = ["std", "backend-default", "renderer-femtovg", "compat-1-2", "image-default-formats"] }
glow = "0.16"
png = "0.18"
ureq = { version = "3", optional = true }
image = { version = "0.25", optional = true, default-features = false, features = ["jpeg", "png", "webp"] }
gstreamer = { version = "0.25", optional = true }
gstreamer-app = { version = "0.25", optional = true }
gstreamer-video = { version = "0.25", optional = true }

7
crates/sf-ui/build.rs Normal file
View File

@@ -0,0 +1,7 @@
// Tells the build scripts of apps that depend on sf-ui where its Slint
// library is: they read it as DEP_SF_UI_UI_DIR and map it to "@sf-ui".
fn main() {
let dir = std::path::Path::new(&std::env::var("CARGO_MANIFEST_DIR").unwrap()).join("ui");
println!("cargo:ui_dir={}", dir.display());
println!("cargo:rerun-if-changed=build.rs");
}

View File

@@ -0,0 +1,21 @@
[package]
name = "sf-ui-gallery"
description = "Every sf-ui component on one screen (example and visual test)"
version.workspace = true
edition.workspace = true
license = "GPL-3.0-only"
publish = false
[dependencies]
sf-ui = { path = ".." }
slint = "1.18"
anyhow.workspace = true
log.workspace = true
env_logger.workspace = true
[features]
# SF_UI_VIDEO=<uri>: plays a video as the backdrop (Linux, GStreamer).
video = ["sf-ui/video"]
[build-dependencies]
slint-build = "1.18"

View File

@@ -0,0 +1,7 @@
fn main() {
// sf-ui's build script publishes where its Slint library is.
let sf_ui = std::env::var("DEP_SF_UI_UI_DIR").expect("sf-ui must be a direct dependency");
let config = slint_build::CompilerConfiguration::new()
.with_library_paths(std::collections::HashMap::from([("sf-ui".to_string(), sf_ui.into())]));
slint_build::compile_with_config("ui/gallery.slint", config).expect("compiling ui/gallery.slint");
}

View File

@@ -0,0 +1,101 @@
//! sf-ui gallery: every component on one screen.
//!
//! cargo run -p sf-ui-gallery
//! SF_UI_SIZE=1920x1080 SF_UI_KEYS="down right" SF_UI_SNAPSHOT=shot.png cargo run -p sf-ui-gallery
use std::time::Duration;
use slint::{ComponentHandle, Model, Rgba8Pixel, SharedPixelBuffer, VecModel};
slint::include_modules!();
sf_ui::glue!(Gallery);
/// Stand-in artwork: a soft two-colour gradient with a light blob.
fn artwork(a: [u8; 3], b: [u8; 3], w: u32, h: u32) -> SharedPixelBuffer<Rgba8Pixel> {
let mut px = SharedPixelBuffer::<Rgba8Pixel>::new(w, h);
let (cw, ch) = (w as f32, h as f32);
for (i, p) in px.make_mut_slice().iter_mut().enumerate() {
let (x, y) = ((i as u32 % w) as f32 / cw, (i as u32 / w) as f32 / ch);
let t = (x * 0.6 + y * 0.4).clamp(0.0, 1.0);
let d = ((x - 0.7).powi(2) + (y - 0.3).powi(2)).sqrt();
let glow = (1.0 - d * 2.2).max(0.0).powi(2) * 0.55;
let c = |k: usize| ((a[k] as f32 * (1.0 - t) + b[k] as f32 * t) * (1.0 - glow) + 255.0 * glow) as u8;
*p = Rgba8Pixel { r: c(0), g: c(1), b: c(2), a: 255 };
}
px
}
fn main() -> anyhow::Result<()> {
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
sf_ui::init()?;
let ui = Gallery::new()?;
ui.sf_ui_setup();
let colours = [
([190, 70, 40], [30, 10, 40]),
([30, 110, 160], [10, 20, 40]),
([60, 140, 80], [10, 30, 20]),
([170, 140, 40], [40, 20, 10]),
([120, 60, 170], [20, 10, 40]),
];
let pictures: Vec<SharedPixelBuffer<Rgba8Pixel>> = colours.iter().map(|(a, b)| artwork(*a, *b, 640, 360)).collect();
let images: Vec<slint::Image> = pictures.iter().map(|p| slint::Image::from_rgba8(p.clone())).collect();
ui.set_art(slint::ModelRc::new(VecModel::from(images)));
let weak = ui.as_weak();
ui.on_search(move |text| {
if let Some(ui) = weak.upgrade() {
ui.set_typed(text);
}
});
let glass = sf_ui::Glass::install(&ui, |ui, panels| {
panels.extend(ui.get_glass().iter());
panels.extend(ui.get_glass_menu().iter());
panels.extend(ui.get_glass_modal().iter());
panels.extend(ui.get_glass_keyboard().iter());
})?;
glass.set_palette(sf_ui::Palette::from_hex(["#ffb27a", "#8a3d12", "#120805"]));
// SF_UI_VIDEO=<uri> (feature "video"): the film plays under the glass.
#[cfg(feature = "video")]
let _video = match std::env::var("SF_UI_VIDEO") {
Ok(uri) => {
sf_ui::video::init()?;
log::info!("hardware decoding: {}", sf_ui::video::hardware_decoding());
let player = std::rc::Rc::new(std::cell::RefCell::new(sf_ui::video::Player::new(&uri, Default::default())?));
glass.set_video(Some(player.borrow().video()));
let p = player.clone();
let poll = slint::Timer::default();
poll.start(slint::TimerMode::Repeated, Duration::from_millis(100), move || {
let mut p = p.borrow_mut();
for ev in p.poll() {
log::info!("video: {ev:?}");
if let sf_ui::video::Event::Ready { .. } = ev {
log::info!("audio: {:?}", p.audio_tracks());
log::info!("text: {:?}", p.text_tracks());
}
}
});
Some((player, poll))
}
Err(_) => None,
};
// The focused card's artwork becomes the backdrop (crossfades), and the
// light follows the focus.
let weak = ui.as_weak();
let mut shown: Option<usize> = None;
let timer = slint::Timer::default();
timer.start(slint::TimerMode::Repeated, Duration::from_millis(100), move || {
let Some(ui) = weak.upgrade() else { return };
let want = (ui.get_area() == 2).then(|| ui.get_card() as usize);
if want != shown {
shown = want;
glass.set_backdrop(want.map(|i| sf_ui::Backdrop::new(pictures[i].clone()).dim(0.2)));
}
glass.set_light((ui.get_card() as f32 - 2.0) * 0.08);
});
ui.run()?;
Ok(())
}

View File

@@ -0,0 +1,181 @@
// sf-ui gallery: every component on one screen. Also the smallest complete
// example of an sf-ui app: TvWindow root, one FocusScope that owns the
// focus state, glass exported as [GlassRect] arrays for the Rust side.
import { TvWindow, Tv, SfText, GlassRect, GlassPane, GlassButton, GlassMenu, MenuItem, ProgressBar, ArtworkCard, Spinner, Keyboard, Icon, Headline, Title, Body, Label, Caption, SectionTitle } from "@sf-ui/sf-ui.slint";
// Rust needs these two globals (sf_ui::glue! wires SfText).
export { Tv, SfText }
export component Gallery inherits TvWindow {
title: "sf-ui gallery";
forward-focus: keys;
in property <[image]> art;
in-out property <float> progress: 0.36;
in property <string> typed;
callback search(string);
// Focus: 0 = buttons, 1 = menu, 2 = cards.
in-out property <int> area: 0;
in-out property <int> button: 0;
in-out property <int> item: 1;
in-out property <int> card: 0;
in-out property <bool> kb-open;
out property <float> kb-t: self.kb-open ? 1 : 0;
animate kb-t { duration: 480ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
// Content under the keyboard pane goes away completely before it arrives.
property <float> dim: max(0, 1 - 1.6 * self.kb-t);
keys := FocusScope {
key-pressed(event) => {
if root.kb-open {
return kb.key(event);
}
if event.text == Key.UpArrow {
if root.area == 1 { root.item = max(0, root.item - 1); }
if root.area == 2 { root.area = 0; }
} else if event.text == Key.DownArrow {
if root.area == 1 { if root.item < 4 { root.item += 1; } else { root.area = 2; } }
if root.area == 0 { root.area = 2; }
} else if event.text == Key.LeftArrow {
if root.area == 0 { root.button = max(0, root.button - 1); }
if root.area == 2 { root.card = max(0, root.card - 1); }
if root.area == 1 { root.area = 0; }
} else if event.text == Key.RightArrow {
if root.area == 0 { if root.button < 2 { root.button += 1; } else { root.area = 1; } }
if root.area == 2 { root.card = min(4, root.card + 1); }
} else if event.text == Key.Return {
if root.area == 0 && root.button == 1 {
kb.reset();
root.kb-open = true;
} else if root.area == 0 && root.button == 0 {
root.progress = root.progress > 0.9 ? 0 : root.progress + 0.1;
}
} else {
return reject;
}
accept
}
}
// ---- heading ----
Headline {
x: Tv.safe-x;
y: Tv.safe-y;
text: "sf-ui";
opacity: root.dim;
}
Caption {
x: Tv.safe-x;
y: Tv.safe-y + 72 * Tv.u;
text: "Nyilak: mozgás · OK: kiválasztás · Keresés: billentyűzet";
opacity: root.dim;
}
// ---- a details pane with buttons ----
pane := GlassPane {
x: Tv.safe-x;
y: 200 * Tv.u;
width: 1040 * Tv.u;
height: 520 * Tv.u;
alpha: root.dim;
VerticalLayout {
padding: 56 * Tv.u;
spacing: 20 * Tv.u;
opacity: root.dim;
Label { text: "Film · 2024 · 2 ó 16 p"; }
Title { text: "A dűne második része"; }
Body {
text: "Paul Atreides egyesül Chanival és a fremenekkel, miközben bosszút áll a családját elpusztító összeesküvőkön.";
vertical-stretch: 1;
}
HorizontalLayout {
spacing: 24 * Tv.u;
alignment: start;
b0 := GlassButton { text: "Lejátszás"; icon: "play"; primary: true; nested: true; focused: root.area == 0 && root.button == 0; alpha: root.dim; }
b1 := GlassButton { text: "Keresés"; icon: "search"; nested: true; focused: root.area == 0 && root.button == 1; alpha: root.dim; }
b2 := GlassButton { icon: "plus"; nested: true; focused: root.area == 0 && root.button == 2; alpha: root.dim; }
}
bar := ProgressBar { value: root.progress; buffered: root.progress + 0.2; alpha: root.dim; }
}
}
// ---- a menu ----
menu := GlassMenu {
x: 1264 * Tv.u;
y: 200 * Tv.u;
title: "Hang";
alpha: root.dim;
focused-index: root.area == 1 ? root.item : -1;
items: [
{ text: "Magyar", detail: "5.1", checked: root.item == 0 },
{ text: "Angol", detail: "Atmos", checked: root.item == 1 },
{ text: "Angol — Kommentár", detail: "Sztereó", checked: root.item == 2 },
{ text: "Német", detail: "5.1", checked: root.item == 3 },
{ text: "Francia", detail: "Sztereó", checked: root.item == 4 },
];
}
// ---- artwork ----
SectionTitle {
x: Tv.safe-x;
y: 760 * Tv.u;
text: root.typed == "" ? "Népszerű" : "Keresés: " + root.typed;
opacity: root.dim;
}
for i in 5: ArtworkCard {
x: Tv.safe-x + i * 344 * Tv.u;
y: 830 * Tv.u;
width: 312 * Tv.u;
height: 176 * Tv.u;
image: i < root.art.length ? root.art[i] : @image-url("");
placeholder: "Kártya \{i + 1}";
progress: i == 1 ? 0.4 : -1;
badge: i == 0 ? "Új rész" : "";
focused: root.area == 2 && root.card == i;
opacity: root.dim;
}
Spinner {
x: 1264 * Tv.u + 560 * Tv.u - self.width;
y: Tv.safe-y;
opacity: root.dim;
}
// ---- keyboard on a modal pane ----
modal := GlassPane {
x: (root.width - self.width) / 2;
y: (root.height - self.height) / 2;
width: 1720 * Tv.u;
height: 760 * Tv.u;
radius: 56 * Tv.u;
frost: 3.8;
tint: Tv.smoke.with-alpha(0.48);
glow: Tv.orange;
alpha: root.kb-t;
kb := Keyboard {
x: 0;
y: 96 * Tv.u;
width: parent.width;
title: "Keresés";
subtitle: "Filmek és sorozatok címe";
placeholder: "Cím";
submit-label: "Keresés";
min-length: 2;
alpha: root.kb-t;
submitted(text) => {
root.kb-open = false;
root.search(text);
}
cancelled => {
root.kb-open = false;
}
}
}
// ---- glass, in drawing order ----
out property <[GlassRect]> glass: [pane.glass, b0.glass, b1.glass, b2.glass, bar.glass];
out property <[GlassRect]> glass-menu: menu.glass;
out property <[GlassRect]> glass-modal: [modal.glass];
out property <[GlassRect]> glass-keyboard: kb.glass;
}

103
crates/sf-ui/src/dev.rs Normal file
View File

@@ -0,0 +1,103 @@
//! Dev helper, built into every [`crate::Glass`] window: scripted key presses
//! and a PNG snapshot of the window, so a UI can be checked (by you, a CI job
//! or an AI) without anyone at the screen.
//!
//! - `SF_UI_SIZE=1920x1080`: physical window size.
//! - `SF_UI_KEYS="down down right enter wait esc"`: keys sent one by one
//! (left, right, up, down, enter, esc, back = esc, backspace, space;
//! a single character types it, `wait` = pause,
//! `hold` = enter held 0.8 s), starting after 1.5 s, every 0.6 s.
//! - `SF_UI_SNAPSHOT=out.png`: saves the frame and quits, 1.5 s after the
//! last key (or after `SF_UI_SNAPSHOT_MS` milliseconds).
use std::cell::{Cell, RefCell};
use std::path::PathBuf;
use std::rc::Rc;
use std::time::Duration;
use slint::ComponentHandle;
use slint::platform::{Key, WindowEvent};
const FIRST_KEY_MS: u64 = 1500;
const KEY_STEP_MS: u64 = 600;
/// A snapshot waiting to be taken (shared with the rendering notifier).
#[derive(Default)]
pub(crate) struct Snapshot {
pub(crate) path: RefCell<Option<PathBuf>>,
pub(crate) due: Cell<bool>,
}
pub(crate) fn setup<C: ComponentHandle + 'static>(ui: &C) -> Rc<Snapshot> {
let snap = Rc::new(Snapshot::default());
if let Some((w, h)) = std::env::var("SF_UI_SIZE").ok().and_then(|s| {
let (w, h) = s.split_once('x')?;
Some((w.trim().parse().ok()?, h.trim().parse().ok()?))
}) {
ui.window().set_size(slint::PhysicalSize::new(w, h));
}
let keys: Vec<String> =
std::env::var("SF_UI_KEYS").map(|s| s.split_whitespace().map(str::to_string).collect()).unwrap_or_default();
let mut at = FIRST_KEY_MS;
for k in &keys {
let hold = k == "hold";
let text: Option<slint::SharedString> = match k.to_lowercase().as_str() {
"hold" | "enter" => Some(Key::Return.into()),
"left" => Some(Key::LeftArrow.into()),
"right" => Some(Key::RightArrow.into()),
"up" => Some(Key::UpArrow.into()),
"down" => Some(Key::DownArrow.into()),
"esc" | "back" => Some(Key::Escape.into()),
"backspace" => Some(Key::Backspace.into()),
"space" => Some(" ".into()),
"wait" => None,
_ if k.chars().count() == 1 => Some(k.as_str().into()),
_ => None,
};
let start = at;
at += if hold { 2 * KEY_STEP_MS } else { KEY_STEP_MS };
let Some(text) = text else { continue };
let weak = ui.as_weak();
let t = text.clone();
slint::Timer::single_shot(Duration::from_millis(start), move || {
if let Some(ui) = weak.upgrade() {
ui.window().dispatch_event(WindowEvent::KeyPressed { text: t.clone() });
if !hold {
ui.window().dispatch_event(WindowEvent::KeyReleased { text: t });
}
}
});
if hold {
let weak = ui.as_weak();
slint::Timer::single_shot(Duration::from_millis(start + 800), move || {
if let Some(ui) = weak.upgrade() {
ui.window().dispatch_event(WindowEvent::KeyReleased { text });
}
});
}
}
if let Some(path) = std::env::var_os("SF_UI_SNAPSHOT").map(PathBuf::from) {
let ms = std::env::var("SF_UI_SNAPSHOT_MS").ok().and_then(|s| s.parse().ok()).unwrap_or(at + 1500);
*snap.path.borrow_mut() = Some(path);
let s = snap.clone();
slint::Timer::single_shot(Duration::from_millis(ms), move || s.due.set(true));
}
snap
}
/// Writes top-down RGBA8 pixels as a PNG.
pub(crate) fn save_png(path: &std::path::Path, w: u32, h: u32, rgba: &[u8]) -> anyhow::Result<()> {
let file = std::io::BufWriter::new(std::fs::File::create(path)?);
let mut enc = png::Encoder::new(file, w, h);
enc.set_color(png::ColorType::Rgba);
enc.set_depth(png::BitDepth::Eight);
// The window has no meaningful alpha: make every pixel opaque.
let mut data = rgba.to_vec();
for px in data.chunks_exact_mut(4) {
px[3] = 255;
}
enc.write_header()?.write_image_data(&data)?;
Ok(())
}

386
crates/sf-ui/src/glass.rs Normal file
View File

@@ -0,0 +1,386 @@
//! The Liquid Glass layer for a Slint window: install it once, then tell it
//! each frame which panels to draw (usually the `[GlassRect]` arrays your
//! .slint file exports), and set the backdrop (palette, picture, video).
//!
//! ```ignore
//! sf_ui::init()?; // before creating the window
//! let ui = App::new()?;
//! ui.sf_ui_setup(); // from sf_ui::glue!(App)
//! let glass = sf_ui::Glass::install(&ui, |ui, panels| {
//! panels.extend(ui.get_glass().iter());
//! })?;
//! glass.set_palette(sf_ui::Palette::from_hex(["#ffb27a", "#8a3d12", "#120805"]));
//! ui.run()?;
//! ```
use std::cell::RefCell;
use std::rc::Rc;
use std::time::Instant;
use slint::{ComponentHandle, Rgba8Pixel, SharedPixelBuffer};
use crate::render::{Frame, GlassRenderer, ImageDraw, ImageId, Nv12Frame, Panel, Quality, VideoDraw};
use crate::Palette;
/// Time constant of palette and brightness changes (seconds).
const EASE: f32 = 0.35;
/// Crossfade time of pictures and video (seconds).
const FADE: f32 = 0.45;
/// A picture for the backdrop (artwork behind a details page, a hero...).
/// Glass panels refract and frost it like the gradient.
#[derive(Clone)]
pub struct Backdrop {
pixels: SharedPixelBuffer<Rgba8Pixel>,
dim: f32,
fade_left: f32,
fade_bottom: f32,
align: [f32; 2],
sharp: bool,
}
impl Backdrop {
/// Defaults: slightly dimmed, darker towards the left and bottom (room
/// for titles), sharp, cropped around the centre.
pub fn new(pixels: SharedPixelBuffer<Rgba8Pixel>) -> Backdrop {
Backdrop { pixels, dim: 0.12, fade_left: 0.75, fade_bottom: 0.6, align: [0.5, 0.35], sharp: true }
}
/// Darkens the whole picture: 0 = as is, 1 = black.
pub fn dim(mut self, v: f32) -> Self {
self.dim = v.clamp(0.0, 1.0);
self
}
/// Darkening towards the left edge, 0..1.
pub fn fade_left(mut self, v: f32) -> Self {
self.fade_left = v.clamp(0.0, 1.0);
self
}
/// Darkening towards the bottom edge, 0..1.
pub fn fade_bottom(mut self, v: f32) -> Self {
self.fade_bottom = v.clamp(0.0, 1.0);
self
}
/// Which part stays visible when cropped (0..1 per axis, 0.5 = centre).
pub fn align(mut self, x: f32, y: f32) -> Self {
self.align = [x.clamp(0.0, 1.0), y.clamp(0.0, 1.0)];
self
}
/// Soft: only the blurred low-resolution copy shows (a frosted wallpaper).
pub fn soft(mut self) -> Self {
self.sharp = false;
self
}
}
/// Where video frames come from (see `sf_ui::video::Player`, or your own
/// decoder). Called once per rendered frame on the UI thread.
pub trait VideoSource {
/// The newest frame since the last call, if any.
fn take_frame(&self) -> Option<Box<dyn Nv12Frame + '_>>;
}
/// Collects the glass panels of one frame, in logical pixels (the units of
/// your .slint file). Draw order is push order: later panels lie on top.
pub struct Panels {
scale: f32,
out: Vec<Panel>,
}
impl Panels {
/// One panel (logical px).
pub fn push(&mut self, panel: impl Into<Panel>) {
let p = panel.into();
if p.alpha > 0.002 && p.w > 0.0 && p.h > 0.0 {
self.out.push(p.scaled(self.scale));
}
}
/// Many panels, e.g. `panels.extend(ui.get_glass().iter())`.
pub fn extend<T: Into<Panel>>(&mut self, panels: impl IntoIterator<Item = T>) {
for p in panels {
self.push(p);
}
}
}
struct Slot {
backdrop: Backdrop,
id: Option<ImageId>,
alpha: f32,
target: f32,
}
struct State {
palette: [f32; 9],
palette_target: [f32; 9],
brightness: f32,
brightness_target: f32,
images: Vec<Slot>,
free: Vec<ImageId>,
video: Option<Rc<dyn VideoSource>>,
video_alpha: f32,
video_on: bool,
clear_video: bool,
light: f32,
zoom: f32,
last: f32,
quality: Quality,
}
/// Handle to an installed glass layer (cheap to clone).
#[derive(Clone)]
pub struct Glass {
state: Rc<RefCell<State>>,
}
impl Glass {
/// Draws the glass layer under `ui`'s window. `panels` runs before every
/// frame and adds that frame's panels. The backdrop animates, so frames
/// keep coming (vsync-limited).
///
/// Call [`crate::init`] before creating the window: the layer needs the
/// OpenGL (FemtoVG) renderer.
pub fn install<C: ComponentHandle + 'static>(
ui: &C,
mut panels: impl FnMut(&C, &mut Panels) + 'static,
) -> anyhow::Result<Glass> {
let neutral = Palette::NEUTRAL.to_floats();
let state = Rc::new(RefCell::new(State {
palette: neutral,
palette_target: neutral,
brightness: 1.0,
brightness_target: 1.0,
images: Vec::new(),
free: Vec::new(),
video: None,
video_alpha: 0.0,
video_on: false,
clear_video: false,
light: 0.0,
zoom: 1.0,
last: 0.0,
quality: Quality::Full,
}));
let glass = Glass { state: state.clone() };
let snapshot = crate::dev::setup(ui);
let renderer: Rc<RefCell<Option<GlassRenderer>>> = Rc::default();
let start = Instant::now();
let weak = ui.as_weak();
ui.window()
.set_rendering_notifier(move |rs, api| match rs {
slint::RenderingState::RenderingSetup => {
let slint::GraphicsAPI::NativeOpenGL { get_proc_address } = api else {
log::error!("sf-ui: the glass layer needs OpenGL (call sf_ui::init() first)");
return;
};
let gl = unsafe { glow::Context::from_loader_function_cstr(|s| get_proc_address(s)) };
match unsafe { GlassRenderer::new(gl) } {
Ok(r) => *renderer.borrow_mut() = Some(r),
Err(e) => log::error!("sf-ui: glass layer disabled: {e:#}"),
}
}
slint::RenderingState::BeforeRendering => {
let mut guard = renderer.borrow_mut();
let (Some(ui), Some(r)) = (weak.upgrade(), guard.as_mut()) else { return };
let time = start.elapsed().as_secs_f32();
let size = ui.window().size();
let scale = ui.window().scale_factor();
let mut list = Panels { scale, out: Vec::new() };
panels(&ui, &mut list);
let mut st = state.borrow_mut();
let dt = (time - st.last).clamp(0.0, 0.25);
st.last = time;
st.step(dt);
// SAFETY: the rendering notifier runs with the GL context current.
unsafe { st.sync_images(r) };
if std::mem::take(&mut st.clear_video) {
r.clear_video();
}
let draws: Vec<ImageDraw> = st
.images
.iter()
.filter_map(|s| {
Some(ImageDraw {
image: s.id?,
alpha: s.alpha,
dim: s.backdrop.dim,
fade_left: s.backdrop.fade_left,
fade_bottom: s.backdrop.fade_bottom,
align: s.backdrop.align,
sharp: s.backdrop.sharp,
})
})
.collect();
let video = st.video.clone();
let frame_box = video.as_ref().and_then(|v| v.take_frame());
let angle = -2.25 + 0.10 * (time * 0.35).sin() + st.light;
let frame = Frame {
width: size.width,
height: size.height,
scale,
time,
palette: st.palette,
brightness: st.brightness,
light: [angle.cos(), angle.sin()],
zoom: st.zoom,
images: &draws,
video: (st.video_alpha > 0.002 || frame_box.is_some())
.then(|| VideoDraw { frame: frame_box.as_deref(), alpha: st.video_alpha }),
rects: list.out,
quality: st.quality,
};
drop(st);
// SAFETY: as above.
unsafe { r.render(&frame) };
}
slint::RenderingState::AfterRendering => {
let Some(ui) = weak.upgrade() else { return };
if snapshot.due.get() {
if let (Some(path), Some(r)) = (snapshot.path.borrow_mut().take(), renderer.borrow().as_ref()) {
let size = ui.window().size();
// SAFETY: after Slint rendered, context current.
let px = unsafe { r.read_pixels(size.width, size.height) };
match crate::dev::save_png(&path, size.width, size.height, &px) {
Ok(()) => log::info!("sf-ui: snapshot {}", path.display()),
Err(e) => log::error!("sf-ui: snapshot {}: {e:#}", path.display()),
}
let _ = slint::quit_event_loop();
}
}
ui.window().request_redraw();
}
slint::RenderingState::RenderingTeardown => {
if let Some(mut r) = renderer.borrow_mut().take() {
unsafe { r.destroy() };
}
// Textures died with the context: upload again if it comes back.
for s in state.borrow_mut().images.iter_mut() {
s.id = None;
}
}
_ => {}
})
.map_err(|e| anyhow::anyhow!("sf-ui: rendering notifier: {e:?}"))?;
Ok(glass)
}
/// The backdrop gradient's colours; eases over from the current ones.
pub fn set_palette(&self, palette: Palette) {
self.state.borrow_mut().palette_target = palette.to_floats();
}
/// Backdrop brightness, 0..1 (1 = full). Lower it to calm the backdrop
/// behind dense content.
pub fn set_brightness(&self, v: f32) {
self.state.borrow_mut().brightness_target = v.clamp(0.0, 1.0);
}
/// A picture over the gradient (crossfades from the previous one), or
/// `None` to fade back to the gradient.
pub fn set_backdrop(&self, backdrop: Option<Backdrop>) {
let mut st = self.state.borrow_mut();
match backdrop {
Some(b) => {
// Already showing this very picture: keep it.
if let Some(last) = st.images.last_mut() {
if last.backdrop.pixels.as_bytes().as_ptr() == b.pixels.as_bytes().as_ptr() {
last.backdrop = b;
last.target = 1.0;
return;
}
}
st.images.push(Slot { backdrop: b, id: None, alpha: 0.0, target: 1.0 });
}
None => {
for s in st.images.iter_mut() {
s.target = 0.0;
}
}
}
}
/// Video as the backdrop (glass refracts the film), or `None` to fade it
/// out. The source is polled once per frame.
pub fn set_video(&self, source: Option<Rc<dyn VideoSource>>) {
let mut st = self.state.borrow_mut();
st.video_on = source.is_some();
if source.is_some() {
st.video = source;
st.clear_video = true;
}
}
/// Turns the key light (radians, small values like ±0.3), e.g. to follow
/// the focus across the screen.
pub fn set_light(&self, offset: f32) {
self.state.borrow_mut().light = offset;
}
/// How much of the glass effect to draw ([`Quality::Light`] or
/// [`Quality::Flat`] on weaker hardware).
pub fn set_quality(&self, q: Quality) {
self.state.borrow_mut().quality = q;
}
/// Zooms the backdrop gradient (1 = none).
pub fn set_zoom(&self, zoom: f32) {
self.state.borrow_mut().zoom = zoom.max(0.1);
}
}
impl State {
fn step(&mut self, dt: f32) {
let k = 1.0 - (-dt / EASE).exp();
for (c, t) in self.palette.iter_mut().zip(self.palette_target) {
*c += (t - *c) * k;
}
self.brightness += (self.brightness_target - self.brightness) * k;
let fade = dt / FADE;
for s in self.images.iter_mut() {
s.alpha = if s.target > s.alpha { (s.alpha + fade).min(s.target) } else { (s.alpha - fade).max(s.target) };
}
// A picture fully covered by a newer, opaque one is no longer needed;
// faded-out ones neither.
let covered = self.images.iter().rposition(|s| s.alpha >= 0.999).unwrap_or(0);
let mut i = 0;
self.images.retain(|s| {
let keep = i >= covered && !(s.target == 0.0 && s.alpha <= 0.0);
i += 1;
if !keep {
if let Some(id) = s.id {
self.free.push(id);
}
}
keep
});
let target = if self.video_on { 1.0 } else { 0.0 };
self.video_alpha = if target > self.video_alpha {
(self.video_alpha + dt / 0.3).min(1.0)
} else {
(self.video_alpha - dt / 0.3).max(0.0)
};
if !self.video_on && self.video_alpha <= 0.0 {
self.video = None;
}
}
unsafe fn sync_images(&mut self, r: &mut GlassRenderer) {
for id in self.free.drain(..) {
unsafe { r.free_image(id) };
}
for s in self.images.iter_mut().filter(|s| s.id.is_none()) {
let px = &s.backdrop.pixels;
match unsafe { r.upload_image(px.width(), px.height(), px.as_bytes()) } {
Ok(id) => s.id = Some(id),
Err(e) => {
log::warn!("sf-ui: backdrop picture: {e:#}");
s.target = 0.0;
s.alpha = 0.0;
}
}
}
}
}

259
crates/sf-ui/src/images.rs Normal file
View File

@@ -0,0 +1,259 @@
//! Artwork over HTTP(S): downloaded, decoded and scaled on worker threads,
//! kept in a memory cache, handed to you on the UI thread.
//!
//! ```ignore
//! let images = sf_ui::images::Images::new(256 << 20);
//! images.load(&poster_url, (240, 360), move |img| card.set_image(img));
//! ```
//!
//! Sizes are the size you show the picture at, in *physical* pixels (design
//! px × the window's scale): the picture is scaled down to cover that box
//! (never up), so a 4K TV gets sharper artwork and a 1080p one uses less memory.
use std::cell::RefCell;
use std::collections::{HashMap, VecDeque};
use std::io::Read;
use std::rc::{Rc, Weak};
use std::sync::atomic::{AtomicU64, Ordering};
use std::sync::mpsc;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use slint::{Rgba8Pixel, SharedPixelBuffer};
/// Bigger downloads are refused.
const MAX_DOWNLOAD: u64 = 24 << 20;
const WORKERS: usize = 4;
type Pixels = SharedPixelBuffer<Rgba8Pixel>;
type Key = (String, u32, u32);
type Waiter = Box<dyn FnOnce(&Pixels)>;
struct Job {
owner: u64,
key: Key,
}
struct Inner {
id: u64,
budget: usize,
used: RefCell<usize>,
cache: RefCell<HashMap<Key, Pixels>>,
order: RefCell<VecDeque<Key>>,
waiting: RefCell<HashMap<Key, Vec<Waiter>>>,
jobs: Mutex<Option<mpsc::Sender<()>>>,
queue: Arc<Mutex<VecDeque<Job>>>,
}
thread_local! {
static OWNERS: RefCell<HashMap<u64, Weak<Inner>>> = RefCell::new(HashMap::new());
}
static NEXT_ID: AtomicU64 = AtomicU64::new(1);
/// The image loader and cache (cheap to clone; use it on the UI thread).
#[derive(Clone)]
pub struct Images {
inner: Rc<Inner>,
}
impl Images {
/// `budget`: bytes of decoded pixels to keep (e.g. `256 << 20`).
pub fn new(budget: usize) -> Images {
let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
let queue: Arc<Mutex<VecDeque<Job>>> = Arc::default();
let (tx, rx) = mpsc::channel::<()>();
let rx = Arc::new(Mutex::new(rx));
let agent: ureq::Agent = ureq::Agent::config_builder()
.timeout_global(Some(Duration::from_secs(30)))
.user_agent("SmartFox sf-ui")
.build()
.into();
for _ in 0..WORKERS {
let rx = rx.clone();
let queue = queue.clone();
let agent = agent.clone();
std::thread::spawn(move || {
// Wake-ups come over the channel; the newest request is served first
// (what the user looks at now), from the shared queue.
while rx.lock().unwrap().recv().is_ok() {
let Some(job) = queue.lock().unwrap().pop_back() else { continue };
let result = fetch(&agent, &job.key.0, job.key.1, job.key.2);
if let Err(e) = &result {
log::debug!("image {}: {e:#}", job.key.0);
}
let (owner, key) = (job.owner, job.key);
let _ = slint::invoke_from_event_loop(move || deliver(owner, key, result.ok()));
}
});
}
let inner = Rc::new(Inner {
id,
budget,
used: RefCell::new(0),
cache: RefCell::default(),
order: RefCell::default(),
waiting: RefCell::default(),
jobs: Mutex::new(Some(tx)),
queue,
});
OWNERS.with(|o| o.borrow_mut().insert(id, Rc::downgrade(&inner)));
Images { inner }
}
/// Loads `url` scaled to cover `size` (physical px) and calls `done` with
/// it on the UI thread: at once if cached, later otherwise. On failure
/// `done` is not called.
pub fn load(&self, url: &str, size: (u32, u32), done: impl FnOnce(slint::Image) + 'static) {
self.load_pixels(url, size, move |px| done(slint::Image::from_rgba8(px.clone())));
}
/// Like [`Images::load`], but hands over the pixels (for
/// [`crate::Backdrop`] or your own processing).
pub fn load_pixels(&self, url: &str, size: (u32, u32), done: impl FnOnce(&Pixels) + 'static) {
if url.is_empty() {
return;
}
let key: Key = (url.to_string(), size.0.max(1), size.1.max(1));
if let Some(px) = self.inner.cache.borrow().get(&key).cloned() {
self.touch(&key);
done(&px);
return;
}
let mut waiting = self.inner.waiting.borrow_mut();
if let Some(list) = waiting.get_mut(&key) {
list.push(Box::new(done));
return;
}
waiting.insert(key.clone(), vec![Box::new(done)]);
drop(waiting);
self.inner.queue.lock().unwrap().push_back(Job { owner: self.inner.id, key });
if let Some(tx) = self.inner.jobs.lock().unwrap().as_ref() {
let _ = tx.send(());
}
}
/// The cached picture, if it is already loaded.
pub fn cached(&self, url: &str, size: (u32, u32)) -> Option<slint::Image> {
let key: Key = (url.to_string(), size.0.max(1), size.1.max(1));
self.inner.cache.borrow().get(&key).map(|px| slint::Image::from_rgba8(px.clone()))
}
/// Drops requests that have not started yet (e.g. after leaving a screen).
pub fn cancel_pending(&self) {
let mut q = self.inner.queue.lock().unwrap();
let mut waiting = self.inner.waiting.borrow_mut();
for job in q.drain(..) {
waiting.remove(&job.key);
}
}
fn touch(&self, key: &Key) {
let mut order = self.inner.order.borrow_mut();
if let Some(i) = order.iter().position(|k| k == key) {
let k = order.remove(i).unwrap();
order.push_back(k);
}
}
}
impl Inner {
fn insert(&self, key: Key, px: Pixels) {
let bytes = px.as_bytes().len();
let mut cache = self.cache.borrow_mut();
let mut order = self.order.borrow_mut();
let mut used = self.used.borrow_mut();
while *used + bytes > self.budget {
let Some(old) = order.pop_front() else { break };
if let Some(p) = cache.remove(&old) {
*used -= p.as_bytes().len();
}
}
*used += bytes;
order.push_back(key.clone());
cache.insert(key, px);
}
}
impl Drop for Inner {
fn drop(&mut self) {
// Ends the worker threads.
self.jobs.lock().unwrap().take();
let id = self.id;
let _ = OWNERS.try_with(|o| o.borrow_mut().remove(&id));
}
}
fn deliver(owner: u64, key: Key, px: Option<Pixels>) {
let Some(inner) = OWNERS.with(|o| o.borrow().get(&owner).and_then(Weak::upgrade)) else { return };
let waiters = inner.waiting.borrow_mut().remove(&key).unwrap_or_default();
let Some(px) = px else { return };
inner.insert(key, px.clone());
for w in waiters {
w(&px);
}
}
fn fetch(agent: &ureq::Agent, url: &str, w: u32, h: u32) -> anyhow::Result<Pixels> {
let mut resp = agent.get(url).call()?;
let mut bytes = Vec::new();
resp.body_mut().as_reader().take(MAX_DOWNLOAD + 1).read_to_end(&mut bytes)?;
anyhow::ensure!((bytes.len() as u64) <= MAX_DOWNLOAD, "larger than {MAX_DOWNLOAD} bytes");
decode(&bytes, w, h)
}
/// Decodes and scales down to cover `w` x `h` (never up).
pub fn decode(bytes: &[u8], w: u32, h: u32) -> anyhow::Result<Pixels> {
let img = image::load_from_memory(bytes)?;
let (iw, ih) = (img.width().max(1), img.height().max(1));
let k = (w as f32 / iw as f32).max(h as f32 / ih as f32);
let img = if k < 0.98 {
let (nw, nh) = (((iw as f32 * k).round() as u32).max(1), ((ih as f32 * k).round() as u32).max(1));
img.resize_exact(nw, nh, image::imageops::FilterType::Triangle)
} else {
img
};
let rgba = img.into_rgba8();
Ok(SharedPixelBuffer::clone_from_slice(rgba.as_raw(), rgba.width(), rgba.height()))
}
/// The average colour of a picture (for a matching [`crate::Palette`]),
/// leaning towards its saturated parts.
pub fn average_color(px: &Pixels) -> slint::Color {
let (mut r, mut g, mut b, mut n) = (0f64, 0f64, 0f64, 0f64);
let bytes = px.as_bytes();
for p in bytes.chunks_exact(4).step_by(7) {
let (pr, pg, pb) = (p[0] as f64, p[1] as f64, p[2] as f64);
let max = pr.max(pg).max(pb);
let min = pr.min(pg).min(pb);
let wgt = 0.15 + (max - min) / 255.0 + max / 510.0;
r += pr * wgt;
g += pg * wgt;
b += pb * wgt;
n += wgt;
}
if n == 0.0 {
return slint::Color::from_rgb_u8(0x2a, 0x31, 0x40);
}
slint::Color::from_rgb_u8((r / n) as u8, (g / n) as u8, (b / n) as u8)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn scales_to_cover() {
let mut png = Vec::new();
let img = image::RgbaImage::from_pixel(400, 600, image::Rgba([200, 40, 30, 255]));
image::DynamicImage::ImageRgba8(img)
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.unwrap();
let px = decode(&png, 100, 100).unwrap();
assert_eq!((px.width(), px.height()), (100, 150));
let px = decode(&png, 1000, 1000).unwrap();
assert_eq!((px.width(), px.height()), (400, 600));
let c = average_color(&px);
assert!(c.red() > 150 && c.green() < 80);
}
}

191
crates/sf-ui/src/lib.rs Normal file
View File

@@ -0,0 +1,191 @@
//! sf-ui: the SmartFox TV UI kit for Slint apps.
//!
//! - **Liquid Glass** ([`Glass`]): the refracting, frosted glass of the
//! SmartFox launcher, drawn by an OpenGL layer under your Slint UI, over an
//! animated palette backdrop, a picture or a playing video.
//! - **Slint components** (`@sf-ui/sf-ui.slint`): design tokens (`Tv`), text
//! styles, glass panes, buttons, chips, a progress bar, an on-screen
//! keyboard, icons and the Onest font.
//! - **Images** ([`images::Images`], feature `images`): artwork over HTTP,
//! decoded and scaled off the UI thread, cached.
//! - **Video** (`video::Player`, feature `video`, Linux): GStreamer playback
//! with hardware decoding, its frames shown as the glass backdrop.
//!
//! Guide: `docs/sf-ui.md` in the SmartFox repository.
pub mod render;
mod dev;
mod glass;
#[cfg(feature = "images")]
pub mod images;
pub mod text;
#[cfg(feature = "video")]
pub mod video;
pub use glass::{Backdrop, Glass, Panels, VideoSource};
pub use render::{Matrix, Nv12Frame, Panel, Quality};
/// Selects Slint's OpenGL renderer (FemtoVG), which the glass layer draws
/// with. Call it first in `main`, before creating any window.
pub fn init() -> anyhow::Result<()> {
slint::BackendSelector::new()
.renderer_name("femtovg".into())
.select()
.map_err(|e| anyhow::anyhow!("selecting the femtovg (OpenGL) renderer: {e}"))
}
/// The backdrop gradient's three colours: highlight, mid, deep. Use the
/// `palette` of your app.toml, or one per screen / per focused item.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Palette {
pub highlight: slint::Color,
pub mid: slint::Color,
pub deep: slint::Color,
}
impl Palette {
/// The neutral system palette (no app colour).
pub const NEUTRAL: Palette = Palette {
highlight: slint::Color::from_rgb_u8(0x9a, 0xa4, 0xb5),
mid: slint::Color::from_rgb_u8(0x2a, 0x31, 0x40),
deep: slint::Color::from_rgb_u8(0x06, 0x07, 0x0a),
};
pub fn new(highlight: slint::Color, mid: slint::Color, deep: slint::Color) -> Palette {
Palette { highlight, mid, deep }
}
/// From three "#rrggbb" strings (as in app.toml); bad ones fall back to
/// the neutral palette's colour.
pub fn from_hex(hex: [&str; 3]) -> Palette {
let n = Palette::NEUTRAL;
Palette {
highlight: parse_hex(hex[0]).unwrap_or(n.highlight),
mid: parse_hex(hex[1]).unwrap_or(n.mid),
deep: parse_hex(hex[2]).unwrap_or(n.deep),
}
}
/// A palette from one colour, e.g. the average colour of a poster:
/// a lighter highlight, the colour itself, a near-black deep tone.
pub fn from_color(c: slint::Color) -> Palette {
let [r, g, b] = rgb(c);
let mix = |k: f32, t: f32| -> slint::Color {
let f = |v: f32| ((v * k + t * (1.0 - k)).clamp(0.0, 1.0) * 255.0) as u8;
slint::Color::from_rgb_u8(f(r), f(g), f(b))
};
Palette { highlight: mix(0.7, 1.0), mid: mix(0.55, 0.0), deep: mix(0.08, 0.0) }
}
/// rgb 0..1 for the renderer.
pub fn to_floats(self) -> [f32; 9] {
let mut out = [0.0; 9];
for (i, c) in [self.highlight, self.mid, self.deep].into_iter().enumerate() {
out[i * 3..i * 3 + 3].copy_from_slice(&rgb(c));
}
out
}
}
/// "#rrggbb" or "rrggbb".
pub fn parse_hex(hex: &str) -> Option<slint::Color> {
let h = hex.trim().trim_start_matches('#');
let v = u32::from_str_radix(h.get(..6)?, 16).ok()?;
Some(slint::Color::from_rgb_u8((v >> 16) as u8, (v >> 8) as u8, v as u8))
}
fn rgb(c: slint::Color) -> [f32; 3] {
[c.red() as f32 / 255.0, c.green() as f32 / 255.0, c.blue() as f32 / 255.0]
}
impl Panel {
/// From the fields of a Slint `GlassRect` (used by [`glue!`]).
#[allow(clippy::too_many_arguments)]
pub fn from_slint(
x: f32,
y: f32,
w: f32,
h: f32,
r: f32,
focus: f32,
alpha: f32,
blur: f32,
glow: slint::Color,
tint: slint::Color,
group: i32,
) -> Panel {
let [tr, tg, tb] = rgb(tint);
Panel {
x,
y,
w,
h,
radius: r,
focus,
alpha,
blur,
glow: rgb(glow),
group: group as f32,
tint: [tr, tg, tb, tint.alpha() as f32 / 255.0],
}
}
}
/// Connects the types Slint generated in *your* crate to sf-ui. Put it once
/// next to `slint::include_modules!()`, with your root component's name:
///
/// ```ignore
/// slint::include_modules!();
/// sf_ui::glue!(App);
/// ```
///
/// It makes `GlassRect` convertible to [`Panel`] (so `panels.extend(...)`
/// takes your `[GlassRect]` arrays) and adds `App::sf_ui_setup()`, which
/// wires the Slint helper callbacks (`SfText`). Your main .slint file must
/// export the helpers: `export { Tv, SfText } from "@sf-ui/sf-ui.slint";`.
#[macro_export]
macro_rules! glue {
($app:ident) => {
impl ::core::convert::From<GlassRect> for $crate::Panel {
fn from(g: GlassRect) -> Self {
$crate::Panel::from_slint(g.x, g.y, g.w, g.h, g.r, g.focus, g.alpha, g.blur, g.glow.color(), g.tint.color(), g.group)
}
}
impl $app {
/// Wires the sf-ui Slint helpers (text editing for the keyboard).
/// Call it once after creating the window.
#[allow(dead_code)]
pub fn sf_ui_setup(&self) {
use ::slint::ComponentHandle as _;
let t = self.global::<SfText>();
t.on_drop_last(|s| $crate::text::drop_last(&s).into());
t.on_dots(|n| $crate::text::dots(n.max(0) as usize).into());
t.on_truncate(|s, n| $crate::text::truncate(&s, n.max(0) as usize).into());
t.on_typable(|s| $crate::text::typable(&s).into());
}
}
};
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn hex_colours() {
assert_eq!(parse_hex("#ff7a35"), Some(slint::Color::from_rgb_u8(0xff, 0x7a, 0x35)));
assert_eq!(parse_hex("121317"), Some(slint::Color::from_rgb_u8(0x12, 0x13, 0x17)));
assert_eq!(parse_hex("#12"), None);
let p = Palette::from_hex(["#ffffff", "nope", "#000000"]);
assert_eq!(p.mid, Palette::NEUTRAL.mid);
assert_eq!(p.to_floats()[0], 1.0);
}
#[test]
fn panel_scaling() {
let p = Panel { x: 10.0, y: 20.0, w: 30.0, h: 40.0, radius: 5.0, alpha: 1.0, ..Panel::default() }.scaled(2.0);
assert_eq!((p.x, p.y, p.w, p.h, p.radius), (20.0, 40.0, 60.0, 80.0, 10.0));
}
}

View File

@@ -0,0 +1,167 @@
//! The low-level Liquid Glass renderer: an OpenGL pass drawn *under* the
//! Slint UI. Most apps use [`crate::Glass`] instead, which drives this from a
//! Slint rendering notifier; use this module directly only if you need your
//! own notifier (the launcher does, for its dev snapshots).
//!
//! Per frame: the backdrop (animated gradient, optional pictures, optional
//! video) goes into a small mipmapped texture and onto the window; then every
//! glass panel is drawn as its own quad, refracting and frosting that texture.
mod renderer;
mod shaders;
pub use renderer::GlassRenderer;
/// Panels drawn per frame at most (each one is its own small draw call).
pub const MAX_RECTS: usize = 48;
/// Members of one merged (liquid) group at most.
pub const MAX_GROUP: usize = 4;
/// One glass panel. In [`Frame`] it is in physical pixels (top-left origin);
/// [`crate::Panels`] takes it in logical pixels and scales it.
#[derive(Debug, Clone, Copy, Default, PartialEq)]
pub struct Panel {
pub x: f32,
pub y: f32,
pub w: f32,
pub h: f32,
pub radius: f32,
/// 0..1, brightens the rim and adds the accent glow.
pub focus: f32,
pub alpha: f32,
/// Frost: mip level of the backdrop seen through it (higher = blurrier).
/// Negative = nested glass that sits on another pane.
pub blur: f32,
/// Accent light (rgb 0..1) for focus glow and rim.
pub glow: [f32; 3],
/// Consecutive panels with the same group (> 0) melt into one shape.
pub group: f32,
/// rgb + amount (0..1).
pub tint: [f32; 4],
}
impl Panel {
/// The same panel with every length multiplied by `k` (logical → physical).
pub fn scaled(mut self, k: f32) -> Panel {
self.x *= k;
self.y *= k;
self.w *= k;
self.h *= k;
self.radius *= k;
self
}
}
/// A picture uploaded with [`GlassRenderer::upload_image`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ImageId(pub(crate) u32);
/// One picture on the backdrop, drawn over the gradient (and under the glass).
#[derive(Debug, Clone, Copy)]
pub struct ImageDraw {
pub image: ImageId,
/// 0..1, for crossfades.
pub alpha: f32,
/// Darkens the whole picture (0 = as is).
pub dim: f32,
/// Darkens towards the left edge (room for a title), 0..1.
pub fade_left: f32,
/// Darkens towards the bottom edge, 0..1.
pub fade_bottom: f32,
/// Which part stays visible when the picture is cropped to the screen
/// (0..1 per axis, 0.5 = centre).
pub align: [f32; 2],
/// Drawn sharp at full resolution. When false only the soft (blurred,
/// low resolution) copy shows, like a frosted wallpaper.
pub sharp: bool,
}
/// Colour matrix of a video frame.
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Matrix {
Bt601,
#[default]
Bt709,
Bt2020,
}
/// One decoded video frame in NV12: a full-size Y plane and a half-size
/// plane of interleaved Cb/Cr bytes.
pub trait Nv12Frame {
fn width(&self) -> u32;
fn height(&self) -> u32;
/// Display aspect ratio (width / height, pixel aspect included).
fn aspect(&self) -> f32 {
self.width() as f32 / self.height().max(1) as f32
}
/// Plane 0 (Y) or 1 (CbCr): bytes and the stride (bytes per row).
fn plane(&self, index: usize) -> (&[u8], usize);
fn matrix(&self) -> Matrix {
Matrix::Bt709
}
fn full_range(&self) -> bool {
false
}
}
/// The video layer of a frame. The renderer keeps the last uploaded frame,
/// so `frame` only needs to be set when a new one arrived.
pub struct VideoDraw<'a> {
pub frame: Option<&'a dyn Nv12Frame>,
/// 0..1, for fading in.
pub alpha: f32,
}
/// How much of the glass effect to draw (weaker TVs: lighter modes).
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
pub enum Quality {
/// Refraction, dispersion, Fresnel: the full Liquid Glass.
#[default]
Full,
/// Frosted glass with the lit rim, no lensing.
Light,
/// No frost: tinted panes with the rim only.
Flat,
}
/// Everything the renderer needs for one frame.
pub struct Frame<'a> {
pub width: u32,
pub height: u32,
/// Physical pixels per logical pixel (glass sizes depend on it).
pub scale: f32,
/// Seconds since start (animation clock).
pub time: f32,
/// Backdrop palette (highlight, mid, deep), rgb 0..1 each.
pub palette: [f32; 9],
/// Backdrop brightness, 0..1 (1 = full).
pub brightness: f32,
/// Direction towards the key light (screen space, y down).
pub light: [f32; 2],
/// Backdrop zoom (1 = none), e.g. for a launch fly-in.
pub zoom: f32,
/// Pictures over the gradient, in drawing order.
pub images: &'a [ImageDraw],
pub video: Option<VideoDraw<'a>>,
pub rects: Vec<Panel>,
pub quality: Quality,
}
impl Default for Frame<'_> {
fn default() -> Self {
Frame {
width: 0,
height: 0,
scale: 1.0,
time: 0.0,
palette: crate::Palette::NEUTRAL.to_floats(),
brightness: 1.0,
light: [-0.63, -0.78],
zoom: 1.0,
images: &[],
video: None,
rects: Vec::new(),
quality: Quality::Full,
}
}
}

View File

@@ -1,14 +1,18 @@
//! OpenGL underlay drawn before Slint renders its items. //! OpenGL underlay drawn before Slint renders its items.
//! //!
//! Pass 1 renders the backdrop (a smooth gradient) into a small, mipmapped //! Pass 1 renders the backdrop (gradient, then pictures, then video) into a
//! texture. Pass 2 upscales it to the window. Pass 3 draws every glass panel //! small, mipmapped texture: that is what the glass refracts and frosts.
//! as its own quad, covering only the panel and its shadow, blended onto the //! Pass 2 puts the backdrop on the window: the small texture upscaled, then
//! window. Uniform locations are looked up once. //! sharp pictures and the video at full resolution. Pass 3 draws every glass
//! panel as its own quad, covering only the panel and its shadow. Uniform
//! locations are looked up once; GL state is handed back to Slint untouched.
use std::collections::HashMap;
use glow::HasContext; use glow::HasContext;
use super::shaders; use super::shaders;
use super::{Frame, MAX_GROUP, MAX_RECTS, Panel}; use super::{Frame, ImageDraw, ImageId, MAX_GROUP, MAX_RECTS, Matrix, Nv12Frame, Panel};
/// The backdrop is blurry by design, so it never needs more than this width. /// The backdrop is blurry by design, so it never needs more than this width.
const SCENE_MAX_W: i32 = 640; const SCENE_MAX_W: i32 = 640;
@@ -20,7 +24,7 @@ struct SceneLocs {
time: Loc, time: Loc,
pal: Loc, pal: Loc,
zoom: Loc, zoom: Loc,
shelf: Loc, bright: Loc,
} }
struct BlitLocs { struct BlitLocs {
@@ -28,6 +32,27 @@ struct BlitLocs {
time: Loc, time: Loc,
} }
struct ImageLocs {
image: Loc,
img: Loc,
res: Loc,
align: Loc,
dim: Loc,
fade_left: Loc,
fade_bottom: Loc,
alpha: Loc,
}
struct VideoLocs {
y: Loc,
uv: Loc,
res: Loc,
aspect: Loc,
matrix: Loc,
full: Loc,
alpha: Loc,
}
struct GlassLocs { struct GlassLocs {
box_: Loc, box_: Loc,
res: Loc, res: Loc,
@@ -40,6 +65,24 @@ struct GlassLocs {
param: Loc, param: Loc,
glow: Loc, glow: Loc,
tint: Loc, tint: Loc,
mode: Loc,
}
struct Image {
tex: glow::Texture,
w: i32,
h: i32,
}
/// The last uploaded video frame.
struct Video {
y: glow::Texture,
uv: glow::Texture,
size: (i32, i32),
aspect: f32,
matrix: Matrix,
full: bool,
ready: bool,
} }
pub struct GlassRenderer { pub struct GlassRenderer {
@@ -47,15 +90,22 @@ pub struct GlassRenderer {
vao: glow::VertexArray, vao: glow::VertexArray,
scene_prog: glow::Program, scene_prog: glow::Program,
blit_prog: glow::Program, blit_prog: glow::Program,
image_prog: glow::Program,
video_prog: glow::Program,
glass_prog: glow::Program, glass_prog: glow::Program,
scene_locs: SceneLocs, scene_locs: SceneLocs,
blit_locs: BlitLocs, blit_locs: BlitLocs,
image_locs: ImageLocs,
video_locs: VideoLocs,
glass_locs: GlassLocs, glass_locs: GlassLocs,
fbo: glow::Framebuffer, fbo: glow::Framebuffer,
tex: glow::Texture, tex: glow::Texture,
tex_size: (i32, i32), tex_size: (i32, i32),
/// RGBA16F if the driver can render to it (no banding in dark gradients). /// RGBA16F if the driver can render to it (no banding in dark gradients).
half_float: bool, half_float: bool,
images: HashMap<u32, Image>,
next_image: u32,
video: Option<Video>,
} }
/// GL state we touch and must hand back to the Slint renderer untouched. /// GL state we touch and must hand back to the Slint renderer untouched.
@@ -66,6 +116,7 @@ struct SavedState {
framebuffer: i32, framebuffer: i32,
active_texture: i32, active_texture: i32,
texture0: i32, texture0: i32,
texture1: i32,
viewport: [i32; 4], viewport: [i32; 4],
blend: bool, blend: bool,
blend_func: [i32; 4], blend_func: [i32; 4],
@@ -74,6 +125,8 @@ struct SavedState {
depth: bool, depth: bool,
stencil: bool, stencil: bool,
cull: bool, cull: bool,
unpack_alignment: i32,
unpack_row_length: i32,
} }
impl GlassRenderer { impl GlassRenderer {
@@ -92,6 +145,8 @@ impl GlassRenderer {
let scene_prog = link(&gl, header, shaders::VERTEX, shaders::SCENE)?; let scene_prog = link(&gl, header, shaders::VERTEX, shaders::SCENE)?;
let blit_prog = link(&gl, header, shaders::VERTEX, shaders::BLIT)?; let blit_prog = link(&gl, header, shaders::VERTEX, shaders::BLIT)?;
let image_prog = link(&gl, header, shaders::VERTEX, shaders::IMAGE)?;
let video_prog = link(&gl, header, shaders::VERTEX, shaders::VIDEO)?;
let glass_prog = link(&gl, header, shaders::QUAD_VERTEX, shaders::GLASS)?; 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 loc = |p: glow::Program, name: &str| gl.get_uniform_location(p, name);
let scene_locs = SceneLocs { let scene_locs = SceneLocs {
@@ -99,9 +154,28 @@ impl GlassRenderer {
time: loc(scene_prog, "uTime"), time: loc(scene_prog, "uTime"),
pal: loc(scene_prog, "uPal"), pal: loc(scene_prog, "uPal"),
zoom: loc(scene_prog, "uZoom"), zoom: loc(scene_prog, "uZoom"),
shelf: loc(scene_prog, "uShelf"), bright: loc(scene_prog, "uBright"),
}; };
let blit_locs = BlitLocs { scene: loc(blit_prog, "uScene"), time: loc(blit_prog, "uTime") }; let blit_locs = BlitLocs { scene: loc(blit_prog, "uScene"), time: loc(blit_prog, "uTime") };
let image_locs = ImageLocs {
image: loc(image_prog, "uImage"),
img: loc(image_prog, "uImg"),
res: loc(image_prog, "uRes"),
align: loc(image_prog, "uAlign"),
dim: loc(image_prog, "uDim"),
fade_left: loc(image_prog, "uFadeLeft"),
fade_bottom: loc(image_prog, "uFadeBottom"),
alpha: loc(image_prog, "uAlpha"),
};
let video_locs = VideoLocs {
y: loc(video_prog, "uY"),
uv: loc(video_prog, "uUV"),
res: loc(video_prog, "uRes"),
aspect: loc(video_prog, "uAspect"),
matrix: loc(video_prog, "uMatrix"),
full: loc(video_prog, "uFull"),
alpha: loc(video_prog, "uAlpha"),
};
let glass_locs = GlassLocs { let glass_locs = GlassLocs {
box_: loc(glass_prog, "uBox"), box_: loc(glass_prog, "uBox"),
res: loc(glass_prog, "uRes"), res: loc(glass_prog, "uRes"),
@@ -114,6 +188,7 @@ impl GlassRenderer {
param: loc(glass_prog, "uParam"), param: loc(glass_prog, "uParam"),
glow: loc(glass_prog, "uGlow"), glow: loc(glass_prog, "uGlow"),
tint: loc(glass_prog, "uTint"), tint: loc(glass_prog, "uTint"),
mode: loc(glass_prog, "uMode"),
}; };
let vao = gl.create_vertex_array().map_err(anyhow::Error::msg)?; let vao = gl.create_vertex_array().map_err(anyhow::Error::msg)?;
let fbo = gl.create_framebuffer().map_err(anyhow::Error::msg)?; let fbo = gl.create_framebuffer().map_err(anyhow::Error::msg)?;
@@ -124,14 +199,21 @@ impl GlassRenderer {
vao, vao,
scene_prog, scene_prog,
blit_prog, blit_prog,
image_prog,
video_prog,
glass_prog, glass_prog,
scene_locs, scene_locs,
blit_locs, blit_locs,
image_locs,
video_locs,
glass_locs, glass_locs,
fbo, fbo,
tex, tex,
tex_size: (0, 0), tex_size: (0, 0),
half_float: true, half_float: true,
images: HashMap::new(),
next_image: 1,
video: None,
}) })
} }
} }
@@ -142,6 +224,8 @@ impl GlassRenderer {
let mut viewport = [0; 4]; let mut viewport = [0; 4];
gl.get_parameter_i32_slice(glow::VIEWPORT, &mut viewport); gl.get_parameter_i32_slice(glow::VIEWPORT, &mut viewport);
let active_texture = gl.get_parameter_i32(glow::ACTIVE_TEXTURE); let active_texture = gl.get_parameter_i32(glow::ACTIVE_TEXTURE);
gl.active_texture(glow::TEXTURE1);
let texture1 = gl.get_parameter_i32(glow::TEXTURE_BINDING_2D);
gl.active_texture(glow::TEXTURE0); gl.active_texture(glow::TEXTURE0);
SavedState { SavedState {
program: gl.get_parameter_i32(glow::CURRENT_PROGRAM), program: gl.get_parameter_i32(glow::CURRENT_PROGRAM),
@@ -150,6 +234,7 @@ impl GlassRenderer {
framebuffer: gl.get_parameter_i32(glow::FRAMEBUFFER_BINDING), framebuffer: gl.get_parameter_i32(glow::FRAMEBUFFER_BINDING),
active_texture, active_texture,
texture0: gl.get_parameter_i32(glow::TEXTURE_BINDING_2D), texture0: gl.get_parameter_i32(glow::TEXTURE_BINDING_2D),
texture1,
viewport, viewport,
blend: gl.is_enabled(glow::BLEND), blend: gl.is_enabled(glow::BLEND),
blend_func: [ blend_func: [
@@ -166,6 +251,8 @@ impl GlassRenderer {
depth: gl.is_enabled(glow::DEPTH_TEST), depth: gl.is_enabled(glow::DEPTH_TEST),
stencil: gl.is_enabled(glow::STENCIL_TEST), stencil: gl.is_enabled(glow::STENCIL_TEST),
cull: gl.is_enabled(glow::CULL_FACE), cull: gl.is_enabled(glow::CULL_FACE),
unpack_alignment: gl.get_parameter_i32(glow::UNPACK_ALIGNMENT),
unpack_row_length: gl.get_parameter_i32(glow::UNPACK_ROW_LENGTH),
} }
} }
} }
@@ -178,6 +265,8 @@ impl GlassRenderer {
gl.bind_vertex_array(nz(s.vao).map(glow::NativeVertexArray)); 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_buffer(glow::ARRAY_BUFFER, nz(s.array_buffer).map(glow::NativeBuffer));
gl.bind_framebuffer(glow::FRAMEBUFFER, nz(s.framebuffer).map(glow::NativeFramebuffer)); gl.bind_framebuffer(glow::FRAMEBUFFER, nz(s.framebuffer).map(glow::NativeFramebuffer));
gl.active_texture(glow::TEXTURE1);
gl.bind_texture(glow::TEXTURE_2D, nz(s.texture1).map(glow::NativeTexture));
gl.active_texture(glow::TEXTURE0); gl.active_texture(glow::TEXTURE0);
gl.bind_texture(glow::TEXTURE_2D, nz(s.texture0).map(glow::NativeTexture)); gl.bind_texture(glow::TEXTURE_2D, nz(s.texture0).map(glow::NativeTexture));
gl.active_texture(s.active_texture as u32); gl.active_texture(s.active_texture as u32);
@@ -191,6 +280,8 @@ impl GlassRenderer {
set(glow::DEPTH_TEST, s.depth); set(glow::DEPTH_TEST, s.depth);
set(glow::STENCIL_TEST, s.stencil); set(glow::STENCIL_TEST, s.stencil);
set(glow::CULL_FACE, s.cull); set(glow::CULL_FACE, s.cull);
gl.pixel_store_i32(glow::UNPACK_ALIGNMENT, s.unpack_alignment);
gl.pixel_store_i32(glow::UNPACK_ROW_LENGTH, s.unpack_row_length);
} }
} }
@@ -211,10 +302,7 @@ impl GlassRenderer {
ty, ty,
glow::PixelUnpackData::Slice(None), glow::PixelUnpackData::Slice(None),
); );
gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_MIN_FILTER, glow::LINEAR_MIPMAP_LINEAR as i32); set_filter(gl, true);
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.generate_mipmap(glow::TEXTURE_2D);
gl.bind_framebuffer(glow::FRAMEBUFFER, Some(self.fbo)); 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.framebuffer_texture_2d(glow::FRAMEBUFFER, glow::COLOR_ATTACHMENT0, glow::TEXTURE_2D, Some(self.tex), 0);
@@ -238,6 +326,165 @@ impl GlassRenderer {
self.tex_size = (w, h); self.tex_size = (w, h);
} }
/// Uploads a picture (RGBA8, top row first) for [`ImageDraw`].
///
/// # Safety
/// Must be called with the context current (inside the rendering notifier).
pub unsafe fn upload_image(&mut self, width: u32, height: u32, rgba: &[u8]) -> anyhow::Result<ImageId> {
let (w, h) = (width as i32, height as i32);
anyhow::ensure!(w > 0 && h > 0 && rgba.len() >= (width * height * 4) as usize, "bad image size");
let gl = &self.gl;
unsafe {
let unpack = (gl.get_parameter_i32(glow::UNPACK_ALIGNMENT), gl.get_parameter_i32(glow::UNPACK_ROW_LENGTH));
let bound = gl.get_parameter_i32(glow::TEXTURE_BINDING_2D);
let tex = gl.create_texture().map_err(anyhow::Error::msg)?;
gl.bind_texture(glow::TEXTURE_2D, Some(tex));
gl.pixel_store_i32(glow::UNPACK_ALIGNMENT, 1);
gl.pixel_store_i32(glow::UNPACK_ROW_LENGTH, 0);
gl.tex_image_2d(
glow::TEXTURE_2D,
0,
glow::RGBA8 as i32,
w,
h,
0,
glow::RGBA,
glow::UNSIGNED_BYTE,
glow::PixelUnpackData::Slice(Some(&rgba[..(width * height * 4) as usize])),
);
set_filter(gl, true);
gl.generate_mipmap(glow::TEXTURE_2D);
gl.pixel_store_i32(glow::UNPACK_ALIGNMENT, unpack.0);
gl.pixel_store_i32(glow::UNPACK_ROW_LENGTH, unpack.1);
gl.bind_texture(glow::TEXTURE_2D, std::num::NonZeroU32::new(bound as u32).map(glow::NativeTexture));
let id = self.next_image;
self.next_image += 1;
self.images.insert(id, Image { tex, w, h });
Ok(ImageId(id))
}
}
/// # Safety
/// Must be called with the context current.
pub unsafe fn free_image(&mut self, id: ImageId) {
if let Some(img) = self.images.remove(&id.0) {
unsafe { self.gl.delete_texture(img.tex) };
}
}
/// Forgets the last video frame (the next one starts from black).
pub fn clear_video(&mut self) {
if let Some(v) = &mut self.video {
v.ready = false;
}
}
unsafe fn upload_video(&mut self, frame: &dyn Nv12Frame) -> anyhow::Result<()> {
let (w, h) = (frame.width() as i32, frame.height() as i32);
anyhow::ensure!(w > 1 && h > 1, "empty video frame");
let (cw, ch) = ((w + 1) / 2, (h + 1) / 2);
let (y, y_stride) = frame.plane(0);
let (uv, uv_stride) = frame.plane(1);
anyhow::ensure!(y_stride >= w as usize && y.len() >= y_stride * (h as usize - 1) + w as usize, "short Y plane");
anyhow::ensure!(
uv_stride >= 2 * cw as usize && uv.len() >= uv_stride * (ch as usize - 1) + 2 * cw as usize,
"short CbCr plane"
);
let gl = &self.gl;
unsafe {
if self.video.is_none() {
let y = gl.create_texture().map_err(anyhow::Error::msg)?;
let uv = gl.create_texture().map_err(anyhow::Error::msg)?;
self.video =
Some(Video { y, uv, size: (0, 0), aspect: 1.0, matrix: Matrix::Bt709, full: false, ready: false });
}
let v = self.video.as_mut().unwrap();
let realloc = v.size != (w, h);
gl.pixel_store_i32(glow::UNPACK_ALIGNMENT, 1);
let planes = [
(v.y, y, y_stride, w, h, glow::R8, glow::RED, 1usize),
(v.uv, uv, uv_stride, cw, ch, glow::RG8, glow::RG, 2usize),
];
for (tex, data, stride, pw, ph, internal, format, bpp) in planes {
gl.bind_texture(glow::TEXTURE_2D, Some(tex));
gl.pixel_store_i32(glow::UNPACK_ROW_LENGTH, (stride / bpp) as i32);
let len = stride * (ph as usize - 1) + pw as usize * bpp;
let pixels = glow::PixelUnpackData::Slice(Some(&data[..len]));
if realloc {
gl.tex_image_2d(glow::TEXTURE_2D, 0, internal as i32, pw, ph, 0, format, glow::UNSIGNED_BYTE, pixels);
set_filter(gl, true);
} else {
gl.tex_sub_image_2d(glow::TEXTURE_2D, 0, 0, 0, pw, ph, format, glow::UNSIGNED_BYTE, pixels);
}
// Mipmaps keep the small backdrop copy free of shimmer.
gl.generate_mipmap(glow::TEXTURE_2D);
}
gl.pixel_store_i32(glow::UNPACK_ROW_LENGTH, 0);
v.size = (w, h);
v.aspect = frame.aspect();
v.matrix = frame.matrix();
v.full = frame.full_range();
v.ready = true;
}
Ok(())
}
/// Pictures and video into the current framebuffer (viewport `w` x `h`).
/// `all`: also the soft-only pictures (the small backdrop copy).
unsafe fn draw_layers(&self, f: &Frame, w: i32, h: i32, all: bool, video_alpha: f32) {
let gl = &self.gl;
unsafe {
gl.enable(glow::BLEND);
gl.blend_equation_separate(glow::FUNC_ADD, glow::FUNC_ADD);
gl.blend_func_separate(glow::SRC_ALPHA, glow::ONE_MINUS_SRC_ALPHA, glow::ZERO, glow::ONE);
for d in f.images.iter().filter(|d| d.alpha > 0.002 && (all || d.sharp)) {
let Some(img) = self.images.get(&d.image.0) else { continue };
self.draw_image(img, d, w, h);
}
if let Some(v) = self.video.as_ref().filter(|v| v.ready && video_alpha > 0.002) {
let l = &self.video_locs;
gl.use_program(Some(self.video_prog));
gl.active_texture(glow::TEXTURE1);
gl.bind_texture(glow::TEXTURE_2D, Some(v.uv));
gl.active_texture(glow::TEXTURE0);
gl.bind_texture(glow::TEXTURE_2D, Some(v.y));
gl.uniform_1_i32(l.y.as_ref(), 0);
gl.uniform_1_i32(l.uv.as_ref(), 1);
gl.uniform_2_f32(l.res.as_ref(), w as f32, h as f32);
gl.uniform_1_f32(l.aspect.as_ref(), v.aspect);
let m = match v.matrix {
Matrix::Bt601 => 0,
Matrix::Bt709 => 1,
Matrix::Bt2020 => 2,
};
gl.uniform_1_i32(l.matrix.as_ref(), m);
gl.uniform_1_i32(l.full.as_ref(), v.full as i32);
gl.uniform_1_f32(l.alpha.as_ref(), video_alpha.clamp(0.0, 1.0));
gl.draw_arrays(glow::TRIANGLES, 0, 3);
}
gl.disable(glow::BLEND);
}
}
unsafe fn draw_image(&self, img: &Image, d: &ImageDraw, w: i32, h: i32) {
let gl = &self.gl;
let l = &self.image_locs;
unsafe {
gl.use_program(Some(self.image_prog));
gl.active_texture(glow::TEXTURE0);
gl.bind_texture(glow::TEXTURE_2D, Some(img.tex));
gl.uniform_1_i32(l.image.as_ref(), 0);
gl.uniform_2_f32(l.img.as_ref(), img.w as f32, img.h as f32);
gl.uniform_2_f32(l.res.as_ref(), w as f32, h as f32);
gl.uniform_2_f32(l.align.as_ref(), d.align[0], d.align[1]);
gl.uniform_1_f32(l.dim.as_ref(), d.dim);
gl.uniform_1_f32(l.fade_left.as_ref(), d.fade_left);
gl.uniform_1_f32(l.fade_bottom.as_ref(), d.fade_bottom);
gl.uniform_1_f32(l.alpha.as_ref(), d.alpha.clamp(0.0, 1.0));
gl.draw_arrays(glow::TRIANGLES, 0, 3);
}
}
/// # Safety /// # Safety
/// Must be called from the Slint rendering notifier with the context current. /// Must be called from the Slint rendering notifier with the context current.
pub unsafe fn render(&mut self, f: &Frame) { pub unsafe fn render(&mut self, f: &Frame) {
@@ -253,9 +500,20 @@ impl GlassRenderer {
gl.disable(glow::DEPTH_TEST); gl.disable(glow::DEPTH_TEST);
gl.disable(glow::STENCIL_TEST); gl.disable(glow::STENCIL_TEST);
gl.disable(glow::CULL_FACE); gl.disable(glow::CULL_FACE);
let mut video_alpha = 0.0;
if let Some(v) = &f.video {
video_alpha = v.alpha;
if let Some(frame) = v.frame {
if let Err(e) = self.upload_video(frame) {
log::warn!("glass: video frame: {e:#}");
}
}
}
let gl = &self.gl;
gl.bind_vertex_array(Some(self.vao)); gl.bind_vertex_array(Some(self.vao));
// Pass 1: backdrop at low resolution (it is a smooth gradient). // Pass 1: backdrop at low resolution (blurred by the glass anyway).
let sw = (w / 4).clamp(1, SCENE_MAX_W); let sw = (w / 4).clamp(1, SCENE_MAX_W);
let sh = ((sw as i64 * h as i64 / w as i64) as i32).max(1); let sh = ((sw as i64 * h as i64 / w as i64) as i32).max(1);
self.ensure_target(sw, sh); self.ensure_target(sw, sh);
@@ -268,13 +526,16 @@ impl GlassRenderer {
gl.uniform_1_f32(l.time.as_ref(), f.time); gl.uniform_1_f32(l.time.as_ref(), f.time);
gl.uniform_3_f32_slice(l.pal.as_ref(), &f.palette); 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.zoom.as_ref(), f.zoom);
gl.uniform_1_f32(l.shelf.as_ref(), f.shelf); gl.uniform_1_f32(l.bright.as_ref(), f.brightness);
gl.draw_arrays(glow::TRIANGLES, 0, 3); gl.draw_arrays(glow::TRIANGLES, 0, 3);
self.draw_layers(f, sw, sh, true, video_alpha);
let gl = &self.gl;
gl.active_texture(glow::TEXTURE0);
gl.bind_texture(glow::TEXTURE_2D, Some(self.tex)); gl.bind_texture(glow::TEXTURE_2D, Some(self.tex));
gl.generate_mipmap(glow::TEXTURE_2D); gl.generate_mipmap(glow::TEXTURE_2D);
// Pass 2: upscale to the window framebuffer. // Pass 2: the window. Upscaled backdrop, then sharp pictures and video.
gl.bind_framebuffer( gl.bind_framebuffer(
glow::FRAMEBUFFER, glow::FRAMEBUFFER,
std::num::NonZeroU32::new(saved.framebuffer as u32).map(glow::NativeFramebuffer), std::num::NonZeroU32::new(saved.framebuffer as u32).map(glow::NativeFramebuffer),
@@ -285,8 +546,12 @@ impl GlassRenderer {
gl.uniform_1_i32(l.scene.as_ref(), 0); gl.uniform_1_i32(l.scene.as_ref(), 0);
gl.uniform_1_f32(l.time.as_ref(), f.time); gl.uniform_1_f32(l.time.as_ref(), f.time);
gl.draw_arrays(glow::TRIANGLES, 0, 3); gl.draw_arrays(glow::TRIANGLES, 0, 3);
self.draw_layers(f, w, h, false, video_alpha);
// Pass 3: glass, one quad per panel or merged group: dst * a + rgb. // Pass 3: glass, one quad per panel or merged group: dst * a + rgb.
let gl = &self.gl;
gl.active_texture(glow::TEXTURE0);
gl.bind_texture(glow::TEXTURE_2D, Some(self.tex));
gl.enable(glow::BLEND); gl.enable(glow::BLEND);
gl.blend_equation_separate(glow::FUNC_ADD, glow::FUNC_ADD); gl.blend_equation_separate(glow::FUNC_ADD, glow::FUNC_ADD);
gl.blend_func_separate(glow::ONE, glow::SRC_ALPHA, glow::ZERO, glow::ONE); gl.blend_func_separate(glow::ONE, glow::SRC_ALPHA, glow::ZERO, glow::ONE);
@@ -297,6 +562,12 @@ impl GlassRenderer {
gl.uniform_1_f32(l.scale.as_ref(), f.scale); gl.uniform_1_f32(l.scale.as_ref(), f.scale);
gl.uniform_1_f32(l.time.as_ref(), f.time); gl.uniform_1_f32(l.time.as_ref(), f.time);
gl.uniform_2_f32(l.light.as_ref(), f.light[0], f.light[1]); gl.uniform_2_f32(l.light.as_ref(), f.light[0], f.light[1]);
let mode = match f.quality {
super::Quality::Full => 0,
super::Quality::Light => 1,
super::Quality::Flat => 2,
};
gl.uniform_1_i32(l.mode.as_ref(), mode);
let rects = &f.rects[..f.rects.len().min(MAX_RECTS)]; let rects = &f.rects[..f.rects.len().min(MAX_RECTS)];
let mut rect = [0f32; MAX_GROUP * 4]; let mut rect = [0f32; MAX_GROUP * 4];
@@ -370,8 +641,17 @@ impl GlassRenderer {
/// Must be called with the context current. /// Must be called with the context current.
pub unsafe fn destroy(&mut self) { pub unsafe fn destroy(&mut self) {
unsafe { unsafe {
for (_, img) in self.images.drain() {
self.gl.delete_texture(img.tex);
}
if let Some(v) = self.video.take() {
self.gl.delete_texture(v.y);
self.gl.delete_texture(v.uv);
}
self.gl.delete_program(self.scene_prog); self.gl.delete_program(self.scene_prog);
self.gl.delete_program(self.blit_prog); self.gl.delete_program(self.blit_prog);
self.gl.delete_program(self.image_prog);
self.gl.delete_program(self.video_prog);
self.gl.delete_program(self.glass_prog); self.gl.delete_program(self.glass_prog);
self.gl.delete_vertex_array(self.vao); self.gl.delete_vertex_array(self.vao);
self.gl.delete_framebuffer(self.fbo); self.gl.delete_framebuffer(self.fbo);
@@ -380,6 +660,17 @@ impl GlassRenderer {
} }
} }
/// Linear filtering on the bound texture, with mipmaps for minification.
unsafe fn set_filter(gl: &glow::Context, mipmaps: bool) {
let min = if mipmaps { glow::LINEAR_MIPMAP_LINEAR } else { glow::LINEAR };
unsafe {
gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_MIN_FILTER, min 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);
}
}
/// Splits the panels into draw runs: consecutive panels sharing a group /// Splits the panels into draw runs: consecutive panels sharing a group
/// (> 0) melt together and are drawn as one; the rest are drawn alone. /// (> 0) melt together and are drawn as one; the rest are drawn alone.
fn runs(rects: &[Panel]) -> impl Iterator<Item = &[Panel]> { fn runs(rects: &[Panel]) -> impl Iterator<Item = &[Panel]> {
@@ -423,3 +714,22 @@ unsafe fn link(gl: &glow::Context, header: &str, vs: &str, fs: &str) -> anyhow::
Ok(program) Ok(program)
} }
} }
#[cfg(test)]
mod tests {
use super::*;
fn p(group: f32) -> Panel {
Panel { group, alpha: 1.0, ..Panel::default() }
}
#[test]
fn groups_merge_only_when_consecutive() {
let rects = [p(0.0), p(1.0), p(1.0), p(2.0), p(1.0), p(0.0), p(0.0)];
let sizes: Vec<usize> = runs(&rects).map(<[Panel]>::len).collect();
assert_eq!(sizes, [1, 2, 1, 1, 1, 1]);
let big = [p(3.0); 6];
let sizes: Vec<usize> = runs(&big).map(<[Panel]>::len).collect();
assert_eq!(sizes, [MAX_GROUP, 2]);
}
}

View File

@@ -35,7 +35,7 @@ uniform vec2 uRes;
uniform float uTime; uniform float uTime;
uniform vec3 uPal[3]; // highlight, mid, deep uniform vec3 uPal[3]; // highlight, mid, deep
uniform float uZoom; // launch fly-in uniform float uZoom; // launch fly-in
uniform float uShelf; // 1 = top shelf showing, 0 = scrolled into the grid uniform float uBright; // backdrop brightness: 1 = full, lower = calmer (launcher: shelf hidden)
float field(vec2 d, float r) { float field(vec2 d, float r) {
return exp(-dot(d, d) / (r * r)); return exp(-dot(d, d) / (r * r));
@@ -83,9 +83,9 @@ void main() {
// Soft shoulder so bright palettes stay "dark mode". // Soft shoulder so bright palettes stay "dark mode".
col = col / (1.0 + col * 1.2); col = col / (1.0 + col * 1.2);
// Calmer at the bottom where the icons sit; dimmer when the shelf is gone. // Calmer at the bottom where the icons sit; dimmer when asked (uBright).
col *= mix(1.0, 0.62, smoothstep(0.45, 1.0, uv.y)); col *= mix(1.0, 0.62, smoothstep(0.45, 1.0, uv.y));
col *= mix(0.42, 1.0, uShelf); col *= mix(0.42, 1.0, uBright);
vec2 v = uv - 0.5; vec2 v = uv - 0.5;
col *= 1.0 - 0.30 * dot(v, v); col *= 1.0 - 0.30 * dot(v, v);
@@ -113,6 +113,90 @@ void main() {
} }
"#; "#;
/// A backdrop picture (artwork), cover-fitted to the viewport and toned for
/// text on top: darkened overall (`uDim`) and towards the left and bottom
/// edges, where titles usually sit. Blended with alpha (crossfades).
pub const IMAGE: &str = r#"
in vec2 vUv;
out vec4 fragColor;
uniform sampler2D uImage;
uniform vec2 uImg; // image size, px
uniform vec2 uRes; // viewport size, px
uniform vec2 uAlign; // which part stays visible when cropping (0..1, 0.5 = centre)
uniform float uDim;
uniform float uFadeLeft;
uniform float uFadeBottom;
uniform float uAlpha;
void main() {
vec2 uv = vec2(vUv.x, 1.0 - vUv.y); // top-left origin, like the image rows
float va = uRes.x / uRes.y;
float ia = uImg.x / max(uImg.y, 1.0);
vec2 st = uv;
if (ia > va) {
float f = va / ia;
st.x = uAlign.x * (1.0 - f) + uv.x * f;
} else {
float f = ia / va;
st.y = uAlign.y * (1.0 - f) + uv.y * f;
}
vec3 col = texture(uImage, st).rgb;
float kl = uFadeLeft * (1.0 - smoothstep(0.05, 0.85, uv.x));
float kb = uFadeBottom * smoothstep(0.30, 0.95, uv.y);
float k = 1.0 - (1.0 - kl) * (1.0 - kb);
col = mix(col, vec3(0.018, 0.018, 0.022), k) * (1.0 - uDim);
fragColor = vec4(col, uAlpha);
}
"#;
/// A video frame (NV12: full-size Y plane, half-size interleaved CbCr plane),
/// contain-fitted with black bars, converted to RGB here.
pub const VIDEO: &str = r#"
in vec2 vUv;
out vec4 fragColor;
uniform sampler2D uY;
uniform sampler2D uUV;
uniform vec2 uRes; // viewport size, px
uniform float uAspect; // display aspect of the video
uniform int uMatrix; // 0 = BT.601, 1 = BT.709, 2 = BT.2020
uniform int uFull; // 1 = full range (0..255), else limited (16..235)
uniform float uAlpha;
void main() {
vec2 uv = vec2(vUv.x, 1.0 - vUv.y);
float va = uRes.x / uRes.y;
vec2 st = uv;
float inside = 1.0;
if (uAspect > va) {
float h = va / uAspect;
st.y = (uv.y - 0.5) / h + 0.5;
} else {
float w = uAspect / va;
st.x = (uv.x - 0.5) / w + 0.5;
}
if (st.x < 0.0 || st.x > 1.0 || st.y < 0.0 || st.y > 1.0) inside = 0.0;
st = clamp(st, vec2(0.0), vec2(1.0));
float y = texture(uY, st).r;
vec2 c = texture(uUV, st).rg;
if (uFull == 1) {
c -= 0.5;
} else {
y = (y - 16.0 / 255.0) * (255.0 / 219.0);
c = (c - 128.0 / 255.0) * (255.0 / 224.0);
}
vec3 rgb;
if (uMatrix == 0) {
rgb = vec3(y + 1.402 * c.y, y - 0.344136 * c.x - 0.714136 * c.y, y + 1.772 * c.x);
} else if (uMatrix == 2) {
rgb = vec3(y + 1.4746 * c.y, y - 0.16455 * c.x - 0.57135 * c.y, y + 1.8814 * c.x);
} else {
rgb = vec3(y + 1.5748 * c.y, y - 0.1873 * c.x - 0.4681 * c.y, y + 1.8556 * c.x);
}
fragColor = vec4(clamp(rgb, 0.0, 1.0) * inside, uAlpha);
}
"#;
/// One Liquid Glass panel (or one merged group of panels), drawn as a quad /// One Liquid Glass panel (or one merged group of panels), drawn as a quad
/// over its bounds plus the shadow margin. /// over its bounds plus the shadow margin.
/// ///
@@ -142,6 +226,7 @@ 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 uParam[MAX_GROUP]; // radius, focus, alpha, frost (mip lod; < 0 = nested on other glass)
uniform vec4 uGlow[MAX_GROUP]; // accent rgb, unused uniform vec4 uGlow[MAX_GROUP]; // accent rgb, unused
uniform vec4 uTint[MAX_GROUP]; // tint rgb, tint amount uniform vec4 uTint[MAX_GROUP]; // tint rgb, tint amount
uniform int uMode; // 0 = full, 1 = light (frost, no lensing), 2 = flat (no frost)
float sdRoundRect(vec2 p, vec2 b, float r) { float sdRoundRect(vec2 p, vec2 b, float r) {
vec2 q = abs(p) - b + r; vec2 q = abs(p) - b + r;
@@ -298,9 +383,11 @@ void main() {
// The glass colour is affine in what is underneath: g = dst * A + B. // The glass colour is affine in what is underneath: g = dst * A + B.
float A = 0.0; float A = 0.0;
vec3 B; vec3 B;
if (nested) { if (nested || uMode == 2) {
A = 1.0; A = 1.0;
B = vec3(0.0); B = vec3(0.0);
} else if (uMode == 1) {
B = sceneAt(p / uRes, lod);
} else if (slope > 0.02) { } else if (slope > 0.02) {
// Bevel: refract each channel with its own IOR (dispersion). // Bevel: refract each channel with its own IOR (dispersion).
B.r = sceneAt((p + refractOffset(N, height, 1.46) * lens + mag) / uRes, lod).r; B.r = sceneAt((p + refractOffset(N, height, 1.46) * lens + mag) / uRes, lod).r;
@@ -344,7 +431,7 @@ void main() {
// Fresnel: steep bevel reflects the (blurred, brightened) surroundings. // Fresnel: steep bevel reflects the (blurred, brightened) surroundings.
float cosT = clamp(N.z, 0.0, 1.0); float cosT = clamp(N.z, 0.0, 1.0);
float F = 0.04 + 0.96 * pow(1.0 - cosT, 5.0); float F = 0.04 + 0.96 * pow(1.0 - cosT, 5.0);
float Fm = clamp(F, 0.0, 1.0) * 0.35 * mat; float Fm = uMode == 0 ? clamp(F, 0.0, 1.0) * 0.35 * mat : 0.0;
vec3 env = mix(sceneAt((p + n2 * 60.0 * s) / uRes, 5.0) * 1.6, vec3(0.92), 0.35); vec3 env = mix(sceneAt((p + n2 * 60.0 * s) / uRes, 5.0) * 1.6, vec3(0.92), 0.35);
A *= 1.0 - Fm; A *= 1.0 - Fm;
B = mix(B, env, Fm); B = mix(B, env, Fm);

39
crates/sf-ui/src/text.rs Normal file
View File

@@ -0,0 +1,39 @@
//! String helpers Slint lacks (wired into the `SfText` global by `glue!`).
/// Without its last character.
pub fn drop_last(s: &str) -> String {
let mut s = s.to_string();
s.pop();
s
}
/// `n` bullets (a masked password).
pub fn dots(n: usize) -> String {
"•".repeat(n)
}
/// The characters of a key event's text that can be typed: no controls, no
/// Slint special keys (arrows etc. arrive as private-use code points).
pub fn typable(s: &str) -> String {
s.chars().filter(|c| !c.is_control() && !('\u{E000}'..='\u{F8FF}').contains(c)).collect()
}
/// At most `n` characters.
pub fn truncate(s: &str, n: usize) -> String {
s.chars().take(n).collect()
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn edits() {
assert_eq!(drop_last("abő"), "ab");
assert_eq!(drop_last(""), "");
assert_eq!(dots(3), "•••");
assert_eq!(truncate("árvíz", 3), "árv");
assert_eq!(typable("a\u{F700}\n"), "a");
assert_eq!(typable("Ő"), "Ő");
}
}

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