diff --git a/.gitattributes b/.gitattributes index 2b6265d..add667a 100644 --- a/.gitattributes +++ b/.gitattributes @@ -1,3 +1,4 @@ * text=auto eol=lf *.ttf binary *.png binary +*.gpg binary diff --git a/.gitea/workflows/packages.yml b/.gitea/workflows/packages.yml index 2d8d62d..a17154a 100644 --- a/.gitea/workflows/packages.yml +++ b/.gitea/workflows/packages.yml @@ -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 # isn't published yet: bump the version to release (docs/updates.md). # @@ -19,6 +19,10 @@ on: - "tools/siri-remote/fastpair.py" - ".gitea/workflows/packages.yml" workflow_dispatch: + # Steam follows Valve's official steam-launcher package (tools/pkg/steam): + # look for a new one every Monday; nothing is built if it's published already. + schedule: + - cron: "17 4 * * 1" jobs: packages: @@ -43,8 +47,9 @@ jobs: run: | export DEBIAN_FRONTEND=noninteractive apt-get update -qq - apt-get install -y -qq --no-install-recommends build-essential pkg-config zstd \ - libfontconfig1-dev libfreetype-dev libxkbcommon-dev libdbus-1-dev libudev-dev >/dev/null + 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 \ + libinput-dev libgbm-dev libseat-dev libdrm-dev libegl-dev >/dev/null rm -rf /var/lib/apt/lists/* curl -sSf https://sh.rustup.rs | sh -s -- -y -q --profile minimal --no-modify-path /tmp/sf-build/cargo/bin/rustc --version diff --git a/.gitignore b/.gitignore index 62fa6a6..df0fb79 100644 --- a/.gitignore +++ b/.gitignore @@ -6,3 +6,5 @@ /image/ovmf-vars.fd /image/out /image/secrets +# Store apps developed in place, each its own git repository (apps//.git). +/apps/netflex-tv/ diff --git a/.impeccable/design.json b/.impeccable/design.json new file mode 100644 index 0000000..249299e --- /dev/null +++ b/.impeccable/design.json @@ -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": "
Miracast
", + "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": "
82%Otthon-5G
", + "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": "
", + "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": "
", + "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": "
", + "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": "
Otthon-5G
", + "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": "
", + "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": "
Mindig futKísérleti
", + "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." + ] + } +} diff --git a/.impeccable/review/before-home.png b/.impeccable/review/before-home.png new file mode 100644 index 0000000..46a32c4 Binary files /dev/null and b/.impeccable/review/before-home.png differ diff --git a/.impeccable/review/tv-home-hero.png b/.impeccable/review/tv-home-hero.png new file mode 100644 index 0000000..26e13b6 Binary files /dev/null and b/.impeccable/review/tv-home-hero.png differ diff --git a/.impeccable/review/tv-home-row2.png b/.impeccable/review/tv-home-row2.png new file mode 100644 index 0000000..6e954ac Binary files /dev/null and b/.impeccable/review/tv-home-row2.png differ diff --git a/.impeccable/review/tv-home-shelf.png b/.impeccable/review/tv-home-shelf.png new file mode 100644 index 0000000..050ba6a Binary files /dev/null and b/.impeccable/review/tv-home-shelf.png differ diff --git a/.impeccable/review/tv-pairing.png b/.impeccable/review/tv-pairing.png new file mode 100644 index 0000000..f3a34ad Binary files /dev/null and b/.impeccable/review/tv-pairing.png differ diff --git a/.impeccable/review/tv-settings.png b/.impeccable/review/tv-settings.png new file mode 100644 index 0000000..ca75439 Binary files /dev/null and b/.impeccable/review/tv-settings.png differ diff --git a/.impeccable/review/tv-sheet.png b/.impeccable/review/tv-sheet.png new file mode 100644 index 0000000..d6fa27a Binary files /dev/null and b/.impeccable/review/tv-sheet.png differ diff --git a/.impeccable/surfaces/crates-sf-launcher-ui-app-slint.md b/.impeccable/surfaces/crates-sf-launcher-ui-app-slint.md new file mode 100644 index 0000000..65cb809 --- /dev/null +++ b/.impeccable/surfaces/crates-sf-launcher-ui-app-slint.md @@ -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 diff --git a/Cargo.lock b/Cargo.lock index 5e5d57d..bca93f6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -18,6 +18,114 @@ version = "0.1.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618" +[[package]] +name = "accesskit" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3b7f7f85a7e5f68090000ed7622545829afd484d210358702ae4cb97dd0c320" +dependencies = [ + "uuid", +] + +[[package]] +name = "accesskit_atspi_common" +version = "0.19.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "023da0e5097f46df7092d5280b02efb9bbf8d93298daeced42652463e357d636" +dependencies = [ + "accesskit", + "accesskit_consumer", + "atspi-common", + "phf", + "serde", + "zvariant", +] + +[[package]] +name = "accesskit_consumer" +version = "0.38.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d10a236f96f87d70732e44520046785431ef01d5bcd6b041317bfadd2f88245" +dependencies = [ + "accesskit", + "hashbrown 0.16.1", +] + +[[package]] +name = "accesskit_ios" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "750c4e9f6ce888dfe8a10c0f1b5ceb646a7854fd46579d74919219d1bb314083" +dependencies = [ + "accesskit", + "accesskit_consumer", + "hashbrown 0.16.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", + "objc2-ui-kit 0.2.2", +] + +[[package]] +name = "accesskit_macos" +version = "0.26.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce02dc63b43f0c9296af9ac946312a2dc8814427d7a64d2d600971dac55b6076" +dependencies = [ + "accesskit", + "accesskit_consumer", + "hashbrown 0.16.1", + "objc2 0.5.3", + "objc2-app-kit 0.2.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "accesskit_unix" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03e156ed3802e35eefe894ef2671bc6c889303d8a7e110b5e1b48f504b91362f" +dependencies = [ + "accesskit", + "accesskit_atspi_common", + "async-channel", + "async-executor", + "async-task", + "atspi", + "futures-lite", + "futures-util", + "serde", + "zbus", +] + +[[package]] +name = "accesskit_windows" +version = "0.34.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "106c2b961215864d1c2e703ee63269c25c4e80a577ffb2c1017b9c17dcdf83a1" +dependencies = [ + "accesskit", + "accesskit_consumer", + "hashbrown 0.16.1", + "static_assertions", + "windows", + "windows-core", +] + +[[package]] +name = "accesskit_winit" +version = "0.33.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5b41e63a69f36d9f1f41e70464c7e5f72eee485ef26aab19f0b4f86e6c0a84c" +dependencies = [ + "accesskit", + "accesskit_ios", + "accesskit_macos", + "accesskit_unix", + "accesskit_windows", + "raw-window-handle", + "winit", +] + [[package]] name = "adler2" version = "2.0.1" @@ -46,6 +154,24 @@ dependencies = [ "memchr", ] +[[package]] +name = "aligned" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee4508988c62edf04abd8d92897fca0c2995d907ce1dfeaf369dac3716a40685" +dependencies = [ + "as-slice", +] + +[[package]] +name = "aligned-vec" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc890384c8602f339876ded803c97ad529f3842aba97f6392b3dba0dd171769b" +dependencies = [ + "equator", +] + [[package]] name = "allocator-api2" version = "0.2.21" @@ -153,6 +279,27 @@ version = "1.0.104" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470" +[[package]] +name = "appendlist" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e149dc73cd30538307e7ffa2acd3d2221148eaeed4871f246657b1c3eaa1cbd2" + +[[package]] +name = "approx" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f2a05fd1bd10b2527e20a2cd32d8873d115b8b39fe219ee25f42a8aca6ba278" +dependencies = [ + "num-traits", +] + +[[package]] +name = "arbitrary" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" + [[package]] name = "arboard" version = "3.7.0" @@ -171,6 +318,26 @@ dependencies = [ "x11rb", ] +[[package]] +name = "arc-swap" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "380962b3d93b99642e50b9febf72c071e97e8b32d86eae9cf4ef582bb960ae6e" +dependencies = [ + "rustversion", +] + +[[package]] +name = "arg_enum_proc_macro" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ae92a5119aa49cdbcf6b9f893fe4e1d98b04ccbf82ee0584ad948a44a734dea" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "arrayref" version = "0.3.9" @@ -189,6 +356,15 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b" +[[package]] +name = "as-slice" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "516b6b4f0e40d50dcda9365d53964ec74560ad4284da2e7fc97122cd83174516" +dependencies = [ + "stable_deref_trait", +] + [[package]] name = "ash" version = "0.38.0+1.3.281" @@ -335,12 +511,104 @@ version = "1.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" +[[package]] +name = "atomic_float" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "628d228f918ac3b82fe590352cc719d30664a0c13ca3a60266fe02c7132d480a" + +[[package]] +name = "atomic_refcell" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "21e4227379beff4205943696e6c3e0cd809bacdf3f0edd6e3dd153e2269571a4" + +[[package]] +name = "atspi" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c77886257be21c9cd89a4ae7e64860c6f0eefca799bb79127913052bd0eefb3d" +dependencies = [ + "atspi-common", + "atspi-proxies", +] + +[[package]] +name = "atspi-common" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20c5617155740c98003016429ad13fe43ce7a77b007479350a9f8bf95a29f63d" +dependencies = [ + "enumflags2", + "serde", + "static_assertions", + "zbus", + "zbus-lockstep", + "zbus-lockstep-macros", + "zbus_names", + "zvariant", +] + +[[package]] +name = "atspi-proxies" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2230e48787ed3eb4088996eab66a32ca20c0b67bbd4fd6cdfe79f04f1f04c9fc" +dependencies = [ + "atspi-common", + "serde", + "zbus", +] + [[package]] name = "autocfg" version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" +[[package]] +name = "av-scenechange" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f321d77c20e19b92c39e7471cf986812cbb46659d2af674adc4331ef3f18394" +dependencies = [ + "aligned", + "anyhow", + "arg_enum_proc_macro", + "arrayvec", + "log", + "num-rational", + "num-traits", + "pastey 0.1.1", + "rayon", + "thiserror 2.0.21", + "v_frame", + "y4m", +] + +[[package]] +name = "av1-grain" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8cfddb07216410377231960af4fcab838eaa12e013417781b78bd95ee22077f8" +dependencies = [ + "anyhow", + "arrayvec", + "log", + "nom 8.0.0", + "num-rational", + "v_frame", +] + +[[package]] +name = "avif-serialize" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7178fe5f7d460b13895ebb9dcb28a3a6216d2df2574a0806cb51b555d297f38" +dependencies = [ + "arrayvec", +] + [[package]] name = "base64" version = "0.22.1" @@ -404,6 +672,12 @@ version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" +[[package]] +name = "bit_field" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e4b40c7323adcfc0a41c4b88143ed58346ff65a288fc144329c5c45e05d70c6" + [[package]] name = "bitflags" version = "1.3.2" @@ -419,6 +693,15 @@ dependencies = [ "serde_core", ] +[[package]] +name = "bitstream-io" +version = "4.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7eff00be299a18769011411c9def0d827e8f2d7bf0c3dbf53633147a8867fd1f" +dependencies = [ + "no_std_io2", +] + [[package]] name = "bitvec" version = "1.1.1" @@ -510,6 +793,12 @@ dependencies = [ "cfg_aliases", ] +[[package]] +name = "built" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c0e531d93d39c34eef561e929e8a7f86d77a5af08aac4f6d6e39976c51858e9" + [[package]] name = "bumpalo" version = "3.20.3" @@ -613,6 +902,16 @@ dependencies = [ "nom 7.1.3", ] +[[package]] +name = "cfg-expr" +version = "0.20.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ba9e9ec16c447027685b1f897b720e18e9a8afd00bd7332c483537e38086c9f" +dependencies = [ + "smallvec", + "target-lexicon", +] + [[package]] name = "cfg-if" version = "1.0.5" @@ -634,6 +933,16 @@ dependencies = [ "libc", ] +[[package]] +name = "cgmath" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a98d30140e3296250832bbaaff83b27dcd6fa3cc70fb6f1f3e5c9c0023b5317" +dependencies = [ + "approx", + "num-traits", +] + [[package]] name = "chrono" version = "0.4.45" @@ -850,6 +1159,15 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "crossbeam-queue" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" +dependencies = [ + "crossbeam-utils", +] + [[package]] name = "crossbeam-utils" version = "0.8.23" @@ -1267,6 +1585,26 @@ dependencies = [ "log", ] +[[package]] +name = "equator" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4711b213838dfee0117e3be6ac926007d7f433d7bbe33595975d4190cb07e6fc" +dependencies = [ + "equator-macro", +] + +[[package]] +name = "equator-macro" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44f23cf4b44bfce11a86ace86f8a73ffdec849c9fd00a386a53d278bd9e81fb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "equivalent" version = "1.0.3" @@ -1331,12 +1669,34 @@ dependencies = [ "pin-project-lite", ] +[[package]] +name = "exr" +version = "1.74.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "711fe42c9964295e01ee3fba3f9fe0e1d24b98886950d68efe81b1c76e21adf3" +dependencies = [ + "bit_field", + "half", + "lebe", + "miniz_oxide 0.8.9", + "num-complex", + "pulp", + "smallvec", + "zune-inflate", +] + [[package]] name = "fastrand" version = "2.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" +[[package]] +name = "fax" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a" + [[package]] name = "fdeflate" version = "0.3.7" @@ -1721,6 +2081,19 @@ dependencies = [ "weezl", ] +[[package]] +name = "gio-sys" +version = "0.22.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c28739f914c15b87a9856000bed9cbd5b3a8afbca5e982d9a299e1601422cb5" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps", + "windows-sys 0.61.2", +] + [[package]] name = "gl_generator" version = "0.14.0" @@ -1732,6 +2105,49 @@ dependencies = [ "xml-rs", ] +[[package]] +name = "glib" +version = "0.22.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4cf9e5bd8713f1990a92c422998826e0fb34824277b46bc59757373483c6694" +dependencies = [ + "bitflags 2.13.2", + "futures-channel", + "futures-core", + "futures-executor", + "futures-task", + "futures-util", + "gio-sys", + "glib-macros", + "glib-sys", + "gobject-sys", + "libc", + "memchr", + "smallvec", +] + +[[package]] +name = "glib-macros" +version = "0.22.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9597c68fa7bdf4154a3079642cd21c4dccac0b0bdd2897d82861523bf91e7b9" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "glib-sys" +version = "0.22.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "99b38907e67e40dec9b60f858bcada952598719cb512a13eb13d6cdcd16f8295" +dependencies = [ + "libc", + "system-deps", +] + [[package]] name = "glob" version = "0.3.4" @@ -1828,6 +2244,17 @@ dependencies = [ "gl_generator", ] +[[package]] +name = "gobject-sys" +version = "0.22.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "07595c9ba696bd9819cb6a8df39f08078f3dd679508fe052dd558492c2053834" +dependencies = [ + "glib-sys", + "libc", + "system-deps", +] + [[package]] name = "gpu-allocator" version = "0.28.0" @@ -1848,6 +2275,129 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b40ca9252762c466af32d0b1002e91e4e1bc5398f77455e55474deb466355ff5" +[[package]] +name = "gstreamer" +version = "0.25.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4237e2066a25ecb7e54be6c066409e30615920265b9799b8d560ef8ac9857c6" +dependencies = [ + "cfg-if", + "futures-channel", + "futures-core", + "futures-util", + "glib", + "gstreamer-sys", + "itertools 0.15.0", + "kstring", + "libc", + "muldiv", + "num-integer", + "num-rational", + "option-operations", + "pastey 0.2.3", + "pin-project-lite", + "smallvec", + "thiserror 2.0.21", +] + +[[package]] +name = "gstreamer-app" +version = "0.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97f8ae9238c2352398dcc084de28df3f7099af216ac6c160b52318d23f25c010" +dependencies = [ + "futures-core", + "futures-sink", + "glib", + "gstreamer", + "gstreamer-app-sys", + "gstreamer-base", + "libc", +] + +[[package]] +name = "gstreamer-app-sys" +version = "0.25.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0798b8aef6694341d40bb81edc759f8979b896b59f9f0f45d8cfa3bb7bf2e743" +dependencies = [ + "glib-sys", + "gstreamer-base-sys", + "gstreamer-sys", + "libc", + "system-deps", +] + +[[package]] +name = "gstreamer-base" +version = "0.25.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17cbd8f59586a369c40d4b0d2f3a61cf9e9287b3cf5503cdcd8e7c5faa99265e" +dependencies = [ + "atomic_refcell", + "cfg-if", + "glib", + "gstreamer", + "gstreamer-base-sys", + "libc", +] + +[[package]] +name = "gstreamer-base-sys" +version = "0.25.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b05f77bfd76b5afee6b29c27dae19eaf5018b5cf8d0d17520f3de44c6385c32" +dependencies = [ + "glib-sys", + "gobject-sys", + "gstreamer-sys", + "libc", + "system-deps", +] + +[[package]] +name = "gstreamer-sys" +version = "0.25.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "436d9532847489a8285d57b8c3670762c12a18f777fdc2ab159b52e0e6f521b9" +dependencies = [ + "cfg-if", + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + +[[package]] +name = "gstreamer-video" +version = "0.25.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffe4d77b2a5e679973d9c6b6c052da8cda86b83f5c268872f8691fde693fde84" +dependencies = [ + "cfg-if", + "futures-channel", + "glib", + "gstreamer", + "gstreamer-base", + "gstreamer-video-sys", + "libc", + "thiserror 2.0.21", +] + +[[package]] +name = "gstreamer-video-sys" +version = "0.25.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef455da22edca97ac9299d682b868227f3d9217b303748ce0161b31ae82dc106" +dependencies = [ + "glib-sys", + "gobject-sys", + "gstreamer-base-sys", + "gstreamer-sys", + "libc", + "system-deps", +] + [[package]] name = "half" version = "2.7.1" @@ -1959,6 +2509,7 @@ version = "1.18.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0f519a8611a4982921e46e391015e5e40ceac5cc63813333ef91ada77df180d8" dependencies = [ + "bytemuck", "calloop 0.14.5", "cfg_aliases", "drm", @@ -1967,11 +2518,13 @@ dependencies = [ "i-slint-common", "i-slint-core", "i-slint-renderer-femtovg", - "input", + "i-slint-renderer-software", + "input 0.10.0", "libseat", + "memmap2", "nix 0.31.3", "raw-window-handle", - "xkbcommon", + "xkbcommon 0.9.0", ] [[package]] @@ -1983,6 +2536,7 @@ dependencies = [ "cfg-if", "cfg_aliases", "i-slint-backend-linuxkms", + "i-slint-backend-testing", "i-slint-backend-winit", "i-slint-common", "i-slint-core", @@ -1990,14 +2544,30 @@ dependencies = [ "i-slint-renderer-femtovg", ] +[[package]] +name = "i-slint-backend-testing" +version = "1.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01943d6c5ea5bc913d497bdaa423c309e7627afff47a6794bfd13be5c564209f" +dependencies = [ + "cfg_aliases", + "i-slint-common", + "i-slint-core", + "i-slint-renderer-software", + "vtable", +] + [[package]] name = "i-slint-backend-winit" version = "1.18.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dae4fcf1b19e9cb109984d2af87d2b9485388c619265bff71dd523133888bee2" dependencies = [ + "accesskit", + "accesskit_winit", "arboard", "block2 0.6.2", + "bytemuck", "cfg-if", "cfg_aliases", "futures", @@ -2008,6 +2578,8 @@ dependencies = [ "i-slint-core-macros", "i-slint-renderer-femtovg", "i-slint-renderer-skia", + "i-slint-renderer-software", + "imgref", "lyon_path", "muda", "objc2 0.6.5", @@ -2017,6 +2589,7 @@ dependencies = [ "objc2-ui-kit 0.3.2", "pin-weak", "raw-window-handle", + "rgb", "scoped-tls-hkt", "scopeguard", "softbuffer", @@ -2087,6 +2660,8 @@ version = "1.18.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed2ea15059d70bc31b1a8b1eb4c34f2c5df04cb7e53f36179b43c0261231d646" dependencies = [ + "accesskit", + "async-channel", "bitflags 2.13.2", "cfg-if", "chrono", @@ -2099,6 +2674,7 @@ dependencies = [ "icu_normalizer", "image", "js-sys", + "ksni", "lyon_algorithms", "lyon_extra", "lyon_geom", @@ -2453,9 +3029,17 @@ checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" dependencies = [ "bytemuck", "byteorder-lite", + "color_quant", + "exr", + "gif", + "image-webp", "moxcms", "num-traits", "png", + "qoi", + "ravif", + "rgb", + "tiff", "zune-core", "zune-jpeg", ] @@ -2492,6 +3076,18 @@ dependencies = [ "hashbrown 0.17.1", ] +[[package]] +name = "input" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fbdc09524a91f9cacd26f16734ff63d7dc650daffadd2b6f84d17a285bd875a9" +dependencies = [ + "bitflags 2.13.2", + "input-sys", + "libc", + "udev", +] + [[package]] name = "input" version = "0.10.0" @@ -2511,6 +3107,17 @@ version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "36eee07d8e02bd95bf52b2e642cf13d33701b94c6e4b04fbf1d1fb07e9cb19e7" +[[package]] +name = "interpolate_name" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c34819042dc3d3971c46c2190835914dfbe0c3c13f61449b2997f4e9722dfa60" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "io-lifetimes" version = "1.0.11" @@ -2537,6 +3144,15 @@ dependencies = [ "either", ] +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + [[package]] name = "itertools" version = "0.15.0" @@ -2685,6 +3301,35 @@ version = "3.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc" +[[package]] +name = "ksni" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bcc1cb43797140f74b711f1c4a49f48a7a7429f211c5fb78264e7bcd1e99caf" +dependencies = [ + "arc-swap", + "async-executor", + "async-io", + "async-lock", + "crossbeam-queue", + "futures-channel", + "futures-lite", + "futures-util", + "pastey 0.2.3", + "serde", + "task-local", + "zbus", +] + +[[package]] +name = "kstring" +version = "2.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a09b82a7f771ed02dc0dd9b27130a0fa5499fa15ed3027116c1e5e4e591bd9e" +dependencies = [ + "static_assertions", +] + [[package]] name = "kurbo" version = "0.13.1" @@ -2703,6 +3348,12 @@ version = "1.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" +[[package]] +name = "lebe" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8" + [[package]] name = "libc" version = "0.2.191" @@ -2718,6 +3369,16 @@ dependencies = [ "pkg-config", ] +[[package]] +name = "libfuzzer-sys" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9fd2f41a1cba099f79a0b6b6c35656cf7c03351a7bae8ff0f28f25270f929d2" +dependencies = [ + "arbitrary", + "cc", +] + [[package]] name = "libloading" version = "0.8.9" @@ -2827,6 +3488,15 @@ version = "0.4.34" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" +[[package]] +name = "loop9" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fae87c125b03c1d2c0150c90365d7d6bcc53fb73a9acaef207d2d065860f062" +dependencies = [ + "imgref", +] + [[package]] name = "lyon_algorithms" version = "1.0.22" @@ -2874,6 +3544,24 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baee0bbc17ce759db233beb01648088061bf678383130602a298e6998eedb2d8" +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "maybe-rayon" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ea1f30cedd69f0a2954655f7188c6a834246d2bcf1e315e2ac40c4b24dc9519" +dependencies = [ + "cfg-if", +] + [[package]] name = "memchr" version = "2.8.3" @@ -2964,6 +3652,12 @@ dependencies = [ "windows-sys 0.61.2", ] +[[package]] +name = "muldiv" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "956787520e75e9bd233246045d19f42fb73242759cc57fba9611d940ae96d4b0" + [[package]] name = "naga" version = "30.0.1" @@ -3038,6 +3732,12 @@ dependencies = [ "jni-sys 0.3.1", ] +[[package]] +name = "new_debug_unreachable" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" + [[package]] name = "nix" version = "0.29.0" @@ -3062,6 +3762,15 @@ dependencies = [ "libc", ] +[[package]] +name = "no_std_io2" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "418abd1b6d34fbf6cae440dc874771b0525a604428704c76e48b29a5e67b8003" +dependencies = [ + "memchr", +] + [[package]] name = "nom" version = "7.1.3" @@ -3081,6 +3790,41 @@ dependencies = [ "memchr", ] +[[package]] +name = "noop_proc_macro" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0676bb32a98c1a483ce53e500a81ad9c3d5b3f7c920c28c24e9cb0980d0b5bc8" + +[[package]] +name = "nu-ansi-term" +version = "0.50.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-complex" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" +dependencies = [ + "bytemuck", + "num-traits", +] + [[package]] name = "num-derive" version = "0.4.2" @@ -3092,6 +3836,26 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "num-integer" +version = "0.1.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ce2d95d4b3734dc35aa2f45e1aa22cd416814592a4f9d9205e11affd5b8e10b" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint", + "num-integer", + "num-traits", +] + [[package]] name = "num-traits" version = "0.2.19" @@ -3463,6 +4227,15 @@ version = "1.70.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe" +[[package]] +name = "option-operations" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aca39cf52b03268400c16eeb9b56382ea3c3353409309b63f5c8f0b1faf42754" +dependencies = [ + "pastey 0.2.3", +] + [[package]] name = "orbclient" version = "0.3.55" @@ -3552,6 +4325,7 @@ version = "0.11.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "22d2ff88bd3f7d68d1d9b09c7e6209f9a8e8c05088295140a2bcf2e9b17038c5" dependencies = [ + "accesskit", "fontique", "harfrust", "hashbrown 0.17.1", @@ -3573,6 +4347,24 @@ dependencies = [ "icu_properties", ] +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + +[[package]] +name = "pastey" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec" + +[[package]] +name = "pastey" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" + [[package]] name = "percent-encoding" version = "2.3.2" @@ -3590,6 +4382,49 @@ dependencies = [ "indexmap", ] +[[package]] +name = "phf" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" +dependencies = [ + "phf_macros", + "phf_shared", + "serde", +] + +[[package]] +name = "phf_generator" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" +dependencies = [ + "fastrand", + "phf_shared", +] + +[[package]] +name = "phf_macros" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" +dependencies = [ + "phf_generator", + "phf_shared", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "phf_shared" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" +dependencies = [ + "siphasher", +] + [[package]] name = "pico-args" version = "0.5.0" @@ -3732,6 +4567,15 @@ dependencies = [ "zerovec", ] +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + [[package]] name = "presser" version = "0.3.1" @@ -3771,6 +4615,19 @@ name = "profiling" version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5" +dependencies = [ + "profiling-procmacros", +] + +[[package]] +name = "profiling-procmacros" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4488a4a36b9a4ba6b9334a32a39971f77c1436ec82c38707bce707699cc3bbcb" +dependencies = [ + "quote", + "syn 2.0.119", +] [[package]] name = "pulldown-cmark" @@ -3783,12 +4640,44 @@ dependencies = [ "unicase", ] +[[package]] +name = "pulp" +version = "0.22.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "046aa45b989642ec2e4717c8e72d677b13edd831a4d3b6cf37d9a3e54912496a" +dependencies = [ + "bytemuck", + "cfg-if", + "libm", + "num-complex", + "paste", + "pulp-wasm-simd-flag", + "raw-cpuid", + "reborrow", + "version_check", +] + +[[package]] +name = "pulp-wasm-simd-flag" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d8f70e07b9c3962945a74e59ca1c511bba65b6419468acc217c457d93f3c740" + [[package]] name = "pxfm" version = "0.1.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" +[[package]] +name = "qoi" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f6d64c71eb498fe9eae14ce4ec935c555749aef511cca85b5568910d6e48001" +dependencies = [ + "bytemuck", +] + [[package]] name = "quick-error" version = "2.0.1" @@ -3831,6 +4720,26 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dc33ff2d4973d518d823d61aa239014831e521c75da58e3df4840d3f47749d09" +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + [[package]] name = "rand_core" version = "0.6.4" @@ -3840,12 +4749,79 @@ dependencies = [ "getrandom 0.2.17", ] +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + [[package]] name = "range-alloc" version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ca45419789ae5a7899559e9512e58ca889e41f04f1f2445e9f4b290ceccd1d08" +[[package]] +name = "rav1e" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43b6dd56e85d9483277cde964fd1bdb0428de4fec5ebba7540995639a21cb32b" +dependencies = [ + "aligned-vec", + "arbitrary", + "arg_enum_proc_macro", + "arrayvec", + "av-scenechange", + "av1-grain", + "bitstream-io", + "built", + "cfg-if", + "interpolate_name", + "itertools 0.14.0", + "libc", + "libfuzzer-sys", + "log", + "maybe-rayon", + "new_debug_unreachable", + "noop_proc_macro", + "num-derive", + "num-traits", + "paste", + "profiling", + "rand", + "rand_chacha", + "simd_helpers", + "thiserror 2.0.21", + "v_frame", + "wasm-bindgen", +] + +[[package]] +name = "ravif" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e52310197d971b0f5be7fe6b57530dcd27beb35c1b013f29d66c1ad73fbbcc45" +dependencies = [ + "avif-serialize", + "imgref", + "loop9", + "quick-error", + "rav1e", + "rgb", +] + +[[package]] +name = "raw-cpuid" +version = "11.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "498cd0dc59d73224351ee52a95fee0f1a617a2eae0e7d9d720cc622c73a54186" +dependencies = [ + "bitflags 2.13.2", +] + [[package]] name = "raw-window-handle" version = "0.6.2" @@ -3895,6 +4871,12 @@ dependencies = [ "once_cell", ] +[[package]] +name = "reborrow" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03251193000f4bd3b042892be858ee50e8b3719f2b08e5833ac4353724632430" + [[package]] name = "redox_syscall" version = "0.4.1" @@ -4239,9 +5221,44 @@ dependencies = [ "serde_core", ] +[[package]] +name = "sf-compositor" +version = "0.2.1" +dependencies = [ + "anyhow", + "sf-ipc", + "smithay", + "tracing", + "tracing-subscriber", +] + +[[package]] +name = "sf-core" +version = "0.2.1" +dependencies = [ + "anyhow", + "env_logger", + "libc", + "log", + "serde_json", + "sf-dial", + "sf-ipc", + "tokio", +] + +[[package]] +name = "sf-dial" +version = "0.2.1" +dependencies = [ + "anyhow", + "log", + "socket2", + "tokio", +] + [[package]] name = "sf-ipc" -version = "0.1.0" +version = "0.2.1" dependencies = [ "anyhow", "log", @@ -4252,7 +5269,7 @@ dependencies = [ [[package]] name = "sf-launcher" -version = "0.1.0" +version = "0.2.1" dependencies = [ "anyhow", "chrono", @@ -4260,16 +5277,43 @@ dependencies = [ "glow 0.16.0", "log", "png", + "serde", "serde_json", "sf-ipc", + "sf-ui", "slint", "slint-build", + "ureq", "windows-sys 0.61.2", ] +[[package]] +name = "sf-miracast" +version = "0.2.1" +dependencies = [ + "anyhow", + "env_logger", + "libc", + "log", + "tokio", + "zbus", +] + +[[package]] +name = "sf-pack" +version = "0.2.1" +dependencies = [ + "anyhow", + "ruzstd", + "serde", + "sf-ipc", + "tar", + "toml 0.9.12+spec-1.1.0", +] + [[package]] name = "sf-remote" -version = "0.1.0" +version = "0.2.1" dependencies = [ "anyhow", "bluer", @@ -4281,14 +5325,43 @@ dependencies = [ "tokio", ] +[[package]] +name = "sf-ui" +version = "0.2.1" +dependencies = [ + "anyhow", + "glow 0.16.0", + "gstreamer", + "gstreamer-app", + "gstreamer-video", + "image", + "log", + "png", + "slint", + "ureq", +] + +[[package]] +name = "sf-ui-gallery" +version = "0.2.1" +dependencies = [ + "anyhow", + "env_logger", + "log", + "sf-ui", + "slint", + "slint-build", +] + [[package]] name = "sf-update" -version = "0.1.0" +version = "0.2.1" dependencies = [ "anyhow", "base64 0.22.1", "ed25519-dalek", "env_logger", + "libc", "log", "ruzstd", "serde", @@ -4310,6 +5383,15 @@ dependencies = [ "digest", ] +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + [[package]] name = "shlex" version = "1.3.0" @@ -4338,7 +5420,7 @@ version = "2.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" dependencies = [ - "rand_core", + "rand_core 0.6.4", ] [[package]] @@ -4357,6 +5439,15 @@ dependencies = [ "simdutf8", ] +[[package]] +name = "simd_helpers" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95890f873bec569a0362c235787f3aca6e1e887302ba4840839bcc6459c42da6" +dependencies = [ + "quote", +] + [[package]] name = "simdutf8" version = "0.1.5" @@ -4484,6 +5575,52 @@ version = "1.16.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5b3dc8af474f516a851ff4bd12db780f948b9250ad37211e4eec0bccea54e01b" +[[package]] +name = "smithay" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "740cea6927892bc182d5bf70c8f79806c8bc9f68f2fb96e55a30be171b63af98" +dependencies = [ + "appendlist", + "atomic_float", + "bitflags 2.13.2", + "calloop 0.14.5", + "cc", + "cgmath", + "cursor-icon", + "downcast-rs", + "drm", + "drm-ffi", + "drm-fourcc", + "errno", + "gbm", + "gl_generator", + "indexmap", + "input 0.9.1", + "libc", + "libloading", + "libseat", + "pkg-config", + "profiling", + "rand", + "rustix 1.1.5", + "sha2", + "smallvec", + "tempfile", + "thiserror 2.0.21", + "tracing", + "udev", + "wayland-client", + "wayland-cursor", + "wayland-egl", + "wayland-protocols", + "wayland-protocols-misc", + "wayland-protocols-wlr", + "wayland-server", + "winit", + "xkbcommon 0.8.0", +] + [[package]] name = "smithay-client-toolkit" version = "0.19.2" @@ -4771,6 +5908,19 @@ dependencies = [ "web-sys", ] +[[package]] +name = "system-deps" +version = "9.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db551ad38aac61d5e0343e0eeeb0163be3115c4e23b6a025959570ee0c03c67d" +dependencies = [ + "cfg-expr", + "heck", + "pkg-config", + "toml 1.1.8+spec-1.1.0", + "version-compare", +] + [[package]] name = "taffy" version = "0.10.1" @@ -4800,6 +5950,21 @@ dependencies = [ "xattr", ] +[[package]] +name = "target-lexicon" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "adb6935a6f5c20170eeceb1a3835a49e12e19d792f6dd344ccc76a985ca5a6ca" + +[[package]] +name = "task-local" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2972044a9e5e448a506a7ff6f0d03b566d8ef4cd6918a58fc59835a0f8666626" +dependencies = [ + "pin-project-lite", +] + [[package]] name = "tempfile" version = "3.27.0" @@ -4859,6 +6024,29 @@ dependencies = [ "syn 3.0.9", ] +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "tiff" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52" +dependencies = [ + "fax", + "flate2", + "half", + "quick-error", + "weezl", + "zune-jpeg", +] + [[package]] name = "tiny-skia" version = "0.11.4" @@ -4953,6 +6141,7 @@ dependencies = [ "signal-hook-registry", "socket2", "tokio-macros", + "tracing", "windows-sys 0.61.2", ] @@ -5084,6 +6273,36 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" dependencies = [ "once_cell", + "valuable", +] + +[[package]] +name = "tracing-log" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" +dependencies = [ + "log", + "once_cell", + "tracing-core", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "nu-ansi-term", + "once_cell", + "regex-automata", + "sharded-slab", + "smallvec", + "thread_local", + "tracing", + "tracing-core", + "tracing-log", ] [[package]] @@ -5313,6 +6532,29 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "v_frame" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "666b7727c8875d6ab5db9533418d7c764233ac9c0cff1d469aec8fa127597be2" +dependencies = [ + "aligned-vec", + "num-traits", + "wasm-bindgen", +] + +[[package]] +name = "valuable" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" + +[[package]] +name = "version-compare" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e" + [[package]] name = "version_check" version = "0.9.5" @@ -5471,6 +6713,16 @@ dependencies = [ "xcursor", ] +[[package]] +name = "wayland-egl" +version = "0.32.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b97bdb7c49e5bd9b7562f38ff84f0dad47079fdc9e926f691a787f6dbc05451" +dependencies = [ + "wayland-backend", + "wayland-sys", +] + [[package]] name = "wayland-protocols" version = "0.32.13" @@ -5481,6 +6733,20 @@ dependencies = [ "wayland-backend", "wayland-client", "wayland-scanner", + "wayland-server", +] + +[[package]] +name = "wayland-protocols-misc" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e9567599ef23e09b8dad6e429e5738d4509dfc46b3b21f32841a304d16b29c8" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-protocols", + "wayland-scanner", + "wayland-server", ] [[package]] @@ -5507,6 +6773,7 @@ dependencies = [ "wayland-client", "wayland-protocols", "wayland-scanner", + "wayland-server", ] [[package]] @@ -5520,6 +6787,19 @@ dependencies = [ "quote", ] +[[package]] +name = "wayland-server" +version = "0.31.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dde9c29be0f723a573977de51ee455bf3dfa03652730a74f9dd3b337e374d75" +dependencies = [ + "bitflags 2.13.2", + "downcast-rs", + "rustix 1.1.5", + "wayland-backend", + "wayland-scanner", +] + [[package]] name = "wayland-sys" version = "0.31.11" @@ -6172,6 +7452,17 @@ version = "0.3.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "163b33ed8786455e2fa5d72f554057ce3f3182425434f756cd39c99839d88e23" +[[package]] +name = "xkbcommon" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d66ca9352cbd4eecbbc40871d8a11b4ac8107cfc528a6e14d7c19c69d0e1ac9" +dependencies = [ + "libc", + "memmap2", + "xkeysym", +] + [[package]] name = "xkbcommon" version = "0.9.0" @@ -6214,6 +7505,12 @@ version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" +[[package]] +name = "y4m" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a5a4b21e1a62b67a2970e6831bc091d7b87e119e7f9791aef9702e3bef04448" + [[package]] name = "yazi" version = "0.2.1" @@ -6279,6 +7576,7 @@ dependencies = [ "rustix 1.1.5", "serde", "serde_repr", + "tokio", "tracing", "uds_windows", "uuid", @@ -6289,6 +7587,30 @@ dependencies = [ "zvariant", ] +[[package]] +name = "zbus-lockstep" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6998de05217a084b7578728a9443d04ea4cd80f2a0839b8d78770b76ccd45863" +dependencies = [ + "zbus_xml", + "zvariant", +] + +[[package]] +name = "zbus-lockstep-macros" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10da05367f3a7b7553c8cdf8fa91aee6b64afebe32b51c95177957efc47ca3a0" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "zbus-lockstep", + "zbus_xml", + "zvariant", +] + [[package]] name = "zbus_macros" version = "5.19.0" @@ -6315,6 +7637,18 @@ dependencies = [ "zvariant", ] +[[package]] +name = "zbus_xml" +version = "5.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1586c021a01ca0a9216dcd874e546382e156a5cbab5fab6cb5f10087e22682a" +dependencies = [ + "serde", + "winnow 1.0.4", + "zbus_names", + "zvariant", +] + [[package]] name = "zcheapstr" version = "1.1.0" @@ -6430,6 +7764,15 @@ version = "0.5.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" +[[package]] +name = "zune-inflate" +version = "0.2.54" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73ab332fe2f6680068f3582b16a24f90ad7096d5d39b974d1c0aff0125116f02" +dependencies = [ + "simd-adler32", +] + [[package]] name = "zune-jpeg" version = "0.5.15" diff --git a/Cargo.toml b/Cargo.toml index e868610..2a95649 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -1,14 +1,15 @@ [workspace] 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] -version = "0.1.0" +version = "0.2.1" edition = "2024" license = "MIT" [workspace.dependencies] sf-ipc = { path = "crates/sf-ipc" } +sf-dial = { path = "crates/sf-dial" } serde = { version = "1", features = ["derive"] } serde_json = "1" toml = "0.9" diff --git a/DESIGN.md b/DESIGN.md new file mode 100644 index 0000000..5720a77 --- /dev/null +++ b/DESIGN.md @@ -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. diff --git a/PRODUCT.md b/PRODUCT.md new file mode 100644 index 0000000..62314e8 --- /dev/null +++ b/PRODUCT.md @@ -0,0 +1,57 @@ +# Product + + + +## 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//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. diff --git a/README.md b/README.md index a15ba1a..9fc190b 100644 --- a/README.md +++ b/README.md @@ -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. 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 - [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) -- [ ] 2: mkosi Debian image -- [ ] 3: `sf-core` (app indítás, Chromium web runtime) -- [ ] 4: DIAL (YouTube cast), AirPlay, Miracast -- [ ] 5: saját Smithay kompozitor +- [x] **2. fázis:** mkosi Debian image, telepítő ISO, csak olvasható rendszer + adatpartíció +- [x] **3. fázis:** `sf-core`: appok indítása systemd scope-ban, Home-ra fagyasztás, memóriafigyelés; Chromium web runtime +- [x] **4. fázis:** DIAL (YouTube cast telefonról), AirPlay (UxPlay); Miracast **kísérleti**, valódi telefonnal még nincs kipróbálva +- [x] **5. fázis:** saját Smithay kompozitor (`sf-compositor`): app-váltás animációval, hangerő-OSD, `wlr-randr` támogatás ## Futtatás (fejlesztés) ```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). - 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. +- 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`). - 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. @@ -49,8 +50,15 @@ A Netflex szerver a Netflex app beállítása (a Részletek lapon látszik), a c ```toml # settings.toml 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 ``` 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) apps//app.toml appok: kind = "web" | "exec" | "builtin" crates/sf-update/ csomag-frissítő (root): aláírt shell- és app-csomagok a Gitea registryből + és store appok a GitHub/Gitea/GitLab release-ekből +crates/sf-pack/ app-csomagoló fejlesztőknek: kulcs, csomag, aláírás, futtatás sandboxban +templates/rust-app/ sablon egy store apphoz Rustban, release pipeline-okkal tools/pkg/ csomagok építése, aláírása, feltöltése (a CI is ezt futtatja) +crates/sf-core/ daemon: appok életciklusa, DIAL szerver, AirPlay/Miracast vevők felügyelete +crates/sf-dial/ DIAL protokoll (SSDP + REST), a YouTube castoláshoz +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/`). @@ -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; - 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. @@ -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”. - **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 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:** - `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:`); - 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/`); 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 `: ugyanabban a sandboxban futtatja az appot, mint a TV. + +A részletek: [`docs/store.md`](docs/store.md). + ## 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: @@ -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. +## 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--.scope`), saját folyamatcsoportban. A web appok a közös Chromiumot kapják, appra szabott profillal (`~/.config/smartfox/profiles/`). +- **Home:** a kompozitor a launchert hozza elő, az app 0,6 mp múlva megfagy (`systemctl --user freeze`). Újra megnyitva azonnal folytatódik (`thaw`). +- **Memória:** legfeljebb 2 app vár a háttérben, a legrégebbi bezárul. Ha 400 MB alá esik a szabad memória, a legrégebbi háttérapp bezárul (értesítés jelenik meg). +- **cage alatt** (tartalék kompozitor) nem lehet ablakot váltani, ott Home bezárja az appot. +- **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 `), 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 `, `register `, `status`. +- **Fejlesztés:** Linux asztalon ablakban fut: `sf-compositor --winit -- `. WSL alatt a Slint X11-et választ, ezért ott a launcher nem a beágyazott kompozitorhoz csatlakozik. + ## Licenc - A Slint a GPL-3.0 alatt van használva (beágyazott eszközre a royalty-free licenc nem vonatkozik). - Az Inter betűtípus OFL licencű (`crates/sf-launcher/ui/fonts/OFL-LICENSE.txt`). diff --git a/apps/airplay/app.toml b/apps/airplay/app.toml index c4145bc..e5d6266 100644 --- a/apps/airplay/app.toml +++ b/apps/airplay/app.toml @@ -1,11 +1,20 @@ id = "airplay" name = "AirPlay" -version = "1.0.0" +version = "1.0.1" kind = "exec" 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." -exec = ["uxplay", "-n", "SmartFox", "-nh", "-vs", "waylandsink"] +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." +# 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" accent = "#4DA3FF" palette = ["#7cc4ff", "#1d4fa8", "#050c1c"] 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 diff --git a/apps/miracast/app.toml b/apps/miracast/app.toml index cdc55c1..6d2dad2 100644 --- a/apps/miracast/app.toml +++ b/apps/miracast/app.toml @@ -1,11 +1,20 @@ id = "miracast" name = "Miracast" -version = "1.0.0" +version = "1.0.1" kind = "exec" 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." -exec = ["sf-miracast-sink"] +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." +# 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" accent = "#2FE0C0" palette = ["#6ff5dc", "#0f7a6c", "#03130f"] 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 diff --git a/apps/netflex/app.toml b/apps/netflex/app.toml index a0398a5..90e44b4 100644 --- a/apps/netflex/app.toml +++ b/apps/netflex/app.toml @@ -12,4 +12,4 @@ order = 10 [web] # "SMART-TV" turns on the Netflex 10-foot UI (see packages/client/src/remote.ts → isTv). -user_agent_suffix = "SMART-TV SmartFox/0.1" +user_agent_suffix = "SMART-TV FennecOS/0.1" diff --git a/apps/steam/app.toml b/apps/steam/app.toml new file mode 100644 index 0000000..099a221 --- /dev/null +++ b/apps/steam/app.toml @@ -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"] diff --git a/apps/steam/bin/smartfox-steam b/apps/steam/bin/smartfox-steam new file mode 100644 index 0000000..18699f4 --- /dev/null +++ b/apps/steam/bin/smartfox-steam @@ -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 "$@" diff --git a/apps/store/app.toml b/apps/store/app.toml new file mode 100644 index 0000000..4c9ea71 --- /dev/null +++ b/apps/store/app.toml @@ -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 diff --git a/apps/youtube/app.toml b/apps/youtube/app.toml index b019f81..48a501a 100644 --- a/apps/youtube/app.toml +++ b/apps/youtube/app.toml @@ -12,7 +12,7 @@ order = 20 [web] # A Cobalt (TV) user agent makes YouTube serve its leanback UI. -user_agent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0 Safari/537.36 Cobalt/25.lts.30.1034943-gold (unlike Gecko), Unknown_TV_Unknown_0/Unknown (SmartFox, SF1, Wired)" +user_agent = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/138.0 Safari/537.36 Cobalt/25.lts.30.1034943-gold (unlike Gecko), Unknown_TV_Unknown_0/Unknown (Fennec OS, SF1, Wired)" [dial] name = "YouTube" diff --git a/crates/sf-compositor/Cargo.toml b/crates/sf-compositor/Cargo.toml new file mode 100644 index 0000000..6e13d01 --- /dev/null +++ b/crates/sf-compositor/Cargo.toml @@ -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", +] } diff --git a/crates/sf-compositor/src/control.rs b/crates/sf-compositor/src/control.rs new file mode 100644 index 0000000..012c64a --- /dev/null +++ b/crates/sf-compositor/src/control.rs @@ -0,0 +1,72 @@ +//! Control socket for sf-core. One command per line, one reply line: +//! focus launcher | focus -> ok +//! register -> ok (windows of that process group belong to the app) +//! status -> ok visible= 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::().is_ok() && !id.trim().is_empty() => { + st.register(pgid.parse().unwrap(), id.trim().to_string()); + "ok".into() + } + _ => "err usage: register ".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:?}"), + } +} diff --git a/crates/sf-compositor/src/main.rs b/crates/sf-compositor/src/main.rs new file mode 100644 index 0000000..598b921 --- /dev/null +++ b/crates/sf-compositor/src/main.rs @@ -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 ` 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] -- `; 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 = 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 = EventLoop::try_new()?; + let display: Display = 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(()) +} diff --git a/crates/sf-compositor/src/output_mgmt.rs b/crates/sf-compositor/src/output_mgmt.rs new file mode 100644 index 0000000..806f20d --- /dev/null +++ b/crates/sf-compositor/src/output_mgmt.rs @@ -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, + pub current: Option, + 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 { + let output = state.output.as_ref()?; + let props = output.physical_properties(); + let modes: Vec = output + .user_data() + .get::() + .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>); + +/// What a client asked for in one configuration. +#[derive(Debug, Default, Clone)] +struct Requested { + enabled: Option, + mode: Option, + /// 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, + 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, + modes: Vec, +} + +pub struct OutputMgmtState { + _global: GlobalId, + managers: Vec, + info: Option, + serial: u32, +} + +impl OutputMgmtState { + pub fn new(dh: &DisplayHandle) -> Self { + let global = dh.create_global::(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) { + 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::(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::(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 for State { + fn bind( + state: &mut State, + dh: &DisplayHandle, + _client: &Client, + resource: New, + _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 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 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 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>; + +impl Dispatch 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 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::() { + 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) + } +} diff --git a/crates/sf-compositor/src/state.rs b/crates/sf-compositor/src/state.rs new file mode 100644 index 0000000..c0c907d --- /dev/null +++ b/crates/sf-compositor/src/state.rs @@ -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, + Scaled=RescaleRenderElement>, + 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, + pub pid: Option, + /// Has a buffer, can be shown. + pub mapped: bool, + pub mapped_at: Option, + 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, + 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, + pub data_device_state: DataDeviceState, + pub dmabuf_state: DmabufState, + pub dmabuf_global: Option, + #[allow(dead_code)] + pub viewporter_state: ViewporterState, + #[allow(dead_code)] + pub decoration_state: XdgDecorationState, + pub output_mgmt: OutputMgmtState, + pub pending_configs: Vec, + pub popups: PopupManager, + pub seat: Seat, + pub space: Space, + pub session: Option, + + pub output: Option, + pub wins: Vec, + /// Process groups of apps, from sf-core (`register`). + pub registered: std::collections::HashMap, + 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, + hold_poll: bool, + pub visible: Option, + pub transition: Option, + pub osd: Option, + 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//stat). +fn pgid_of(pid: i32) -> Option { + 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 `); +/// 2. its systemd scope (`sf-app--.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) -> Option { + 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::() + .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) -> anyhow::Result { + let dh = display.handle(); + let compositor_state = CompositorState::new::(&dh); + let xdg_shell_state = XdgShellState::new::(&dh); + let shm_state = ShmState::new::(&dh, vec![]); + let output_manager_state = OutputManagerState::new_with_xdg_output::(&dh); + let mut seat_state = SeatState::new(); + let data_device_state = DataDeviceState::new::(&dh); + let viewporter_state = ViewporterState::new::(&dh); + let decoration_state = XdgDecorationState::new::(&dh); + let output_mgmt = OutputMgmtState::new(&dh); + + let mut seat: Seat = 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 { + 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) { + 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 = 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 { + self.win_of(window).and_then(|w| w.app.clone()) + } + + fn find_visible(&self) -> Option { + 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 { + 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 { + 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(&mut self, event: InputEvent) { + 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::(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) { + 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::().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> { + let origin: Point = (0, 0).into(); + let loc: Point = (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 { + let mut out: Vec = 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 = (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::().unwrap().compositor_state + } + + fn commit(&mut self, surface: &WlSurface) { + on_commit_buffer_handler::(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::() + .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) { + 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 { + &mut self.seat_state + } + + fn focus_changed(&mut self, seat: &Seat, 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::(); + } +} + +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); diff --git a/crates/sf-compositor/src/udev.rs b/crates/sf-compositor/src/udev.rs new file mode 100644 index 0000000..939d3bb --- /dev/null +++ b/crates/sf-compositor/src/udev.rs @@ -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; +type Exporter = GbmFramebufferExporter; + +const FORMATS: &[Fourcc] = &[Fourcc::Argb8888, Fourcc::Abgr8888, Fourcc::Xrgb8888]; + +struct Out { + drm_output: DrmOutput, + connector: connector::Handle, + crtc: crtc::Handle, + modes: Vec, + output: Output, + global: Option, + 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, + renderer: GlesRenderer, + out: Option, + 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 { + 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.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::>(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::(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.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 = 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(()) + } +} diff --git a/crates/sf-compositor/src/winit.rs b/crates/sf-compositor/src/winit.rs new file mode 100644 index 0000000..7401cff --- /dev/null +++ b/crates/sf-compositor/src/winit.rs @@ -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, + 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 { + let (mut backend, winit_loop) = winit::init::().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.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.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(()) + } +} diff --git a/crates/sf-core/Cargo.toml b/crates/sf-core/Cargo.toml new file mode 100644 index 0000000..59b0329 --- /dev/null +++ b/crates/sf-core/Cargo.toml @@ -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" diff --git a/crates/sf-core/src/apps.rs b/crates/sf-core/src/apps.rs new file mode 100644 index 0000000..ab1a1e7 --- /dev/null +++ b/crates/sf-core/src/apps.rs @@ -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--.scope`), if scopes are used. + unit: Option, + frozen: bool, + last_used: Instant, + serial: u64, +} + +#[derive(Default)] +struct State { + apps: Vec, + running: Vec, + foreground: Option, + serial: u64, + /// While a cast window is up: what to show when it ends (None: launcher). + cast_return: Option>, +} + +pub struct Core { + apps_dirs: Vec, + /// Installed store apps (sandboxed, see sf_ipc::sandbox). + store_dir: Option, + settings_path: PathBuf, + scopes: bool, + pub events: broadcast::Sender, + state: Mutex, +} + +/// 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 { + let text = std::fs::read_to_string("/proc/meminfo").ok()?; + let line = text.lines().find(|l| l.starts_with("MemAvailable:"))?; + line.split_whitespace().nth(1)?.parse().ok() +} + +impl Core { + pub fn new(apps_dirs: Vec, store_dir: Option, settings_path: PathBuf) -> Result { + let apps = sf_ipc::manifest::load_all(&apps_dirs, store_dir.as_deref())?; + 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 { + self.state.lock().unwrap().apps.clone() + } + + pub fn foreground(&self) -> Option { + 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, id: &str, query: Option, 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 = 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 { + let mut st = self.state.lock().unwrap(); + if let Some(id) = id { + if let Some(r) = st.running.iter_mut().find(|r| r.id == id) { + r.last_used = Instant::now(); + } + } + let prev = std::mem::replace(&mut st.foreground, id.map(str::to_string)); + prev.filter(|p| Some(p.as_str()) != id) + } + + /// The previous foreground app goes to the background (or is closed + /// when the compositor can't keep it there). + fn leave_foreground(self: &Arc, prev: Option, switching: bool) { + let Some(prev) = prev else { return }; + if switching { + self.freeze_later(prev); + } else { + self.stop(&prev); + } + } + + fn spawn(self: &Arc, 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) { + let prev = self.set_foreground(None); + let switching = wm::available(); + wm::focus(None); + self.leave_foreground(prev, switching); + self.enforce_background_limit(); + } + + fn freeze_later(self: &Arc, id: String) { + let core = self.clone(); + tokio::spawn(async move { + tokio::time::sleep(FREEZE_DELAY).await; + let target = { + let st = core.state.lock().unwrap(); + if st.foreground.as_deref() == Some(id.as_str()) { + return; // came back in the meantime + } + st.running.iter().find(|r| r.id == id && !r.frozen).map(|r| (r.unit.clone(), r.pid)) + }; + let Some((unit, pid)) = target else { return }; + let ok = match &unit { + Some(u) => systemctl("freeze", u).await.map_err(|e| log::warn!("{e:#}")).is_ok(), + None => kill_group(pid, libc::SIGSTOP), + }; + if ok { + // It may have been brought back while we were freezing it. + let back = { + let mut st = core.state.lock().unwrap(); + if let Some(r) = st.running.iter_mut().find(|r| r.id == id) { + r.frozen = true; + } + st.foreground.as_deref() == Some(id.as_str()) + }; + if back { + core.thaw(&id, unit.as_deref(), pid).await; + } else { + log::info!("{id} frozen"); + } + } + }); + } + + async fn thaw(&self, id: &str, unit: Option<&str>, pid: u32) { + match unit { + Some(u) => { + if let Err(e) = systemctl("thaw", u).await { + log::warn!("{e:#}"); + } + } + None => { + kill_group(pid, libc::SIGCONT); + } + } + if let Some(r) = self.state.lock().unwrap().running.iter_mut().find(|r| r.id == id) { + r.frozen = false; + } + log::info!("{id} thawed"); + } + + /// Closes the app (asynchronously); false if it wasn't running. + pub fn stop(self: &Arc, id: &str) -> bool { + let target = { + let st = self.state.lock().unwrap(); + st.running.iter().find(|r| r.id == id).map(|r| (r.unit.clone(), r.pid)) + }; + let 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, 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 { + let st = self.state.lock().unwrap(); + st.running + .iter() + .filter(|r| st.foreground.as_deref() != Some(r.id.as_str())) + .min_by_key(|r| r.last_used) + .map(|r| r.id.clone()) + } + + fn background_count(&self) -> usize { + let st = self.state.lock().unwrap(); + st.running.iter().filter(|r| st.foreground.as_deref() != Some(r.id.as_str())).count() + } + + fn enforce_background_limit(self: &Arc) { + while self.background_count() > MAX_BACKGROUND { + let Some(id) = self.oldest_background() else { break }; + log::info!("too many apps in the background, closing {id}"); + if !self.stop(&id) { + break; + } + // Don't pick it again while it shuts down. + self.state.lock().unwrap().running.retain(|r| r.id != id); + self.emit(CoreEvent::AppStopped { app_id: id }); + } + } + + /// A receiver (AirPlay/Miracast) got a connection: its window goes on + /// top, the foreground app pauses in the background. + pub fn cast_connected(self: &Arc, app_id: &str, device: &str) { + let switching = wm::available(); + let prev = { + let mut st = self.state.lock().unwrap(); + if st.cast_return.is_none() { + st.cast_return = Some(st.foreground.clone()); + } + if switching { st.foreground.take() } else { None } + }; + if let Some(prev) = prev { + self.freeze_later(prev); + } + 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, 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) { + let ids: Vec<(Option, 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) { + let mut tick = tokio::time::interval(Duration::from_secs(5)); + loop { + tick.tick().await; + let Some(avail) = mem_available_kb() else { continue }; + if avail >= LOW_MEMORY_KB { + continue; + } + let Some(id) = core.oldest_background() else { continue }; + let name = core.apps().into_iter().find(|a| a.id == id).map(|a| a.name).unwrap_or(id.clone()); + log::warn!("low memory ({} MB available), closing {id}", avail / 1024); + if core.stop(&id) { + core.state.lock().unwrap().running.retain(|r| r.id != id); + core.emit(CoreEvent::AppStopped { app_id: id }); + core.emit(CoreEvent::Toast { text: format!("Kevés a memória: {name} bezárva") }); + } + } +} diff --git a/crates/sf-core/src/dial.rs b/crates/sf-core/src/dial.rs new file mode 100644 index 0000000..7e02496 --- /dev/null +++ b/crates/sf-core/src/dial.rs @@ -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); + +impl Dial { + fn app_for(&self, dial_name: &str) -> Option { + self.0.apps().into_iter().find(|a| a.dial.as_ref().is_some_and(|d| d.name == dial_name)).map(|a| a.id) + } +} + +impl Handler for Dial { + fn state(&self, name: &str) -> Option { + 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, 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 +} diff --git a/crates/sf-core/src/main.rs b/crates/sf-core/src/main.rs new file mode 100644 index 0000000..8d875b4 --- /dev/null +++ b/crates/sf-core/src/main.rs @@ -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 `). + +#[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, + store_dir: Option, + 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(()) + }) +} diff --git a/crates/sf-core/src/server.rs b/crates/sf-core/src/server.rs new file mode 100644 index 0000000..1808f64 --- /dev/null +++ b/crates/sf-core/src/server.rs @@ -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) -> 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, 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::(line) { + Ok(req) => handle(&core, req).await, + Err(e) => log::warn!("bad request {line:?}: {e}"), + } + } + writer.abort(); + Ok(()) +} + +async fn handle(core: &Arc, 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); + } + } +} diff --git a/crates/sf-core/src/services.rs b/crates/sf-core/src/services.rs new file mode 100644 index 0000000..fd7dd07 --- /dev/null +++ b/crates/sf-core/src/services.rs @@ -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 () with deviceID = …`, +/// `Open connections: `; +/// - our own receivers: `SF-EVENT connected `, `SF-EVENT ended`. +pub fn parse_line(line: &str, connected: bool) -> Option { + 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) { + for app in core.apps().into_iter().filter(|a| a.service) { + tokio::spawn(supervise(core.clone(), app)); + } +} + +async fn supervise(core: Arc, 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::(); + for out in [child.stdout.take().map(|s| Box::new(s) as Box), + child.stderr.take().map(|s| Box::new(s) as Box)] + .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); + } +} diff --git a/crates/sf-core/src/wm.rs b/crates/sf-core/src/wm.rs new file mode 100644 index 0000000..a962b02 --- /dev/null +++ b/crates/sf-core/src/wm.rs @@ -0,0 +1,56 @@ +//! Client for the sf-compositor control socket. One command per line, one +//! reply line (`ok` or `err `): +//! focus launcher show the launcher +//! focus show that app's window (as soon as it has one) +//! register 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:#}"); + } +} diff --git a/crates/sf-dial/Cargo.toml b/crates/sf-dial/Cargo.toml new file mode 100644 index 0000000..5e4d235 --- /dev/null +++ b/crates/sf-dial/Cargo.toml @@ -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"] } diff --git a/crates/sf-dial/src/http.rs b/crates/sf-dial/src/http.rs new file mode 100644 index 0000000..00ad1d3 --- /dev/null +++ b/crates/sf-dial/src/http.rs @@ -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, +} + +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 for ReadError { + fn from(e: anyhow::Error) -> Self { + ReadError::Bad(e) + } +} + +pub async fn read_request(stream: &mut S) -> Result { + tokio::time::timeout(Duration::from_secs(10), read_inner(stream)) + .await + .map_err(|_| ReadError::Bad(anyhow::anyhow!("timeout")))? +} + +async fn read_inner(stream: &mut S) -> Result { + 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 { + hay.windows(needle.len()).position(|w| w == needle) +} + +fn parse_head(head: &str) -> Result { + 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, +} + +impl Response { + pub fn new(status: u16) -> Self { + Response { status, headers: vec![], body: vec![] } + } + + pub fn header(mut self, k: &str, v: impl Into) -> 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) -> Self { + self.body = body; + self + } + + pub async fn write(&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('&', "&").replace('<', "<").replace('>', ">").replace('"', """).replace('\'', "'") +} + +#[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"); + } +} diff --git a/crates/sf-dial/src/lib.rs b/crates/sf-dial/src/lib.rs new file mode 100644 index 0000000..23c279a --- /dev/null +++ b/crates/sf-dial/src/lib.rs @@ -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?`, 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; + 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::().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 { + config: Config, + handler: H, + /// `additionalData` posted by running apps, per DIAL app name. + data: Mutex>>, +} + +/// Runs SSDP and the HTTP server until an error stops one of them. +pub async fn run(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 Server { + fn base_url(&self, local: Option) -> 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) -> 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) -> Response { + let c = &self.config; + let xml = format!( + r#" + + 10 + + urn:dial-multiscreen-org:device:dial:1 + {} + {} + {} + uuid:{} + + + urn:dial-multiscreen-org:service:dial:1 + urn:dial-multiscreen-org:serviceId:dial + /ssdp/notfound + /ssdp/notfound + /ssdp/notfound + + + + +"#, + 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}>{}", xml_escape(v))) + .collect() + }) + .unwrap_or_default(); + let xml = format!( + r#" + + {} + + {}{} + {data} + +"#, + xml_escape(name), + if running { "running" } else { "stopped" }, + if running { "\n " } else { "" }, + ); + Response::xml(200, xml) + } + + fn launch(&self, name: &str, req: &Request, peer: SocketAddr, local: Option) -> 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>, + } + + impl Handler for Arc { + fn state(&self, name: &str) -> Option { + (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 = 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("stopped")); + 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&xrunning")); + assert!(body.contains("s1")); + + 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); + } +} diff --git a/crates/sf-dial/src/ssdp.rs b/crates/sf-dial/src/ssdp.rs new file mode 100644 index 0000000..a83b2d8 --- /dev/null +++ b/crates/sf-dial/src/ssdp.rs @@ -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 { + 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 { + 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 { + 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")); + } +} diff --git a/crates/sf-ipc/Cargo.toml b/crates/sf-ipc/Cargo.toml index 781fe0e..59b0a3b 100644 --- a/crates/sf-ipc/Cargo.toml +++ b/crates/sf-ipc/Cargo.toml @@ -1,6 +1,6 @@ [package] 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 edition.workspace = true license.workspace = true diff --git a/crates/sf-ipc/src/launch.rs b/crates/sf-ipc/src/launch.rs new file mode 100644 index 0000000..a30701e --- /dev/null +++ b/crates/sf-ipc/src/launch.rs @@ -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//environ` to tell windows apart. +pub const APP_ENV: &str = "SMARTFOX_APP"; + +pub struct Browser { + pub exe: PathBuf, + /// Full version, used to build a realistic user agent. + pub version: String, +} + +pub fn find_browser() -> Option { + let mut candidates: Vec = Vec::new(); + if let Ok(p) = std::env::var("SMARTFOX_BROWSER") { + candidates.push(p.into()); + } + #[cfg(windows)] + { + for base in ["ProgramFiles", "ProgramFiles(x86)", "LOCALAPPDATA"] { + if let Some(b) = std::env::var_os(base) { + let b = PathBuf::from(b); + candidates.push(b.join(r"Google\Chrome\Application\chrome.exe")); + candidates.push(b.join(r"Chromium\Application\chrome.exe")); + candidates.push(b.join(r"Microsoft\Edge\Application\msedge.exe")); + } + } + } + #[cfg(not(windows))] + { + for name in ["chromium", "chromium-browser", "google-chrome-stable", "google-chrome"] { + for dir in ["/usr/bin", "/usr/local/bin", "/snap/bin"] { + candidates.push(Path::new(dir).join(name)); + } + } + } + let exe = candidates.into_iter().find(|p| p.is_file())?; + let version = browser_version(&exe).unwrap_or_else(|| "141.0.0.0".into()); + Some(Browser { exe, version }) +} + +fn browser_version(exe: &Path) -> Option { + // Windows installs keep a folder named after the version next to the exe. + if cfg!(windows) { + let dir = exe.parent()?; + let mut versions: Vec = std::fs::read_dir(dir) + .ok()? + .flatten() + .filter_map(|e| e.file_name().into_string().ok()) + .filter(|n| n.split('.').count() == 4 && n.split('.').all(|p| p.parse::().is_ok())) + .collect(); + versions.sort_by_key(|v| v.split('.').map(|p| p.parse::().unwrap_or(0)).collect::>()); + return versions.pop(); + } + let out = Command::new(exe).arg("--version").output().ok()?; + String::from_utf8_lossy(&out.stdout) + .split_whitespace() + .find(|w| w.chars().next().is_some_and(|c| c.is_ascii_digit()) && w.contains('.')) + .map(str::to_string) +} + +fn default_user_agent(version: &str) -> String { + let platform = if cfg!(windows) { "Windows NT 10.0; Win64; x64" } else { "X11; Linux x86_64" }; + let major = version.split('.').next().unwrap_or("141"); + format!("Mozilla/5.0 ({platform}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{major}.0.0.0 Safari/537.36") +} + +pub struct LaunchOptions<'a> { + /// Per-app browser profiles live in `/profiles/`. + pub data_dir: &'a Path, + pub fullscreen: bool, + /// Windowed mode: open the app exactly over the launcher (x, y, w, h). + pub bounds: Option<(i32, i32, u32, u32)>, + /// Extra query string for the start URL (DIAL launch parameters). + pub query: Option<&'a str>, +} + +/// A program with its arguments and environment, before it is (maybe) put +/// into the sandbox. +struct Inner { + program: String, + args: Vec, + env: Vec<(String, String)>, +} + +/// The bwrap binary if `app` runs sandboxed (`sandbox` module). Store apps +/// never run without it. Official apps run unsandboxed when bwrap is missing +/// (an older image under a newer shell) or with `SMARTFOX_SANDBOX=off` +/// (debugging), with a warning. +fn sandbox_for(app: &AppManifest) -> Result> { + if app.origin == crate::Origin::Store { + anyhow::ensure!(cfg!(target_os = "linux"), "store apps only run on the TV (Linux)"); + return sandbox::bwrap_path().context("bubblewrap (bwrap) is not installed, and store apps only run sandboxed").map(Some); + } + if !cfg!(target_os = "linux") || !app.sandboxed() { + return Ok(None); + } + if std::env::var("SMARTFOX_SANDBOX").is_ok_and(|v| v == "off") { + log::warn!("{}: SMARTFOX_SANDBOX=off, running without a sandbox", app.id); + return Ok(None); + } + let bwrap = sandbox::bwrap_path(); + if bwrap.is_none() { + log::warn!("{}: bubblewrap is not installed, running without a sandbox", app.id); + } + Ok(bwrap) +} + +/// The command that starts `app`. Not spawned yet, so callers can wrap it +/// (sf-core runs it inside a systemd scope). +pub fn command(app: &AppManifest, settings: &Settings, opts: &LaunchOptions) -> Result { + let bwrap = sandbox_for(app)?; + // Where the app's files are, as the app sees them. + let root = if bwrap.is_some() { PathBuf::from(sandbox::APP_DIR) } else { app.dir.clone() }; + let data = paths::app_data_dir(&app.id); + let inner = match app.kind { + AppKind::Web => web_command(app, settings, opts, &root, bwrap.is_some().then_some(data.as_path()))?, + AppKind::Exec => { + let line = app.resolved_exec(&root); + let (prog, args) = line.split_first().context("empty exec command")?; + Inner { program: prog.clone(), args: args.to_vec(), env: Vec::new() } + } + AppKind::Builtin => bail!("built-in app has no process"), + }; + let mut env = inner.env; + env.extend(app.env.iter().map(|(k, v)| (k.clone(), settings.expand(v)))); + + let mut cmd = match bwrap { + Some(bwrap) => { + std::fs::create_dir_all(&data).with_context(|| format!("creating {}", data.display()))?; + // Store apps sit behind symlinks (store/apps/ -> ../store-/current). + let app_dir = std::fs::canonicalize(&app.dir).unwrap_or_else(|_| app.dir.clone()); + let permissions = app.permissions(); + let spec = sandbox::Spec { + app_id: &app.id, + app_dir: &app_dir, + data_dir: &data, + extra_rw: Vec::new(), + permissions: &permissions, + env, + program: inner.program, + args: inner.args, + }; + let cmd = sandbox::command(&bwrap, &spec, &sandbox::Host::current()); + log::info!("{}: sandboxed, permissions: {:?}", app.id, permissions.iter().map(|p| p.key()).collect::>()); + cmd + } + None => { + let mut cmd = Command::new(&inner.program); + cmd.args(&inner.args).envs(env).env("SMARTFOX_APP_DIR", &app.dir); + cmd + } + }; + cmd.env(APP_ENV, &app.id); + // Own process group, so stopping the app also ends its helper processes. + #[cfg(unix)] + { + use std::os::unix::process::CommandExt; + cmd.process_group(0); + } + Ok(cmd) +} + +/// Adds `query` to `url`, before any `#fragment`. +pub fn with_query(url: &str, query: Option<&str>) -> String { + let Some(q) = query.map(|q| q.trim_start_matches(['?', '&'])).filter(|q| !q.is_empty()) else { + return url.to_string(); + }; + let (base, frag) = match url.find('#') { + Some(i) => (&url[..i], &url[i..]), + None => (url, ""), + }; + let sep = if base.contains('?') { '&' } else { '?' }; + format!("{base}{sep}{q}{frag}") +} + +/// First-run preferences for an app profile: no translate prompt, Hungarian +/// content language. Existing profiles are left alone. +fn seed_profile(profile: &Path) -> Result<()> { + let prefs = profile.join("Default").join("Preferences"); + if prefs.exists() { + return Ok(()); + } + std::fs::create_dir_all(prefs.parent().unwrap())?; + std::fs::write( + &prefs, + r#"{"translate":{"enabled":false},"intl":{"accept_languages":"hu-HU,hu,en"},"browser":{"has_seen_welcome_page":true}}"#, + )?; + Ok(()) +} + +/// The browser command for a web app. `sandbox_home`: the app's data folder +/// when it runs sandboxed; its Chromium profile then lives in there. +fn web_command(app: &AppManifest, settings: &Settings, opts: &LaunchOptions, root: &Path, sandbox_home: Option<&Path>) -> Result { + let browser = find_browser().context("no Chromium/Chrome/Edge found (set SMARTFOX_BROWSER)")?; + let url = app.resolved_url(settings).filter(|u| !u.is_empty()).context("app has no URL")?; + if url.starts_with('/') { + bail!("URL is not set (check settings: {url})"); + } + let url = with_query(&url, opts.query); + let old_profile = opts.data_dir.join("profiles").join(&app.id); + let profile = match sandbox_home { + Some(home) => { + let profile = home.join("chromium"); + // Profiles from before the sandbox (logins, settings) move along. + if old_profile.is_dir() && !profile.exists() { + std::fs::create_dir_all(home)?; + if let Err(e) = std::fs::rename(&old_profile, &profile) { + log::warn!("{}: moving the browser profile: {e}", app.id); + } + } + profile + } + None => old_profile, + }; + seed_profile(&profile)?; + + let ua = match (&app.web.user_agent, &app.web.user_agent_suffix) { + (Some(ua), _) => ua.clone(), + (None, Some(suffix)) => format!("{} {suffix}", default_user_agent(&browser.version)), + (None, None) => default_user_agent(&browser.version), + }; + + let mut args: Vec = vec![ + format!("--user-data-dir={}", profile.display()), + format!("--user-agent={ua}"), + "--no-first-run".into(), + "--no-default-browser-check".into(), + "--disable-session-crashed-bubble".into(), + "--hide-crash-restore-bubble".into(), + "--disable-features=Translate,TranslateUI,MediaRouter,LocalNetworkAccessChecks".into(), + "--lang=hu".into(), + "--accept-lang=hu-HU,hu,en".into(), + // Dark first paint instead of a white flash before the page draws. + "--force-dark-mode".into(), + "--autoplay-policy=no-user-gesture-required".into(), + "--overscroll-history-navigation=0".into(), + ]; + if opts.fullscreen { + args.extend(["--kiosk".into(), url]); + } else { + args.push(format!("--app={url}")); + match opts.bounds { + Some((x, y, w, h)) => args.extend([format!("--window-position={x},{y}"), format!("--window-size={w},{h}")]), + None => args.push("--window-size=1600,900".into()), + } + } + let mut env = Vec::new(); + if cfg!(target_os = "linux") { + // Chromium on Linux picks its UI language from the environment, not --lang. + env.push(("LANGUAGE".to_string(), "hu".to_string())); + args.push("--enable-features=VaapiVideoDecoder,VaapiIgnoreDriverChecks,PlatformHEVCDecoderSupport".into()); + if std::env::var_os("WAYLAND_DISPLAY").is_some() { + args.push("--ozone-platform=wayland".into()); + } + } + for ext in &app.web.extensions { + args.push(format!("--load-extension={}", root.join(ext).display())); + } + Ok(Inner { program: browser.exe.to_string_lossy().into_owned(), args, env }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn adds_query() { + assert_eq!(with_query("https://www.youtube.com/tv", Some("a=1&b=2")), "https://www.youtube.com/tv?a=1&b=2"); + assert_eq!(with_query("https://x/tv?x=1#f", Some("?a=1")), "https://x/tv?x=1&a=1#f"); + assert_eq!(with_query("https://x/", None), "https://x/"); + assert_eq!(with_query("https://x/", Some("")), "https://x/"); + } +} diff --git a/crates/sf-ipc/src/lib.rs b/crates/sf-ipc/src/lib.rs index 34a4278..0152e4d 100644 --- a/crates/sf-ipc/src/lib.rs +++ b/crates/sf-ipc/src/lib.rs @@ -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 message; +pub mod paths; +pub mod sandbox; 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 settings::Settings; diff --git a/crates/sf-ipc/src/manifest.rs b/crates/sf-ipc/src/manifest.rs index fe9bf36..7e5d2e5 100644 --- a/crates/sf-ipc/src/manifest.rs +++ b/crates/sf-ipc/src/manifest.rs @@ -1,5 +1,13 @@ //! App manifests: one `app.toml` per folder under the apps directory. +//! +//! Apps come from two places: +//! - factory apps (the image) and official packages (`sf-app-`, signed +//! with the Fennec OS key); +//! - the store: third-party apps from their own GitHub/Gitea/GitLab repos, +//! published in their own repo (docs/store.md). These always run sandboxed and +//! can never replace an official app. +use std::collections::BTreeMap; use std::path::{Path, PathBuf}; use anyhow::{Context, Result}; @@ -18,6 +26,101 @@ pub enum AppKind { 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::ALL.into_iter().find(|p| p.key() == key) + } + + /// Hungarian label for the store screen. + pub fn label(self) -> &'static str { + match self { + Permission::Network => "Internet és helyi hálózat", + Permission::Gpu => "Grafikus gyorsítás", + Permission::Audio => "Hang", + Permission::Gamepad => "Játékvezérlők", + Permission::DbusSession => "Munkamenet D-Bus", + Permission::DbusSystem => "Rendszer D-Bus", + Permission::Devices => "Minden eszköz (/dev)", + } + } + + /// Worth a warning: the app can reach far outside its sandbox. + pub fn risky(self) -> bool { + matches!(self, Permission::DbusSession | Permission::DbusSystem | Permission::Devices) + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SandboxOptions { + /// Run in a bubblewrap sandbox. Only official apps may turn it off + /// (system receivers like AirPlay); store apps are always sandboxed. + /// Unset: on, except for official background services. + #[serde(default)] + pub enabled: Option, + #[serde(default)] + pub permissions: Vec, +} + +impl Default for SandboxOptions { + fn default() -> Self { + SandboxOptions { enabled: None, permissions: Vec::new() } + } +} + #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AppManifest { pub id: String, @@ -59,9 +162,26 @@ pub struct AppManifest { /// launcher tile only opens the details sheet. #[serde(default)] pub service: bool, + #[serde(default)] + pub sandbox: SandboxOptions, + /// Extra environment for the app's process. + #[serde(default)] + pub env: BTreeMap, + /// Legacy store manifest field. Older signed releases may still contain it. + #[serde(default)] + pub public_key: Option, + /// Store apps: source code / home page, shown on the store screen. + #[serde(default)] + pub homepage: Option, + #[serde(default)] + pub author: Option, + #[serde(default)] + pub license: Option, /// Folder the manifest was loaded from (not serialized). #[serde(skip)] pub dir: PathBuf, + #[serde(skip)] + pub origin: Origin, } #[derive(Debug, Clone, Default, Serialize, Deserialize)] @@ -96,6 +216,79 @@ impl AppManifest { pub fn resolved_url(&self, settings: &Settings) -> Option { self.url.as_ref().map(|u| settings.expand(u)) } + + /// The command line with `${app}` replaced by `app_root` (where the app's + /// files are: its folder, or /app inside the sandbox). A relative program + /// path with a slash (`bin/hello`) is inside the app folder too; a bare + /// name (`uxplay`) is looked up in PATH. + pub fn resolved_exec(&self, app_root: &Path) -> Vec { + let root = app_root.to_string_lossy(); + let mut line: Vec = self.exec.iter().flatten().map(|a| a.replace("${app}", &root)).collect(); + if let Some(first) = line.first_mut() { + if first.contains('/') && !first.starts_with('/') { + *first = format!("{}/{}", root.trim_end_matches('/'), first.trim_start_matches("./")); + } + } + line + } + + /// What the app may reach from its sandbox. Web apps always get what a + /// browser needs. + pub fn permissions(&self) -> Vec { + let mut p = self.sandbox.permissions.clone(); + if self.kind == AppKind::Web { + p.extend([Permission::Network, Permission::Gpu, Permission::Audio]); + } + p.sort(); + p.dedup(); + p + } + + /// Store apps always run sandboxed; official ones unless they opt out. + pub fn sandboxed(&self) -> bool { + self.origin == Origin::Store || self.sandbox.enabled.unwrap_or(!self.service) + } + + /// An image file shipped with the app (`icon = "icon.png"`), if `icon` + /// isn't one of the launcher's built-in icon names. + pub fn icon_file(&self) -> Option { + let lower = self.icon.to_ascii_lowercase(); + if ![".png", ".svg", ".jpg", ".jpeg"].iter().any(|ext| lower.ends_with(ext)) { + return None; + } + if self.icon.contains("..") || Path::new(&self.icon).is_absolute() { + return None; + } + let path = self.dir.join(&self.icon); + path.is_file().then_some(path) + } + + /// Rules a store app must follow (checked by sf-update before installing + /// and by the launcher when loading). + pub fn check_store_rules(&self) -> Result<()> { + anyhow::ensure!(is_store_id(&self.id), "store app id {:?} must be a reverse domain name (io.github.user.app)", self.id); + anyhow::ensure!(self.kind != AppKind::Builtin, "store apps can't be built-in"); + anyhow::ensure!(!self.service, "store apps can't be background services"); + anyhow::ensure!(self.dial.is_none(), "store apps can't register for DIAL"); + anyhow::ensure!(self.sandbox.enabled != Some(false), "store apps can't turn off the sandbox"); + match self.kind { + AppKind::Exec => anyhow::ensure!(!self.resolved_exec(Path::new("/app")).is_empty(), "exec is missing"), + AppKind::Web => anyhow::ensure!(self.url.as_deref().is_some_and(|u| u.starts_with("https://")), "web apps need an https:// url"), + AppKind::Builtin => {} + } + Ok(()) + } +} + +/// Store app ids are reverse domain names with at least one dot +/// (`io.github.user.app`). Official app ids never have a dot, so a store app +/// can't take the place of one. +pub fn is_store_id(id: &str) -> bool { + let parts: Vec<&str> = id.split('.').collect(); + id.len() <= 128 + && parts.len() >= 2 + && parts.iter().all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')) + && parts[0].bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit()) } /// Loads every `*/app.toml` under `dir`, sorted by `order` then name. @@ -128,6 +321,12 @@ pub fn load_apps_from(dirs: &[PathBuf]) -> Result> { } found = true; for app in load_apps(dir)? { + // Official ids have no dot; a store app here (developed inside + // the apps folder) belongs to the store, not the factory set. + if is_store_id(&app.id) { + log::info!("skipping {}: a store app id in an official apps folder", app.id); + continue; + } match apps.iter_mut().find(|a| a.id == app.id) { Some(old) if version_cmp(&app.version, &old.version).is_ge() => *old = app, Some(_) => {} @@ -140,16 +339,37 @@ pub fn load_apps_from(dirs: &[PathBuf]) -> Result> { 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> { + 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]) { apps.sort_by(|a, b| a.order.cmp(&b.order).then_with(|| a.name.cmp(&b.name))); } -/// Compares dotted numeric versions ("1.10.0" > "1.9.2"); anything that -/// isn't a number compares as 0. +/// Compares dotted numeric versions ("1.10.0" > "1.9.2"), up to four parts +/// (the Steam launcher is 1.0.0.87); anything that isn't a number compares as 0. pub fn version_cmp(a: &str, b: &str) -> std::cmp::Ordering { - let parts = |v: &str| -> Vec { v.split(['.', '-', '+']).take(3).map(|p| p.parse().unwrap_or(0)).collect() }; + let parts = |v: &str| -> Vec { v.split(['.', '-', '+']).take(4).map(|p| p.parse().unwrap_or(0)).collect() }; let (a, b) = (parts(a), parts(b)); - (0..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 { @@ -174,7 +394,7 @@ mod tests { accent = "#E50914" palette = ["#ff3b3b", "#7a0a10", "#0c0203"] [web] - user_agent_suffix = "SMART-TV SmartFox/0.1" + user_agent_suffix = "SMART-TV FennecOS/0.1" "##, ) .unwrap(); @@ -191,5 +411,49 @@ mod tests { assert_eq!(version_cmp("1.10.0", "1.9.2"), Greater); assert_eq!(version_cmp("0.2", "0.2.0"), Equal); assert_eq!(version_cmp("0.1.9", "0.2.0"), Less); + assert_eq!(version_cmp("1.0.0.87", "1.0.0.9"), Greater); + assert_eq!(version_cmp("1.0.0", "1.0.0.0"), Equal); + } + + #[test] + fn store_ids() { + assert!(is_store_id("io.github.user.app")); + assert!(is_store_id("org.example.My_App-2")); + assert!(!is_store_id("youtube")); + assert!(!is_store_id("IO.github.x")); + assert!(!is_store_id("io..x")); + assert!(!is_store_id("io.x/../y")); + assert!(!is_store_id(".io.x")); + } + + #[test] + fn exec_and_permissions() { + let app: AppManifest = toml::from_str( + r#" + id = "io.github.fox.hello" + name = "Hello" + kind = "exec" + exec = ["bin/hello", "--data", "${app}/share"] + [sandbox] + permissions = ["network", "gamepad"] + "#, + ) + .unwrap(); + assert_eq!(app.resolved_exec(Path::new("/app")), ["/app/bin/hello", "--data", "/app/share"]); + assert_eq!(app.permissions(), [Permission::Network, Permission::Gamepad]); + assert!(app.sandboxed()); + app.check_store_rules().unwrap(); + + let mut bad = app.clone(); + bad.sandbox.enabled = Some(false); + assert!(bad.check_store_rules().is_err()); + bad = app.clone(); + bad.id = "youtube".into(); + assert!(bad.check_store_rules().is_err()); + + let web: AppManifest = toml::from_str("id = 'a'\nname = 'A'\nkind = 'web'\nurl = 'https://x'\n").unwrap(); + assert_eq!(web.permissions(), [Permission::Network, Permission::Gpu, Permission::Audio]); + let path: AppManifest = toml::from_str("id = 'a'\nname = 'A'\nkind = 'exec'\nexec = ['uxplay', '-n']\n").unwrap(); + assert_eq!(path.resolved_exec(Path::new("/x")), ["uxplay", "-n"]); } } diff --git a/crates/sf-ipc/src/message.rs b/crates/sf-ipc/src/message.rs index 504fe87..40246ba 100644 --- a/crates/sf-ipc/src/message.rs +++ b/crates/sf-ipc/src/message.rs @@ -1,23 +1,82 @@ -//! Messages between the launcher and the core daemon (newline-delimited JSON -//! over a unix socket). The core daemon itself comes in phase 3. +//! Messages between the launcher and the core daemon: newline-delimited JSON +//! 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}; -#[derive(Debug, Clone, Serialize, Deserialize)] +#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)] #[serde(tag = "type", rename_all = "snake_case")] pub enum LauncherRequest { - Launch { app_id: String }, - /// Bring the launcher back to the front (freezes the foreground app). + /// Start the app, or bring it back if it waits in the background. + Launch { + app_id: String, + /// Extra query string for the start URL (DIAL uses this). + #[serde(default, skip_serializing_if = "Option::is_none")] + query: Option, + }, + /// Show the launcher. The foreground app is frozen in the background if + /// the compositor can switch windows, otherwise it is closed. 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")] 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, + }, + /// 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 }, /// Something connected over DIAL/AirPlay/Miracast. CastConnected { app_id: String, device: String }, + /// The cast session ended. + CastEnded { app_id: 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 }); + } +} diff --git a/crates/sf-ipc/src/paths.rs b/crates/sf-ipc/src/paths.rs new file mode 100644 index 0000000..139e331 --- /dev/null +++ b/crates/sf-ipc/src/paths.rs @@ -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 `, `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 `). +pub fn wm_socket() -> PathBuf { + from_env("SMARTFOX_WM_SOCKET", "smartfox-wm.sock") +} + +/// The settings file: `$SMARTFOX_SETTINGS`, else `/smartfox/settings.toml`. +pub fn settings_file() -> PathBuf { + if let Ok(p) = std::env::var("SMARTFOX_SETTINGS") { + return p.into(); + } + let base = std::env::var_os("XDG_CONFIG_HOME") + .map(PathBuf::from) + .or_else(|| std::env::var_os("APPDATA").map(PathBuf::from)) + .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config"))) + .unwrap_or_else(|| PathBuf::from(".")); + base.join("smartfox").join("settings.toml") +} + +/// An app's private data folder; its `$HOME` inside the sandbox: +/// `$XDG_DATA_HOME/smartfox/apps/` (default `~/.local/share/...`). +pub fn app_data_dir(id: &str) -> PathBuf { + let base = std::env::var_os("XDG_DATA_HOME") + .map(PathBuf::from) + .or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".local").join("share"))) + .or_else(|| std::env::var_os("LOCALAPPDATA").map(PathBuf::from)) + .unwrap_or_else(|| PathBuf::from(".")); + base.join("smartfox").join("apps").join(id) +} + +/// Installed store apps (`/var/lib/sf-pkg/store/apps/`), written by sf-update. +pub const STORE_APPS: &str = "/var/lib/sf-pkg/store/apps"; + +/// 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") +} diff --git a/crates/sf-ipc/src/sandbox.rs b/crates/sf-ipc/src/sandbox.rs new file mode 100644 index 0000000..f1035cf --- /dev/null +++ b/crates/sf-ipc/src/sandbox.rs @@ -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/`), the only writable place that lasts; +//! - the Wayland socket (it can show a window), nothing else from +//! `$XDG_RUNTIME_DIR` (no launcher, sf-core or compositor sockets); +//! - fresh /tmp, /run, /var and its own PID, IPC and UTS namespaces; +//! - and only what its permissions allow (`Permission`): network, GPU, +//! sound, game controllers, D-Bus, devices. + +use std::path::{Path, PathBuf}; +use std::process::Command; + +use crate::manifest::Permission; + +/// Where the app's own files are inside the sandbox. +pub const APP_DIR: &str = "/app"; + +/// Environment variables passed through from the session when set. +const PASS_ENV: [&str; 7] = ["LANG", "LANGUAGE", "LC_ALL", "TZ", "XCURSOR_THEME", "XCURSOR_SIZE", "RUST_LOG"]; + +/// What a host path is, for building the mount list (a function so tests +/// can fake the file system). +#[derive(Debug, Clone, PartialEq, Eq)] +pub enum Entry { + Missing, + Dir, + Other, + Symlink(PathBuf), + /// There, but we may not read it (bwrap's `--*-bind-try` fails on that). + Denied, +} + +pub fn probe(path: &Path) -> Entry { + if let Err(e) = std::fs::metadata(path) { + if e.kind() == std::io::ErrorKind::PermissionDenied { + return Entry::Denied; + } + } + match std::fs::symlink_metadata(path) { + Err(_) => Entry::Missing, + Ok(m) if m.file_type().is_symlink() => std::fs::read_link(path).map(Entry::Symlink).unwrap_or(Entry::Missing), + Ok(m) if m.is_dir() => Entry::Dir, + Ok(_) => Entry::Other, + } +} + +/// The session the app is started from. +#[derive(Debug, Clone)] +pub struct Host { + pub uid: u32, + pub user: String, + pub home: PathBuf, + pub runtime_dir: PathBuf, + pub wayland_display: Option, + pub hostname: Option, + /// Allowed variables from the session (`PASS_ENV`). + pub env: Vec<(String, String)>, + /// /dev/hidraw* (controllers that talk raw HID, like DualSense). + pub hidraw: Vec, +} + +impl Host { + pub fn current() -> Host { + let var = |k: &str| std::env::var(k).ok().filter(|v| !v.is_empty()); + let home = var("HOME").map(PathBuf::from).unwrap_or_else(|| PathBuf::from("/tmp")); + let hidraw = std::fs::read_dir("/dev") + .map(|d| d.flatten().map(|e| e.path()).filter(|p| p.file_name().is_some_and(|n| n.to_string_lossy().starts_with("hidraw"))).collect()) + .unwrap_or_default(); + Host { + uid: current_uid(), + user: var("USER").unwrap_or_else(|| "tv".into()), + home, + runtime_dir: crate::paths::runtime_dir(), + wayland_display: var("WAYLAND_DISPLAY"), + hostname: std::fs::read_to_string("/etc/hostname").ok().map(|h| h.trim().to_string()).filter(|h| !h.is_empty()), + env: PASS_ENV.iter().filter_map(|k| var(k).map(|v| (k.to_string(), v))).collect(), + hidraw, + } + } +} + +#[cfg(unix)] +fn current_uid() -> u32 { + use std::os::unix::fs::MetadataExt; + // The owner of our own /proc entry is our uid (no libc needed). + std::fs::metadata("/proc/self").map(|m| m.uid()).unwrap_or(1000) +} + +#[cfg(not(unix))] +fn current_uid() -> u32 { + 1000 +} + +/// One sandboxed process. +#[derive(Debug, Clone)] +pub struct Spec<'a> { + pub app_id: &'a str, + /// The app's files (host path), read-only at `/app`. + pub app_dir: &'a Path, + /// The app's private data (host path), mounted as `$HOME`. + pub data_dir: &'a Path, + /// More writable folders, at the same path inside (a browser profile). + pub extra_rw: Vec, + pub permissions: &'a [Permission], + /// Extra environment for the app. + pub env: Vec<(String, String)>, + pub program: String, + pub args: Vec, +} + +pub fn bwrap_path() -> Option { + if let Ok(p) = std::env::var("SMARTFOX_BWRAP") { + return Some(p.into()); + } + ["/usr/bin/bwrap", "/usr/local/bin/bwrap"].iter().map(PathBuf::from).find(|p| p.is_file()) +} + +/// The bwrap command for `spec`. +pub fn command(bwrap: &Path, spec: &Spec, host: &Host) -> Command { + let mut cmd = Command::new(bwrap); + cmd.args(args(spec, host, &probe)); + cmd +} + +/// The bwrap arguments. Mount order matters: later mounts go on top. +pub fn args(spec: &Spec, host: &Host, fs: &dyn Fn(&Path) -> Entry) -> Vec { + let has = |p: Permission| spec.permissions.contains(&p); + let mut a: Vec = Vec::new(); + let mut push = |items: &[&str]| a.extend(items.iter().map(|s| s.to_string())); + + push(&["--die-with-parent", "--unshare-all"]); + if has(Permission::Network) { + push(&["--share-net"]); + } + if host.uid == 0 { + // Unprivileged bwrap drops every capability by itself; as root + // (development) do it explicitly. + push(&["--cap-drop", "ALL"]); + } + if let Some(h) = &host.hostname { + push(&["--hostname", h]); + } + + // The system, read-only. /bin, /lib... are symlinks into /usr on Debian. + push(&["--ro-bind", "/usr", "/usr"]); + for top in ["/bin", "/sbin", "/lib", "/lib32", "/lib64", "/libx32"] { + match fs(Path::new(top)) { + Entry::Symlink(t) => push(&["--symlink", &t.to_string_lossy(), top]), + Entry::Dir => push(&["--ro-bind", top, top]), + _ => {} + } + } + push(&["--ro-bind", "/etc", "/etc", "--proc", "/proc"]); + + // Devices. + if has(Permission::Devices) { + push(&["--dev-bind", "/dev", "/dev"]); + } else { + push(&["--dev", "/dev", "--tmpfs", "/dev/shm"]); + if has(Permission::Gpu) { + push(&["--dev-bind-try", "/dev/dri", "/dev/dri"]); + } + if has(Permission::Gamepad) { + push(&["--dev-bind-try", "/dev/input", "/dev/input", "--dev-bind-try", "/dev/uinput", "/dev/uinput"]); + for h in &host.hidraw { + let h = h.to_string_lossy(); + push(&["--dev-bind-try", &h, &h]); + } + } + } + if has(Permission::Gpu) || has(Permission::Gamepad) || has(Permission::Devices) { + push(&["--ro-bind", "/sys", "/sys"]); + } + + // Fresh writable scratch space. + push(&["--tmpfs", "/tmp", "--tmpfs", "/var", "--tmpfs", "/run", "--dir", "/var/tmp", "--symlink", "../run", "/var/run"]); + push(&["--ro-bind-try", "/var/cache/fontconfig", "/var/cache/fontconfig"]); + if has(Permission::Gamepad) || has(Permission::Devices) { + // Hotplug of controllers (SDL, Steam) goes through udev. + push(&["--ro-bind-try", "/run/udev", "/run/udev"]); + } + if has(Permission::Network) { + // /etc/resolv.conf points at systemd-resolved's stub file on the TV; + // elsewhere (WSL: /mnt/wsl/resolv.conf) bind whatever it points at. + push(&["--ro-bind-try", "/run/systemd/resolve", "/run/systemd/resolve"]); + if let Entry::Symlink(t) = fs(Path::new("/etc/resolv.conf")) { + let target = Path::new("/etc").join(t); + let target = target.to_string_lossy(); + if !target.starts_with("/run/systemd/resolve/") && !target.starts_with("/etc/") && !target.starts_with("/usr/") { + push(&["--ro-bind-try", &target, &target]); + } + } + } + if has(Permission::DbusSystem) { + push(&["--ro-bind-try", "/run/dbus/system_bus_socket", "/run/dbus/system_bus_socket"]); + } + + // The session's runtime dir: only the sockets the app may use. + let rt = host.runtime_dir.to_string_lossy().to_string(); + push(&["--perms", "0700", "--dir", &rt]); + let mut socket = |name: &str| { + let p = format!("{rt}/{name}"); + if fs(Path::new(&p)) != Entry::Denied { + push(&["--ro-bind-try", &p, &p]); + } + }; + if let Some(wl) = &host.wayland_display { + socket(wl); + } + if has(Permission::Audio) { + socket("pipewire-0"); + socket("pulse/native"); + } + if has(Permission::DbusSession) { + socket("bus"); + } + + // $HOME is the app's own data folder (at the real home path, so programs + // that remember absolute paths keep working). + let home = host.home.to_string_lossy().to_string(); + if let Entry::Symlink(t) = fs(Path::new("/home")) { + push(&["--symlink", &t.to_string_lossy(), "/home"]); + } + push(&["--bind", &spec.data_dir.to_string_lossy(), &home]); + for p in &spec.extra_rw { + let p = p.to_string_lossy(); + push(&["--bind", &p, &p]); + } + push(&["--ro-bind", &spec.app_dir.to_string_lossy(), APP_DIR, "--chdir", &home]); + + // A clean environment. + push(&["--clearenv"]); + let mut env: Vec<(String, String)> = vec![ + ("PATH".into(), "/usr/local/bin:/usr/bin:/bin:/usr/games".into()), + ("HOME".into(), home.clone()), + ("USER".into(), host.user.clone()), + ("LOGNAME".into(), host.user.clone()), + ("SHELL".into(), "/bin/sh".into()), + ("XDG_RUNTIME_DIR".into(), rt.clone()), + ("XDG_SESSION_TYPE".into(), "wayland".into()), + ("SMARTFOX_APP".into(), spec.app_id.into()), + ("SMARTFOX_APP_DIR".into(), APP_DIR.into()), + ]; + if let Some(wl) = &host.wayland_display { + env.push(("WAYLAND_DISPLAY".into(), wl.clone())); + } + if has(Permission::DbusSession) { + env.push(("DBUS_SESSION_BUS_ADDRESS".into(), format!("unix:path={rt}/bus"))); + } + env.extend(host.env.iter().cloned()); + env.extend(spec.env.iter().cloned()); + for (k, v) in env { + push(&["--setenv", &k, &v]); + } + + push(&["--", &spec.program]); + a.extend(spec.args.iter().cloned()); + a +} + +#[cfg(test)] +mod tests { + use super::*; + + fn host() -> Host { + Host { + uid: 1000, + user: "tv".into(), + home: "/var/home/tv".into(), + runtime_dir: "/run/user/1000".into(), + wayland_display: Some("wayland-1".into()), + hostname: Some("smartfox".into()), + env: vec![("LANG".into(), "C.UTF-8".into())], + hidraw: vec!["/dev/hidraw0".into()], + } + } + + fn fake_fs(p: &Path) -> Entry { + match p.to_str().unwrap() { + "/bin" => Entry::Symlink("usr/bin".into()), + "/lib" => Entry::Symlink("usr/lib".into()), + "/lib64" => Entry::Symlink("usr/lib64".into()), + "/home" => Entry::Symlink("var/home".into()), + _ => Entry::Missing, + } + } + + fn has_seq(args: &[String], seq: &[&str]) -> bool { + args.windows(seq.len()).any(|w| w.iter().zip(seq).all(|(a, b)| a == b)) + } + + #[test] + fn minimal_sandbox() { + let spec = Spec { + app_id: "io.github.fox.hello", + app_dir: Path::new("/var/lib/sf-pkg/store-io.github.fox.hello/1.0.0"), + data_dir: Path::new("/var/home/tv/.local/share/smartfox/apps/io.github.fox.hello"), + extra_rw: vec![], + permissions: &[], + env: vec![("FOO".into(), "bar".into())], + program: "/app/bin/hello".into(), + args: vec!["--x".into()], + }; + let a = args(&spec, &host(), &fake_fs); + assert!(has_seq(&a, &["--unshare-all"])); + assert!(!a.contains(&"--share-net".to_string())); + assert!(!a.iter().any(|s| s == "/dev/dri" || s == "/sys")); + assert!(!a.iter().any(|s| s.contains("pipewire") || s.ends_with("/bus"))); + assert!(has_seq(&a, &["--symlink", "usr/bin", "/bin"])); + assert!(has_seq(&a, &["--ro-bind-try", "/run/user/1000/wayland-1", "/run/user/1000/wayland-1"])); + assert!(has_seq(&a, &["--bind", "/var/home/tv/.local/share/smartfox/apps/io.github.fox.hello", "/var/home/tv"])); + assert!(has_seq(&a, &["--ro-bind", "/var/lib/sf-pkg/store-io.github.fox.hello/1.0.0", "/app"])); + assert!(has_seq(&a, &["--setenv", "SMARTFOX_APP", "io.github.fox.hello"])); + assert!(has_seq(&a, &["--setenv", "FOO", "bar"])); + assert!(has_seq(&a, &["--", "/app/bin/hello", "--x"])); + assert_eq!(a.last().unwrap(), "--x"); + // /run must be fresh before the runtime dir and sockets go in. + let run = a.iter().position(|s| s == "/run").unwrap(); + let sock = a.iter().position(|s| s == "/run/user/1000/wayland-1").unwrap(); + assert!(run < sock); + } + + #[test] + fn permissions_open_doors() { + let perms = [Permission::Network, Permission::Gpu, Permission::Audio, Permission::Gamepad, Permission::DbusSession]; + let spec = Spec { + app_id: "steam", + app_dir: Path::new("/usr/share/smartfox/apps/steam"), + data_dir: Path::new("/d"), + extra_rw: vec!["/var/home/tv/.config/smartfox/profiles/steam".into()], + permissions: &perms, + env: vec![], + program: "/app/x".into(), + args: vec![], + }; + let a = args(&spec, &host(), &fake_fs); + assert!(a.contains(&"--share-net".to_string())); + assert!(has_seq(&a, &["--dev-bind-try", "/dev/dri", "/dev/dri"])); + assert!(has_seq(&a, &["--dev-bind-try", "/dev/hidraw0", "/dev/hidraw0"])); + assert!(has_seq(&a, &["--ro-bind", "/sys", "/sys"])); + assert!(has_seq(&a, &["--ro-bind-try", "/run/user/1000/pipewire-0", "/run/user/1000/pipewire-0"])); + assert!(has_seq(&a, &["--setenv", "DBUS_SESSION_BUS_ADDRESS", "unix:path=/run/user/1000/bus"])); + assert!(has_seq(&a, &["--bind", "/var/home/tv/.config/smartfox/profiles/steam", "/var/home/tv/.config/smartfox/profiles/steam"])); + } +} diff --git a/crates/sf-ipc/src/store.rs b/crates/sf-ipc/src/store.rs new file mode 100644 index 0000000..c509306 --- /dev/null +++ b/crates/sf-ipc/src/store.rs @@ -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/ 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, + /// Installed (or to be installed) apps by id. + #[serde(default)] + pub apps: BTreeMap, +} + +#[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, +} + +impl Wanted { + pub fn parse(text: &str) -> Result { + toml::from_str(text).context("store.toml") + } + + pub fn load(path: &Path) -> Result { + 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, +} + +#[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, + #[serde(default)] + pub apps: Vec, +} + +#[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, +} + +#[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, + /// The app's repo (canonical https URL). + pub source: String, + /// The catalog it was listed in, if any. + #[serde(default)] + pub catalog: Option, + pub package_url: String, + /// Installed version, if any. + #[serde(default)] + pub installed: Option, + /// Why the newest version isn't installed: "permissions" (asks for more + /// than approved). + #[serde(default)] + pub blocked: Option, +} + +impl Catalog { + pub fn load(path: &Path) -> Option { + 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 { + 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]); + } +} diff --git a/crates/sf-launcher/Cargo.toml b/crates/sf-launcher/Cargo.toml index baaa05e..afc4b02 100644 --- a/crates/sf-launcher/Cargo.toml +++ b/crates/sf-launcher/Cargo.toml @@ -1,6 +1,6 @@ [package] 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 edition.workspace = true # Slint is used under GPL-3.0 (or its royalty-free license on desktop). @@ -8,11 +8,14 @@ license = "GPL-3.0-only" [dependencies] sf-ipc.workspace = true +sf-ui = { path = "../sf-ui", default-features = false } anyhow.workspace = true log.workspace = true env_logger.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" png = "0.18" chrono = { version = "0.4", default-features = false, features = ["clock", "std"] } diff --git a/crates/sf-launcher/build.rs b/crates/sf-launcher/build.rs index 29ee3db..96950f3 100644 --- a/crates/sf-launcher/build.rs +++ b/crates/sf-launcher/build.rs @@ -1,3 +1,7 @@ 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"); } diff --git a/crates/sf-launcher/src/core_client.rs b/crates/sf-launcher/src/core_client.rs new file mode 100644 index 0000000..50f662f --- /dev/null +++ b/crates/sf-launcher/src/core_client.rs @@ -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>, +} + +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 { + 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::(&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 { + 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; + } +} diff --git a/crates/sf-launcher/src/devshot.rs b/crates/sf-launcher/src/devshot.rs index 3a2ad2a..0946f24 100644 --- a/crates/sf-launcher/src/devshot.rs +++ b/crates/sf-launcher/src/devshot.rs @@ -17,7 +17,7 @@ use slint::ComponentHandle; use slint::platform::{Key, WindowEvent}; use crate::App; -use crate::glass::GlassRenderer; +use sf_ui::render::GlassRenderer; pub struct Snapshot { path: Option, diff --git a/crates/sf-launcher/src/glass/mod.rs b/crates/sf-launcher/src/glass/mod.rs deleted file mode 100644 index 0f9e6ac..0000000 --- a/crates/sf-launcher/src/glass/mod.rs +++ /dev/null @@ -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, -} diff --git a/crates/sf-launcher/src/ipc.rs b/crates/sf-launcher/src/ipc.rs index f16240f..4aaccba 100644 --- a/crates/sf-launcher/src/ipc.rs +++ b/crates/sf-launcher/src/ipc.rs @@ -1,5 +1,5 @@ #![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. //! Protocol: one command per line: //! `home` bring the launcher to the front diff --git a/crates/sf-launcher/src/keyboard.rs b/crates/sf-launcher/src/keyboard.rs index 6a4d58f..6073929 100644 --- a/crates/sf-launcher/src/keyboard.rs +++ b/crates/sf-launcher/src/keyboard.rs @@ -8,7 +8,7 @@ use std::cell::RefCell; use slint::ComponentHandle; use crate::App; -use crate::glass::Panel; +use sf_ui::render::Panel; pub struct Request { pub title: String, diff --git a/crates/sf-launcher/src/main.rs b/crates/sf-launcher/src/main.rs index 1dd1ca6..306b557 100644 --- a/crates/sf-launcher/src/main.rs +++ b/crates/sf-launcher/src/main.rs @@ -1,27 +1,30 @@ -//! SmartFox launcher. +//! Fennec OS launcher. //! -//! Slint draws text and icons; the `glass` module draws the animated backdrop -//! and frosted glass panels underneath via a rendering notifier. +//! Slint draws text and icons; sf-ui's glass renderer draws the animated +//! backdrop and frosted glass panels underneath via a rendering notifier. -mod glass; +mod core_client; mod ipc; mod devshot; mod keyboard; mod power; mod runtime; mod settings_screen; +mod shelf; +mod status; +mod store_screen; mod system; #[cfg(windows)] mod winfade; -use std::cell::RefCell; +use std::cell::{Cell, RefCell}; use std::path::{Path, PathBuf}; use std::rc::Rc; use std::time::{Duration, Instant}; use anyhow::{Context, Result}; use chrono::{Datelike, Local, Timelike}; -use glass::{Frame, GlassRenderer, Panel}; +use sf_ui::render::{Frame, GlassRenderer, Panel}; use sf_ipc::{AppKind, AppManifest, Settings}; use slint::{ComponentHandle, Model, ModelRc, SharedString, VecModel}; @@ -33,18 +36,22 @@ const CROSSFADE: f32 = 0.35; struct Options { /// Factory apps, then installed app packages (`--apps` may repeat). apps_dirs: Vec, + /// Installed store apps (sandboxed; docs/store.md). + store_dir: Option, settings_path: PathBuf, fullscreen: bool, } fn parse_args() -> Options { let mut apps_dirs = Vec::new(); + let mut store_dir = None; let mut settings_path = None; let mut fullscreen = false; let mut args = std::env::args().skip(1); while let Some(a) = args.next() { match a.as_str() { "--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), "--fullscreen" | "-f" => fullscreen = true, other => log::warn!("unknown argument {other}"), @@ -56,6 +63,7 @@ fn parse_args() -> Options { } else { apps_dirs }, + store_dir, settings_path: settings_path.unwrap_or_else(default_settings_path), fullscreen, } @@ -114,12 +122,20 @@ fn palette_of(app: &AppManifest) -> [f32; 9] { 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 { - AppKind::Web => ("web", "Webes alkalmazás (Chromium)", app.resolved_url(settings).unwrap_or_default()), - AppKind::Exec => ("exec", "Natív alkalmazás", app.exec.clone().unwrap_or_default().join(" ")), - AppKind::Builtin => ("builtin", "Beépített", String::new()), + _ if app.service && services => ("service", "Mindig fut a háttérben", app.exec.clone().unwrap_or_default().join(" ")), + AppKind::Web => ("web", "Webes alkalmazás", app.resolved_url(settings).unwrap_or_default()), + 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 { id: app.id.clone().into(), name: app.name.clone().into(), @@ -130,9 +146,132 @@ fn entry_of(app: &AppManifest, settings: &Settings) -> AppEntry { kind: kind.into(), kind_label: kind_label.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 = 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 { + 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| { + 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 = 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. struct Backdrop { palette: [f32; 9], @@ -175,6 +314,7 @@ fn card_rects(ui: &App, scale: f32, accents: &[[f32; 3]]) -> Vec { 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 scroll = ui.get_grid_scroll(); + let shelf = ui.get_shelf_t(); let menu_t = ui.get_menu_t().clamp(0.0, 1.0); 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(); @@ -184,6 +324,8 @@ fn card_rects(ui: &App, scale: f32, accents: &[[f32; 3]]) -> Vec { 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 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 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; @@ -222,7 +364,8 @@ fn card_rects(ui: &App, scale: f32, accents: &[[f32; 3]]) -> Vec { } 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) { let now = Local::now(); @@ -296,6 +439,73 @@ fn show_toast(ui: &App, text: impl Into, timer: &slint::Timer) { }); } +thread_local! { + /// The app sf-core shows in the foreground, as far as the UI knows. + static CORE_APP: RefCell> = 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<()> { env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init(); 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 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); system::confirm_shell_trial(); let ui = App::new()?; - let entries: Vec = apps.iter().map(|a| entry_of(a, &settings)).collect(); + let entries: Vec = apps.iter().map(|a| entry_of(a, &settings, true)).collect(); ui.set_apps(ModelRc::new(VecModel::from(entries))); 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); power::configure_from(&settings); 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 running: Rc>> = 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 = 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 apps = apps.clone(); @@ -360,20 +606,27 @@ fn main() -> Result<()> { let running = running.clone(); let data_dir = data_dir.clone(); let fullscreen = opts.fullscreen; + let core = core.clone(); ui.on_launch(move |index| { let Some(ui) = weak.upgrade() 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() { runtime::stop(&mut old); } - ui.set_launch_detail("indítása…".into()); - ui.set_app_ready(false); let pos = ui.window().position(); let size = ui.window().size(); - let opts = runtime::LaunchOptions { + let opts = sf_ipc::launch::LaunchOptions { data_dir: &data_dir, fullscreen, bounds: Some((pos.x, pos.y, size.width, size.height)), + query: None, }; match runtime::launch(app, &settings, &opts) { Ok(child) => { @@ -382,7 +635,7 @@ fn main() -> Result<()> { { // Keep the window hidden until the morph finishes and the page loads. 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 || { let _ = weak.upgrade_in_event_loop(|ui| ui.set_app_ready(true)); }); @@ -399,22 +652,38 @@ fn main() -> Result<()> { } { let running = running.clone(); + let core = core.clone(); 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() { log::info!("closing {name}"); 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 core = core.clone(); ipc::listen(move |cmd| { let Some(ui) = weak.upgrade() else { return }; match cmd { ipc::Command::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_app_ready(false); ui.set_sheet_open(false); @@ -527,10 +796,13 @@ fn main() -> Result<()> { scale, time, palette: bd.palette, - shelf: ui.get_shelf_t(), + brightness: ui.get_shelf_t(), light: [angle.cos(), angle.sin()], zoom: 1.0 + 0.35 * ui.get_launch_t() * ui.get_launch_t(), + images: &[], + video: None, rects, + quality: Default::default(), }; drop(bd); // SAFETY: called on the UI thread with the Slint GL context current. diff --git a/crates/sf-launcher/src/runtime.rs b/crates/sf-launcher/src/runtime.rs index 1b0f320..079a589 100644 --- a/crates/sf-launcher/src/runtime.rs +++ b/crates/sf-launcher/src/runtime.rs @@ -1,178 +1,24 @@ -//! Starts apps. Web apps run in a Chromium-family browser in app/kiosk mode -//! with a per-app profile; exec apps are spawned directly. -//! -//! This lives in the launcher for local testing; on the TV it moves into the -//! sf-core daemon (systemd scopes, freeze/thaw). +//! Starts apps locally, when no sf-core is running (desktop testing). The +//! command line comes from `sf_ipc::launch`; on the TV sf-core does this. -use std::path::{Path, PathBuf}; -use std::process::{Child, Command}; +use std::process::Child; -use anyhow::{Context, Result, bail}; -use sf_ipc::{AppKind, 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 { - let mut candidates: Vec = Vec::new(); - if let Ok(p) = std::env::var("SMARTFOX_BROWSER") { - candidates.push(p.into()); - } - #[cfg(windows)] - { - for base in ["ProgramFiles", "ProgramFiles(x86)", "LOCALAPPDATA"] { - if let Some(b) = std::env::var_os(base) { - let b = PathBuf::from(b); - candidates.push(b.join(r"Google\Chrome\Application\chrome.exe")); - candidates.push(b.join(r"Chromium\Application\chrome.exe")); - candidates.push(b.join(r"Microsoft\Edge\Application\msedge.exe")); - } - } - } - #[cfg(not(windows))] - { - for name in ["chromium", "chromium-browser", "google-chrome-stable", "google-chrome"] { - for dir in ["/usr/bin", "/usr/local/bin", "/snap/bin"] { - candidates.push(Path::new(dir).join(name)); - } - } - } - let exe = candidates.into_iter().find(|p| p.is_file())?; - let version = browser_version(&exe).unwrap_or_else(|| "141.0.0.0".into()); - Some(Browser { exe, version }) -} - -fn browser_version(exe: &Path) -> Option { - // Windows installs keep a folder named after the version next to the exe. - if cfg!(windows) { - let dir = exe.parent()?; - let mut versions: Vec = std::fs::read_dir(dir) - .ok()? - .flatten() - .filter_map(|e| e.file_name().into_string().ok()) - .filter(|n| n.split('.').count() == 4 && n.split('.').all(|p| p.parse::().is_ok())) - .collect(); - versions.sort_by_key(|v| v.split('.').map(|p| p.parse::().unwrap_or(0)).collect::>()); - return versions.pop(); - } - let out = Command::new(exe).arg("--version").output().ok()?; - String::from_utf8_lossy(&out.stdout) - .split_whitespace() - .find(|w| w.chars().next().is_some_and(|c| c.is_ascii_digit()) && w.contains('.')) - .map(str::to_string) -} - -fn default_user_agent(version: &str) -> String { - let platform = if cfg!(windows) { "Windows NT 10.0; Win64; x64" } else { "X11; Linux x86_64" }; - let major = version.split('.').next().unwrap_or("141"); - format!("Mozilla/5.0 ({platform}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{major}.0.0.0 Safari/537.36") -} - -pub struct LaunchOptions<'a> { - 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)>, -} +use anyhow::{Context, Result}; +use sf_ipc::launch::{LaunchOptions, command}; +use sf_ipc::{AppManifest, Settings}; pub fn launch(app: &AppManifest, settings: &Settings, opts: &LaunchOptions) -> Result { - match app.kind { - AppKind::Web => launch_web(app, settings, opts), - AppKind::Exec => { - 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 { - 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::>()); - cmd.spawn().with_context(|| format!("starting {}", browser.exe.display())) + let mut cmd = command(app, settings, opts)?; + log::info!("{} {:?}", cmd.get_program().to_string_lossy(), cmd.get_args().collect::>()); + cmd.spawn().with_context(|| format!("starting {}", cmd.get_program().to_string_lossy())) } /// Stops an app and everything it started. pub fn stop(child: &mut Child) { #[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(); for _ in 0..20 { if matches!(child.try_wait(), Ok(Some(_))) { diff --git a/crates/sf-launcher/src/settings_screen.rs b/crates/sf-launcher/src/settings_screen.rs index 17e413c..3567f18 100644 --- a/crates/sf-launcher/src/settings_screen.rs +++ b/crates/sf-launcher/src/settings_screen.rs @@ -10,7 +10,7 @@ use std::time::{Duration, Instant}; 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::{App, SettingRow, keyboard}; @@ -19,9 +19,10 @@ const KEEP_SECS: u64 = 15; const DISPLAY: i32 = 0; const DEVICES: i32 = 1; -const NETWORK: i32 = 2; -const ENERGY: i32 = 3; -const SYSTEM: i32 = 4; +const AUDIO: i32 = 2; +const NETWORK: i32 = 3; +const ENERGY: i32 = 4; +const SYSTEM: i32 = 5; #[derive(Clone, PartialEq)] enum Action { @@ -42,6 +43,9 @@ enum Action { Back, PairRemote, ReplaceRemote, + AudioOutput(String), + BtAudioScan, + BtAudioConnect(String), Restart, ConfirmRestart, RemoteDebug, @@ -82,6 +86,10 @@ struct Pending { enum Loaded { Display(Result), Devices(Result, String>), + Audio(Result, String>), + BtAudio(Result, String>), + AudioDone(Result), + BtAudioScanDone(Result, String>), Net(NetInfo), Wifi(Result, String>), /// A Wi-Fi action finished: notice text, or the error. `retry` reopens the @@ -105,6 +113,8 @@ struct State { parent_row: i32, display: Option>, devices: Option, String>>, + audio: Option, String>>, + bt_audio: Option, String>>, net: Option, /// Ok(None) = no Wi-Fi adapter. wifi: Option, String>>, @@ -187,6 +197,8 @@ impl Screen { parent_row: 0, display: None, devices: None, + audio: None, + bt_audio: None, net: None, wifi: None, wifi_pending: None, @@ -205,13 +217,27 @@ impl Screen { SCREEN.with(|s| *s.borrow_mut() = Some(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 || { + if store_mode(&s) { + if let Some(store) = crate::store_screen::current() { + store.opened(); + } + return; + } s.state.borrow_mut().notice.clear(); s.refresh_all(); s.rebuild(None); }); let s = screen.clone(); 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(); st.category = i; @@ -226,9 +252,15 @@ impl Screen { s.rebuild(Some(0)); }); 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(); - 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. let s = Rc::downgrade(&screen); @@ -255,12 +287,14 @@ impl Screen { } 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) { post(|| Loaded::Display(system::display().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::Wifi(wifi_result(system::wifi()))); post(|| Loaded::RemoteDebug(system::remote_debug())); @@ -292,6 +326,10 @@ impl Screen { } match category { 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 => { post(|| Loaded::Net(system::network())); post(|| Loaded::Wifi(wifi_result(system::wifi()))); @@ -382,6 +420,30 @@ impl Screen { match loaded { Loaded::Display(d) => self.state.borrow_mut().display = 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::Wifi(w) => { if let Err(e) = &w { @@ -681,6 +743,33 @@ impl Screen { 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::ConfirmRestart => { log::info!("restarting the launcher (settings)"); @@ -776,6 +865,10 @@ impl Screen { /// Pushes the current page to Slint. `row` moves the focus (clamped). fn rebuild(&self, row: Option) { 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 len = rows.len() as i32; 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."), ) } + (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) => { match &st.net { None => push(row("Hálózat lekérdezése…", "", "", "info"), Action::None), Some(n) => { let conn = match (&n.iface, n.ip.is_some(), n.wireless) { - (Some(i), true, true) => format!("Wi-Fi · {i}"), - (Some(i), true, false) => format!("Vezetékes · {i}"), + (Some(_), true, true) => "Wi-Fi".to_string(), + (Some(_), true, false) => "Vezetékes".to_string(), _ => "Nincs kapcsolat".to_string(), }; push(row("Kapcsolat", conn, "", "info"), Action::None); @@ -1002,7 +1121,8 @@ impl Screen { (false, true) => "Be", (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.networks.is_empty() { 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, _) => { let info = st.info.clone().unwrap_or_default(); 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("Kernel", info.kernel, "", "info"), Action::None); 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. -pub fn glass(ui: &App, scale: f32) -> Vec { - use crate::glass::Panel; +pub fn glass(ui: &App, scale: f32) -> Vec { + use sf_ui::render::Panel; use slint::Model; let t = ui.get_set_t(); @@ -1120,51 +1240,63 @@ pub fn glass(ui: &App, scale: f32) -> Vec { tint, }; 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()); - 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. + // The on-screen keyboard takes over the screen: categories and rows fade out. 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 (nav_pos, nav_active) = (ui.get_nav_pos(), ui.get_nav_active()); for i in 0..ui.get_set_nav_count() { let sel = (1.0 - (nav_pos - i as f32).abs()).max(0.0); 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 (w, h) = (nw * s, nh * s); 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 (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()); - 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 over = (ry - top).max(top + rh - (ry + view)) / rh; 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; } - let f = (1.0 - (row_pos - j as f32).abs()).max(0.0) * active; - let s = 1.0 + 0.02 * f; - let (w, h) = (rw * s, rh * s); + let (x0, w0) = (rx + inset, rw - 2.0 * inset); + let s = 1.0 + 0.015 * f; + let (w, h) = (w0 * s, rh * s); let (glow, tint) = if row.kind == "danger" { - let red = [1.0, 0.27, 0.23]; - (red, [1.0, 0.27, 0.23, 0.10 + 0.72 * f]) + ([1.0, 0.27, 0.23], [1.0, 0.27, 0.23, 0.86 * f]) } 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 } -/// 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) { let checked = || { use chrono::TimeZone; diff --git a/crates/sf-launcher/src/shelf.rs b/crates/sf-launcher/src/shelf.rs new file mode 100644 index 0000000..ae51614 --- /dev/null +++ b/crates/sf-launcher/src/shelf.rs @@ -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 `/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, + /// 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, +} + +pub struct Source { + /// Netflex server base URL ("https://netflex.example"). + pub server: Option, + pub token: Option, + /// `/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::(&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 { + 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, + year_label: Option, +} + +#[derive(Deserialize)] +struct Continue { + title: Title, + season: Option, + episode: Option, + position: Option, + duration: Option, +} + +#[derive(Deserialize)] +struct Row { + title: String, + items: Vec, +} + +#[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)); + } +} diff --git a/crates/sf-launcher/src/status.rs b/crates/sf-launcher/src/status.rs new file mode 100644 index 0000000..8efb585 --- /dev/null +++ b/crates/sf-launcher/src/status.rs @@ -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}"); + } +} diff --git a/crates/sf-launcher/src/store_screen.rs b/crates/sf-launcher/src/store_screen.rs new file mode 100644 index 0000000..35cbaaa --- /dev/null +++ b/crates/sf-launcher/src/store_screen.rs @@ -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(¬ice, |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")); + } +} diff --git a/crates/sf-launcher/src/system.rs b/crates/sf-launcher/src/system.rs index e75e014..c6fa358 100644 --- a/crates/sf-launcher/src/system.rs +++ b/crates/sf-launcher/src/system.rs @@ -439,6 +439,142 @@ pub fn bt_remove(addr: &str) -> Result<()> { 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 ------------------------------------------------- #[derive(Debug, Clone, Default)] @@ -877,7 +1013,7 @@ pub struct UpdateStatus { #[derive(Debug, Clone, Default)] pub struct UpdatePackage { - /// Display name ("SmartFox felület", "YouTube"). + /// Display name ("Fennec OS felület", "YouTube"). pub title: String, pub installed: 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 { 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")]; - sf_ipc::manifest::load_apps_from(&dirs) + sf_ipc::manifest::load_all(&dirs, Some(Path::new(sf_ipc::paths::STORE_APPS))) .ok() .and_then(|apps| apps.into_iter().find(|a| a.id == id).map(|a| a.name)) .unwrap_or_else(|| id.to_string()) @@ -930,8 +1066,8 @@ pub fn update_status() -> Option<UpdateStatus> { staged: None, }; 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")], - _ => vec![pkg("SmartFox felület", "0.2.0", "0.2.0"), pkg("YouTube", "1.1.0", "1.1.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("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 }); } @@ -1021,6 +1157,16 @@ mod tests { 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] fn parses_iwd_objects() { let objects: serde_json::Value = serde_json::from_str( diff --git a/crates/sf-launcher/src/winfade.rs b/crates/sf-launcher/src/winfade.rs index 3d195c4..21ff9d0 100644 --- a/crates/sf-launcher/src/winfade.rs +++ b/crates/sf-launcher/src/winfade.rs @@ -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)); } - let fade = Duration::from_millis(340); + // Same crossfade as sf-compositor on the TV. + let fade = Duration::from_millis(560); let t0 = Instant::now(); while t0.elapsed() < fade { 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); std::thread::sleep(Duration::from_millis(8)); } diff --git a/crates/sf-launcher/ui/app.slint b/crates/sf-launcher/ui/app.slint index 7f2a118..84018a7 100644 --- a/crates/sf-launcher/ui/app.slint +++ b/crates/sf-launcher/ui/app.slint @@ -1,21 +1,30 @@ -// SmartFox launcher UI. +// Fennec OS launcher UI. // -// Everything is laid out on a 1920x1080 design grid scaled by `u`. -// The frosted glass surfaces are NOT drawn here: Slint exports their geometry -// (`glass-rects` plus the card-row properties) and the Rust OpenGL layer draws -// them underneath. Slint only draws text, icons and simple overlays on top. +// Everything is laid out on a 1920x1080 design grid scaled by `u`: +// 96 px side margins, 64 px top and bottom, an 8 px rhythm. +// The glass surfaces are NOT drawn here: Slint exports their geometry +// (`glass-*` arrays plus the card-row properties) and the Rust OpenGL layer +// draws them underneath. Slint only draws text, icons and images on top, so +// nothing Slint draws may sit under a glass pane. -import "fonts/Inter-Regular.ttf"; -import "fonts/Inter-Medium.ttf"; -import "fonts/Inter-SemiBold.ttf"; -import "fonts/InterDisplay-Bold.ttf"; -import "fonts/InterDisplay-ExtraBold.ttf"; +import "@sf-ui/fonts/Onest-Regular.ttf"; +import "@sf-ui/fonts/Onest-Medium.ttf"; +import "@sf-ui/fonts/Onest-SemiBold.ttf"; +import "@sf-ui/fonts/Onest-Bold.ttf"; -import { AppIcon, WifiIcon, BluetoothIcon, PlayIcon, InfoIcon } from "icons.slint"; +import { AppIcon, NamedIcon, PlayIcon, InfoIcon } from "icons.slint"; import { PairingGuide } from "pairing.slint"; import { SettingsView, SettingRow } from "settings.slint"; import { KeyboardView } from "keyboard.slint"; +// A live line under the focused app's name ("Siri Remote 82%"). +export struct Fact { + icon: string, + text: string, + // "" | "ok" | "warn" + tone: string, +} + export struct AppEntry { id: string, name: string, @@ -26,6 +35,25 @@ export struct AppEntry { kind: string, kind-label: string, target: string, + version: string, + // Web apps: the address without the scheme ("netflex.furbidden.cloud"). + host: string, + facts: [Fact], + // A picture shipped with the app (store apps): replaces the vector icon. + image: image, + has-image: bool, + // No picture and no built-in icon: the name's first letter is drawn. + initial: string, +} + +// Top Shelf card (Netflex: continue watching or its first home row). +export struct ShelfItem { + title: string, + detail: string, + image: image, + has-image: bool, + // 0..1, 0 = no bar + progress: float, } export struct GlassRect { @@ -46,9 +74,9 @@ export struct GlassRect { } export component App inherits Window { - title: "SmartFox"; + title: "Fennec OS"; background: #050506; - default-font-family: "Inter"; + default-font-family: "Onest"; preferred-width: 1600px; preferred-height: 900px; forward-focus: keys; @@ -56,8 +84,16 @@ export component App inherits Window { // ---- data from Rust ------------------------------------------------- in property <[AppEntry]> apps; in property <string> clock: "21:42"; - in property <string> date: "csütörtök, okt. 23."; + in property <string> date: "csütörtök, október 23."; in property <string> remote-status: "Nincs párosítva"; + // Status capsule: network ("wired" | "wifi" | "none") and the remote's battery (-1 = unknown). + in property <string> net-icon: "wired"; + in property <string> net-label: ""; + in property <int> remote-battery: -1; + // Top Shelf: shown while the app `shelf-app` is focused and there are items. + in property <string> shelf-app: "netflex"; + in property <string> shelf-title; + in property <[ShelfItem]> shelf-items; // Remote pairing guide (state comes from sf-remote). in-out property <string> remote-state; in-out property <bool> pairing-open: false; @@ -84,8 +120,12 @@ export component App inherits Window { in property <string> set-title; in property <string> set-subtitle; in property <[SettingRow]> set-rows; - // Keep in sync with the category constants in settings_screen.rs. - out property <[string]> set-categories: ["Kijelző", "Távirányító és Bluetooth", "Hálózat", "Energia", "Rendszer"]; + // "settings" or "store": the App Store uses the same pane (store_screen.rs). + in-out property <string> set-mode: "settings"; + // Keep in sync with the category constants in settings_screen.rs / store_screen.rs. + out property <[string]> set-categories: self.set-mode == "store" + ? ["Felfedezés", "Telepítve", "Források"] + : ["Kijelző", "Távirányító és Bluetooth", "Hang", "Hálózat", "Energia", "Rendszer"]; out property <int> set-nav-count: self.set-categories.length; callback settings-opened(); callback settings-nav-changed(int); @@ -103,27 +143,28 @@ export component App inherits Window { animate nav-active { duration: 300ms; easing: ease-out; } out property <float> content-active: (self.settings-open && self.set-area == 1) ? 1 : 0; animate content-active { duration: 300ms; easing: ease-out; } - // Geometry, mirrored by settings_screen::glass. + // Geometry, mirrored by settings_screen::glass. The screen uses the whole + // safe area: categories on the left, one grouped platter of rows on the right. out property <length> sp-x: 96 * self.u; - out property <length> sp-y: 150 * self.u + (1 - self.set-t) * 40 * self.u; + out property <length> sp-y: 64 * self.u + (1 - self.set-t) * 32 * self.u; out property <length> sp-w: 1728 * self.u; - out property <length> sp-h: 870 * self.u; - out property <length> nav-x: self.sp-x + 40 * self.u; - out property <length> nav-y: self.sp-y + 176 * self.u; - out property <length> nav-w: 480 * self.u; - out property <length> nav-h: 92 * self.u; - out property <length> nav-step: 106 * self.u; - out property <length> rows-x: self.sp-x + 576 * self.u; - out property <length> rows-y: self.sp-y + 176 * self.u; - out property <length> rows-w: self.sp-w - 624 * self.u; + out property <length> sp-h: 952 * self.u; + out property <length> nav-x: self.sp-x; + out property <length> nav-y: self.sp-y + 184 * self.u; + out property <length> nav-w: 512 * self.u; + out property <length> nav-h: 80 * self.u; + out property <length> nav-step: 88 * self.u; + out property <length> rows-x: self.sp-x + 608 * self.u; + out property <length> rows-y: self.sp-y + 320 * self.u; + out property <length> rows-w: self.sp-w - 608 * self.u; out property <length> set-row-h: 88 * self.u; - out property <length> set-row-step: 100 * self.u; - out property <length> rows-view-h: 600 * self.u; - out property <length> rows-scroll: max(0, self.set-row - 5) * self.set-row-step; + out property <length> set-row-step: 88 * self.u; + out property <length> rows-view-h: 7 * self.set-row-step; + out property <length> rows-scroll: max(0, min(self.set-row - 5, self.set-rows.length - 7)) * self.set-row-step; animate rows-scroll { duration: 420ms; easing: cubic-bezier(0.22, 1, 0.36, 1); } // ---- on-screen keyboard (text and callbacks: keyboard.rs) ---------------- - // Opens inside the settings pane; Rust owns the text and validation. + // Opens in place of the settings content; Rust owns the text and validation. in-out property <bool> kb-open: false; in property <string> kb-title; in property <string> kb-subtitle; @@ -172,19 +213,19 @@ export component App inherits Window { out property <float> kb-chips-active: (self.kb-open && self.kb-area == 1) ? 1 : 0; animate kb-chips-active { duration: 260ms; easing: ease-out; } // Geometry, mirrored by keyboard::glass. - out property <length> kb-field-w: 1300 * self.u; - out property <length> kb-field-h: 100 * self.u; + out property <length> kb-field-w: 1200 * self.u; + out property <length> kb-field-h: 96 * self.u; out property <length> kb-field-x: self.sp-x + (self.sp-w - self.kb-field-w) / 2; - out property <length> kb-field-y: self.sp-y + 210 * self.u; + out property <length> kb-field-y: self.sp-y + 264 * self.u; out property <length> kb-key-w: min(58 * self.u, 1600 * self.u / self.kb-n); out property <length> kb-row-x: self.sp-x + (self.sp-w - self.kb-n * self.kb-key-w) / 2; - out property <length> kb-row-y: self.sp-y + 410 * self.u; + out property <length> kb-row-y: self.sp-y + 472 * self.u; out property <length> kb-row-h: 120 * self.u; out property <length> kb-chip-w: 200 * self.u; - out property <length> kb-chip-h: 76 * self.u; - out property <length> kb-chip-step: 220 * self.u; - out property <length> kb-chip-x: self.sp-x + (self.sp-w - 6 * self.kb-chip-step + 20 * self.u) / 2; - out property <length> kb-chip-y: self.sp-y + 600 * self.u; + out property <length> kb-chip-h: 72 * self.u; + out property <length> kb-chip-step: 216 * self.u; + out property <length> kb-chip-x: self.sp-x + (self.sp-w - 6 * self.kb-chip-step + 16 * self.u) / 2; + out property <length> kb-chip-y: self.sp-y + 664 * self.u; function kb-press-key() { if root.kb-index == 0 { @@ -217,20 +258,20 @@ export component App inherits Window { in property <string> launch-detail: "indítása…"; // ---- home grid (tvOS layout; exported so the glass layer can mirror it) ---- - // Five icons per row. The first row sits under the top shelf (the backdrop - // in the focused app's colours); further rows scroll up and the shelf dims. + // Five icons per row, the name under each. The first row sits under the + // Top Shelf; further rows scroll up and the shelf dims. out property <length> u: min(self.width / 1920, self.height / 1080); out property <int> cols: 5; - out property <length> row-x: 90 * self.u; - out property <length> row-y: 774 * self.u; - out property <length> card-w: 308 * self.u; - out property <length> card-h: 185 * self.u; - out property <length> card-gap: 50 * self.u; - out property <length> row-step: 249 * self.u; - out property <length> card-r: 40 * self.u; + out property <length> row-x: 96 * self.u; + out property <length> row-y: 760 * self.u; + out property <length> card-w: 320 * self.u; + out property <length> card-h: 192 * self.u; + out property <length> card-gap: 32 * self.u; + out property <length> row-step: 296 * self.u; + out property <length> card-r: 36 * self.u; // Focused icon lift (tvOS-like) and the press-in while OK is held. - out property <float> lift: 0.14; - out property <float> press-in: 0.06; + out property <float> lift: 0.12; + out property <float> press-in: 0.05; // ---- focus state ----------------------------------------------------- in-out property <int> focus-index: 0; @@ -248,7 +289,7 @@ export component App inherits Window { animate row-active { duration: 320ms; easing: ease-out; } // Row 0: the shelf is showing. Deeper rows: the focused row moves to the middle, the row above stays in view. - out property <length> grid-scroll: self.focus-row == 0 ? 0 : self.row-y + self.focus-row * self.row-step - 470 * self.u; + out property <length> grid-scroll: self.focus-row == 0 ? 0 : self.row-y + self.focus-row * self.row-step - 520 * self.u; animate grid-scroll { duration: 560ms; easing: cubic-bezier(0.22, 1, 0.36, 1); } out property <float> shelf-t: self.focus-row == 0 ? 1 : 0; animate shelf-t { duration: 600ms; easing: ease-in-out; } @@ -284,13 +325,13 @@ export component App inherits Window { property <length> fc-h: self.card-h * (1 + self.lift); property <length> fc-x: self.row-x + self.focus-col * (self.card-w + self.card-gap) + (self.card-w - self.fc-w) / 2; property <length> fc-y: self.row-y + self.focus-row * self.row-step - self.grid-scroll + (self.card-h - self.fc-h) / 2; - out property <length> menu-w: 440 * self.u; - out property <length> menu-item-h: 76 * self.u; + out property <length> menu-w: 432 * self.u; + out property <length> menu-item-h: 72 * self.u; out property <length> menu-pad: 12 * self.u; property <length> menu-h: self.menu-items.length * self.menu-item-h + 2 * self.menu-pad; - property <bool> menu-above: self.fc-y - 36 * self.u - self.menu-h > 40 * self.u; - property <length> menu-x-end: clamp(self.fc-x, 60 * self.u, self.width - 60 * self.u - self.menu-w); - property <length> menu-y-end: self.menu-above ? self.fc-y - 36 * self.u - self.menu-h : self.fc-y + self.fc-h + 36 * self.u; + property <bool> menu-above: self.fc-y - 32 * self.u - self.menu-h > 64 * self.u; + property <length> menu-x-end: clamp(self.fc-x, 96 * self.u, self.width - 96 * self.u - self.menu-w); + property <length> menu-y-end: self.menu-above ? self.fc-y - 32 * self.u - self.menu-h : self.fc-y + self.fc-h + 32 * self.u; property <float> me: clamp(self.menu-t, 0, 1.2); out property <length> mx: self.fc-x + (self.menu-x-end - self.fc-x) * self.me; out property <length> my: self.fc-y + (self.menu-y-end - self.fc-y) * self.me; @@ -305,7 +346,9 @@ export component App inherits Window { animate sheet-t { duration: 560ms; easing: cubic-bezier(0.22, 1, 0.36, 1); } out property <float> launch-t: self.launching ? 1 : 0; - animate launch-t { duration: 900ms; easing: cubic-bezier(0.72, 0, 0.16, 1); } + // Moves from the first frame and settles softly; sf-compositor shows the + // app only once this is nearly done (its MORPH constant). + animate launch-t { duration: 800ms; easing: cubic-bezier(0.45, 0, 0.15, 1); } // Set by Rust once the app window is visible on top. in property <bool> app-ready: false; @@ -322,45 +365,71 @@ export component App inherits Window { // Splash content appears in the second half of the morph. property <float> splash: clamp((self.le - 0.55) / 0.45, 0, 1); - property <AppEntry> focused: self.apps.length > 0 ? self.apps[self.focus-index] : { name: "SmartFox" }; + property <AppEntry> focused: self.apps.length > 0 ? self.apps[self.focus-index] : { name: "Fennec OS" }; + + // The shelf follows the focus as it glides: it fades out halfway between + // two icons and comes back with the next app's content. + property <int> hero-col: clamp(Math.round(self.focus-x), 0, self.cols - 1); + property <int> hero-row: max(0, Math.round(self.focus-y)); + property <int> hero-index: max(0, min(self.apps.length - 1, self.hero-row * self.cols + self.hero-col)); + property <AppEntry> hero: self.apps.length > 0 ? self.apps[self.hero-index] : { name: "Fennec OS" }; + property <float> hero-fade: clamp(1 - 2.4 * max(abs(self.focus-x - self.hero-col), abs(self.focus-y - self.hero-row)), 0, 1); + property <bool> show-shelf: self.hero.id == self.shelf-app && self.shelf-items.length > 0; property <float> top-in: clamp(self.intro * 2.0 - 0.15, 0, 1); + // Home content (top bar, shelf) goes away under the screens that cover it. + property <float> home-vis: self.top-in * (1 - self.launch-t) * (1 - self.sheet-t) * self.dim; + property <float> shelf-vis: self.home-vis * self.shelf-t * clamp(self.intro * 1.6 - 0.3, 0, 1); - // geometry of the static glass surfaces - property <length> capsule-w: 404 * self.u; - property <length> capsule-h: 66 * self.u; - property <length> capsule-x: 1920 * self.u - 96 * self.u - self.capsule-w; - property <length> capsule-y: 50 * self.u; + // ---- status capsule (right end of the top bar) ---------------------------- + property <length> capsule-h: 64 * self.u; + property <length> capsule-w: status-row.preferred-width; + property <length> capsule-x: self.width - 96 * self.u - self.capsule-w; + property <length> capsule-y: 56 * self.u; // The toast buds off the status capsule like a droplet (merged glass). - property <length> toast-w-end: 620 * self.u; - property <length> toast-h-end: 76 * self.u; + property <length> toast-w-end: 640 * self.u; + property <length> toast-h-end: 72 * self.u; property <float> toast-e: clamp(self.toast-t, 0, 1.2); property <length> toast-w: self.capsule-w + (self.toast-w-end - self.capsule-w) * clamp(self.toast-e, 0, 1); property <length> toast-h: self.capsule-h + (self.toast-h-end - self.capsule-h) * clamp(self.toast-e, 0, 1); property <length> toast-x: self.capsule-x + self.capsule-w - self.toast-w; - property <length> toast-y: self.capsule-y + self.toast-e * (self.capsule-h + 18 * self.u); - // Pairing pane and the glass bits inside it (see pairing.slint for the layout). - property <length> pane-x: (self.width - 1300 * self.u) / 2; - property <length> pane-y: (self.height - 720 * self.u) / 2 + (1 - self.pair-t) * 50 * self.u; - property <length> pc-x: self.pane-x + 420 * self.u; - property <length> pc-y: self.pane-y + 70 * self.u; + property <length> toast-y: self.capsule-y + self.toast-e * (self.capsule-h + 16 * self.u); + + // ---- pairing pane (pairing.slint draws the content at these offsets) ----- + property <length> pane-w: 1312 * self.u; + property <length> pane-h: 720 * self.u; + property <length> pane-x: (self.width - self.pane-w) / 2; + property <length> pane-y: (self.height - self.pane-h) / 2 + (1 - self.pair-t) * 48 * self.u; + property <length> pc-x: self.pane-x + 440 * self.u; + property <length> pc-y: self.pane-y + 88 * self.u; + property <[length]> pair-steps: [128 * self.u, 200 * self.u, 312 * self.u]; + property <length> pair-pill-y: 480 * self.u; property <bool> remote-ok: self.remote-state == "paired" || self.remote-state == "connected"; property <bool> remote-broken: self.remote-state == "no-adapter"; property <float> pair-in: self.pair-t * self.pair-t; // Launch splash bits. property <float> splash-bar: self.splash * (self.app-ready ? 0 : 1); animate splash-bar { duration: 300ms; } - property <length> sheet-w: 700 * self.u; - property <length> sheet-x: 1920 * self.u - 64 * self.u - self.sheet-w + (1 - self.sheet-t) * 90 * self.u; + + // ---- details sheet -------------------------------------------------------- + property <length> sheet-w: 720 * self.u; + property <length> sheet-x: self.width - 64 * self.u - self.sheet-w + (1 - self.sheet-t) * 96 * self.u; property <length> sheet-y: 64 * self.u; - property <length> sheet-h: 952 * self.u; + // The sheet fits its content: icon, name, category, description, info rows. + property <length> sheet-h: self.info-y - self.sheet-y + self.info-rows.length * self.info-row-h + self.sheet-pad; + property <length> sheet-pad: 56 * self.u; + property <length> info-row-h: 80 * self.u; + property <[{k: string, v: string}]> info-rows: self.focused.kind == "service" + ? [{ k: "Működés", v: self.focused.kind-label }, { k: "Verzió", v: self.focused.version }] + : [{ k: "Verzió", v: self.focused.version }]; + property <length> info-y: self.sheet-y + self.sheet-pad + 296 * self.u + sheet-desc.preferred-height + 48 * self.u; // Drawn below the app cards. out property <[GlassRect]> glass-under: [ // Status capsule and the toast that grows out of it (group 1). { x: self.capsule-x, y: self.capsule-y, w: self.capsule-w, h: self.capsule-h, - r: self.capsule-h / 2, focus: 0, alpha: self.top-in * (1 - self.launch-t) * (1 - self.sheet-t), blur: 1.2, + r: self.capsule-h / 2, focus: 0, alpha: self.home-vis * (1 - self.pair-t), blur: 1.2, glow: #ffffff, tint: #ffffff06, group: 1, }, { @@ -375,7 +444,7 @@ export component App inherits Window { out property <[GlassRect]> glass-menu: [ { x: self.mx, y: self.my, w: self.mw, h: self.mh, - r: self.card-r * (1 + self.lift) + (34 * self.u - self.card-r * (1 + self.lift)) * clamp(self.me, 0, 1), + r: self.card-r * (1 + self.lift) + (32 * self.u - self.card-r * (1 + self.lift)) * clamp(self.me, 0, 1), focus: 0.12, alpha: clamp(self.menu-t * 3, 0, 1), blur: 3.0, glow: self.focused.accent, tint: #0b0c12.with-alpha(0.42), group: 2, }, @@ -395,76 +464,55 @@ export component App inherits Window { alpha: clamp(self.le * 8, 0, 1), blur: 1.6 + 2.6 * self.le, glow: self.focused.accent, tint: self.focused.accent.darker(0.75).with-alpha(0.10 + 0.55 * self.le), }, - // Splash: loading track and the back hint, nested on the full-screen glass. + // Splash: loading track, nested on the full-screen glass. { x: (self.width - 280 * self.u) / 2, y: self.height / 2 + 144 * self.u, w: 280 * self.u, h: 16 * self.u, r: 8 * self.u, focus: 0, alpha: self.splash-bar, blur: -1, glow: self.focused.accent, tint: #00000030, }, - { - x: (self.width - 440 * self.u) / 2, y: self.height - 112 * self.u, w: 440 * self.u, h: 56 * self.u, - r: 28 * self.u, focus: 0, alpha: self.splash, blur: -1, - glow: #ffffff, tint: #ffffff08, - }, { x: self.pane-x, y: self.pane-y, - w: 1300 * self.u, h: 720 * self.u, + w: self.pane-w, h: self.pane-h, r: 56 * self.u, focus: 0.2 * self.pair-t, alpha: self.pair-t, blur: 3.8, glow: #ff7a35, tint: #0b0c12.with-alpha(0.48), }, - // Pairing: step numbers, live status pill and the skip chip. + // Pairing: step beads, live status pill and the skip chip. { - x: self.pc-x - 2 * self.u, y: self.pc-y + 152 * self.u, w: 44 * self.u, h: 44 * self.u, - r: 22 * self.u, focus: 0.3, alpha: self.pair-in, blur: -1, + x: self.pc-x, y: self.pc-y + self.pair-steps[0], w: 48 * self.u, h: 48 * self.u, + r: 24 * self.u, focus: 0.3, alpha: self.pair-in, blur: -1, glow: #ff7a35, tint: #ff7a3526, }, { - x: self.pc-x - 2 * self.u, y: self.pc-y + 228 * self.u, w: 44 * self.u, h: 44 * self.u, - r: 22 * self.u, focus: 0.3, alpha: self.pair-in, blur: -1, + x: self.pc-x, y: self.pc-y + self.pair-steps[1], w: 48 * self.u, h: 48 * self.u, + r: 24 * self.u, focus: 0.3, alpha: self.pair-in, blur: -1, glow: #ff7a35, tint: #ff7a3526, }, { - x: self.pc-x - 2 * self.u, y: self.pc-y + 332 * self.u, w: 44 * self.u, h: 44 * self.u, - r: 22 * self.u, focus: 0.3, alpha: self.pair-in, blur: -1, + x: self.pc-x, y: self.pc-y + self.pair-steps[2], w: 48 * self.u, h: 48 * self.u, + r: 24 * self.u, focus: 0.3, alpha: self.pair-in, blur: -1, glow: #ff7a35, tint: #ff7a3526, }, { - x: self.pc-x, y: self.pc-y + 510 * self.u, w: 520 * self.u, h: 64 * self.u, - r: 32 * self.u, focus: self.remote-ok ? 0.6 : 0.15, alpha: self.pair-in, blur: -1, + x: self.pc-x, y: self.pc-y + self.pair-pill-y, w: 520 * self.u, h: 64 * self.u, + r: 32 * self.u, focus: self.remote-ok ? 0.6 : 0.15, alpha: self.pair-in * (self.remote-ok || self.remote-broken ? 1 : 0), blur: -1, glow: self.remote-ok ? #34c759 : self.remote-broken ? #ff9f0a : #ff7a35, tint: self.remote-ok ? #34c75940 : self.remote-broken ? #ff9f0a38 : #ffffff0a, }, { - x: self.pc-x + 556 * self.u, y: self.pc-y + 512 * self.u, w: 204 * self.u, h: 60 * self.u, - r: 30 * self.u, focus: 0, alpha: self.pair-in, blur: -1, - glow: #ffffff, tint: #ffffff06, + x: self.pc-x + 544 * self.u, y: self.pc-y + self.pair-pill-y, w: 200 * self.u, h: 64 * self.u, + r: 32 * self.u, focus: 0, alpha: self.pair-in, blur: -1, + glow: #ffffff, tint: #ffffff08, }, { x: self.sheet-x, y: self.sheet-y, w: self.sheet-w, h: self.sheet-h, - r: 44 * self.u, focus: 0.15 * self.sheet-t, alpha: self.sheet-t, blur: 3.4, - glow: self.focused.accent, tint: #0a0b10.with-alpha(0.34), + r: 48 * self.u, focus: 0.15 * self.sheet-t, alpha: self.sheet-t, blur: 3.4, + glow: self.focused.accent, tint: #0a0b10.with-alpha(0.38), }, - // Sheet: icon tile, info rows and the back chip, nested on the sheet. + // Sheet: the icon tile and one grouped info platter, nested on the sheet. { - x: self.sheet-x + 40 * self.u, y: self.sheet-y + 48 * self.u, w: 120 * self.u, h: 120 * self.u, - r: 34 * self.u, focus: 0.25, alpha: self.sheet-t, blur: -1, - glow: self.focused.accent, tint: self.focused.accent.darker(0.6).with-alpha(0.10), - }, - { - x: self.sheet-x + 56 * self.u, y: self.sheet-y + 420 * self.u, w: self.sheet-w - 112 * self.u, h: 92 * self.u, - r: 26 * self.u, focus: 0, alpha: self.sheet-t, blur: -1, glow: #ffffff, tint: #ffffff06, - }, - { - x: self.sheet-x + 56 * self.u, y: self.sheet-y + 530 * self.u, w: self.sheet-w - 112 * self.u, h: 92 * self.u, - r: 26 * self.u, focus: 0, alpha: self.sheet-t, blur: -1, glow: #ffffff, tint: #ffffff06, - }, - { - x: self.sheet-x + 56 * self.u, y: self.sheet-y + 640 * self.u, w: self.sheet-w - 112 * self.u, h: 92 * self.u, - r: 26 * self.u, focus: 0, alpha: self.sheet-t, blur: -1, glow: #ffffff, tint: #ffffff06, - }, - { - x: self.sheet-x + 56 * self.u, y: self.sheet-y + self.sheet-h - 86 * self.u, w: 250 * self.u, h: 56 * self.u, - r: 28 * self.u, focus: 0, alpha: self.sheet-t, blur: -1, glow: #ffffff, tint: #ffffff06, + x: self.sheet-x + self.sheet-pad, y: self.sheet-y + self.sheet-pad, w: 128 * self.u, h: 128 * self.u, + r: 36 * self.u, focus: 0.25, alpha: self.sheet-t, blur: -1, + glow: self.focused.accent, tint: self.focused.accent.darker(0.6).with-alpha(0.12), }, ]; @@ -486,7 +534,15 @@ export component App inherits Window { function activate() { if root.apps.length == 0 { return; } if root.focused.kind == "builtin" { + // The store tile opens the settings pane in store mode. + if root.set-mode != (root.focused.id == "store" ? "store" : "settings") { + root.set-mode = root.focused.id == "store" ? "store" : "settings"; + root.set-nav = 0; + } root.open-settings(); + } else if root.focused.kind == "service" { + // Receivers run all the time; the sheet explains how to connect. + root.sheet-open = true; } else { root.launching = true; root.launch(root.focus-index); @@ -641,55 +697,254 @@ export component App inherits Window { keys.focus(); } - // ---- status capsule --------------------------------------------------- + // ---- top bar: the time on the left ------------------------------------------ + Rectangle { + x: 96 * root.u; + y: 44 * root.u; + width: 720 * root.u; + height: 136 * root.u; + opacity: root.home-vis * (1 - root.pair-t); + Text { + x: 0; + y: 0; + width: parent.width; + height: 88 * root.u; + vertical-alignment: center; + text: root.clock; + font-size: 64 * root.u; + font-weight: 600; + letter-spacing: -1 * root.u; + color: #ffffff; + } + Text { + x: 0; + y: 84 * root.u; + width: parent.width; + text: root.date; + font-size: 26 * root.u; + font-weight: 500; + color: #ffffffb8; + } + } + + // ---- status capsule: remote battery and network -------------------------------- Rectangle { x: root.capsule-x; y: root.capsule-y; width: root.capsule-w; height: root.capsule-h; - opacity: root.top-in * (1 - root.launch-t) * (1 - root.sheet-t); - WifiIcon { - x: 28 * root.u; - y: (parent.height - self.height) / 2; + opacity: root.home-vis * (1 - root.pair-t); + status-row := HorizontalLayout { + padding-left: 24 * root.u; + padding-right: 28 * root.u; + spacing: 12 * root.u; + + if root.remote-battery >= 0: Rectangle { width: 30 * root.u; - height: 30 * root.u; + NamedIcon { + y: (parent.height - self.height) / 2; + width: 30 * root.u; + height: 30 * root.u; + name: "remote"; + ink: root.remote-battery <= 15 ? #ffb340 : #ffffffd0; + } } - BluetoothIcon { - x: 70 * root.u; - y: (parent.height - self.height) / 2; - width: 30 * root.u; - height: 30 * root.u; - ink: #ffffffb0; + if root.remote-battery >= 0: Text { + vertical-alignment: center; + text: root.remote-battery + "%"; + font-size: 24 * root.u; + font-weight: 600; + color: root.remote-battery <= 15 ? #ffb340 : #ffffff; + } + if root.remote-battery >= 0: Rectangle { + width: 20 * root.u; + Rectangle { + x: (parent.width - self.width) / 2; + y: (parent.height - self.height) / 2; + width: 1.5 * root.u; + height: 26 * root.u; + background: #ffffff38; + } } Rectangle { - x: 118 * root.u; - y: 18 * root.u; - width: 1.5 * root.u; - height: parent.height - 36 * root.u; - background: #ffffff38; + width: 30 * root.u; + NamedIcon { + y: (parent.height - self.height) / 2; + width: 30 * root.u; + height: 30 * root.u; + name: root.net-icon == "wifi" ? "wifi" : root.net-icon == "none" ? "alert" : "wired"; + ink: root.net-icon == "none" ? #ffb340 : #ffffffd0; + } } Text { - x: 138 * root.u; - width: parent.width - 138 * root.u - 30 * root.u; - height: parent.height; vertical-alignment: center; - text: root.date; - font-size: 21 * root.u; - color: #ffffffb8; + text: root.net-label; + font-size: 24 * root.u; + font-weight: 500; + color: root.net-icon == "none" ? #ffb340 : #ffffffd8; } + } + } + + // ---- Top Shelf: Netflex cards ------------------------------------------------ + if root.show-shelf: Rectangle { + x: 96 * root.u + (1 - root.hero-fade) * 16 * root.u; + y: 0; + width: 1728 * root.u; + height: 720 * root.u; + opacity: root.shelf-vis * root.hero-fade; + Text { - width: parent.width - 30 * root.u; - height: parent.height; - vertical-alignment: center; - horizontal-alignment: right; - text: root.clock; - font-size: 28 * root.u; + x: 0; + y: 268 * root.u; + width: parent.width; + text: root.shelf-title; + font-size: 36 * root.u; font-weight: 600; color: #ffffff; } + for item[i] in root.shelf-items: Rectangle { + property <length> cw: 402 * root.u; + x: i * (self.cw + 40 * root.u); + y: 336 * root.u; + width: self.cw; + height: 226 * root.u; + visible: i < 4; + // Shadow under the artwork. + Rectangle { + width: 100%; + height: 100%; + border-radius: 24 * root.u; + background: #000000; + drop-shadow-blur: 28 * root.u; + drop-shadow-offset-y: 12 * root.u; + drop-shadow-color: #00000080; + } + Rectangle { + width: 100%; + height: 100%; + border-radius: 24 * root.u; + clip: true; + background: #ffffff12; + if item.has-image: Image { + width: 100%; + height: 100%; + source: item.image; + image-fit: cover; + } + if !item.has-image: Text { + x: 24 * root.u; + width: parent.width - 48 * root.u; + height: 100%; + vertical-alignment: center; + horizontal-alignment: center; + wrap: word-wrap; + text: item.title; + font-size: 32 * root.u; + font-weight: 700; + color: #ffffffd0; + } + if item.progress > 0: Rectangle { + y: parent.height - 72 * root.u; + height: 72 * root.u; + background: @linear-gradient(180deg, #00000000 0%, #000000a0 100%); + } + if item.progress > 0: Rectangle { + x: 24 * root.u; + y: parent.height - 26 * root.u; + width: parent.width - 48 * root.u; + height: 6 * root.u; + border-radius: self.height / 2; + background: #ffffff47; + Rectangle { + width: parent.width * clamp(item.progress, 0.04, 1); + border-radius: self.height / 2; + background: #ffffff; + } + } + } + Text { + x: 0; + y: parent.height + 20 * root.u; + width: parent.width; + text: item.title; + font-size: 26 * root.u; + font-weight: 600; + color: #ffffff; + overflow: elide; + } + Text { + x: 0; + y: parent.height + 56 * root.u; + width: parent.width; + text: item.detail; + font-size: 22 * root.u; + font-weight: 500; + color: #ffffffa6; + overflow: elide; + } + } } - // ---- app grid (no names: tvOS-like icons only) --------------------------- + // ---- Top Shelf: the focused app itself --------------------------------------------- + if !root.show-shelf: Rectangle { + x: 96 * root.u + (1 - root.hero-fade) * 16 * root.u; + y: 0; + width: 1400 * root.u; + height: 720 * root.u; + opacity: root.shelf-vis * root.hero-fade; + + Text { + x: 0; + y: 260 * root.u; + width: parent.width; + text: root.hero.name; + font-size: 96 * root.u; + font-weight: 700; + letter-spacing: -2 * root.u; + color: #ffffff; + } + Text { + x: 0; + y: 384 * root.u; + width: 1040 * root.u; + height: 80 * root.u; + text: root.hero.description; + wrap: word-wrap; + overflow: elide; + font-size: 28 * root.u; + color: #ffffffcc; + } + HorizontalLayout { + x: 0; + y: 512 * root.u; + height: 40 * root.u; + alignment: start; + spacing: 40 * root.u; + for fact in root.hero.facts: HorizontalLayout { + spacing: 12 * root.u; + Rectangle { + width: 30 * root.u; + NamedIcon { + y: (parent.height - self.height) / 2; + width: 30 * root.u; + height: 30 * root.u; + name: fact.icon; + ink: fact.tone == "ok" ? #5ee07a : fact.tone == "warn" ? #ffb340 : #ffffffc0; + } + } + Text { + vertical-alignment: center; + text: fact.text; + font-size: 26 * root.u; + font-weight: 500; + color: fact.tone == "warn" ? #ffc66b : #ffffffe0; + } + } + } + } + + // ---- app row: icon cards, the name under each ------------------------------------ for app[i] in root.apps: Rectangle { // Keep these formulas in sync with `card_rects` in src/main.rs. property <int> gc: Math.mod(i, root.cols); @@ -697,11 +952,12 @@ export component App inherits Window { property <float> f: max(0, 1 - abs(root.focus-x - self.gc)) * max(0, 1 - abs(root.focus-y - self.gr)) * root.row-active; property <float> s: 1 + (root.lift - root.press-in * root.press) * self.f; property <float> appear: clamp(root.intro * 2.2 - self.gc * 0.12 - self.gr * 0.2 - 0.4, 0, 1); - property <float> others: i == root.focus-index ? 1 : 1 - 0.55 * clamp(root.menu-t, 0, 1); + property <float> others: (i == root.focus-index ? 1 : 1 - 0.55 * clamp(root.menu-t, 0, 1)) + * (self.gr > 0 ? 1 - root.shelf-t : 1); // Slint draws above the glass, so icons under the menu must go away entirely. property <bool> under-menu: i != root.focus-index && self.x < root.menu-x-end + root.menu-w && self.x + self.width > root.menu-x-end - && self.y < root.menu-y-end + root.menu-h && self.y + self.height > root.menu-y-end; + && self.y < root.menu-y-end + root.menu-h && self.y + self.height + 56 * root.u > root.menu-y-end; property <float> covered: self.under-menu ? clamp(root.menu-t * 2, 0, 1) : 0; width: root.card-w * self.s; height: root.card-h * self.s; @@ -711,11 +967,26 @@ export component App inherits Window { AppIcon { icon: app.icon; - width: 92 * root.u * parent.s; + image: app.image; + has-image: app.has-image; + letter: app.initial; + width: 104 * root.u * parent.s; height: self.width; x: (parent.width - self.width) / 2; y: (parent.height - self.height) / 2; } + Text { + x: (parent.width - self.width) / 2; + y: parent.height + 16 * root.u; + width: root.card-w + 24 * root.u; + horizontal-alignment: center; + text: app.name; + font-size: 24 * root.u; + font-weight: 600; + color: #ffffff.with-alpha(0.56 + 0.44 * parent.f); + overflow: elide; + opacity: 1 - clamp(root.menu-t * 2, 0, 1) * (i == root.focus-index && !root.menu-above ? 1 : 0); + } } // ---- context menu (long press on OK) ------------------------------------- @@ -733,33 +1004,33 @@ export component App inherits Window { width: parent.width - 2 * root.menu-pad; height: root.menu-item-h; if k == 0: PlayIcon { - x: 30 * root.u; + x: 28 * root.u; y: (parent.height - self.height) / 2; width: 26 * root.u; height: 26 * root.u; ink: parent.ink; } if k == 1: InfoIcon { - x: 29 * root.u; + x: 27 * root.u; y: (parent.height - self.height) / 2; width: 28 * root.u; height: 28 * root.u; ink: parent.ink; } Text { - x: 80 * root.u; - width: parent.width - 100 * root.u; + x: 76 * root.u; + width: parent.width - 96 * root.u; height: parent.height; vertical-alignment: center; text: item; color: parent.ink; - font-size: 27 * root.u; + font-size: 26 * root.u; font-weight: 600; } } } - // ---- details / settings sheet --------------------------------------- + // ---- details sheet --------------------------------------------------------- Rectangle { x: root.sheet-x; y: root.sheet-y; @@ -768,75 +1039,81 @@ export component App inherits Window { opacity: root.sheet-t; AppIcon { - x: 56 * root.u; - y: 64 * root.u; - width: 88 * root.u; - height: 88 * root.u; + x: root.sheet-pad + (128 * root.u - self.width) / 2; + y: root.sheet-pad + (128 * root.u - self.height) / 2; + width: 84 * root.u; + height: 84 * root.u; icon: root.focused.icon; + image: root.focused.image; + has-image: root.focused.has-image; + letter: root.focused.initial; } Text { - x: 56 * root.u; - y: 176 * root.u; + x: root.sheet-pad; + y: root.sheet-pad + 160 * root.u; + width: parent.width - 2 * root.sheet-pad; text: root.focused.name; - font-family: "Inter Display"; - font-weight: 800; - font-size: 64 * root.u; - letter-spacing: -2 * root.u; + font-weight: 700; + font-size: 60 * root.u; + letter-spacing: -1.2 * root.u; color: #ffffff; + overflow: elide; } Text { - x: 56 * root.u; - y: 262 * root.u; - width: parent.width - 112 * root.u; + x: root.sheet-pad; + y: root.sheet-pad + 240 * root.u; + width: parent.width - 2 * root.sheet-pad; + text: root.focused.category; + font-size: 24 * root.u; + font-weight: 500; + color: #ffffff99; + overflow: elide; + } + sheet-desc := Text { + x: root.sheet-pad; + y: root.sheet-pad + 296 * root.u; + width: parent.width - 2 * root.sheet-pad; text: root.focused.description; wrap: word-wrap; - font-size: 24 * root.u; - color: #ffffffbb; + font-size: 28 * root.u; + color: #ffffffd8; } - VerticalLayout { - x: 56 * root.u; - y: 420 * root.u; - width: parent.width - 112 * root.u; - spacing: 18 * root.u; - - for row in [ - { k: "Típus", v: root.focused.kind-label }, - { k: root.focused.kind == "web" ? (root.focused.id == "netflex" ? "Szerver" : "Cím") : "Parancs", v: root.focused.target }, - { k: "Azonosító", v: root.focused.id }, - ]: Rectangle { - height: 92 * root.u; - Text { - x: 28 * root.u; - y: 16 * root.u; - text: row.k; - font-size: 19 * root.u; - font-weight: 600; - color: #ffffff80; - } - Text { - x: 28 * root.u; - y: 44 * root.u; - width: parent.width - 56 * root.u; - text: row.v; - font-size: 25 * root.u; - color: #ffffff; - overflow: elide; - } + // Info rows straight on the sheet, a hairline above each. + for row[k] in root.info-rows: Rectangle { + x: root.sheet-pad; + y: root.info-y - root.sheet-y + k * root.info-row-h; + width: parent.width - 2 * root.sheet-pad; + height: root.info-row-h; + Rectangle { + x: 0; + y: 0; + width: parent.width; + height: 1.5 * root.u; + background: #ffffff24; + } + Text { + x: 0; + width: 180 * root.u; + height: parent.height; + vertical-alignment: center; + text: row.k; + font-size: 24 * root.u; + font-weight: 500; + color: #ffffffa0; + } + Text { + x: 180 * root.u; + width: parent.width - 180 * root.u; + height: parent.height; + vertical-alignment: center; + horizontal-alignment: right; + text: row.v; + font-size: 24 * root.u; + font-weight: 500; + color: #ffffff; + overflow: elide; } - } - - Text { - x: 56 * root.u; - y: parent.height - 86 * root.u; - width: 250 * 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; } } @@ -869,6 +1146,8 @@ export component App inherits Window { subtitle: root.set-subtitle; rows: root.set-rows; categories: root.set-categories; + heading: root.set-mode == "store" ? "App Store" : "Beállítások"; + icon-base: root.set-mode == "store" ? 6 : 0; } // ---- on-screen keyboard --------------------------------------------------------- @@ -881,7 +1160,6 @@ export component App inherits Window { pane-y: root.sp-y; pane-w: root.sp-w; pane-h: root.sp-h; - back-x: root.nav-x; field-x: root.kb-field-x; field-y: root.kb-field-y; field-w: root.kb-field-w; @@ -915,10 +1193,14 @@ export component App inherits Window { if root.pair-t > 0.001: PairingGuide { x: root.pane-x; y: root.pane-y; - width: 1300 * root.u; - height: 720 * root.u; + width: root.pane-w; + height: root.pane-h; u: root.u; state: root.remote-state; + content-x: root.pc-x - root.pane-x; + content-y: root.pc-y - root.pane-y; + steps: root.pair-steps; + pill-y: root.pair-pill-y; opacity: root.pair-t; } @@ -929,24 +1211,27 @@ export component App inherits Window { // The app icon flies from its card to the center and grows. AppIcon { - property <length> size: (92 * (1 + root.lift) + 90 * root.le) * root.u; + property <length> size: (104 * (1 + root.lift) + 80 * root.le) * root.u; property <length> cx: (root.lc-x + root.lc-w / 2) * (1 - root.le) + (parent.width / 2) * root.le; - property <length> cy: (root.lc-y + root.lc-h / 2) * (1 - root.le) + (parent.height / 2 - 50 * root.u) * root.le; + property <length> cy: (root.lc-y + root.lc-h / 2) * (1 - root.le) + (parent.height / 2 - 48 * root.u) * root.le; icon: root.focused.icon; + image: root.focused.image; + has-image: root.focused.has-image; + letter: root.focused.initial; width: self.size; height: self.size; x: self.cx - self.size / 2; y: self.cy - self.size / 2; } Text { - y: parent.height / 2 + 70 * root.u + (1 - root.splash) * 20 * root.u; + x: 0; + y: parent.height / 2 + 72 * root.u + (1 - root.splash) * 16 * root.u; width: parent.width; horizontal-alignment: center; text: root.focused.name; - font-family: "Inter Display"; - font-weight: 800; - font-size: 44 * root.u; - letter-spacing: -1.2 * root.u; + font-weight: 700; + font-size: 48 * root.u; + letter-spacing: -0.8 * root.u; color: #ffffff; opacity: root.splash; } @@ -969,18 +1254,20 @@ export component App inherits Window { } } Text { - y: parent.height - 112 * root.u; + x: 0; + y: parent.height - 64 * root.u - 32 * root.u; width: parent.width; - height: 56 * root.u; + height: 32 * root.u; horizontal-alignment: center; vertical-alignment: center; - text: "‹ Bezárás és vissza · Esc"; - font-size: 21 * root.u; + text: "A Vissza gombbal bezárhatod"; + font-size: 22 * root.u; font-weight: 500; - color: #ffffffc0; + color: #ffffff8c; opacity: root.splash; } } + // ---- toast --------------------------------------------------------- Rectangle { x: root.toast-x; @@ -989,16 +1276,16 @@ export component App inherits Window { height: root.toast-h; opacity: clamp((root.toast-t - 0.55) * 2.5, 0, 1); Rectangle { - x: 26 * root.u; + x: 28 * root.u; y: (parent.height - self.height) / 2; - width: 14 * root.u; - height: 14 * root.u; + width: 12 * root.u; + height: 12 * root.u; border-radius: self.width / 2; background: root.focused.accent.brighter(0.3); } Text { x: 56 * root.u; - width: parent.width - 82 * root.u; + width: parent.width - 84 * root.u; height: parent.height; vertical-alignment: center; text: root.toast-text; @@ -1009,7 +1296,6 @@ export component App inherits Window { } } - // ---- standby ------------------------------------------------------------- if root.standby-t > 0.001: Rectangle { width: 100%; @@ -1023,8 +1309,8 @@ export component App inherits Window { horizontal-alignment: center; vertical-alignment: center; text: "Készenlét · nyomj meg egy gombot"; - font-size: 22 * root.u; - color: #ffffff30; + font-size: 24 * root.u; + color: #ffffff38; } } } diff --git a/crates/sf-launcher/ui/fonts/Inter-Medium.ttf b/crates/sf-launcher/ui/fonts/Inter-Medium.ttf deleted file mode 100644 index 458cd06..0000000 Binary files a/crates/sf-launcher/ui/fonts/Inter-Medium.ttf and /dev/null differ diff --git a/crates/sf-launcher/ui/fonts/Inter-Regular.ttf b/crates/sf-launcher/ui/fonts/Inter-Regular.ttf deleted file mode 100644 index b7aaca8..0000000 Binary files a/crates/sf-launcher/ui/fonts/Inter-Regular.ttf and /dev/null differ diff --git a/crates/sf-launcher/ui/fonts/Inter-SemiBold.ttf b/crates/sf-launcher/ui/fonts/Inter-SemiBold.ttf deleted file mode 100644 index 47f8ab1..0000000 Binary files a/crates/sf-launcher/ui/fonts/Inter-SemiBold.ttf and /dev/null differ diff --git a/crates/sf-launcher/ui/fonts/InterDisplay-Bold.ttf b/crates/sf-launcher/ui/fonts/InterDisplay-Bold.ttf deleted file mode 100644 index b8f0d82..0000000 Binary files a/crates/sf-launcher/ui/fonts/InterDisplay-Bold.ttf and /dev/null differ diff --git a/crates/sf-launcher/ui/fonts/InterDisplay-ExtraBold.ttf b/crates/sf-launcher/ui/fonts/InterDisplay-ExtraBold.ttf deleted file mode 100644 index 4ad8a62..0000000 Binary files a/crates/sf-launcher/ui/fonts/InterDisplay-ExtraBold.ttf and /dev/null differ diff --git a/crates/sf-launcher/ui/icons.slint b/crates/sf-launcher/ui/icons.slint index c82d9c7..a3eca38 100644 --- a/crates/sf-launcher/ui/icons.slint +++ b/crates/sf-launcher/ui/icons.slint @@ -3,6 +3,59 @@ export component AppIcon inherits Rectangle { in property <string> icon; 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 { // 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 { Path { width: 100%; height: 100%; @@ -293,3 +346,273 @@ export component PowerIcon inherits Rectangle { 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; + } +} diff --git a/crates/sf-launcher/ui/keyboard.slint b/crates/sf-launcher/ui/keyboard.slint index 955f83e..cdea1e3 100644 --- a/crates/sf-launcher/ui/keyboard.slint +++ b/crates/sf-launcher/ui/keyboard.slint @@ -1,7 +1,7 @@ // On-screen keyboard in the tvOS style: one horizontal row of characters, // 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, // chips) comes from `keyboard::glass` in Rust, which mirrors the geometry the // 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-w; in property <length> pane-h; - in property <length> back-x; in property <length> field-x; in property <length> field-y; in property <length> field-w; @@ -50,24 +49,23 @@ export component KeyboardView inherits Rectangle { // ---- heading ---------------------------------------------------------- Text { x: root.pane-x; - y: root.pane-y + 58 * root.u; + y: root.pane-y + 88 * root.u; width: root.pane-w; horizontal-alignment: center; text: root.title; - font-family: "Inter Display"; - font-weight: 800; - font-size: 46 * root.u; - letter-spacing: -1.2 * root.u; + font-weight: 700; + font-size: 48 * root.u; + letter-spacing: -0.8 * root.u; color: #ffffff; overflow: elide; } Text { 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; horizontal-alignment: center; text: root.subtitle; - font-size: 23 * root.u; + font-size: 24 * root.u; color: #ffffffa8; overflow: elide; } @@ -114,12 +112,12 @@ export component KeyboardView inherits Rectangle { } Text { 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; horizontal-alignment: center; text: root.hint; - font-size: 21 * root.u; - color: root.hint-error ? #ff8278 : #ffffff8c; + font-size: 22 * root.u; + color: root.hint-error ? #ff8278 : #ffffff99; } // ---- key row --------------------------------------------------------------- @@ -175,16 +173,4 @@ export component KeyboardView inherits Rectangle { : 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; - } } diff --git a/crates/sf-launcher/ui/pairing.slint b/crates/sf-launcher/ui/pairing.slint index 3a04260..feacac8 100644 --- a/crates/sf-launcher/ui/pairing.slint +++ b/crates/sf-launcher/ui/pairing.slint @@ -1,6 +1,8 @@ // 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). +import { BackGlyph, TvGlyph, PlayPauseGlyph, MuteGlyph, PlusGlyph, MinusGlyph, PowerGlyph, CheckIcon, AlertIcon } from "icons.slint"; + // Pulsing ring that draws the eye to a button. component Pulse inherits Rectangle { in property <length> size; @@ -17,9 +19,12 @@ component Pulse inherits Rectangle { component RemoteButton inherits Rectangle { in property <length> u; + // back | tv | playpause | mute | plus in property <string> glyph; in property <bool> hot; 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; height: self.width; border-radius: self.width / 2; @@ -40,14 +45,11 @@ component RemoteButton inherits Rectangle { x: (parent.width - self.width) / 2; y: (parent.height - self.height) / 2; } - Text { - text: root.glyph; - color: root.hot ? root.accent.brighter(0.5) : #e8e8ea; - font-size: 24 * root.u; - font-weight: 600; - horizontal-alignment: center; - vertical-alignment: center; - } + 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; } + 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; } + 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; } + 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; } + 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; } } // Apple Siri Remote (2nd gen, aluminium), drawn front-on. @@ -57,7 +59,9 @@ export component SiriRemote inherits Rectangle { width: 150 * self.u; height: 560 * 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-color: #000000a0; drop-shadow-offset-y: 16 * self.u; @@ -79,12 +83,12 @@ export component SiriRemote inherits Rectangle { height: 18 * root.u; border-radius: self.width / 2; background: #1b1b1d; - Text { - text: "⏻"; - color: #d0d0d4; - font-size: 11 * root.u; - horizontal-alignment: center; - vertical-alignment: center; + PowerGlyph { + x: (parent.width - self.width) / 2; + y: (parent.height - self.height) / 2; + width: 12 * root.u; + height: 12 * root.u; + ink: #d0d0d4; } } // Clickpad: outer touch ring and center. @@ -118,10 +122,10 @@ export component SiriRemote inherits Rectangle { // Button grid below the clickpad. property <length> col1: 18 * 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.col2; y: 200 * root.u; glyph: "▭"; } - 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: 336 * root.u; glyph: "🔇"; } + 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: "tv"; } + 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: "mute"; } // Volume rocker: + is the one to hold. Rectangle { x: root.col2; @@ -135,19 +139,16 @@ export component SiriRemote inherits Rectangle { accent: root.accent; x: 0; y: 0; - glyph: "+"; + glyph: "plus"; hot: true; background: transparent; } - Text { - y: parent.height - 52 * root.u; - width: parent.width; - height: 52 * root.u; - text: "−"; - color: #e8e8ea; - font-size: 24 * root.u; - horizontal-alignment: center; - vertical-alignment: center; + MinusGlyph { + x: (parent.width - self.width) / 2; + y: parent.height - 52 * root.u + (52 * root.u - self.height) / 2; + width: 26 * root.u; + height: 26 * root.u; + ink: #e8e8ea; } } } @@ -157,81 +158,76 @@ component Step inherits Rectangle { in property <int> n; in property <string> label; in property <color> accent; - height: 70 * self.u; - Rectangle { + // The glass bead behind the number is drawn by the glass layer (app.slint), + // on the same 48 px square. + Text { x: 0; - y: 4 * root.u; - width: 40 * root.u; - height: self.width; - // The glass bead behind the number is drawn by the glass layer (app.slint). - Text { - text: root.n; - color: root.accent.brighter(0.6); - font-size: 20 * root.u; - font-weight: 700; - horizontal-alignment: center; - vertical-alignment: center; - } + y: 0; + width: 48 * root.u; + height: 48 * root.u; + text: root.n; + color: root.accent.brighter(0.6); + font-size: 22 * root.u; + font-weight: 700; + horizontal-alignment: center; + vertical-alignment: center; } Text { - x: 60 * root.u; - y: 10 * root.u; - width: parent.width - 60 * root.u; + x: 72 * root.u; + y: 6 * root.u; + width: parent.width - 72 * root.u; text: root.label; wrap: word-wrap; - font-size: 24 * root.u; - color: #ffffffd8; + font-size: 26 * root.u; + 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 { in property <length> u; in property <string> state; 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> broken: self.state == "no-adapter"; SiriRemote { u: root.u; accent: root.accent; - x: 120 * root.u; + x: (root.content-x - self.width) / 2; y: (parent.height - self.height) / 2; } Rectangle { - x: 420 * root.u; - y: 70 * root.u; - width: parent.width - 420 * root.u - 80 * root.u; - height: parent.height - 140 * root.u; + x: root.content-x; + y: root.content-y; + width: parent.width - root.content-x - 88 * root.u; + height: parent.height - root.content-y; Text { x: 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; text: "Párosítsd a Siri Remote-ot"; - wrap: word-wrap; - font-family: "Inter Display"; - font-weight: 800; - font-size: 58 * root.u; - letter-spacing: -1.6 * root.u; + font-weight: 700; + font-size: 52 * root.u; + letter-spacing: -1 * root.u; color: #ffffff; + overflow: elide; } Step { u: root.u; accent: root.accent; x: 0; - y: 150 * root.u; + y: root.steps[0]; width: parent.width; + height: 64 * root.u; n: 1; 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; accent: root.accent; x: 0; - y: 226 * root.u; + y: root.steps[1]; width: parent.width; + height: 100 * root.u; 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 { u: root.u; accent: root.accent; x: 0; - y: 330 * root.u; + y: root.steps[2]; width: parent.width; + height: 64 * root.u; n: 3; 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 { x: 0; - y: parent.height - 70 * root.u; + y: root.pill-y; width: 520 * 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 { - x: 26 * root.u; - width: 60 * root.u; + x: 0; + width: 56 * root.u; spacing: 8 * root.u; alignment: start; for i in 3: Rectangle { @@ -278,41 +275,47 @@ export component PairingGuide inherits Rectangle { opacity: 0.25 + 0.75 * abs(sin(self.p * 180deg)); } } - if root.ok || root.broken: Text { - x: 26 * root.u; - width: 40 * root.u; - height: parent.height; - text: root.ok ? "✓" : "!"; - color: root.ok ? #34c759 : #ff9f0a; - font-size: 30 * root.u; - font-weight: 800; - vertical-alignment: center; + if root.ok: CheckIcon { + x: 24 * root.u; + y: (parent.height - self.height) / 2; + width: 32 * root.u; + height: 32 * root.u; + ink: #34c759; + } + if root.broken: AlertIcon { + x: 24 * root.u; + y: (parent.height - self.height) / 2; + width: 32 * root.u; + height: 32 * root.u; + ink: #ff9f0a; } Text { - x: 92 * root.u; - width: parent.width - 110 * root.u; + x: root.ok || root.broken ? 72 * root.u : 64 * root.u; + width: parent.width - 96 * root.u; height: parent.height; vertical-alignment: center; font-size: 24 * root.u; font-weight: 500; 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.state == "pairing" ? "Párosítás…" : "Távirányító keresése…"; } } + // Skip chip (glass in app.slint, 200 x 64). Text { - x: 556 * root.u; - y: parent.height - 68 * root.u; - width: 204 * root.u; - height: 60 * root.u; + x: 544 * root.u; + y: root.pill-y; + width: 200 * root.u; + height: 64 * root.u; horizontal-alignment: center; vertical-alignment: center; - text: "Kihagyás · Esc"; - font-size: 21 * root.u; - font-weight: 500; - color: #ffffffc0; + text: "Kihagyás"; + font-size: 24 * root.u; + font-weight: 600; + color: #ffffffd0; } } } diff --git a/crates/sf-launcher/ui/settings.slint b/crates/sf-launcher/ui/settings.slint index c7fa3d5..9de1692 100644 --- a/crates/sf-launcher/ui/settings.slint +++ b/crates/sf-launcher/ui/settings.slint @@ -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 -// `settings_screen::glass` in Rust, which mirrors the geometry below: keep the -// row/nav formulas (position, focus `f`, visibility `vis`) in sync with it. +// Only text and icons are drawn here. The glass (platter, focus pills) comes +// from `settings_screen::glass` in Rust, which mirrors the geometry below: keep +// 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 { title: string, @@ -22,9 +23,14 @@ component NavIcon inherits Rectangle { in property <color> 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 == 2: WifiIcon { width: 100%; height: 100%; ink: root.ink; } - if root.index == 3: PowerIcon { width: 100%; height: 100%; ink: root.ink; } - if root.index == 4: InfoIcon { width: 100%; height: 100%; ink: root.ink; } + if root.index == 2: AudioIcon { width: 100%; height: 100%; ink: root.ink; } + if root.index == 3: WifiIcon { 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 { @@ -52,38 +58,47 @@ export component SettingsView inherits Rectangle { in property <string> subtitle; in property <[SettingRow]> rows; 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 ---------------------------------------------------- Text { - x: root.nav-x + 8 * root.u; - y: root.pane-y + 50 * root.u; - text: "Beállítások"; - font-family: "Inter Display"; - font-weight: 800; - font-size: 50 * root.u; - letter-spacing: -1.5 * root.u; + x: root.nav-x; + y: root.pane-y; + width: root.nav-w; + height: 88 * root.u; + vertical-alignment: center; + text: root.heading; + font-weight: 700; + font-size: 56 * root.u; + letter-spacing: -1 * root.u; color: #ffffff; } for name[i] in root.categories: Rectangle { 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 <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; y: root.nav-y + i * root.nav-step; width: root.nav-w; height: root.nav-h; NavIcon { - x: 28 * root.u; + x: 24 * root.u; y: (parent.height - self.height) / 2; - width: 34 * root.u; - height: 34 * root.u; - index: i; + width: 32 * root.u; + height: 32 * root.u; + index: i + root.icon-base; ink: parent.ink; } Text { - x: 82 * root.u; - width: parent.width - 100 * root.u; + x: 76 * root.u; + width: parent.width - 96 * root.u; height: parent.height; vertical-alignment: center; 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 --------------------------------------------------- Text { - x: root.rows-x + 8 * root.u; - y: root.pane-y + 44 * root.u; - width: root.rows-w - 16 * root.u; + x: root.rows-x + root.inset + root.pad; + y: root.nav-y; + width: root.rows-w - 2 * (root.inset + root.pad); + height: root.nav-h; + vertical-alignment: center; text: root.title; - font-family: "Inter Display"; - font-weight: 800; + font-weight: 700; font-size: 40 * root.u; - letter-spacing: -1 * root.u; color: #ffffff; overflow: elide; } Text { - x: root.rows-x + 8 * root.u; - y: root.pane-y + 102 * root.u; - width: root.rows-w - 16 * root.u; - height: 64 * root.u; + x: root.rows-x + root.inset + root.pad; + y: root.nav-y + root.nav-h; + width: root.rows-w - 2 * (root.inset + root.pad); + height: root.rows-y - root.nav-y - root.nav-h - 24 * root.u; text: root.subtitle; wrap: word-wrap; overflow: elide; - font-size: 21 * root.u; + font-size: 24 * root.u; color: #ffffffa8; } for row[j] in root.rows: r := Rectangle { 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 <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); @@ -143,17 +147,25 @@ export component SettingsView inherits Rectangle { property <color> ink-dim: self.hot ? (self.danger ? #ffffffd0 : #121317b0) : #ffffff99; property <bool> chevron: row.kind == "choice" || row.kind == "device"; property <bool> network: row.kind == "network"; - x: root.rows-x; + x: root.rows-x + root.inset; y: self.top; - width: root.rows-w; + width: root.rows-w - 2 * root.inset; height: root.row-h; opacity: self.vis; 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 { - x: 30 * root.u; - y: row.detail == "" ? (parent.height - self.height) / 2 : 15 * root.u; - width: parent.width * 0.55; + x: root.pad; + y: row.detail == "" ? (parent.height - self.height) / 2 : 14 * root.u; + width: parent.width * 0.56; text: row.title; font-size: 26 * root.u; font-weight: 600; @@ -161,45 +173,43 @@ export component SettingsView inherits Rectangle { overflow: elide; } if row.detail != "": Text { - x: 30 * root.u; - y: 51 * root.u; - width: parent.width * 0.55; + x: root.pad; + y: 50 * root.u; + width: parent.width * 0.56; text: row.detail; - font-size: 19 * root.u; + font-size: 21 * root.u; color: r.ink-dim; overflow: elide; } Text { 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; horizontal-alignment: right; vertical-alignment: center; 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; color: row.kind == "option" ? (r.hot ? #121317 : #ff9a5c) : r.ink-dim; overflow: elide; } - if r.chevron: Text { - x: parent.width - 50 * root.u; + if r.chevron: ChevronIcon { + x: parent.width - root.pad - self.width + 4 * root.u; + y: (parent.height - self.height) / 2; width: 24 * root.u; - height: parent.height; - vertical-alignment: center; - text: "›"; - font-size: 36 * root.u; - color: r.ink-dim; + height: 24 * root.u; + ink: r.ink-dim; } // Wi-Fi network: lock (protected) and signal strength on the right. 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; width: 24 * root.u; height: 24 * root.u; ink: r.ink-dim; } if r.network: SignalIcon { - x: parent.width - 66 * root.u; + x: parent.width - root.pad - self.width; y: (parent.height - self.height) / 2; width: 34 * root.u; height: 34 * root.u; diff --git a/crates/sf-miracast/Cargo.toml b/crates/sf-miracast/Cargo.toml new file mode 100644 index 0000000..e5b212b --- /dev/null +++ b/crates/sf-miracast/Cargo.toml @@ -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"] } diff --git a/crates/sf-miracast/src/linux.rs b/crates/sf-miracast/src/linux.rs new file mode 100644 index 0000000..14116b2 --- /dev/null +++ b/crates/sf-miracast/src/linux.rs @@ -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)") +} diff --git a/crates/sf-miracast/src/main.rs b/crates/sf-miracast/src/main.rs new file mode 100644 index 0000000..89c0832 --- /dev/null +++ b/crates/sf-miracast/src/main.rs @@ -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)") + } +} diff --git a/crates/sf-miracast/src/rtsp.rs b/crates/sf-miracast/src/rtsp.rs new file mode 100644 index 0000000..862070d --- /dev/null +++ b/crates/sf-miracast/src/rtsp.rs @@ -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]); + } +} diff --git a/crates/sf-pack/Cargo.toml b/crates/sf-pack/Cargo.toml new file mode 100644 index 0000000..cb0595e --- /dev/null +++ b/crates/sf-pack/Cargo.toml @@ -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" diff --git a/crates/sf-pack/src/main.rs b/crates/sf-pack/src/main.rs new file mode 100644 index 0000000..39c0de1 --- /dev/null +++ b/crates/sf-pack/src/main.rs @@ -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)); +} diff --git a/crates/sf-remote/Cargo.toml b/crates/sf-remote/Cargo.toml index 32ef99e..5f7b718 100644 --- a/crates/sf-remote/Cargo.toml +++ b/crates/sf-remote/Cargo.toml @@ -1,6 +1,6 @@ [package] 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 edition.workspace = true license.workspace = true diff --git a/crates/sf-remote/src/keyboard.rs b/crates/sf-remote/src/keyboard.rs index 9148abd..53248da 100644 --- a/crates/sf-remote/src/keyboard.rs +++ b/crates/sf-remote/src/keyboard.rs @@ -13,7 +13,7 @@ use evdev::{EventType, KeyCode}; use crate::link::Link; 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) { std::thread::spawn(move || { diff --git a/crates/sf-remote/src/linux.rs b/crates/sf-remote/src/linux.rs index b23b7a9..3336a8d 100644 --- a/crates/sf-remote/src/linux.rs +++ b/crates/sf-remote/src/linux.rs @@ -99,7 +99,7 @@ impl Keys { keys.insert(KeyCode::KEY_PAUSECD); let dev = VirtualDevice::builder() .context("opening /dev/uinput (is the user in the smartfox group?)")? - .name("SmartFox Siri Remote") + .name("Fennec OS Siri Remote") .with_keys(&keys)? .build()?; 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. 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 gestures = Gestures::new(step); 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 last_repeat = Instant::now(); let mut tick = tokio::time::interval(Duration::from_millis(20)); + let mut connection_check = tokio::time::interval(Duration::from_secs(2)); loop { 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() => { let Some(data) = item else { return Ok(()) }; 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 -/// accept list only knows its identity address, so BlueZ's passive -/// auto-connect never sees it. An active scan lets the kernel resolve the -/// address with the bonded IRK; we connect as soon as an advert arrives. -async fn wait_for_advert(adapter: &Adapter, dev: &Device) -> Result<()> { +/// The remote advertises with a rotating private address. Keep discovery +/// active while connecting so BlueZ can resolve that address with the bonded +/// IRK. Also retry without an RSSI event: some controllers do not report one +/// for an already known device after the remote restarts. +async fn connect(adapter: &Adapter, dev: &Device) -> Result<bool> { use bluer::{DeviceEvent, DeviceProperty, DiscoveryFilter, DiscoveryTransport}; + if dev.is_connected().await.unwrap_or(false) { + return Ok(true); + } adapter .set_discovery_filter(DiscoveryFilter { transport: DiscoveryTransport::Le, @@ -335,30 +352,48 @@ async fn wait_for_advert(adapter: &Adapter, dev: &Device) -> Result<()> { .await?; let mut discovery = adapter.discover_devices_with_changes().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 { - tokio::select! { - // A connection may come up between our checks (e.g. a pending Connect()). - _ = 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()); - } - } + let should_connect = tokio::select! { + _ = retry.tick() => true, ev = events.next() => match ev { Some(DeviceEvent::PropertyChanged(DeviceProperty::Rssi(rssi))) => { log::info!("remote advertising (rssi {rssi}), connecting"); - return Ok(()); + true } - Some(DeviceEvent::PropertyChanged(DeviceProperty::Connected(true))) => return Ok(()), - Some(_) => {} + Some(DeviceEvent::PropertyChanged(DeviceProperty::Connected(true))) => return Ok(true), + Some(_) => false, None => anyhow::bail!("device event stream ended"), }, // Keep the discovery session alive and drained. - _ = 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<()> { let opts = parse_args(); let link = Link::new(opts.home_socket.clone()); diff --git a/crates/sf-remote/src/main.rs b/crates/sf-remote/src/main.rs index d5cab75..21e7803 100644 --- a/crates/sf-remote/src/main.rs +++ b/crates/sf-remote/src/main.rs @@ -1,6 +1,6 @@ #![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 //! (BlueZ's own HID plugin must be disabled, it drops these reports) and diff --git a/crates/sf-remote/src/wake.rs b/crates/sf-remote/src/wake.rs index dbabcda..b467923 100644 --- a/crates/sf-remote/src/wake.rs +++ b/crates/sf-remote/src/wake.rs @@ -5,7 +5,7 @@ //! on its USB device and the ports above it. //! 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. -//! 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 //! commands ourselves: Add Device (auto-connect) and Set Device Flags. //! diff --git a/crates/sf-ui/Cargo.toml b/crates/sf-ui/Cargo.toml new file mode 100644 index 0000000..0c8c162 --- /dev/null +++ b/crates/sf-ui/Cargo.toml @@ -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 } diff --git a/crates/sf-ui/build.rs b/crates/sf-ui/build.rs new file mode 100644 index 0000000..c52ddd8 --- /dev/null +++ b/crates/sf-ui/build.rs @@ -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"); +} diff --git a/crates/sf-ui/gallery/Cargo.toml b/crates/sf-ui/gallery/Cargo.toml new file mode 100644 index 0000000..3048076 --- /dev/null +++ b/crates/sf-ui/gallery/Cargo.toml @@ -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" diff --git a/crates/sf-ui/gallery/build.rs b/crates/sf-ui/gallery/build.rs new file mode 100644 index 0000000..7fba5c9 --- /dev/null +++ b/crates/sf-ui/gallery/build.rs @@ -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"); +} diff --git a/crates/sf-ui/gallery/src/main.rs b/crates/sf-ui/gallery/src/main.rs new file mode 100644 index 0000000..7ae883a --- /dev/null +++ b/crates/sf-ui/gallery/src/main.rs @@ -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(()) +} diff --git a/crates/sf-ui/gallery/ui/gallery.slint b/crates/sf-ui/gallery/ui/gallery.slint new file mode 100644 index 0000000..3fb1ac3 --- /dev/null +++ b/crates/sf-ui/gallery/ui/gallery.slint @@ -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; +} diff --git a/crates/sf-ui/src/dev.rs b/crates/sf-ui/src/dev.rs new file mode 100644 index 0000000..3429b7f --- /dev/null +++ b/crates/sf-ui/src/dev.rs @@ -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(()) +} diff --git a/crates/sf-ui/src/glass.rs b/crates/sf-ui/src/glass.rs new file mode 100644 index 0000000..9bf591e --- /dev/null +++ b/crates/sf-ui/src/glass.rs @@ -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; + } + } + } + } +} diff --git a/crates/sf-ui/src/images.rs b/crates/sf-ui/src/images.rs new file mode 100644 index 0000000..391d7c3 --- /dev/null +++ b/crates/sf-ui/src/images.rs @@ -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); + } +} diff --git a/crates/sf-ui/src/lib.rs b/crates/sf-ui/src/lib.rs new file mode 100644 index 0000000..fcbddcf --- /dev/null +++ b/crates/sf-ui/src/lib.rs @@ -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)); + } +} diff --git a/crates/sf-ui/src/render/mod.rs b/crates/sf-ui/src/render/mod.rs new file mode 100644 index 0000000..ab929e2 --- /dev/null +++ b/crates/sf-ui/src/render/mod.rs @@ -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, + } + } +} diff --git a/crates/sf-launcher/src/glass/renderer.rs b/crates/sf-ui/src/render/renderer.rs similarity index 53% rename from crates/sf-launcher/src/glass/renderer.rs rename to crates/sf-ui/src/render/renderer.rs index 370487e..2114a21 100644 --- a/crates/sf-launcher/src/glass/renderer.rs +++ b/crates/sf-ui/src/render/renderer.rs @@ -1,14 +1,18 @@ //! OpenGL underlay drawn before Slint renders its items. //! -//! Pass 1 renders the backdrop (a smooth gradient) into a small, mipmapped -//! texture. Pass 2 upscales it to the window. Pass 3 draws every glass panel -//! as its own quad, covering only the panel and its shadow, blended onto the -//! window. Uniform locations are looked up once. +//! Pass 1 renders the backdrop (gradient, then pictures, then video) into a +//! small, mipmapped texture: that is what the glass refracts and frosts. +//! Pass 2 puts the backdrop on the window: the small texture upscaled, then +//! sharp pictures and the video at full resolution. Pass 3 draws every glass +//! panel as its own quad, covering only the panel and its shadow. Uniform +//! locations are looked up once; GL state is handed back to Slint untouched. + +use std::collections::HashMap; use glow::HasContext; use super::shaders; -use super::{Frame, 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. const SCENE_MAX_W: i32 = 640; @@ -20,7 +24,7 @@ struct SceneLocs { time: Loc, pal: Loc, zoom: Loc, - shelf: Loc, + bright: Loc, } struct BlitLocs { @@ -28,6 +32,27 @@ struct BlitLocs { time: Loc, } +struct ImageLocs { + image: Loc, + img: Loc, + res: Loc, + align: Loc, + dim: Loc, + fade_left: Loc, + fade_bottom: Loc, + alpha: Loc, +} + +struct VideoLocs { + y: Loc, + uv: Loc, + res: Loc, + aspect: Loc, + matrix: Loc, + full: Loc, + alpha: Loc, +} + struct GlassLocs { box_: Loc, res: Loc, @@ -40,6 +65,24 @@ struct GlassLocs { param: Loc, glow: Loc, tint: Loc, + mode: Loc, +} + +struct Image { + tex: glow::Texture, + w: i32, + h: i32, +} + +/// The last uploaded video frame. +struct Video { + y: glow::Texture, + uv: glow::Texture, + size: (i32, i32), + aspect: f32, + matrix: Matrix, + full: bool, + ready: bool, } pub struct GlassRenderer { @@ -47,15 +90,22 @@ pub struct GlassRenderer { vao: glow::VertexArray, scene_prog: glow::Program, blit_prog: glow::Program, + image_prog: glow::Program, + video_prog: glow::Program, glass_prog: glow::Program, scene_locs: SceneLocs, blit_locs: BlitLocs, + image_locs: ImageLocs, + video_locs: VideoLocs, glass_locs: GlassLocs, fbo: glow::Framebuffer, tex: glow::Texture, tex_size: (i32, i32), /// RGBA16F if the driver can render to it (no banding in dark gradients). half_float: bool, + images: HashMap<u32, Image>, + next_image: u32, + video: Option<Video>, } /// GL state we touch and must hand back to the Slint renderer untouched. @@ -66,6 +116,7 @@ struct SavedState { framebuffer: i32, active_texture: i32, texture0: i32, + texture1: i32, viewport: [i32; 4], blend: bool, blend_func: [i32; 4], @@ -74,6 +125,8 @@ struct SavedState { depth: bool, stencil: bool, cull: bool, + unpack_alignment: i32, + unpack_row_length: i32, } impl GlassRenderer { @@ -92,6 +145,8 @@ impl GlassRenderer { let scene_prog = link(&gl, header, shaders::VERTEX, shaders::SCENE)?; 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 loc = |p: glow::Program, name: &str| gl.get_uniform_location(p, name); let scene_locs = SceneLocs { @@ -99,9 +154,28 @@ impl GlassRenderer { time: loc(scene_prog, "uTime"), pal: loc(scene_prog, "uPal"), 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 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 { box_: loc(glass_prog, "uBox"), res: loc(glass_prog, "uRes"), @@ -114,6 +188,7 @@ impl GlassRenderer { param: loc(glass_prog, "uParam"), glow: loc(glass_prog, "uGlow"), tint: loc(glass_prog, "uTint"), + mode: loc(glass_prog, "uMode"), }; let vao = gl.create_vertex_array().map_err(anyhow::Error::msg)?; let fbo = gl.create_framebuffer().map_err(anyhow::Error::msg)?; @@ -124,14 +199,21 @@ impl GlassRenderer { vao, scene_prog, blit_prog, + image_prog, + video_prog, glass_prog, scene_locs, blit_locs, + image_locs, + video_locs, glass_locs, fbo, tex, tex_size: (0, 0), half_float: true, + images: HashMap::new(), + next_image: 1, + video: None, }) } } @@ -142,6 +224,8 @@ impl GlassRenderer { let mut viewport = [0; 4]; gl.get_parameter_i32_slice(glow::VIEWPORT, &mut viewport); let active_texture = gl.get_parameter_i32(glow::ACTIVE_TEXTURE); + gl.active_texture(glow::TEXTURE1); + let texture1 = gl.get_parameter_i32(glow::TEXTURE_BINDING_2D); gl.active_texture(glow::TEXTURE0); SavedState { program: gl.get_parameter_i32(glow::CURRENT_PROGRAM), @@ -150,6 +234,7 @@ impl GlassRenderer { framebuffer: gl.get_parameter_i32(glow::FRAMEBUFFER_BINDING), active_texture, texture0: gl.get_parameter_i32(glow::TEXTURE_BINDING_2D), + texture1, viewport, blend: gl.is_enabled(glow::BLEND), blend_func: [ @@ -166,6 +251,8 @@ impl GlassRenderer { depth: gl.is_enabled(glow::DEPTH_TEST), stencil: gl.is_enabled(glow::STENCIL_TEST), 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_buffer(glow::ARRAY_BUFFER, nz(s.array_buffer).map(glow::NativeBuffer)); gl.bind_framebuffer(glow::FRAMEBUFFER, nz(s.framebuffer).map(glow::NativeFramebuffer)); + gl.active_texture(glow::TEXTURE1); + gl.bind_texture(glow::TEXTURE_2D, nz(s.texture1).map(glow::NativeTexture)); gl.active_texture(glow::TEXTURE0); gl.bind_texture(glow::TEXTURE_2D, nz(s.texture0).map(glow::NativeTexture)); gl.active_texture(s.active_texture as u32); @@ -191,6 +280,8 @@ impl GlassRenderer { set(glow::DEPTH_TEST, s.depth); set(glow::STENCIL_TEST, s.stencil); 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, glow::PixelUnpackData::Slice(None), ); - gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_MIN_FILTER, glow::LINEAR_MIPMAP_LINEAR as i32); - gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_MAG_FILTER, glow::LINEAR as i32); - gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_WRAP_S, glow::CLAMP_TO_EDGE as i32); - gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_WRAP_T, glow::CLAMP_TO_EDGE as i32); + set_filter(gl, true); gl.generate_mipmap(glow::TEXTURE_2D); gl.bind_framebuffer(glow::FRAMEBUFFER, Some(self.fbo)); gl.framebuffer_texture_2d(glow::FRAMEBUFFER, glow::COLOR_ATTACHMENT0, glow::TEXTURE_2D, Some(self.tex), 0); @@ -238,6 +326,165 @@ impl GlassRenderer { 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 /// Must be called from the Slint rendering notifier with the context current. pub unsafe fn render(&mut self, f: &Frame) { @@ -253,9 +500,20 @@ impl GlassRenderer { gl.disable(glow::DEPTH_TEST); gl.disable(glow::STENCIL_TEST); 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)); - // 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 sh = ((sw as i64 * h as i64 / w as i64) as i32).max(1); self.ensure_target(sw, sh); @@ -268,13 +526,16 @@ impl GlassRenderer { gl.uniform_1_f32(l.time.as_ref(), f.time); gl.uniform_3_f32_slice(l.pal.as_ref(), &f.palette); gl.uniform_1_f32(l.zoom.as_ref(), f.zoom); - gl.uniform_1_f32(l.shelf.as_ref(), f.shelf); + gl.uniform_1_f32(l.bright.as_ref(), f.brightness); 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.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( glow::FRAMEBUFFER, 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_f32(l.time.as_ref(), f.time); 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. + let gl = &self.gl; + gl.active_texture(glow::TEXTURE0); + gl.bind_texture(glow::TEXTURE_2D, Some(self.tex)); gl.enable(glow::BLEND); gl.blend_equation_separate(glow::FUNC_ADD, glow::FUNC_ADD); gl.blend_func_separate(glow::ONE, glow::SRC_ALPHA, glow::ZERO, glow::ONE); @@ -297,6 +562,12 @@ impl GlassRenderer { gl.uniform_1_f32(l.scale.as_ref(), f.scale); gl.uniform_1_f32(l.time.as_ref(), f.time); gl.uniform_2_f32(l.light.as_ref(), f.light[0], f.light[1]); + let 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 mut rect = [0f32; MAX_GROUP * 4]; @@ -370,8 +641,17 @@ impl GlassRenderer { /// Must be called with the context current. pub unsafe fn destroy(&mut self) { 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.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_vertex_array(self.vao); 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 /// (> 0) melt together and are drawn as one; the rest are drawn alone. 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) } } + +#[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]); + } +} diff --git a/crates/sf-launcher/src/glass/shaders.rs b/crates/sf-ui/src/render/shaders.rs similarity index 81% rename from crates/sf-launcher/src/glass/shaders.rs rename to crates/sf-ui/src/render/shaders.rs index fa67d00..e6778a6 100644 --- a/crates/sf-launcher/src/glass/shaders.rs +++ b/crates/sf-ui/src/render/shaders.rs @@ -35,7 +35,7 @@ uniform vec2 uRes; uniform float uTime; uniform vec3 uPal[3]; // highlight, mid, deep uniform float uZoom; // launch fly-in -uniform float uShelf; // 1 = top shelf showing, 0 = scrolled into the grid +uniform float uBright; // backdrop brightness: 1 = full, lower = calmer (launcher: shelf hidden) float field(vec2 d, float r) { return exp(-dot(d, d) / (r * r)); @@ -83,9 +83,9 @@ void main() { // Soft shoulder so bright palettes stay "dark mode". col = col / (1.0 + col * 1.2); - // Calmer at the bottom where the icons sit; dimmer when the shelf is gone. + // 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(0.42, 1.0, uShelf); + col *= mix(0.42, 1.0, uBright); vec2 v = uv - 0.5; 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 /// 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 uGlow[MAX_GROUP]; // accent rgb, unused 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) { 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. float A = 0.0; vec3 B; - if (nested) { + if (nested || uMode == 2) { A = 1.0; B = vec3(0.0); + } else if (uMode == 1) { + B = sceneAt(p / uRes, lod); } else if (slope > 0.02) { // Bevel: refract each channel with its own IOR (dispersion). B.r = sceneAt((p + refractOffset(N, height, 1.46) * lens + mag) / uRes, lod).r; @@ -344,7 +431,7 @@ void main() { // Fresnel: steep bevel reflects the (blurred, brightened) surroundings. float cosT = clamp(N.z, 0.0, 1.0); float F = 0.04 + 0.96 * pow(1.0 - cosT, 5.0); - float Fm = clamp(F, 0.0, 1.0) * 0.35 * mat; + 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); A *= 1.0 - Fm; B = mix(B, env, Fm); diff --git a/crates/sf-ui/src/text.rs b/crates/sf-ui/src/text.rs new file mode 100644 index 0000000..0ca3223 --- /dev/null +++ b/crates/sf-ui/src/text.rs @@ -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("Ő"), "Ő"); + } +} diff --git a/crates/sf-ui/src/video.rs b/crates/sf-ui/src/video.rs new file mode 100644 index 0000000..0f825b9 --- /dev/null +++ b/crates/sf-ui/src/video.rs @@ -0,0 +1,483 @@ +//! Video playback with GStreamer, shown through the glass layer: the film is +//! the backdrop, so glass controls on top refract it. +//! +//! - Hardware decoding (VA-API: H.264, HEVC incl. 10-bit, VP9, AV1) when the +//! app has the `gpu` permission; FFmpeg software decoders otherwise. +//! - `vapostproc` converts on the GPU and tone-maps HDR to SDR. +//! - Every audio and subtitle track of the file (MKV, MP4, TS...), with +//! embedded ASS/SRT subtitles rendered by GStreamer. +//! - HTTP(S) streams with range seeking (a server streaming a file while it +//! downloads works). +//! +//! ```ignore +//! sf_ui::video::init()?; +//! let player = Player::new("https://example.com/film.mkv", PlayerOptions { start: 754.0, ..Default::default() })?; +//! glass.set_video(Some(player.video())); +//! // every ~100 ms on the UI thread (slint::Timer): +//! for event in player.poll() { /* Ready, Buffering, Eos, Error... */ } +//! ``` +//! +//! Needs GStreamer 1.22+ on the system (the SmartFox TV has it): base, good, +//! bad (va, assrender), libav, and pipewire for sound. Apps need the `gpu` +//! and `audio` permissions, and `network` for streams. + +use std::rc::Rc; +use std::sync::{Arc, Mutex}; + +use anyhow::{Context, Result}; +use gstreamer as gst; +use gstreamer::glib; +use gstreamer::prelude::*; +use gstreamer_app as gst_app; +use gstreamer_video as gst_video; +use gstreamer_video::prelude::*; + +use crate::glass::VideoSource; +use crate::render::{Matrix, Nv12Frame}; + +/// VA-API decoders, preferred over the software ones when present. +const HW_DECODERS: [&str; 6] = ["vah264dec", "vah265dec", "vavp9dec", "vaav1dec", "vavp8dec", "vampeg2dec"]; + +/// Initialises GStreamer once and ranks the hardware decoders first. +pub fn init() -> Result<()> { + gst::init().context("initialising GStreamer")?; + let registry = gst::Registry::get(); + for name in HW_DECODERS { + if let Some(feature) = registry.lookup_feature(name) { + feature.set_rank(gst::Rank::PRIMARY + 1); + } + } + Ok(()) +} + +/// Whether hardware video decoding is available (diagnostics). +pub fn hardware_decoding() -> bool { + let registry = gst::Registry::get(); + HW_DECODERS.iter().any(|n| registry.lookup_feature(n).is_some()) +} + +#[derive(Debug, Clone)] +pub struct PlayerOptions { + /// Start position in seconds. + pub start: f64, + /// Audio sync correction in milliseconds (positive: audio later). + pub audio_offset_ms: i64, + /// Show subtitles (the default track, see [`Player::set_text`]). + pub subtitles: bool, + /// HTTP user agent for streams. + pub user_agent: Option<String>, + /// Pango font for text subtitles (scaled with the video). + pub subtitle_font: String, +} + +impl Default for PlayerOptions { + fn default() -> Self { + PlayerOptions { + start: 0.0, + audio_offset_ms: 0, + subtitles: true, + user_agent: None, + subtitle_font: "Sans Bold 20".into(), + } + } +} + +/// What happened since the last [`Player::poll`]. +#[derive(Debug, Clone, PartialEq)] +pub enum Event { + /// The stream is open (first frame ready): duration (s, if known) and + /// the tracks can be read now. Playback starts right after. + Ready { duration: Option<f64> }, + /// Network buffering, percent (100 = done; playback pauses meanwhile). + Buffering(i32), + /// Playing or paused (as asked, or because of buffering). + Playing(bool), + /// A seek finished. + Seeked, + /// The end of the stream. + Eos, + /// A fatal error; the player stops. + Error(String), +} + +/// One audio or subtitle track of the stream. +#[derive(Debug, Clone, Default, PartialEq)] +pub struct Track { + /// Index for [`Player::set_audio`] / [`Player::set_text`]. + pub index: i32, + /// ISO 639 code ("hu", "en", "hun"...), if tagged. + pub language: Option<String>, + /// The track's title in the file ("Commentary", "Forced"...). + pub title: Option<String>, + pub codec: Option<String>, +} + +/// The newest decoded frame, shared with the appsink thread. +#[derive(Default)] +struct Feed { + latest: Mutex<Option<gst::Sample>>, +} + +struct FeedSource(Arc<Feed>); + +struct GstFrame { + frame: gst_video::VideoFrame<gst_video::video_frame::Readable>, + aspect: f32, + matrix: Matrix, + full: bool, +} + +impl Nv12Frame for GstFrame { + fn width(&self) -> u32 { + self.frame.width() + } + fn height(&self) -> u32 { + self.frame.height() + } + fn aspect(&self) -> f32 { + self.aspect + } + fn plane(&self, index: usize) -> (&[u8], usize) { + let data = self.frame.plane_data(index as u32).unwrap_or(&[]); + let stride = self.frame.plane_stride().get(index).copied().unwrap_or(0).max(0) as usize; + (data, stride) + } + fn matrix(&self) -> Matrix { + self.matrix + } + fn full_range(&self) -> bool { + self.full + } +} + +impl VideoSource for FeedSource { + fn take_frame(&self) -> Option<Box<dyn Nv12Frame + '_>> { + let sample = self.0.latest.lock().unwrap().take()?; + let info = gst_video::VideoInfo::from_caps(sample.caps()?).ok()?; + if info.format() != gst_video::VideoFormat::Nv12 { + return None; + } + let par = info.par(); + let aspect = info.width() as f32 * par.numer() as f32 / (info.height().max(1) as f32 * par.denom().max(1) as f32); + let colorimetry = info.colorimetry(); + let matrix = match colorimetry.matrix() { + gst_video::VideoColorMatrix::Bt601 | gst_video::VideoColorMatrix::Smpte240m => Matrix::Bt601, + gst_video::VideoColorMatrix::Bt2020 => Matrix::Bt2020, + gst_video::VideoColorMatrix::Bt709 => Matrix::Bt709, + _ if info.height() < 720 => Matrix::Bt601, + _ => Matrix::Bt709, + }; + let full = colorimetry.range() == gst_video::VideoColorRange::Range0_255; + let buffer = sample.buffer_owned()?; + let frame = gst_video::VideoFrame::from_buffer_readable(buffer, &info).ok()?; + Some(Box::new(GstFrame { frame, aspect, matrix, full })) + } +} + +/// A playing stream. Dropping it stops playback. +pub struct Player { + playbin: gst::Element, + bus: gst::Bus, + feed: Arc<Feed>, + start: f64, + /// Playing was asked for (buffering may hold it paused). + want_playing: bool, + buffering: bool, + ready: bool, + seeking: bool, + failed: bool, +} + +impl Player { + /// Opens `uri` (https://, http://, file://) and starts playing as soon + /// as it can. Call [`init`] once before. + pub fn new(uri: &str, opts: PlayerOptions) -> Result<Player> { + let feed = Arc::new(Feed::default()); + + let caps = gst_video::VideoCapsBuilder::new().format(gst_video::VideoFormat::Nv12).build(); + let sink = gst_app::AppSink::builder().caps(&caps).sync(true).max_buffers(2).drop(true).build(); + sink.set_property("enable-last-sample", false); + let shared = feed.clone(); + sink.set_callbacks( + gst_app::AppSinkCallbacks::builder() + .new_sample(move |s| { + let sample = s.pull_sample().map_err(|_| gst::FlowError::Eos)?; + *shared.latest.lock().unwrap() = Some(sample); + Ok(gst::FlowSuccess::Ok) + }) + .build(), + ); + + let playbin = gst::ElementFactory::make("playbin") + .property("uri", uri) + .property("video-sink", &sink) + .build() + .context("GStreamer playbin is missing (gstreamer1.0-plugins-base)")?; + + // GPU colour conversion and HDR tone mapping, before the subtitle + // overlay (which needs system memory) and the sink. + if gst::ElementFactory::find("vapostproc").is_some() { + match gst::parse::bin_from_description("vapostproc name=pp ! video/x-raw,format=NV12", true) { + Ok(bin) => { + if let Some(pp) = bin.by_name("pp") { + if pp.find_property("hdr-tone-mapping").is_some() { + pp.set_property("hdr-tone-mapping", true); + } + } + playbin.set_property("video-filter", &bin); + } + Err(e) => log::warn!("video: vapostproc: {e}"), + } + } + if let Some(audio) = ["pulsesink", "pipewiresink"] + .iter() + .find_map(|n| gst::ElementFactory::make(n).build().ok()) + { + playbin.set_property("audio-sink", &audio); + } + playbin.set_property("subtitle-font-desc", opts.subtitle_font.as_str()); + playbin.set_property("av-offset", opts.audio_offset_ms * 1_000_000); + // A few seconds of network buffer: smooth over a torrent that delivers in bursts. + playbin.set_property("buffer-duration", 8i64 * 1_000_000_000); + if !opts.subtitles { + set_flag(&playbin, "text", false); + } + if let Some(ua) = opts.user_agent.clone() { + playbin.connect("source-setup", false, move |args| { + if let Some(src) = args.get(1).and_then(|v| v.get::<gst::Element>().ok()) { + if src.find_property("user-agent").is_some() { + src.set_property("user-agent", ua.as_str()); + } + } + None + }); + } + + let bus = playbin.bus().context("playbin has no bus")?; + playbin.set_state(gst::State::Paused).context("opening the stream")?; + Ok(Player { + playbin, + bus, + feed, + start: opts.start.max(0.0), + want_playing: true, + buffering: false, + ready: false, + seeking: false, + failed: false, + }) + } + + /// The frame source for [`crate::Glass::set_video`]. + pub fn video(&self) -> Rc<dyn VideoSource> { + Rc::new(FeedSource(self.feed.clone())) + } + + /// Handles what GStreamer reported since the last call. Call it often + /// (every 50–200 ms) on the UI thread; it also drives buffering and the + /// start position. + pub fn poll(&mut self) -> Vec<Event> { + let mut out = Vec::new(); + while let Some(msg) = self.bus.pop() { + use gst::MessageView; + match msg.view() { + MessageView::Eos(_) => out.push(Event::Eos), + MessageView::Error(e) => { + let text = match e.debug() { + Some(d) => format!("{} ({d})", e.error()), + None => e.error().to_string(), + }; + log::warn!("video: {text}"); + self.failed = true; + let _ = self.playbin.set_state(gst::State::Null); + out.push(Event::Error(e.error().to_string())); + } + MessageView::Buffering(b) => { + let pct = b.percent(); + out.push(Event::Buffering(pct)); + if pct < 100 && !self.buffering { + self.buffering = true; + if self.ready && self.want_playing { + let _ = self.playbin.set_state(gst::State::Paused); + } + } else if pct >= 100 && self.buffering { + self.buffering = false; + if self.ready && self.want_playing { + let _ = self.playbin.set_state(gst::State::Playing); + } + } + } + MessageView::AsyncDone(_) => { + if !self.ready { + if self.start > 0.5 { + // First preroll: jump to the start position, then play. + let at = gst::ClockTime::from_nseconds((self.start * 1e9) as u64); + self.start = 0.0; + if self.playbin.seek_simple(gst::SeekFlags::FLUSH | gst::SeekFlags::KEY_UNIT, at).is_ok() { + continue; + } + } + self.ready = true; + out.push(Event::Ready { duration: self.duration() }); + if self.want_playing && !self.buffering { + let _ = self.playbin.set_state(gst::State::Playing); + } + } else if self.seeking { + self.seeking = false; + out.push(Event::Seeked); + } + } + MessageView::StateChanged(s) => { + if s.src().is_some_and(|src| src == &self.playbin) { + match s.current() { + gst::State::Playing => out.push(Event::Playing(true)), + gst::State::Paused if s.old() == gst::State::Playing => out.push(Event::Playing(false)), + _ => {} + } + } + } + _ => {} + } + } + out + } + + pub fn play(&mut self) { + self.want_playing = true; + if self.ready && !self.buffering && !self.failed { + let _ = self.playbin.set_state(gst::State::Playing); + } + } + + pub fn pause(&mut self) { + self.want_playing = false; + if !self.failed { + let _ = self.playbin.set_state(gst::State::Paused); + } + } + + /// Play/pause; returns whether it plays now. + pub fn toggle(&mut self) -> bool { + if self.want_playing { + self.pause(); + } else { + self.play(); + } + self.want_playing + } + + /// Playing was asked for (it may still wait for the network). + pub fn is_playing(&self) -> bool { + self.want_playing + } + + pub fn is_ready(&self) -> bool { + self.ready + } + + pub fn is_buffering(&self) -> bool { + self.buffering || self.seeking || !self.ready + } + + /// Current position in seconds. + pub fn position(&self) -> Option<f64> { + self.playbin.query_position::<gst::ClockTime>().map(|t| t.nseconds() as f64 / 1e9) + } + + /// Duration in seconds, when the stream knows it. + pub fn duration(&self) -> Option<f64> { + self.playbin.query_duration::<gst::ClockTime>().map(|t| t.nseconds() as f64 / 1e9).filter(|d| *d > 0.0) + } + + /// Jumps to `seconds`. `exact` decodes up to that very frame (slower); + /// otherwise it lands on the nearest keyframe before it. + pub fn seek(&mut self, seconds: f64, exact: bool) { + if !self.ready { + self.start = seconds.max(0.0); + return; + } + let flags = gst::SeekFlags::FLUSH | if exact { gst::SeekFlags::ACCURATE } else { gst::SeekFlags::KEY_UNIT }; + let at = gst::ClockTime::from_nseconds((seconds.max(0.0) * 1e9) as u64); + if self.playbin.seek_simple(flags, at).is_ok() { + self.seeking = true; + } + } + + pub fn audio_tracks(&self) -> Vec<Track> { + self.tracks("n-audio", "get-audio-tags", gst::tags::AudioCodec::TAG_NAME) + } + + pub fn text_tracks(&self) -> Vec<Track> { + self.tracks("n-text", "get-text-tags", gst::tags::SubtitleCodec::TAG_NAME) + } + + pub fn current_audio(&self) -> i32 { + self.playbin.property::<i32>("current-audio") + } + + /// The subtitle track shown, or `None` when subtitles are off. + pub fn current_text(&self) -> Option<i32> { + get_flag(&self.playbin, "text").then(|| self.playbin.property::<i32>("current-text")).filter(|i| *i >= 0) + } + + pub fn set_audio(&self, index: i32) { + self.playbin.set_property("current-audio", index); + } + + /// Shows subtitle track `index`, or hides subtitles (`None`). + pub fn set_text(&self, index: Option<i32>) { + match index { + Some(i) => { + set_flag(&self.playbin, "text", true); + self.playbin.set_property("current-text", i); + } + None => set_flag(&self.playbin, "text", false), + } + } + + /// Audio sync correction in milliseconds (positive: audio later). + pub fn set_audio_offset_ms(&self, ms: i64) { + self.playbin.set_property("av-offset", ms * 1_000_000); + } + + fn tracks(&self, count: &str, signal: &str, codec_tag: &str) -> Vec<Track> { + let n = self.playbin.property::<i32>(count); + (0..n) + .map(|i| { + let tags = self.playbin.emit_by_name::<Option<gst::TagList>>(signal, &[&i]); + let mut t = Track { index: i, ..Track::default() }; + if let Some(tags) = tags { + t.language = tags.get::<gst::tags::LanguageCode>().map(|v| v.get().to_string()); + t.title = tags.get::<gst::tags::Title>().map(|v| v.get().to_string()); + t.codec = tags + .generic(codec_tag) + .and_then(|v| v.get::<String>().ok()) + .or_else(|| tags.get::<gst::tags::Codec>().map(|v| v.get().to_string())); + } + t + }) + .collect() + } +} + +impl Drop for Player { + fn drop(&mut self) { + let _ = self.playbin.set_state(gst::State::Null); + } +} + +fn get_flag(playbin: &gst::Element, nick: &str) -> bool { + let value = playbin.property_value("flags"); + let Some(class) = glib::FlagsClass::with_type(value.type_()) else { return false }; + class.value_by_nick(nick).is_some_and(|f| class.is_set(&value, f.value())) +} + +fn set_flag(playbin: &gst::Element, nick: &str, on: bool) { + let value = playbin.property_value("flags"); + let Some(class) = glib::FlagsClass::with_type(value.type_()) else { return }; + let Some(builder) = class.builder_with_value(value) else { return }; + let builder = if on { builder.set_by_nick(nick) } else { builder.unset_by_nick(nick) }; + if let Some(v) = builder.build() { + playbin.set_property_from_value("flags", &v); + } +} diff --git a/crates/sf-ui/ui/fonts/Onest-Bold.ttf b/crates/sf-ui/ui/fonts/Onest-Bold.ttf new file mode 100644 index 0000000..9a53c59 Binary files /dev/null and b/crates/sf-ui/ui/fonts/Onest-Bold.ttf differ diff --git a/crates/sf-ui/ui/fonts/Onest-Medium.ttf b/crates/sf-ui/ui/fonts/Onest-Medium.ttf new file mode 100644 index 0000000..7ea5a2b Binary files /dev/null and b/crates/sf-ui/ui/fonts/Onest-Medium.ttf differ diff --git a/crates/sf-launcher/ui/fonts/OFL-LICENSE.txt b/crates/sf-ui/ui/fonts/Onest-OFL.txt similarity index 96% rename from crates/sf-launcher/ui/fonts/OFL-LICENSE.txt rename to crates/sf-ui/ui/fonts/Onest-OFL.txt index 9b2ca37..b40b684 100644 --- a/crates/sf-launcher/ui/fonts/OFL-LICENSE.txt +++ b/crates/sf-ui/ui/fonts/Onest-OFL.txt @@ -1,8 +1,9 @@ -Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter) +Copyright 2021 The Onest Project Authors (https://github.com/googlefonts/onest) This Font Software is licensed under the SIL Open Font License, Version 1.1. This license is copied below, and is also available with a FAQ at: -http://scripts.sil.org/OFL +https://scripts.sil.org/OFL + ----------------------------------------------------------- SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007 @@ -43,7 +44,7 @@ new environment. "Author" refers to any designer, engineer, programmer, technical writer or other person who contributed to the Font Software. -PERMISSION AND CONDITIONS +PERMISSION & CONDITIONS Permission is hereby granted, free of charge, to any person obtaining a copy of the Font Software, to use, study, copy, merge, embed, modify, redistribute, and sell modified and unmodified copies of the Font diff --git a/crates/sf-ui/ui/fonts/Onest-Regular.ttf b/crates/sf-ui/ui/fonts/Onest-Regular.ttf new file mode 100644 index 0000000..5bd7166 Binary files /dev/null and b/crates/sf-ui/ui/fonts/Onest-Regular.ttf differ diff --git a/crates/sf-ui/ui/fonts/Onest-SemiBold.ttf b/crates/sf-ui/ui/fonts/Onest-SemiBold.ttf new file mode 100644 index 0000000..8aa9993 Binary files /dev/null and b/crates/sf-ui/ui/fonts/Onest-SemiBold.ttf differ diff --git a/crates/sf-ui/ui/sf-ui.slint b/crates/sf-ui/ui/sf-ui.slint new file mode 100644 index 0000000..64905a3 --- /dev/null +++ b/crates/sf-ui/ui/sf-ui.slint @@ -0,0 +1,960 @@ +// sf-ui: the SmartFox TV UI kit for Slint (guide: docs/sf-ui.md). +// +// import { TvWindow, Tv, SfText, GlassRect, GlassPane, GlassButton } from "@sf-ui/sf-ui.slint"; +// +// Two layers make up the screen: +// 1. the glass layer (Rust, OpenGL): the backdrop (gradient, picture or +// video) and every glass pane, drawn first; +// 2. Slint: text, icons and pictures, drawn on top. +// So Slint never draws the glass itself. Each glass component here exposes +// `out property <GlassRect> glass` (its window position, size and look); +// your root component lists them in exported `[GlassRect]` arrays, and Rust +// hands those to the glass layer every frame. Nothing Slint draws may sit +// *under* a glass pane: the pane would cover it. +// +// Sizes are design pixels on a 1920x1080 grid times `Tv.u` (TvWindow keeps +// `Tv.u` up to date), so the UI scales with the screen. + +import "fonts/Onest-Regular.ttf"; +import "fonts/Onest-Medium.ttf"; +import "fonts/Onest-SemiBold.ttf"; +import "fonts/Onest-Bold.ttf"; + +// One glass panel, in window coordinates (logical px). +export struct GlassRect { + x: length, + y: length, + w: length, + h: length, + // Corner radius. + r: length, + // 0..1: light from within, brighter rim, accent glow. + focus: float, + // 0..1: fade in/out (the glass "materializes": lensing ramps with it). + alpha: float, + // Frost (blur of the backdrop seen through it): ~1.2 small controls, + // 2-4 big panes. Negative: nested glass that sits on another pane. + blur: float, + // Accent light colour (a solid colour). + glow: brush, + // Tint colour (solid); its alpha is the amount (0 = clear glass). + tint: brush, + // Consecutive rects with the same group (> 0) melt together like liquid. + group: int, +} + +// Design tokens. All lengths: design px * Tv.u. +export global Tv { + // One design pixel (1920x1080 grid) in logical px. Set by TvWindow. + in-out property <length> u: 1px; + + // Text and focus (DESIGN.md, Fennec OS). + out property <color> text: #ffffff; + out property <color> text-secondary: #ffffffb8; + out property <color> text-tertiary: #ffffff8f; + // Text and icons on a focused (white) platter. + out property <color> ink: #121317; + out property <color> platter: #ffffffe0; + // Dark tint of grouping glass (use with alpha 0.30-0.48). + out property <color> smoke: #0b0c12; + out property <color> hairline: #ffffff1f; + out property <color> night: #050506; + // System accent (system actions only) and states: glass tone + ink tone. + out property <color> orange: #ff7a35; + out property <color> orange-ink: #ff9a5c; + out property <color> ok: #34c759; + out property <color> ok-ink: #5ee07a; + out property <color> warn: #ff9f0a; + out property <color> warn-ink: #ffb340; + out property <color> danger: #ff453a; + out property <color> danger-ink: #ff8278; + + // Safe area: keep content this far from the screen edges. + out property <length> safe-x: 96 * self.u; + out property <length> safe-y: 64 * self.u; +} + +// String helpers Slint lacks; wired to Rust by `sf_ui::glue!(App)` and +// `ui.sf_ui_setup()`. Export it from your main .slint file. +export global SfText { + // The text without its last character. + pure callback drop-last(string) -> string; + // n bullets (a masked password). + pure callback dots(int) -> string; + // The first n characters. + pure callback truncate(string, int) -> string; + // Only the typable characters of a key event's text (no arrows, Return...). + pure callback typable(string) -> string; +} + +// Base window for TV apps: night background (under the glass layer), the +// Onest font, and `Tv.u` kept in sync with the window size. +export component TvWindow inherits Window { + background: Tv.night; + default-font-family: "Onest"; + default-font-size: 28 * Tv.u; + title: "SmartFox"; + preferred-width: 1600px; + preferred-height: 900px; + init => { + Tv.u = min(self.width / 1920, self.height / 1080); + } + changed width => { + Tv.u = min(self.width / 1920, self.height / 1080); + } + changed height => { + Tv.u = min(self.width / 1920, self.height / 1080); + } +} + +// ---- type styles (Onest; tracking tightens from 48 px up) ---------------- + +// The one big name on a screen (96/700). +export component Display inherits Text { + font-size: 96 * Tv.u; + font-weight: 700; + letter-spacing: -2 * Tv.u; + color: Tv.text; + overflow: elide; +} + +// Screen titles (56/700). +export component Headline inherits Text { + font-size: 56 * Tv.u; + font-weight: 700; + letter-spacing: -1 * Tv.u; + color: Tv.text; + overflow: elide; +} + +// Section and page titles (40/700). +export component Title inherits Text { + font-size: 40 * Tv.u; + font-weight: 700; + color: Tv.text; + overflow: elide; +} + +// Row titles (36/600). +export component SectionTitle inherits Text { + font-size: 36 * Tv.u; + font-weight: 600; + color: Tv.text; + overflow: elide; +} + +// Descriptions (28/400); wraps. +export component Body inherits Text { + font-size: 28 * Tv.u; + font-weight: 400; + color: Tv.text-secondary; + wrap: word-wrap; + overflow: elide; +} + +// List and menu items (26/600). +export component Item inherits Text { + font-size: 26 * Tv.u; + font-weight: 600; + color: Tv.text; + overflow: elide; +} + +// Labels, facts (24/500): the smallest text the household must read. +export component Label inherits Text { + font-size: 24 * Tv.u; + font-weight: 500; + color: Tv.text-secondary; + overflow: elide; +} + +// Hints and details (22/500). +export component Caption inherits Text { + font-size: 22 * Tv.u; + font-weight: 500; + color: Tv.text-tertiary; + overflow: elide; +} + +// ---- icons ------------------------------------------------------------------ + +// Line icons on a 32-unit grid. Names: play, pause, back, forward, up, down, +// plus, check, close, search, info, rewind, fast-forward, next, previous, +// subtitles, audio, list, star, home, film, tv, user, settings, warning, +// space, delete, refresh. +export component Icon inherits Rectangle { + in property <string> name; + in property <color> ink: Tv.text; + in property <length> size: 32 * Tv.u; + width: self.size; + height: self.size; + property <bool> filled: self.name == "play" || self.name == "star"; + Path { + width: 100%; + height: 100%; + viewbox-width: 32; + viewbox-height: 32; + stroke: root.filled ? transparent : root.ink; + stroke-width: root.size * (root.name == "pause" ? 3.2 : 2.4) / 32; + fill: root.filled ? root.ink : transparent; + commands: root.name == "play" ? "M 10 6.5 L 25.5 16 L 10 25.5 Z" + : root.name == "pause" ? "M 11 7 L 11 25 M 21 7 L 21 25" + : root.name == "back" ? "M 20 6 L 10 16 L 20 26" + : root.name == "forward" ? "M 12 6 L 22 16 L 12 26" + : root.name == "up" ? "M 6 20 L 16 10 L 26 20" + : root.name == "down" ? "M 6 12 L 16 22 L 26 12" + : root.name == "plus" ? "M 16 6 L 16 26 M 6 16 L 26 16" + : root.name == "check" ? "M 6.5 16.5 L 13 23 L 25.5 9.5" + : root.name == "close" ? "M 8 8 L 24 24 M 24 8 L 8 24" + : root.name == "search" ? "M 14 5 A 9 9 0 1 1 14 23 A 9 9 0 1 1 14 5 M 20.5 20.5 L 27 27" + : root.name == "info" ? "M 16 4 A 12 12 0 1 1 16 28 A 12 12 0 1 1 16 4 M 16 14.5 L 16 22.5 M 16 9.5 L 16 10" + : root.name == "rewind" ? "M 15 8 L 7 16 L 15 24 M 25 8 L 17 16 L 25 24" + : root.name == "fast-forward" ? "M 7 8 L 15 16 L 7 24 M 17 8 L 25 16 L 17 24" + : root.name == "next" ? "M 8 7.5 L 20 16 L 8 24.5 Z M 24.5 8 L 24.5 24" + : root.name == "previous" ? "M 24 7.5 L 12 16 L 24 24.5 Z M 7.5 8 L 7.5 24" + : root.name == "subtitles" ? "M 5 8 L 27 8 L 27 24 L 5 24 Z M 9 15 L 15 15 M 18 15 L 23 15 M 9 19.5 L 19 19.5" + : root.name == "audio" ? "M 5 12.5 L 10 12.5 L 16 7 L 16 25 L 10 19.5 L 5 19.5 Z M 20.5 11.5 A 6 6 0 0 1 20.5 20.5 M 24 8 A 11 11 0 0 1 24 24" + : root.name == "list" ? "M 6 9 L 26 9 M 6 16 L 26 16 M 6 23 L 26 23" + : root.name == "star" ? "M 16 4 L 19.6 11.6 L 27.8 12.5 L 21.7 18.1 L 23.3 26.2 L 16 22.1 L 8.7 26.2 L 10.3 18.1 L 4.2 12.5 L 12.4 11.6 Z" + : root.name == "home" ? "M 5 15 L 16 5.5 L 27 15 M 8.5 12.5 L 8.5 26 L 23.5 26 L 23.5 12.5" + : root.name == "film" ? "M 6 6 L 26 6 L 26 26 L 6 26 Z M 11 6 L 11 26 M 21 6 L 21 26 M 6 16 L 11 16 M 21 16 L 26 16" + : root.name == "tv" ? "M 4 8 L 28 8 L 28 23 L 4 23 Z M 11 27 L 21 27" + : root.name == "user" ? "M 16 5 A 5.5 5.5 0 1 1 16 16 A 5.5 5.5 0 1 1 16 5 M 6 27 A 10 9 0 0 1 26 27" + : root.name == "settings" ? "M 6 10 L 26 10 M 6 22 L 26 22 M 12 7 L 12 13 M 20 19 L 20 25" + : root.name == "warning" ? "M 16 4.5 L 28.5 26.5 L 3.5 26.5 Z M 16 12.5 L 16 19 M 16 22.5 L 16 23" + : root.name == "space" ? "M 6 15 L 6 21 L 26 21 L 26 15" + : root.name == "delete" ? "M 11 7 L 28 7 L 28 25 L 11 25 L 3 16 Z M 15 12 L 23 20 M 23 12 L 15 20" + : root.name == "refresh" ? "M 25 16 A 9 9 0 1 1 22.4 9.6 M 23 4.5 L 23 10 L 17.5 10" + : ""; + } +} + +// ---- glass ------------------------------------------------------------------ + +// A glass pane; put content inside. List `pane.glass` in an exported +// [GlassRect] so the glass layer draws it. Content fades by itself: set its +// opacity together with `alpha`. +export component GlassPane inherits Rectangle { + in property <length> radius: 48 * Tv.u; + // Big modal panes 3-4, grouping platters ~2.2, small controls ~1.2. + in property <float> frost: 3.0; + // Smoke at 30-48% for grouping and modal panes; a colour for accents. + in property <color> tint: Tv.smoke.with-alpha(0.38); + in property <color> glow: #ffffff; + // 0..1: light from within and a brighter rim (a focused pane). + in property <float> lit: 0; + in property <float> alpha: 1; + in property <int> group: 0; + // Sits on another glass pane (lights what is beneath, no own frost). + in property <bool> nested: false; + out property <GlassRect> glass: { + x: self.absolute-position.x, + y: self.absolute-position.y, + w: self.width, + h: self.height, + r: min(self.radius, min(self.width, self.height) / 2), + focus: self.lit, + alpha: self.alpha, + blur: self.nested ? -1 : self.frost, + glow: self.glow, + tint: self.tint, + group: self.group, + }; +} + +// A capsule button. Focus is state you own (`focused`), shown as a white +// platter with dark ink and a small lift; `primary` buttons are accent glass. +export component GlassButton inherits Rectangle { + in property <string> text; + in property <string> icon; + in property <bool> focused; + in property <bool> primary; + in property <bool> enabled: true; + in property <bool> nested; + in property <color> accent: Tv.orange; + in property <float> alpha: 1; + // Height; width follows the content (icon-only buttons are round). + in property <length> size: 72 * Tv.u; + out property <float> f: self.focused && self.enabled ? 1 : 0; + animate f { duration: 240ms; easing: cubic-bezier(0.22, 1, 0.36, 1); } + property <float> s: 1 + 0.05 * self.f; + property <color> ink: self.primary ? Tv.text : Tv.ink.mix(Tv.text, self.f); + height: self.size; + min-width: self.size; + + inner := Rectangle { + transform-scale: root.s; + opacity: root.alpha * (root.enabled ? 1 : 0.45); + HorizontalLayout { + padding-left: root.text == "" ? (root.size - 32 * Tv.u) / 2 : (root.icon == "" ? 36 : 28) * Tv.u; + padding-right: root.text == "" ? (root.size - 32 * Tv.u) / 2 : 36 * Tv.u; + spacing: 12 * Tv.u; + alignment: center; + if root.icon != "": Icon { + y: (parent.height - self.height) / 2; + name: root.icon; + ink: root.ink; + } + if root.text != "": Text { + vertical-alignment: center; + text: root.text; + font-size: 26 * Tv.u; + font-weight: 600; + color: root.ink; + } + } + } + + out property <GlassRect> glass: { + x: self.absolute-position.x - self.width * (self.s - 1) / 2, + y: self.absolute-position.y - self.height * (self.s - 1) / 2, + w: self.width * self.s, + h: self.height * self.s, + r: self.height * self.s / 2, + focus: self.f, + alpha: self.alpha * (self.enabled ? 1 : 0.6), + blur: self.nested ? -1 : 1.4, + glow: self.primary ? self.accent : #ffffff, + tint: self.primary + ? self.accent.with-alpha(self.enabled ? 0.34 + 0.5 * self.f : 0.1) + : #ffffff.with-alpha(0.06 + 0.82 * self.f), + group: 0, + }; +} + +// A track with a fill (playback position, download...). The track is glass, +// the fill is drawn by Slint on top. +export component ProgressBar inherits Rectangle { + in property <float> value; + in property <float> buffered; + in property <color> fill: Tv.text; + in property <float> alpha: 1; + in property <bool> nested: true; + height: 12 * Tv.u; + Rectangle { + x: 0; + width: parent.width * clamp(root.buffered, 0, 1); + border-radius: self.height / 2; + background: #ffffff30; + opacity: root.alpha; + } + Rectangle { + x: 0; + width: max(self.height, parent.width * clamp(root.value, 0, 1)); + border-radius: self.height / 2; + background: root.fill; + opacity: root.value > 0 ? root.alpha : 0; + } + out property <GlassRect> glass: { + x: self.absolute-position.x, + y: self.absolute-position.y, + w: self.width, + h: self.height, + r: self.height / 2, + focus: 0, + alpha: self.alpha, + blur: self.nested ? -1 : 1.2, + glow: #ffffff, + tint: #00000038, + group: 0, + }; +} + +// A spinning arc (loading). +export component Spinner inherits Rectangle { + in property <length> size: 56 * Tv.u; + in property <color> ink: Tv.text; + width: self.size; + height: self.size; + Path { + width: 100%; + height: 100%; + viewbox-width: 32; + viewbox-height: 32; + commands: "M 16 3 A 13 13 0 1 1 3 16"; + stroke: root.ink; + stroke-width: root.size * 3 / 32; + transform-rotation: mod(animation-tick() / 1ms, 1000) / 1000 * 360deg; + } +} + +// Artwork (poster, still, logo) with rounded corners and a focus lift. +// Plain Slint, no glass: shadows on imagery are Slint's job. +export component ArtworkCard inherits Rectangle { + in property <image> image; + // Shown while there is no picture. + in property <string> placeholder; + in property <bool> focused; + // 0..1 bar along the bottom; negative = none. + in property <float> progress: -1; + // Small text over the top-left corner ("Új rész"). + in property <string> badge; + in property <length> radius: 24 * Tv.u; + in property <float> lift: 0.08; + in property <color> accent: Tv.text; + out property <float> f: self.focused ? 1 : 0; + animate f { duration: 260ms; easing: cubic-bezier(0.22, 1, 0.36, 1); } + + Rectangle { + transform-scale: 1 + root.lift * root.f; + // Shadow and the empty-card tone. + Rectangle { + border-radius: root.radius; + background: #1b1d24; + drop-shadow-blur: (14 + 22 * root.f) * Tv.u; + drop-shadow-offset-y: (8 + 12 * root.f) * Tv.u; + drop-shadow-color: #00000090; + } + Rectangle { + border-radius: root.radius; + clip: true; + if root.image.width == 0: Text { + x: 24 * Tv.u; + width: parent.width - 48 * Tv.u; + horizontal-alignment: center; + vertical-alignment: center; + text: root.placeholder; + font-size: 26 * Tv.u; + font-weight: 600; + color: Tv.text-tertiary; + wrap: word-wrap; + } + Image { + width: 100%; + height: 100%; + source: root.image; + image-fit: cover; + } + // Resting cards sit back a little. + Rectangle { + background: #000000; + opacity: 0.22 * (1 - root.f); + } + if root.progress >= 0: Rectangle { + y: parent.height - 8 * Tv.u; + height: 8 * Tv.u; + background: #00000099; + Rectangle { + x: 0; + width: parent.width * clamp(root.progress, 0, 1); + background: root.accent; + } + } + } + if root.badge != "": Rectangle { + x: 14 * Tv.u; + y: 14 * Tv.u; + width: badge-text.preferred-width + 24 * Tv.u; + height: 36 * Tv.u; + border-radius: self.height / 2; + background: #000000b0; + badge-text := Text { + text: root.badge; + font-size: 20 * Tv.u; + font-weight: 600; + color: Tv.text; + } + } + } +} + +// One row of a GlassMenu. +export struct MenuItem { + text: string, + detail: string, + checked: bool, +} + +// A list on a smoke glass platter with a white focus pill: track pickers, +// option lists. Focus and scrolling follow `focused-index`. +// `glass` holds two rects (platter, pill): list both. +export component GlassMenu inherits Rectangle { + in property <[MenuItem]> items; + // The focused row (also where the list scrolls to); -1 = none. + in property <int> focused-index: 0; + // False: the list keeps its scroll position but shows no focus pill + // (another list on screen has the focus). + in property <bool> active: true; + in property <string> title; + in property <float> alpha: 1; + in property <length> row-h: 72 * Tv.u; + in property <int> visible-rows: 7; + in property <color> accent: Tv.orange; + property <length> pad: 12 * Tv.u; + property <length> head: self.title == "" ? 0 : 72 * Tv.u; + property <int> shown-rows: min(self.items.length, self.visible-rows); + out property <float> pos: self.focused-index; + animate pos { duration: 220ms; easing: cubic-bezier(0.22, 1, 0.36, 1); } + property <float> first: clamp(self.pos - (self.visible-rows - 1) / 2, 0, max(0, self.items.length - self.visible-rows)); + width: 560 * Tv.u; + height: self.head + 2 * self.pad + self.shown-rows * self.row-h; + + if root.title != "": Text { + x: 32 * Tv.u; + y: root.pad; + height: root.head; + vertical-alignment: center; + text: root.title; + font-size: 24 * Tv.u; + font-weight: 600; + color: Tv.text-secondary; + opacity: root.alpha; + } + Rectangle { + x: root.pad; + y: root.pad + root.head; + width: root.width - 2 * root.pad; + height: root.shown-rows * root.row-h; + clip: true; + for item[i] in root.items: Rectangle { + property <float> f: root.active ? max(0, 1 - abs(root.pos - i)) : 0; + y: (i - root.first) * root.row-h; + height: root.row-h; + opacity: root.alpha; + HorizontalLayout { + padding-left: 24 * Tv.u; + padding-right: 24 * Tv.u; + spacing: 12 * Tv.u; + Rectangle { + width: 32 * Tv.u; + if item.checked: Icon { + y: (parent.height - self.height) / 2; + name: "check"; + ink: f > 0.5 ? Tv.ink : root.accent.brighter(0.3); + } + } + Text { + horizontal-stretch: 1; + vertical-alignment: center; + text: item.text; + font-size: 26 * Tv.u; + font-weight: 600; + color: Tv.ink.mix(Tv.text, f); + overflow: elide; + } + if item.detail != "": Text { + vertical-alignment: center; + text: item.detail; + font-size: 22 * Tv.u; + color: f > 0.5 ? #121317a0 : Tv.text-tertiary; + } + } + } + } + out property <[GlassRect]> glass: [ + { + x: self.absolute-position.x, + y: self.absolute-position.y, + w: self.width, + h: self.height, + r: 32 * Tv.u, + focus: 0.1, + alpha: self.alpha, + blur: 3.0, + glow: #ffffff, + tint: Tv.smoke.with-alpha(0.46), + group: 0, + }, + { + x: self.absolute-position.x + self.pad, + y: self.absolute-position.y + self.pad + self.head + (self.pos - self.first) * self.row-h, + w: self.width - 2 * self.pad, + h: self.row-h, + r: self.row-h / 2, + focus: 0.6, + alpha: self.items.length > 0 && self.focused-index >= 0 && self.active ? self.alpha : 0, + blur: -1, + glow: #ffffff, + tint: #ffffff.with-alpha(0.86), + group: 0, + }, + ]; +} + +// ---- on-screen keyboard ------------------------------------------------------- + +// tvOS-style keyboard: a text field, one row of keys with a gliding focus +// lens, mode chips. Remote: left/right move, OK types, down = chips, up = +// keys, Back = cancel. A real keyboard types directly. +// +// Pass key events to it while it is open: `kb.key(event)` from your +// FocusScope. Its `glass` holds 9 rects: list them all. Needs SfText. +// Size: 1920 x 572 design px (432 when `compact`); its width may be smaller. +export component Keyboard inherits Rectangle { + in property <string> title; + in property <string> subtitle; + in property <string> placeholder; + // Shows dots (with a "Megjelenítés" chip). + in property <bool> secret; + in property <string> submit-label: "Kész"; + in property <int> min-length: 0; + in property <int> max-length: 64; + in property <float> alpha: 1; + // False while the focus is elsewhere on the screen (no focus lens). + in property <bool> active: true; + // No title/subtitle: 1920 x 432 design px. + in property <bool> compact: false; + in-out property <string> text; + // Shown in red under the field until the text changes ("Hibás jelszó"). + in-out property <string> error; + callback submitted(string); + callback cancelled(); + // Up on the key row / down on the chips: the focus wants to leave the + // keyboard (e.g. to search results). Ignore them to keep it inside. + callback exit-up(); + callback exit-down(); + + in-out property <int> mode: 0; // abc, ABC, 123, #+= + in-out property <int> index: 1; + in-out property <int> area: 0; // 0 = keys, 1 = chips + in-out property <int> chip: 0; + in-out property <bool> reveal: false; + + out property <[string]> keys: self.mode == 1 + ? ["A", "Á", "B", "C", "D", "E", "É", "F", "G", "H", "I", "Í", "J", "K", "L", "M", "N", "O", "Ó", "Ö", "Ő", "P", "Q", "R", "S", "T", "U", "Ú", "Ü", "Ű", "V", "W", "X", "Y", "Z"] + : self.mode == 2 + ? ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", ".", ",", "-", "_", "@", "!", "?", "#", "$", "%", "&", "*", ":", "/"] + : self.mode == 3 + ? ["+", "=", "\\", ";", "'", "\"", "(", ")", "[", "]", "{", "}", "<", ">", "^", "`", "|", "~"] + : ["a", "á", "b", "c", "d", "e", "é", "f", "g", "h", "i", "í", "j", "k", "l", "m", "n", "o", "ó", "ö", "ő", "p", "q", "r", "s", "t", "u", "ú", "ü", "ű", "v", "w", "x", "y", "z"]; + property <int> n: self.keys.length + 2; + out property <[string]> chips: [ + "abc", "ABC", ".?123", "#+=", + self.secret ? (self.reveal ? "Elrejtés" : "Megjelenítés") : "Törlés", + self.submit-label, + ]; + property <int> len: self.text.character-count; + out property <bool> can-submit: self.len >= self.min-length; + property <string> hint: self.error != "" ? self.error + : !self.can-submit && self.len == 0 ? "Legalább \{self.min-length} karakter" + : !self.can-submit ? "Még \{self.min-length - self.len} karakter kell" + : self.len >= self.max-length ? "Legfeljebb \{self.max-length} karakter" + : self.secret ? "\{self.len} karakter" : ""; + property <string> shown-text: self.secret && !self.reveal ? SfText.dots(self.len) : self.text; + + out property <float> pos: self.index; + animate pos { duration: 200ms; easing: cubic-bezier(0.22, 1, 0.36, 1); } + out property <float> cpos: self.chip; + animate cpos { duration: 300ms; easing: cubic-bezier(0.22, 1, 0.36, 1); } + out property <float> keys-active: self.active && self.area == 0 ? 1 : 0; + animate keys-active { duration: 260ms; easing: ease-out; } + out property <float> chips-active: self.active && self.area == 1 ? 1 : 0; + animate chips-active { duration: 260ms; easing: ease-out; } + + // Geometry (local), design px * u. + property <length> field-w: 1200 * Tv.u; + property <length> field-h: 96 * Tv.u; + property <length> field-x: (self.width - self.field-w) / 2; + property <length> top: self.compact ? 0 : 140 * Tv.u; + property <length> field-y: self.top; + property <length> key-w: min(54 * Tv.u, 1640 * Tv.u / self.n); + property <length> row-x: (self.width - self.n * self.key-w) / 2; + property <length> row-y: self.top + 180 * Tv.u; + property <length> row-h: 120 * Tv.u; + property <length> chip-w: 200 * Tv.u; + property <length> chip-h: 72 * Tv.u; + property <length> chip-step: 216 * Tv.u; + property <length> chip-x: (self.width - 6 * self.chip-step + 16 * Tv.u) / 2; + property <length> chip-y: self.top + 360 * Tv.u; + width: 1920 * Tv.u; + height: self.top + 432 * Tv.u; + + // Clears the text and puts the focus back on the first key. + public function reset() { + root.text = ""; + root.error = ""; + root.mode = 0; + root.index = 1; + root.area = 0; + root.chip = 0; + root.reveal = false; + } + + function type-text(s: string) { + if s != "" && root.len < root.max-length { + root.text = SfText.truncate(root.text + s, root.max-length); + root.error = ""; + } + } + + function delete-char() { + root.text = SfText.drop-last(root.text); + root.error = ""; + } + + function press-key() { + if root.index == 0 { + root.type-text(" "); + } else if root.index >= root.n - 1 { + root.delete-char(); + } else { + root.type-text(root.keys[root.index - 1]); + } + } + + function press-chip() { + if root.chip < 4 { + root.mode = root.chip; + root.index = min(root.index, root.keys.length + 1); + root.area = 0; + } else if root.chip == 4 { + if root.secret { + root.reveal = !root.reveal; + } else { + root.text = ""; + root.error = ""; + } + } else if root.can-submit { + root.submitted(root.text); + } + } + + // Handles one key press; call it from your FocusScope while open. + public function key(event: KeyEvent) -> EventResult { + if event.text == Key.Escape { + root.cancelled(); + } else if event.text == Key.Backspace { + root.delete-char(); + } else if event.text == Key.Return { + if root.area == 0 { + root.press-key(); + } else { + root.press-chip(); + } + } else if event.text == Key.LeftArrow { + if root.area == 0 { + root.index = root.index <= 0 ? root.n - 1 : root.index - 1; + } else { + root.chip = max(0, root.chip - 1); + } + } else if event.text == Key.RightArrow { + if root.area == 0 { + root.index = root.index >= root.n - 1 ? 0 : root.index + 1; + } else { + root.chip = min(5, root.chip + 1); + } + } else if event.text == Key.DownArrow { + if root.area == 0 { + root.area = 1; + root.chip = root.can-submit ? 5 : root.mode; + } else { + root.exit-down(); + } + } else if event.text == Key.UpArrow { + if root.area == 1 { + root.area = 0; + } else { + root.exit-up(); + } + } else if !event.modifiers.control && !event.modifiers.alt && !event.modifiers.meta { + root.type-text(SfText.typable(event.text)); + } + accept + } + + // ---- heading ---- + Text { + y: 0; + width: root.width; + height: 60 * Tv.u; + horizontal-alignment: center; + vertical-alignment: center; + text: root.title; + font-weight: 700; + font-size: 48 * Tv.u; + letter-spacing: -0.8 * Tv.u; + color: Tv.text; + opacity: root.compact ? 0 : root.alpha; + overflow: elide; + } + Text { + x: 160 * Tv.u; + y: 72 * Tv.u; + width: root.width - 320 * Tv.u; + horizontal-alignment: center; + text: root.subtitle; + font-size: 24 * Tv.u; + color: Tv.text-secondary; + opacity: root.compact ? 0 : root.alpha; + overflow: elide; + } + + // ---- text field ---- + Rectangle { + x: root.field-x; + y: root.field-y; + width: root.field-w; + height: root.field-h; + clip: true; + opacity: root.alpha; + HorizontalLayout { + padding-left: 36 * Tv.u; + padding-right: 36 * Tv.u; + alignment: start; + spacing: 4 * Tv.u; + if root.shown-text == "": Text { + vertical-alignment: center; + text: root.placeholder; + font-size: 32 * Tv.u; + color: #ffffff59; + } + if root.shown-text != "": Text { + vertical-alignment: center; + text: root.shown-text; + font-size: 34 * Tv.u; + font-weight: 500; + letter-spacing: 1 * Tv.u; + color: Tv.text; + } + Rectangle { + width: 3 * Tv.u; + Rectangle { + y: (parent.height - self.height) / 2; + width: 100%; + height: 44 * Tv.u; + border-radius: self.width / 2; + background: Tv.orange-ink; + opacity: mod(animation-tick() / 1ms, 1000) < 550 ? 1 : 0; + } + } + } + } + Text { + x: root.field-x; + y: root.field-y + root.field-h + 20 * Tv.u; + width: root.field-w; + horizontal-alignment: center; + text: root.hint; + font-size: 22 * Tv.u; + color: root.error != "" ? Tv.danger-ink : #ffffff99; + opacity: root.alpha; + } + + // ---- key row: keys grow as the lens passes them ---- + for key[i] in root.keys: Text { + property <float> f: max(0, 1 - abs(root.pos - (i + 1))) * root.keys-active; + x: root.row-x + (i + 1) * root.key-w - 20 * Tv.u; + y: root.row-y; + width: root.key-w + 40 * Tv.u; + height: root.row-h; + horizontal-alignment: center; + vertical-alignment: center; + text: key; + font-size: (31 + 17 * self.f) * Tv.u; + font-weight: self.f > 0.5 ? 700 : 500; + color: self.f > 0.5 ? Tv.ink : #ffffffd8; + opacity: root.alpha; + } + Icon { + property <float> f: max(0, 1 - abs(root.pos)) * root.keys-active; + size: (30 + 10 * self.f) * Tv.u; + x: root.row-x + (root.key-w - self.size) / 2; + y: root.row-y + (root.row-h - self.size) / 2; + name: "space"; + ink: self.f > 0.5 ? Tv.ink : #ffffffd8; + opacity: root.alpha; + } + Icon { + property <float> f: max(0, 1 - abs(root.pos - (root.n - 1))) * root.keys-active; + size: (32 + 10 * self.f) * Tv.u; + x: root.row-x + (root.n - 1) * root.key-w + (root.key-w - self.size) / 2; + y: root.row-y + (root.row-h - self.size) / 2; + name: "delete"; + ink: self.f > 0.5 ? Tv.ink : #ffffffd8; + opacity: root.alpha; + } + + // ---- chips ---- + for label[i] in root.chips: Text { + property <float> f: max(0, 1 - abs(root.cpos - i)) * root.chips-active; + property <bool> submit: i == root.chips.length - 1; + property <bool> selected: i < 4 && i == root.mode; + x: root.chip-x + i * root.chip-step; + y: root.chip-y; + width: root.chip-w; + height: root.chip-h; + horizontal-alignment: center; + vertical-alignment: center; + text: label; + font-size: 24 * Tv.u; + font-weight: self.submit || self.selected ? 700 : 500; + color: self.submit ? (root.can-submit ? Tv.text : #ffffff66) : self.f > 0.5 ? Tv.ink : self.selected ? Tv.orange-ink : #ffffffc8; + opacity: root.alpha; + } + + // ---- glass ---- + property <length> ax: self.absolute-position.x; + property <length> ay: self.absolute-position.y; + property <length> track-h: self.row-h - 28 * Tv.u; + property <length> lens-w: 86 * Tv.u; + property <length> lens-h: 112 * Tv.u; + + pure function chip-rect(i: int) -> GlassRect { + let f = max(0, 1 - abs(root.cpos - i)) * root.chips-active; + let s = 1 + 0.05 * f; + let sel = i < 4 && i == root.mode ? 0.16 : 0; + { + x: root.ax + root.chip-x + i * root.chip-step - root.chip-w * (s - 1) / 2, + y: root.ay + root.chip-y - root.chip-h * (s - 1) / 2, + w: root.chip-w * s, + h: root.chip-h * s, + r: root.chip-h * s / 2, + focus: f, + alpha: root.alpha, + blur: -1, + glow: i == 5 ? Tv.orange : #ffffff, + tint: i == 5 + ? Tv.orange.with-alpha(root.can-submit ? 0.34 + 0.56 * f : 0.08 + 0.2 * f) + : #ffffff.with-alpha(0.04 + sel + 0.80 * f), + group: 0, + } + } + + out property <[GlassRect]> glass: [ + { + x: root.ax + root.field-x, + y: root.ay + root.field-y, + w: root.field-w, + h: root.field-h, + r: 30 * Tv.u, + focus: 0.25, + alpha: root.alpha, + blur: -1, + glow: Tv.orange, + tint: #ffffff12, + group: 0, + }, + { + x: root.ax + root.row-x - 26 * Tv.u, + y: root.ay + root.row-y + 14 * Tv.u, + w: root.n * root.key-w + 52 * Tv.u, + h: root.track-h, + r: root.track-h / 2, + focus: 0, + alpha: root.alpha, + blur: -1, + glow: #ffffff, + tint: #ffffff09, + group: 0, + }, + { + x: root.ax + root.row-x + (root.pos + 0.5) * root.key-w - root.lens-w / 2, + y: root.ay + root.row-y + (root.row-h - root.lens-h) / 2, + w: root.lens-w, + h: root.lens-h, + r: 30 * Tv.u, + focus: root.keys-active, + alpha: root.alpha * root.keys-active, + blur: -1, + glow: #ffffff, + tint: #ffffff.with-alpha(0.88 * root.keys-active), + group: 0, + }, + root.chip-rect(0), + root.chip-rect(1), + root.chip-rect(2), + root.chip-rect(3), + root.chip-rect(4), + root.chip-rect(5), + ]; +} diff --git a/crates/sf-update/Cargo.toml b/crates/sf-update/Cargo.toml index 0ded4c9..48860c5 100644 --- a/crates/sf-update/Cargo.toml +++ b/crates/sf-update/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "sf-update" -description = "SmartFox package updater: signed shell and app packages from the Gitea package registry" +description = "Fennec OS package updater: signed shell and app packages from the Gitea package registry" version.workspace = true edition.workspace = true license.workspace = true @@ -18,3 +18,6 @@ ed25519-dalek = "2" base64 = "0.22" tar = "0.4" ruzstd = "0.8" + +[target.'cfg(unix)'.dependencies] +libc = "0.2" diff --git a/crates/sf-update/src/appstore.rs b/crates/sf-update/src/appstore.rs new file mode 100644 index 0000000..1c57359 --- /dev/null +++ b/crates/sf-update/src/appstore.rs @@ -0,0 +1,272 @@ +//! The app store side of sf-update (docs/store.md): reads what the user wants +//! (store.toml, written by the launcher), asks the sources what they offer +//! (catalog.json) and works out which store apps to install, update or +//! remove. Downloading, checking and unpacking reuse the package store. + +use std::collections::BTreeMap; +use std::path::Path; +use std::time::{SystemTime, UNIX_EPOCH}; + +use anyhow::{Context, Result}; +use sf_ipc::manifest::{AppManifest, version_cmp}; +use sf_ipc::store::{Catalog, CatalogApp, INDEX_FILE, Index, MAX_WANTED, PACKAGE_PREFIX, SourceInfo, Wanted, missing_permissions}; + +use crate::forge::{self, Repo}; +use crate::store::Store; + +/// Apps one catalog may list. +const MAX_CATALOG_APPS: usize = 200; + +/// A store package to download. +#[derive(Debug, Clone)] +pub struct StoreDownload { + pub id: String, + pub package_url: String, + pub approved: Vec<sf_ipc::Permission>, + pub source: String, +} + +/// Reads store.toml. The launcher (user tv) writes it, so it is read +/// carefully: no symlinks, a regular file, a size limit. +pub fn read_wanted(path: &Path) -> Result<Wanted> { + let mut opts = std::fs::OpenOptions::new(); + opts.read(true); + #[cfg(unix)] + { + use std::os::unix::fs::OpenOptionsExt; + opts.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK); + } + let file = match opts.open(path) { + Ok(f) => f, + Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Wanted::default()), + Err(e) => return Err(e).with_context(|| format!("opening {}", path.display())), + }; + let meta = file.metadata()?; + anyhow::ensure!(meta.is_file(), "{} is not a regular file", path.display()); + anyhow::ensure!(meta.len() <= MAX_WANTED, "{} is too large", path.display()); + let mut text = String::new(); + use std::io::Read; + file.take(MAX_WANTED).read_to_string(&mut text)?; + Wanted::parse(&text) +} + +fn now() -> u64 { + SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0) +} + +/// The canonical address of a source, or the input if it doesn't parse. +pub fn canonical(source: &str) -> String { + Repo::parse(source).map(|r| r.url()).unwrap_or_else(|_| source.trim().to_string()) +} + +/// Asks every source what it offers. +pub fn refresh_catalog(wanted: &Wanted) -> Catalog { + let agent = forge::agent(); + let mut sources: Vec<String> = Vec::new(); + for s in wanted.sources.iter().chain(wanted.apps.values().map(|a| &a.source)) { + let c = canonical(s); + if !sources.contains(&c) { + sources.push(c); + } + } + let mut catalog = Catalog { updated_at: now(), ..Default::default() }; + for url in sources { + let mut info = SourceInfo { url: url.clone(), ..Default::default() }; + match Repo::parse(&url).and_then(|r| forge::detect(&agent, &r)) { + Err(e) => info.error = Some(format!("{e:#}")), + Ok(repo) => match forge::raw_file(&agent, &repo, INDEX_FILE) { + Ok(Some(text)) => { + info.kind = "catalog".into(); + match toml::from_str::<Index>(&text) { + Err(e) => info.error = Some(format!("{INDEX_FILE}: {e}")), + Ok(index) => { + info.name = index.name.clone(); + let mut errors = Vec::new(); + for app_url in index.apps.iter().take(MAX_CATALOG_APPS) { + match Repo::parse(app_url).and_then(|r| forge::detect(&agent, &r)).and_then(|r| app_entry(&agent, &r)) { + Ok(Some(mut app)) => { + app.catalog = Some(url.clone()); + catalog.apps.push(app); + info.apps += 1; + } + Ok(None) => {} + Err(e) => errors.push(format!("{app_url}: {e:#}")), + } + } + for e in &errors { + log::warn!("store: {e}"); + } + if info.apps == 0 && !errors.is_empty() { + info.error = errors.into_iter().next(); + } + } + } + } + Ok(None) | Err(_) => { + info.kind = "app".into(); + match app_entry(&agent, &repo) { + Ok(Some(app)) => { + info.name = app.name.clone(); + info.apps = 1; + catalog.apps.push(app); + } + Ok(None) => info.error = Some("no release with an app.toml yet".into()), + Err(e) => info.error = Some(format!("{e:#}")), + } + } + }, + } + if let Some(e) = &info.error { + log::warn!("store source {url}: {e}"); + } + catalog.sources.push(info); + } + // One entry per id: the source the app is installed from wins, else the first. + let mut seen: BTreeMap<String, usize> = BTreeMap::new(); + let mut apps: Vec<CatalogApp> = Vec::new(); + for app in catalog.apps.drain(..) { + let pinned = wanted.apps.get(&app.id).map(|w| canonical(&w.source)); + match seen.get(&app.id) { + Some(&i) => { + if pinned.as_deref() == Some(app.source.as_str()) && apps[i].source != app.source { + apps[i] = app; + } + } + None => { + seen.insert(app.id.clone(), apps.len()); + apps.push(app); + } + } + } + catalog.apps = apps; + catalog +} + +/// The newest release of one app repo. +fn app_entry(agent: &ureq::Agent, repo: &Repo) -> Result<Option<CatalogApp>> { + let Some(release) = forge::latest_release(agent, repo)? else { return Ok(None) }; + let manifest_asset = release.asset("app.toml").context("app.toml")?; + let app: AppManifest = toml::from_str(&forge::asset_text(agent, manifest_asset)?).context("app.toml")?; + app.check_store_rules()?; + anyhow::ensure!(crate::registry::is_release(&app.version), "version {} is not a release version (1.2.3)", app.version); + let file = format!("{}-{}.tar.zst", app.id, app.version); + let package = release.asset(&file).with_context(|| format!("release {} has no {file}", release.tag))?; + Ok(Some(CatalogApp { + id: app.id.clone(), + name: app.name.clone(), + version: app.version.clone(), + kind: format!("{:?}", app.kind).to_lowercase(), + category: app.category.clone(), + description: app.description.clone(), + author: app.author.clone().unwrap_or_default(), + homepage: app.homepage.clone().unwrap_or_else(|| repo.url()), + license: app.license.clone().unwrap_or_default(), + accent: app.accent.clone(), + permissions: app.permissions(), + source: repo.url(), + catalog: None, + package_url: package.url.clone(), + installed: None, + blocked: None, + })) +} + +/// Marks what's installed and what's held back, and returns the store +/// packages to download (new installs and updates). +pub fn plan(store: &Store, wanted: &Wanted, catalog: &mut Catalog) -> BTreeMap<String, (String, StoreDownload)> { + let mut out = BTreeMap::new(); + for app in &mut catalog.apps { + let name = format!("{PACKAGE_PREFIX}{}", app.id); + app.installed = store.installed(&name); + app.blocked = None; + let Some(want) = wanted.apps.get(&app.id) else { continue }; + if canonical(&want.source) != app.source { + continue; + } + if !missing_permissions(&app.permissions, &want.permissions).is_empty() { + app.blocked = Some("permissions".into()); + continue; + } + let newer = app.installed.as_deref().is_none_or(|i| version_cmp(&app.version, i).is_gt()); + if newer && !store.bad(&name).contains(&app.version) { + out.insert( + name, + ( + app.version.clone(), + StoreDownload { + id: app.id.clone(), + package_url: app.package_url.clone(), + approved: want.permissions.clone(), + source: app.source.clone(), + }, + ), + ); + } + } + out +} + +/// Removes store apps the user no longer wants. +pub fn remove_unwanted(store: &Store, wanted: &Wanted) -> bool { + let mut changed = false; + for id in store.store_apps() { + if !wanted.apps.contains_key(&id) { + match store.remove_store_app(&id) { + Ok(()) => changed = true, + Err(e) => log::error!("removing {id}: {e:#}"), + } + } + } + changed +} + +pub fn write_catalog(path: &Path, catalog: &Catalog) { + let ok = (|| -> Result<()> { + if let Some(dir) = path.parent() { + std::fs::create_dir_all(dir)?; + } + let tmp = path.with_extension("json.tmp"); + std::fs::write(&tmp, serde_json::to_vec_pretty(catalog)?)?; + std::fs::rename(&tmp, path)?; + Ok(()) + })(); + if let Err(e) = ok { + log::warn!("writing {}: {e:#}", path.display()); + } +} + +/// Downloads a store package into `dir`. +pub fn download(d: &StoreDownload, version: &str, dir: &Path) -> Result<std::path::PathBuf> { + let agent = forge::agent(); + let file = dir.join(format!("{}-{version}.tar.zst", d.id)); + let n = forge::download(&agent, &d.package_url, &file, crate::registry::MAX_PACKAGE)?; + log::info!("downloaded {} {version} ({n} bytes)", d.id); + Ok(file) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn canonical_sources() { + assert_eq!(canonical("github.com/Fox/App.git"), "https://github.com/Fox/App"); + assert_eq!(canonical(" not a url "), "not a url"); + } + + #[cfg(unix)] + #[test] + fn wanted_file_is_read_carefully() { + let dir = std::env::temp_dir().join(format!("sf-store-test-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let real = dir.join("real.toml"); + std::fs::write(&real, "sources = ['github.com/a/b']\n").unwrap(); + assert_eq!(read_wanted(&real).unwrap().sources, ["github.com/a/b"]); + let link = dir.join("link.toml"); + let _ = std::fs::remove_file(&link); + std::os::unix::fs::symlink(&real, &link).unwrap(); + assert!(read_wanted(&link).is_err()); + assert!(read_wanted(&dir.join("missing.toml")).unwrap().apps.is_empty()); + std::fs::remove_dir_all(&dir).unwrap(); + } +} diff --git a/crates/sf-update/src/config.rs b/crates/sf-update/src/config.rs index 9606cc9..96265dc 100644 --- a/crates/sf-update/src/config.rs +++ b/crates/sf-update/src/config.rs @@ -21,6 +21,7 @@ struct File { root: Option<PathBuf>, requests: Option<PathBuf>, factory: Option<PathBuf>, + store_wanted: Option<PathBuf>, } impl File { @@ -38,6 +39,7 @@ impl File { root: o.root.or(self.root), requests: o.requests.or(self.requests), factory: o.factory.or(self.factory), + store_wanted: o.store_wanted.or(self.store_wanted), } } } @@ -57,6 +59,10 @@ pub struct Config { pub requests: PathBuf, /// Versions of the copies built into the image. pub factory: PathBuf, + /// What the user wants from the store (written by the launcher). + pub store_wanted: PathBuf, + /// What the store sources offer (written here). + pub catalog: PathBuf, } impl Config { @@ -84,12 +90,15 @@ impl Config { } None => None, }; + let root = file.root.unwrap_or_else(|| "/var/lib/sf-pkg".into()); Ok(Config { + catalog: root.join("store").join("catalog.json"), + store_wanted: file.store_wanted.unwrap_or_else(|| sf_ipc::store::WANTED_FILE.into()), server: server.trim_end_matches('/').to_string(), owner, auth, public_key, - root: file.root.unwrap_or_else(|| "/var/lib/sf-pkg".into()), + root, requests: file.requests.unwrap_or_else(|| "/var/lib/smartfox/update-requests".into()), factory: file.factory.unwrap_or_else(|| "/usr/share/smartfox/factory-versions.toml".into()), }) diff --git a/crates/sf-update/src/forge.rs b/crates/sf-update/src/forge.rs new file mode 100644 index 0000000..95682ab --- /dev/null +++ b/crates/sf-update/src/forge.rs @@ -0,0 +1,326 @@ +//! Store sources: app repos on GitHub, Gitea/Forgejo (Codeberg too) and +//! GitLab. An app is published as a release with two assets (docs/store.md): +//! +//! app.toml the manifest (name, permissions) +//! <id>-<version>.tar.zst the package +//! +//! A catalog repo lists many app repos in `smartfox-store.toml` on its +//! default branch. +//! +//! Requests go without our registry login (it must never reach third-party +//! servers), HTTPS only, with size limits on everything. + +use std::io::Read; +use std::time::Duration; + +use anyhow::{Context, Result, bail}; +use serde::Deserialize; + +const MAX_JSON: u64 = 4 * 1024 * 1024; +const MAX_TEXT: u64 = 256 * 1024; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Forge { + GitHub, + Gitea, + GitLab, +} + +/// A repository on a forge. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Repo { + /// None: not known yet (self-hosted), found out by `detect`. + pub forge: Option<Forge>, + /// https://host + pub base: String, + /// owner/repo (GitLab: group/subgroup/project) + pub path: String, +} + +impl Repo { + /// What the user typed: `https://github.com/o/r(.git)`, `github.com/o/r`, + /// or with an explicit forge: `gitea:git.example.org/o/r`, + /// `gitlab:gitlab.example.org/group/project`, `github:o/r`. + pub fn parse(input: &str) -> Result<Repo> { + let input = input.trim(); + let (forge, rest) = match input.split_once(':') { + Some(("github", r)) => (Some(Forge::GitHub), r), + Some(("gitea" | "forgejo", r)) => (Some(Forge::Gitea), r), + Some(("gitlab", r)) => (Some(Forge::GitLab), r), + _ => (None, input), + }; + let rest = rest.trim_start_matches('/'); + let rest = if let Some(r) = rest.strip_prefix("https://") { + r + } else if rest.starts_with("http://") { + bail!("only https:// sources are allowed"); + } else { + rest + }; + let rest = rest.split(['?', '#']).next().unwrap_or("").trim_end_matches('/'); + let rest = rest.strip_suffix(".git").unwrap_or(rest); + let (host, path) = match (forge, rest.split_once('/')) { + (Some(Forge::GitHub), Some((h, p))) if !h.contains('.') => ("github.com", format!("{h}/{p}")), + (_, Some((h, p))) => (h, p.to_string()), + _ => bail!("not a repository address: {input}"), + }; + let host = host.to_ascii_lowercase(); + let valid_host = !host.is_empty() && host.contains('.') && host.bytes().all(|b| b.is_ascii_alphanumeric() || b"-.:".contains(&b)); + if !valid_host { + bail!("bad host in {input}"); + } + let parts: Vec<&str> = path.split('/').collect(); + let valid_part = |p: &&str| !p.is_empty() && *p != "." && *p != ".." && p.bytes().all(|b| b.is_ascii_alphanumeric() || b"-._".contains(&b)); + if parts.len() < 2 || !parts.iter().all(valid_part) { + bail!("expected owner/repository in {input}"); + } + let forge = forge.or(match host.as_str() { + "github.com" => Some(Forge::GitHub), + "gitlab.com" | "framagit.org" => Some(Forge::GitLab), + "codeberg.org" => Some(Forge::Gitea), + _ => None, + }); + if matches!(forge, Some(Forge::GitHub | Forge::Gitea)) && parts.len() != 2 { + bail!("expected owner/repository in {input}"); + } + Ok(Repo { forge, base: format!("https://{host}"), path }) + } + + /// Canonical form, stored in store.toml and catalog.json. + pub fn url(&self) -> String { + format!("{}/{}", self.base, self.path) + } + + fn encoded_path(&self) -> String { + self.path.replace('/', "%2F") + } +} + +#[derive(Debug, Clone)] +pub struct Asset { + pub name: String, + pub url: String, +} + +#[derive(Debug, Clone)] +pub struct Release { + pub tag: String, + pub assets: Vec<Asset>, +} + +impl Release { + pub fn asset(&self, name: &str) -> Option<&Asset> { + self.assets.iter().find(|a| a.name == name) + } +} + +pub fn agent() -> ureq::Agent { + ureq::Agent::config_builder() + .timeout_connect(Some(Duration::from_secs(15))) + .timeout_recv_response(Some(Duration::from_secs(60))) + .timeout_recv_body(Some(Duration::from_secs(1800))) + .https_only(true) + .user_agent(concat!("FennecOS-store/", env!("CARGO_PKG_VERSION"))) + .build() + .into() +} + +/// GET returning None on 404. +fn get_text(agent: &ureq::Agent, url: &str, limit: u64) -> Result<Option<String>> { + match agent.get(url).header("Accept", "application/json, text/plain, */*").call() { + Ok(resp) => { + let mut body = String::new(); + resp.into_body().into_reader().take(limit + 1).read_to_string(&mut body).with_context(|| format!("reading {url}"))?; + if body.len() as u64 > limit { + bail!("{url}: response is too large"); + } + Ok(Some(body)) + } + Err(ureq::Error::StatusCode(404)) => Ok(None), + Err(ureq::Error::StatusCode(403 | 429)) if url.contains("api.github.com") => { + bail!("GitHub rate limit reached, try again later") + } + Err(e) => Err(e).with_context(|| format!("GET {url}")), + } +} + +/// Works out the forge of a self-hosted repo. +pub fn detect(agent: &ureq::Agent, repo: &Repo) -> Result<Repo> { + if repo.forge.is_some() { + return Ok(repo.clone()); + } + let gitea = format!("{}/api/v1/repos/{}", repo.base, repo.path); + if repo.path.matches('/').count() == 1 && get_text(agent, &gitea, MAX_JSON).ok().flatten().is_some() { + return Ok(Repo { forge: Some(Forge::Gitea), ..repo.clone() }); + } + let gitlab = format!("{}/api/v4/projects/{}", repo.base, repo.encoded_path()); + if get_text(agent, &gitlab, MAX_JSON).ok().flatten().is_some() { + return Ok(Repo { forge: Some(Forge::GitLab), ..repo.clone() }); + } + bail!("{}: no public GitHub, Gitea or GitLab repository found", repo.url()) +} + +#[derive(Deserialize)] +struct GhRelease { + tag_name: String, + #[serde(default)] + draft: bool, + #[serde(default)] + prerelease: bool, + #[serde(default)] + assets: Vec<GhAsset>, +} + +#[derive(Deserialize)] +struct GhAsset { + name: String, + browser_download_url: String, +} + +#[derive(Deserialize)] +struct GlRelease { + tag_name: String, + #[serde(default)] + upcoming_release: bool, + #[serde(default)] + assets: GlAssets, +} + +#[derive(Deserialize, Default)] +struct GlAssets { + #[serde(default)] + links: Vec<GlLink>, +} + +#[derive(Deserialize)] +struct GlLink { + name: String, + url: String, + #[serde(default)] + direct_asset_url: Option<String>, +} + +/// The newest published (not draft, not pre-release) release that carries +/// an `app.toml`. +pub fn latest_release(agent: &ureq::Agent, repo: &Repo) -> Result<Option<Release>> { + let releases: Vec<Release> = match repo.forge.context("unknown forge")? { + Forge::GitHub => { + let url = format!("https://api.github.com/repos/{}/releases?per_page=20", repo.path); + let Some(text) = get_text(agent, &url, MAX_JSON)? else { return Ok(None) }; + let list: Vec<GhRelease> = serde_json::from_str(&text).context("GitHub releases")?; + list.into_iter().filter(|r| !r.draft && !r.prerelease).map(gh_release).collect() + } + Forge::Gitea => { + let url = format!("{}/api/v1/repos/{}/releases?limit=20", repo.base, repo.path); + let Some(text) = get_text(agent, &url, MAX_JSON)? else { return Ok(None) }; + let list: Vec<GhRelease> = serde_json::from_str(&text).context("Gitea releases")?; + list.into_iter().filter(|r| !r.draft && !r.prerelease).map(gh_release).collect() + } + Forge::GitLab => { + let url = format!("{}/api/v4/projects/{}/releases?per_page=20", repo.base, repo.encoded_path()); + let Some(text) = get_text(agent, &url, MAX_JSON)? else { return Ok(None) }; + let list: Vec<GlRelease> = serde_json::from_str(&text).context("GitLab releases")?; + list.into_iter() + .filter(|r| !r.upcoming_release) + .map(|r| Release { + tag: r.tag_name, + assets: r.assets.links.into_iter().map(|l| Asset { url: l.direct_asset_url.unwrap_or(l.url), name: l.name }).collect(), + }) + .collect() + } + }; + Ok(releases.into_iter().find(|r| r.asset("app.toml").is_some())) +} + +fn gh_release(r: GhRelease) -> Release { + Release { tag: r.tag_name, assets: r.assets.into_iter().map(|a| Asset { name: a.name, url: a.browser_download_url }).collect() } +} + +/// A file from the default branch (catalogs: `smartfox-store.toml`). +pub fn raw_file(agent: &ureq::Agent, repo: &Repo, file: &str) -> Result<Option<String>> { + let url = match repo.forge.context("unknown forge")? { + Forge::GitHub => format!("https://raw.githubusercontent.com/{}/HEAD/{file}", repo.path), + Forge::Gitea => format!("{}/api/v1/repos/{}/raw/{file}", repo.base, repo.path), + Forge::GitLab => format!("{}/api/v4/projects/{}/repository/files/{}/raw?ref=HEAD", repo.base, repo.encoded_path(), file.replace('/', "%2F")), + }; + get_text(agent, &url, MAX_TEXT) +} + +/// A small text asset (the release's app.toml). +pub fn asset_text(agent: &ureq::Agent, asset: &Asset) -> Result<String> { + get_text(agent, &asset.url, MAX_TEXT)?.with_context(|| format!("{} is missing", asset.name)) +} + +/// Downloads an asset into `path`, at most `limit` bytes. +pub fn download(agent: &ureq::Agent, url: &str, path: &std::path::Path, limit: u64) -> Result<u64> { + let resp = agent.get(url).call().with_context(|| format!("GET {url}"))?; + let mut out = std::fs::File::create(path).with_context(|| format!("creating {}", path.display()))?; + let mut body = resp.into_body().into_reader().take(limit + 1); + let n = std::io::copy(&mut body, &mut out).with_context(|| format!("downloading {url}"))?; + if n > limit { + bail!("{url} is larger than {limit} bytes"); + } + out.sync_all()?; + Ok(n) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_repo_addresses() { + let r = Repo::parse("https://github.com/Fox/hello-app.git").unwrap(); + assert_eq!((r.forge, r.url()), (Some(Forge::GitHub), "https://github.com/Fox/hello-app".to_string())); + assert_eq!(Repo::parse("github.com/fox/x/").unwrap().url(), "https://github.com/fox/x"); + assert_eq!(Repo::parse("github:fox/x").unwrap().url(), "https://github.com/fox/x"); + let r = Repo::parse("gitlab.com/group/sub/proj").unwrap(); + assert_eq!((r.forge, r.path.as_str()), (Some(Forge::GitLab), "group/sub/proj")); + let r = Repo::parse("gitea:git.example.org/o/r").unwrap(); + assert_eq!((r.forge, r.base.as_str()), (Some(Forge::Gitea), "https://git.example.org")); + let r = Repo::parse("https://gitea.bluefox.support/bluefox/store").unwrap(); + assert_eq!(r.forge, None); + assert!(Repo::parse("http://github.com/a/b").is_err()); + assert!(Repo::parse("github.com/a").is_err()); + assert!(Repo::parse("github.com/a/b/c").is_err()); + assert!(Repo::parse("github.com/../b").is_err()); + assert!(Repo::parse("exa mple.org/a/b").is_err()); + } + + #[test] + fn parses_releases() { + let gh: Vec<GhRelease> = serde_json::from_str( + r#"[{"tag_name":"v2","draft":true,"assets":[]},{"tag_name":"v1","prerelease":false,"assets":[{"name":"app.toml","browser_download_url":"https://x/app.toml","size":3}]}]"#, + ) + .unwrap(); + let rel: Vec<Release> = gh.into_iter().filter(|r| !r.draft).map(gh_release).collect(); + assert_eq!(rel[0].tag, "v1"); + assert_eq!(rel[0].asset("app.toml").unwrap().url, "https://x/app.toml"); + let gl: Vec<GlRelease> = serde_json::from_str(r#"[{"tag_name":"1.0","assets":{"links":[{"name":"app.toml","url":"https://a","direct_asset_url":"https://b"}]}}]"#).unwrap(); + assert_eq!(gl[0].assets.links[0].direct_asset_url.as_deref(), Some("https://b")); + } +} + +/// Talks to the real forges: `cargo test -p sf-update -- --ignored live`. +#[cfg(test)] +mod live { + use super::*; + + #[test] + #[ignore] + fn live_forges() { + let agent = agent(); + for (url, file) in [ + ("github.com/BurntSushi/ripgrep", "README.md"), + ("codeberg.org/forgejo/forgejo", "README.md"), + ("gitlab.com/gitlab-org/cli", "README.md"), + ("gitea:gitea.com/gitea/tea", "README.md"), + ] { + let repo = detect(&agent, &Repo::parse(url).unwrap()).unwrap(); + let release = latest_release(&agent, &repo).unwrap(); + let readme = raw_file(&agent, &repo, file).unwrap(); + println!("{url}: {:?}, release with app.toml: {}, readme: {} bytes", repo.forge, release.is_some(), readme.map(|r| r.len()).unwrap_or(0)); + assert!(raw_file(&agent, &repo, "no-such-file.toml").unwrap().is_none()); + } + } +} diff --git a/crates/sf-update/src/main.rs b/crates/sf-update/src/main.rs index 71a3ef3..0be88ef 100644 --- a/crates/sf-update/src/main.rs +++ b/crates/sf-update/src/main.rs @@ -1,27 +1,32 @@ -//! sf-update: installs signed SmartFox packages (the shell and the apps) from -//! the Gitea package registry onto the writable data partition. The root -//! file system stays read-only and keeps the factory copies as a fallback. +//! sf-update: installs signed Fennec OS packages (the shell and the apps) from +//! the Gitea package registry, and store apps from their own GitHub, Gitea or +//! GitLab repos, onto the writable data partition. The root file system stays +//! read-only and keeps the factory copies as a fallback. //! -//! Protocol and layout: docs/updates.md. +//! Protocol and layout: docs/updates.md, docs/store.md. //! -//! sf-update check ask the server what's new (status.json) +//! sf-update check ask the servers what's new (status.json, catalog.json) //! sf-update auto check, then download and stage what's new (timer) //! sf-update apply switch staged packages live (at boot) //! sf-update install check, download, apply now and restart the UI +//! sf-update store install / remove store apps as store.toml says, now //! sf-update requests handle the launcher's request files (path unit) //! sf-update status print status.json +mod appstore; mod config; +mod forge; mod registry; mod store; +use std::collections::BTreeMap; use std::path::Path; use std::time::Duration; use anyhow::{Context, Result, bail}; use crate::config::Config; -use crate::store::Store; +use crate::store::{Expect, Store}; fn main() { env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init(); @@ -34,14 +39,14 @@ fn main() { fn run(cmd: &str) -> Result<()> { let cfg = Config::load()?; - let store = Store::open(&cfg)?; + let store = Store::open(&cfg.root, &cfg.factory)?; match cmd { "status" => { println!("{}", serde_json::to_string_pretty(&store.read_status())?); return Ok(()); } - "check" | "auto" | "apply" | "install" | "requests" => {} - _ => bail!("usage: sf-update check|auto|apply|install|requests|status"), + "check" | "auto" | "apply" | "install" | "store" | "requests" => {} + _ => bail!("usage: sf-update check|auto|apply|install|store|requests|status"), } // One run at a time (timer, boot and launcher requests can overlap). let _lock = store.lock(Duration::from_secs(600))?; @@ -50,28 +55,78 @@ fn run(cmd: &str) -> Result<()> { "auto" => auto(&cfg, &store), "apply" => apply(&store).map(drop), "install" => install(&cfg, &store), + "store" => store_sync(&cfg, &store), "requests" => requests(&cfg, &store), _ => unreachable!(), } } -/// Asks the registry for the newest version of every package and records -/// which ones are newer than what's installed. -fn check(cfg: &Config, store: &Store) -> Result<Vec<store::Pending>> { - store.set_state("checking", ""); - let latest = match registry::latest_versions(cfg) { - Ok(l) => l, +/// The store's plan: newest versions of the wanted store apps that may be +/// installed, with where to get them. None if store.toml can't be read +/// (then nothing is installed or removed). +fn store_plan(cfg: &Config, store: &Store) -> Option<(sf_ipc::store::Wanted, BTreeMap<String, (String, appstore::StoreDownload)>)> { + let wanted = match appstore::read_wanted(&cfg.store_wanted) { + Ok(w) => w, Err(e) => { - store.set_state("error", &format!("{e:#}")); - return Err(e); + log::error!("store: {e:#}"); + return None; } }; - let pending = store.refresh(&latest); + if wanted.sources.is_empty() && wanted.apps.is_empty() { + appstore::write_catalog(&cfg.catalog, &Default::default()); + return Some((wanted, BTreeMap::new())); + } + let mut catalog = appstore::refresh_catalog(&wanted); + let plan = appstore::plan(store, &wanted, &mut catalog); + appstore::write_catalog(&cfg.catalog, &catalog); + Some((wanted, plan)) +} + +/// Asks the registry and the store sources for the newest version of every +/// package and records which ones are newer than what's installed. +fn check(cfg: &Config, store: &Store) -> Result<Vec<store::Pending>> { + store.set_state("checking", ""); + let official = registry::latest_versions(cfg); + let mut latest = official.as_ref().cloned().unwrap_or_default(); + let mut downloads = BTreeMap::new(); + if let Some((_, plan)) = store_plan(cfg, store) { + for (name, (version, d)) in plan { + latest.insert(name.clone(), version); + downloads.insert(name, d); + } + } + let mut pending = store.refresh(&latest); + for p in &mut pending { + p.store = downloads.remove(&p.name); + } + // A store app without download info (shouldn't happen) is skipped. + pending.retain(|p| registry::store_id(&p.name).is_none() || p.store.is_some()); + if let Err(e) = official { + store.set_state("error", &format!("{e:#}")); + return Err(e); + } store.set_state("idle", ""); log::info!("{} update(s) available", pending.len()); Ok(pending) } +/// Downloads, checks and stages one package. +fn fetch(cfg: &Config, store: &Store, p: &store::Pending) -> Result<()> { + let dir = store.download_dir()?; + match &p.store { + None => { + let (pkg, sig) = registry::download(cfg, &p.name, &p.version, &dir)?; + store.verify_and_unpack(&cfg.public_key, &p.name, &p.version, &pkg, &sig, &Expect::Official)?; + } + Some(d) => { + let pkg = appstore::download(d, &p.version, &dir)?; + let expect = Expect::Store { id: &d.id, approved: &d.approved, source: &d.source }; + store.unpack_store(&p.name, &p.version, &pkg, &expect)?; + } + } + store.stage(&p.name, &p.version) +} + /// Downloads and stages each pending package. Failures of one package don't /// stop the others; the first error is reported. fn download(cfg: &Config, store: &Store, pending: &[store::Pending]) -> Result<usize> { @@ -83,12 +138,7 @@ fn download(cfg: &Config, store: &Store, pending: &[store::Pending]) -> Result<u continue; } store.set_state("downloading", &format!("{} {}", p.name, p.version)); - let result = (|| -> Result<()> { - let dir = store.download_dir()?; - let (pkg, sig) = registry::download(cfg, &p.name, &p.version, &dir)?; - store.verify_and_unpack(cfg, &p.name, &p.version, &pkg, &sig)?; - store.stage(&p.name, &p.version) - })(); + let result = fetch(cfg, store, p); let _ = std::fs::remove_dir_all(store.download_dir_path()); match result { Ok(()) => { @@ -123,7 +173,7 @@ fn auto(cfg: &Config, store: &Store) -> Result<()> { /// Switches staged packages live. Returns which kinds changed. fn apply(store: &Store) -> Result<store::Applied> { - let applied = store.apply_staged()?; + let applied = store.apply_staged(|_| true)?; store.gc(); store.write_status(|_| {}); Ok(applied) @@ -139,13 +189,45 @@ fn install(cfg: &Config, store: &Store) -> Result<()> { result.map(drop) } +/// The store screen changed store.toml: install new apps and approved +/// updates, remove the ones the user uninstalled, all right away. The +/// launcher picks the new app list up by itself; nothing restarts. +fn store_sync(cfg: &Config, store: &Store) -> Result<()> { + store.set_state("checking", ""); + let Some((wanted, plan)) = store_plan(cfg, store) else { + store.set_state("error", "store.toml can't be read"); + bail!("store.toml can't be read"); + }; + appstore::remove_unwanted(store, &wanted); + let pending: Vec<store::Pending> = plan + .into_iter() + .map(|(name, (version, d))| store::Pending { name, version, store: Some(d) }) + .collect(); + let result = download(cfg, store, &pending); + store.apply_staged(|name| registry::store_id(name).is_some())?; + store.link_apps()?; + store.gc(); + // The catalog's "installed" marks are now stale; refresh them from disk. + if let Some(mut catalog) = sf_ipc::store::Catalog::load(&cfg.catalog) { + for app in &mut catalog.apps { + app.installed = store.installed(&format!("{}{}", sf_ipc::store::PACKAGE_PREFIX, app.id)); + } + appstore::write_catalog(&cfg.catalog, &catalog); + } + store.write_status(|_| {}); + if result.is_ok() { + store.set_state("idle", ""); + } + result.map(drop) +} + /// Restarts what an update touched: the remote driver for a new shell, the /// TV session (cage + launcher) for a new shell or new apps. fn restart(applied: &store::Applied) { if applied.shell { systemctl(&["restart", "sf-remote.service"]); } - if applied.shell || applied.apps { + if applied.shell || applied.apps || applied.store { restart_ui(); } } @@ -164,9 +246,10 @@ fn systemctl(args: &[&str]) { /// The launcher (user tv) can't run anything as root; it drops empty files /// named after a request into the requests folder, sf-update-requests.path -/// starts this. Only the file names are used, never their contents. +/// starts this. Only the file names are used, never their contents (the +/// store request reads store.toml, carefully). fn requests(cfg: &Config, store: &Store) -> Result<()> { - const ORDER: [&str; 4] = ["rollback", "confirm", "install", "check"]; + const ORDER: [&str; 5] = ["rollback", "confirm", "store", "install", "check"]; let dir = &cfg.requests; let mut result = Ok(()); for _ in 0..10 { @@ -178,6 +261,7 @@ fn requests(cfg: &Config, store: &Store) -> Result<()> { let r = match name { "rollback" => rollback(store), "confirm" => store.confirm_shell(), + "store" => store_sync(cfg, store), "install" => install(cfg, store), _ => check(cfg, store).map(drop), }; @@ -213,4 +297,3 @@ fn rollback(store: &Store) -> Result<()> { } Ok(()) } - diff --git a/crates/sf-update/src/registry.rs b/crates/sf-update/src/registry.rs index 3b204f8..05ac3c5 100644 --- a/crates/sf-update/src/registry.rs +++ b/crates/sf-update/src/registry.rs @@ -14,18 +14,29 @@ use serde::Deserialize; use sf_ipc::manifest::version_cmp; /// Largest package we'll download. -const MAX_PACKAGE: u64 = 1024 * 1024 * 1024; +pub const MAX_PACKAGE: u64 = 1024 * 1024 * 1024; use crate::config::Config; -/// Package names this updater handles. -pub fn is_ours(name: &str) -> bool { +/// Official package names (from our registry). +pub fn is_official(name: &str) -> bool { name == "sf-shell" || name.strip_prefix("sf-app-").is_some_and(|id| !id.is_empty() && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')) } -/// Release versions only: digits and dots (prereleases like 1.2.0-rc1 are skipped). +/// Store app id of a package name (`store-<id>`). +pub fn store_id(name: &str) -> Option<&str> { + name.strip_prefix(sf_ipc::store::PACKAGE_PREFIX).filter(|id| sf_ipc::manifest::is_store_id(id)) +} + +/// Package names this updater handles: official ones and store apps. +pub fn is_ours(name: &str) -> bool { + is_official(name) || store_id(name).is_some() +} + +/// Release versions only: digits and dots, up to four parts (prereleases +/// like 1.2.0-rc1 are skipped). pub fn is_release(version: &str) -> bool { - !version.is_empty() && version.split('.').all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit())) && version.split('.').count() <= 3 + !version.is_empty() && version.split('.').all(|p| !p.is_empty() && p.len() <= 9 && p.bytes().all(|b| b.is_ascii_digit())) && version.split('.').count() <= 4 } fn agent() -> ureq::Agent { @@ -69,7 +80,7 @@ pub fn latest_versions(cfg: &Config) -> Result<BTreeMap<String, String>> { break; } for p in list { - if !is_ours(&p.name) || !is_release(&p.version) { + if !is_official(&p.name) || !is_release(&p.version) { continue; } match latest.get(&p.name) { @@ -90,7 +101,7 @@ pub fn file_name(name: &str, version: &str) -> String { /// Downloads a package and its signature into `dir`. pub fn download(cfg: &Config, name: &str, version: &str, dir: &Path) -> Result<(PathBuf, Vec<u8>)> { - if !is_ours(name) || !is_release(version) { + if !is_official(name) || !is_release(version) { bail!("refusing package {name} {version}"); } let agent = agent(); @@ -124,7 +135,13 @@ mod tests { assert!(!is_ours("sf-app-")); assert!(!is_ours("sf-app-../x")); assert!(!is_ours("other")); + assert!(is_ours("store-io.github.fox.hello")); + assert!(!is_official("store-io.github.fox.hello")); + assert!(!is_ours("store-youtube")); + assert!(!is_ours("store-io.x/../y")); assert!(is_release("1.2.3")); + assert!(is_release("1.0.0.87")); + assert!(!is_release("1.0.0.0.1")); assert!(!is_release("1.2.3-rc1")); assert!(!is_release("1..2")); assert!(!is_release("../1")); diff --git a/crates/sf-update/src/store.rs b/crates/sf-update/src/store.rs index 98cb24d..d67c36d 100644 --- a/crates/sf-update/src/store.rs +++ b/crates/sf-update/src/store.rs @@ -7,6 +7,9 @@ //! <name>/bad versions that failed, never installed again //! sf-shell/trial a new shell that hasn't confirmed a good start yet //! apps/<id> -> ../sf-app-<id>/current (the launcher reads this folder) +//! store-<id>/ a store app (docs/store.md), same layout plus: +//! source the repo it was installed from +//! store/apps/<id> -> ../../store-<id>/current //! status.json for the launcher's Updates row use std::collections::{BTreeMap, BTreeSet}; @@ -17,9 +20,9 @@ use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH}; use anyhow::{Context, Result, bail}; use ed25519_dalek::{Signature, VerifyingKey}; use serde::{Deserialize, Serialize}; -use sf_ipc::manifest::version_cmp; +use sf_ipc::Permission; +use sf_ipc::manifest::{AppManifest, version_cmp}; -use crate::config::Config; use crate::registry; pub const SHELL: &str = "sf-shell"; @@ -50,14 +53,30 @@ pub struct PackageStatus { pub struct Pending { pub name: String, pub version: String, + /// Store apps: where to get it and what it must be. + pub store: Option<crate::appstore::StoreDownload>, } #[derive(Debug, Default)] pub struct Applied { pub shell: bool, pub apps: bool, + pub store: bool, } +/// What a package must be to be installed. +pub enum Expect<'a> { + /// Ours: signed with the Fennec OS key. + Official, + /// A store app: its manifest must follow the store rules and stay within + /// the approved permissions. + Store { id: &'a str, approved: &'a [Permission], source: &'a str }, +} + +/// Largest unpacked store package and file count. +const MAX_STORE_UNPACKED: u64 = 8 * 1024 * 1024 * 1024; +const MAX_STORE_FILES: usize = 200_000; + #[derive(Deserialize)] struct PkgInfo { name: String, @@ -83,13 +102,18 @@ pub struct Store { pub struct Lock(#[allow(dead_code)] fs::File); impl Store { - pub fn open(cfg: &Config) -> Result<Self> { - fs::create_dir_all(&cfg.root).with_context(|| format!("creating {}", cfg.root.display()))?; - let factory = match fs::read_to_string(&cfg.factory) { - Ok(t) => toml::from_str(&t).with_context(|| format!("parsing {}", cfg.factory.display()))?, + pub fn open(root: &Path, factory: &Path) -> Result<Self> { + fs::create_dir_all(root).with_context(|| format!("creating {}", root.display()))?; + let factory = match fs::read_to_string(factory) { + Ok(t) => toml::from_str(&t).with_context(|| format!("parsing {}", factory.display()))?, Err(_) => BTreeMap::new(), }; - Ok(Store { root: cfg.root.clone(), factory }) + Ok(Store { root: root.to_path_buf(), factory }) + } + + /// Store app folders: `store/` under the root. + pub fn store_dir(&self) -> PathBuf { + self.root.join("store") } pub fn lock(&self, wait: Duration) -> Result<Lock> { @@ -134,7 +158,7 @@ impl Store { } /// The version running now: installed package or factory copy, the newer one. - fn installed(&self, name: &str) -> Option<String> { + pub fn installed(&self, name: &str) -> Option<String> { let current = self.link(name, "current"); let factory = self.factory.get(name).cloned(); match (current, factory) { @@ -143,7 +167,7 @@ impl Store { } } - fn bad(&self, name: &str) -> BTreeSet<String> { + pub fn bad(&self, name: &str) -> BTreeSet<String> { fs::read_to_string(self.dir(name).join("bad")).unwrap_or_default().lines().map(str::to_string).collect() } @@ -164,7 +188,7 @@ impl Store { let Some(v) = latest.get(&name) else { continue }; let newer = self.installed(&name).is_none_or(|i| version_cmp(v, &i).is_gt()); if newer && !self.bad(&name).contains(v) { - pending.push(Pending { name: name.clone(), version: v.clone() }); + pending.push(Pending { name: name.clone(), version: v.clone(), store: None }); } } let now = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0); @@ -190,13 +214,24 @@ impl Store { Ok(d) } - /// Checks the signature and unpacks into `<name>/<version>/`. - pub fn verify_and_unpack(&self, cfg: &Config, name: &str, version: &str, pkg: &Path, sig: &[u8]) -> Result<()> { + /// Checks the signature with `key` and unpacks into `<name>/<version>/`. + pub fn verify_and_unpack(&self, key: &[u8; 32], name: &str, version: &str, pkg: &Path, sig: &[u8], expect: &Expect) -> Result<()> { + anyhow::ensure!(matches!(expect, Expect::Official), "signed install is for official packages"); let data = fs::read(pkg)?; - let key = VerifyingKey::from_bytes(&cfg.public_key).context("public key")?; + let key = VerifyingKey::from_bytes(key).context("public key")?; let sig = Signature::from_slice(sig).context("signature: not 64 bytes")?; key.verify_strict(&data, &sig).context("bad signature")?; + self.unpack(name, version, &data, expect) + } + /// Store packages come from the selected source and need no signature. + pub fn unpack_store(&self, name: &str, version: &str, pkg: &Path, expect: &Expect) -> Result<()> { + anyhow::ensure!(matches!(expect, Expect::Store { .. }), "unsigned install is for store apps"); + let data = fs::read(pkg)?; + self.unpack(name, version, &data, expect) + } + + fn unpack(&self, name: &str, version: &str, data: &[u8], expect: &Expect) -> Result<()> { let dir = self.dir(name); fs::create_dir_all(&dir)?; let dest = dir.join(version); @@ -209,18 +244,60 @@ impl Store { let tmp = dir.join(format!(".tmp-{version}")); let _ = fs::remove_dir_all(&tmp); fs::create_dir_all(&tmp)?; - let decoder = ruzstd::decoding::StreamingDecoder::new(&data[..]).map_err(|e| anyhow::anyhow!("zstd: {e}"))?; - let mut archive = tar::Archive::new(decoder); - archive.set_preserve_permissions(true); - archive.set_preserve_ownerships(false); - archive.unpack(&tmp).context("unpacking")?; - - let info: PkgInfo = toml::from_str(&fs::read_to_string(tmp.join("pkg.toml")).context("pkg.toml missing")?).context("pkg.toml")?; - if info.name != name || info.version != version { + let result = (|| -> Result<()> { + let decoder = ruzstd::decoding::StreamingDecoder::new(&data[..]).map_err(|e| anyhow::anyhow!("zstd: {e}"))?; + let mut archive = tar::Archive::new(decoder); + archive.set_preserve_ownerships(false); + match expect { + Expect::Official => { + archive.set_preserve_permissions(true); + archive.unpack(&tmp).context("unpacking")?; + } + Expect::Store { .. } => unpack_untrusted(&mut archive, &tmp)?, + } + let info: PkgInfo = toml::from_str(&fs::read_to_string(tmp.join("pkg.toml")).context("pkg.toml missing")?).context("pkg.toml")?; + let expected_name = match expect { + Expect::Official => name, + Expect::Store { id, .. } => id, + }; + if info.name != expected_name || info.version != version { + bail!("package says it is {} {}, expected {expected_name} {version}", info.name, info.version); + } + if let Expect::Store { id, approved, .. } = expect { + check_store_manifest(&tmp, id, version, approved)?; + } + Ok(()) + })(); + if let Err(e) = result { let _ = fs::remove_dir_all(&tmp); - bail!("package says it is {} {}, expected {name} {version}", info.name, info.version); + return Err(e); } fs::rename(&tmp, &dest)?; + if let Expect::Store { source, .. } = expect { + fs::write(dir.join("source"), format!("{source}\n"))?; + } + Ok(()) + } + + /// Ids of the store apps on disk. + pub fn store_apps(&self) -> Vec<String> { + let Ok(entries) = fs::read_dir(&self.root) else { return Vec::new() }; + entries + .flatten() + .filter_map(|e| e.file_name().into_string().ok()) + .filter_map(|n| registry::store_id(&n).map(str::to_string)) + .collect() + } + + /// Uninstalls a store app (its files; the user's data stays in their home). + pub fn remove_store_app(&self, id: &str) -> Result<()> { + let name = format!("{}{id}", sf_ipc::store::PACKAGE_PREFIX); + anyhow::ensure!(registry::store_id(&name).is_some(), "bad store app id {id}"); + let _ = fs::remove_file(self.store_dir().join("apps").join(id)); + if self.dir(&name).exists() { + fs::remove_dir_all(self.dir(&name)).with_context(|| format!("removing {name}"))?; + log::info!("removed store app {id}"); + } Ok(()) } @@ -228,12 +305,12 @@ impl Store { self.set_link(name, "staged", version) } - /// Makes every staged package live. - pub fn apply_staged(&self) -> Result<Applied> { + /// Makes every staged package live for which `which(name)` says so. + pub fn apply_staged(&self, which: impl Fn(&str) -> bool) -> Result<Applied> { let mut applied = Applied::default(); let Ok(entries) = fs::read_dir(&self.root) else { return Ok(applied) }; for e in entries.flatten() { - let Some(name) = e.file_name().into_string().ok().filter(|n| registry::is_ours(n)) else { continue }; + let Some(name) = e.file_name().into_string().ok().filter(|n| registry::is_ours(n) && which(n)) else { continue }; let Some(v) = self.staged(&name) else { continue }; if self.link(&name, "current").as_deref() != Some(v.as_str()) { if let Some(cur) = self.link(&name, "current") { @@ -244,6 +321,8 @@ impl Store { if name == SHELL { fs::write(self.dir(&name).join("trial"), &v)?; applied.shell = true; + } else if registry::store_id(&name).is_some() { + applied.store = true; } else { applied.apps = true; } @@ -254,17 +333,33 @@ impl Store { Ok(applied) } - /// apps/<id> -> ../sf-app-<id>/current for every installed app. - fn link_apps(&self) -> Result<()> { + /// apps/<id> -> ../sf-app-<id>/current for every installed app, and + /// store/apps/<id> -> ../../store-<id>/current for store apps. + pub fn link_apps(&self) -> Result<()> { let apps = self.root.join("apps"); + let store_apps = self.store_dir().join("apps"); fs::create_dir_all(&apps)?; + fs::create_dir_all(&store_apps)?; let Ok(entries) = fs::read_dir(&self.root) else { return Ok(()) }; for e in entries.flatten() { let Some(name) = e.file_name().into_string().ok() else { continue }; - let Some(id) = name.strip_prefix("sf-app-").filter(|_| registry::is_ours(&name)) else { continue }; - let link = apps.join(id); + let (link, target) = if let Some(id) = name.strip_prefix("sf-app-").filter(|_| registry::is_official(&name)) { + (apps.join(id), format!("../{name}/current")) + } else if let Some(id) = registry::store_id(&name) { + (store_apps.join(id), format!("../../{name}/current")) + } else { + continue; + }; if self.link(&name, "current").is_some() && fs::symlink_metadata(&link).is_err() { - symlink(format!("../{name}/current"), &link)?; + symlink(target, &link)?; + } + } + // Links of removed store apps. + if let Ok(entries) = fs::read_dir(&store_apps) { + for e in entries.flatten() { + if !e.path().join("app.toml").exists() { + let _ = fs::remove_file(e.path()); + } } } Ok(()) @@ -362,3 +457,213 @@ impl Store { }); } } + +/// Unpacks a package from a third party: only plain files, folders and +/// symlinks that stay inside, no setuid/setgid bits, nothing writable by +/// others, within size limits. +fn unpack_untrusted<R: std::io::Read>(archive: &mut tar::Archive<R>, dest: &Path) -> Result<()> { + use std::path::Component; + archive.set_preserve_permissions(false); + let mut total = 0u64; + let mut files = 0usize; + for entry in archive.entries().context("reading the package")? { + let mut entry = entry.context("reading the package")?; + let path = entry.path().context("bad path")?.into_owned(); + if !path.components().all(|c| matches!(c, Component::Normal(_) | Component::CurDir)) { + bail!("package path {} leaves the package", path.display()); + } + match entry.header().entry_type() { + tar::EntryType::Regular | tar::EntryType::Directory => {} + tar::EntryType::Symlink => { + let target = entry.link_name().ok().flatten().context("symlink without target")?; + // Depth of the folder the link is in; ".." may not climb above the package. + let mut level = path.components().filter(|c| matches!(c, Component::Normal(_))).count() as i64 - 1; + for c in target.components() { + match c { + Component::Normal(_) => level += 1, + Component::ParentDir => level -= 1, + Component::CurDir => {} + _ => bail!("symlink {} points outside the package", path.display()), + } + if level < 0 { + bail!("symlink {} points outside the package", path.display()); + } + } + } + other => bail!("{}: {other:?} entries are not allowed", path.display()), + } + total += entry.header().size().unwrap_or(0); + files += 1; + if total > MAX_STORE_UNPACKED || files > MAX_STORE_FILES { + bail!("the package is too large"); + } + if !entry.unpack_in(dest).with_context(|| format!("unpacking {}", path.display()))? { + bail!("package path {} leaves the package", path.display()); + } + } + strip_modes(dest) +} + +/// No setuid/setgid/sticky and no group/other write anywhere in `dir`. +#[cfg(unix)] +fn strip_modes(dir: &Path) -> Result<()> { + use std::os::unix::fs::PermissionsExt; + for e in fs::read_dir(dir)?.flatten() { + let meta = fs::symlink_metadata(e.path())?; + if meta.file_type().is_symlink() { + continue; + } + let mode = meta.permissions().mode() & 0o755; + fs::set_permissions(e.path(), fs::Permissions::from_mode(mode))?; + if meta.is_dir() { + strip_modes(&e.path())?; + } + } + Ok(()) +} + +#[cfg(not(unix))] +fn strip_modes(_dir: &Path) -> Result<()> { + Ok(()) +} + +/// The manifest inside a store package must match what was offered. +fn check_store_manifest(dir: &Path, id: &str, version: &str, approved: &[Permission]) -> Result<()> { + let text = fs::read_to_string(dir.join("app.toml")).context("app.toml missing")?; + let app: AppManifest = toml::from_str(&text).context("app.toml")?; + anyhow::ensure!(app.id == id, "app.toml says id {}, expected {id}", app.id); + anyhow::ensure!(app.version == version, "app.toml says version {}, expected {version}", app.version); + app.check_store_rules()?; + let missing = sf_ipc::store::missing_permissions(&app.permissions(), approved); + anyhow::ensure!(missing.is_empty(), "the package asks for permissions that were not approved: {missing:?}"); + Ok(()) +} + +#[cfg(all(test, unix))] +mod tests { + use super::*; + + const ID: &str = "io.github.fox.hello"; + + struct Pkg { + tar: tar::Builder<Vec<u8>>, + } + + impl Pkg { + fn new(version: &str, perms: &str) -> Pkg { + let mut p = Pkg { tar: tar::Builder::new(Vec::new()) }; + p.file("pkg.toml", &format!("name = \"{ID}\"\nversion = \"{version}\"\n"), 0o644); + p.file( + "app.toml", + &format!("id = \"{ID}\"\nname = \"Hello\"\nversion = \"{version}\"\nkind = \"exec\"\nexec = [\"bin/hello\"]\n[sandbox]\npermissions = [{perms}]\n"), + 0o644, + ); + p.file("bin/hello", "#!/bin/sh\n", 0o755); + p + } + + fn file(&mut self, path: &str, body: &str, mode: u32) { + let mut h = tar::Header::new_gnu(); + h.set_size(body.len() as u64); + h.set_mode(mode); + self.tar.append_data(&mut h, path, body.as_bytes()).unwrap(); + } + + fn link(&mut self, path: &str, target: &str) { + let mut h = tar::Header::new_gnu(); + h.set_entry_type(tar::EntryType::Symlink); + h.set_size(0); + self.tar.append_link(&mut h, path, target).unwrap(); + } + + fn write(self, dir: &Path) -> PathBuf { + let tar = self.tar.into_inner().unwrap(); + let zst = ruzstd::encoding::compress_to_vec(&tar[..], ruzstd::encoding::CompressionLevel::Fastest); + let path = dir.join("pkg.tar.zst"); + fs::write(&path, &zst).unwrap(); + path + } + } + + fn setup(name: &str) -> (PathBuf, Store) { + let root = std::env::temp_dir().join(format!("sf-update-{name}-{}", std::process::id())); + let _ = fs::remove_dir_all(&root); + let store = Store::open(&root, &root.join("none.toml")).unwrap(); + (root, store) + } + + #[test] + fn installs_a_store_app_and_refuses_bad_ones() { + let (root, store) = setup("store"); + let name = format!("store-{ID}"); + let approved = [Permission::Network]; + let expect = Expect::Store { id: ID, approved: &approved, source: "https://github.com/fox/hello" }; + + // A good package, with a setuid bit that must be stripped. + let mut p = Pkg::new("1.0.0", "\"network\""); + p.file("bin/suid", "x", 0o4777); + p.link("bin/alias", "hello"); + let pkg = p.write(&root); + store.unpack_store(&name, "1.0.0", &pkg, &expect).unwrap(); + store.stage(&name, "1.0.0").unwrap(); + let applied = store.apply_staged(|_| true).unwrap(); + assert!(applied.store && !applied.apps); + assert!(root.join("store/apps").join(ID).join("app.toml").is_file()); + assert_eq!(store.installed(&name).as_deref(), Some("1.0.0")); + assert_eq!(fs::read_to_string(root.join(&name).join("source")).unwrap().trim(), "https://github.com/fox/hello"); + use std::os::unix::fs::PermissionsExt; + let mode = fs::metadata(root.join(&name).join("1.0.0/bin/suid")).unwrap().permissions().mode() & 0o7777; + assert_eq!(mode, 0o755); + + // An unsigned update installs from the selected source. + let pkg = Pkg::new("1.1.0", "\"network\"").write(&root); + store.unpack_store(&name, "1.1.0", &pkg, &expect).unwrap(); + // More permissions than approved. + let pkg = Pkg::new("1.1.0", "\"network\", \"devices\"").write(&root); + let err = store.unpack_store(&name, "1.1.0", &pkg, &expect).unwrap_err(); + assert!(format!("{err:#}").contains("not approved"), "{err:#}"); + // A symlink out of the package. + let mut p = Pkg::new("1.1.0", "\"network\""); + p.link("bin/evil", "../../../../etc/shadow"); + let pkg = p.write(&root); + assert!(store.unpack_store(&name, "1.1.0", &pkg, &expect).is_err()); + let mut p = Pkg::new("1.1.0", "\"network\""); + p.link("evil", "/etc/shadow"); + let pkg = p.write(&root); + assert!(store.unpack_store(&name, "1.1.0", &pkg, &expect).is_err()); + // Nothing half-unpacked is left behind. + assert!(!root.join(&name).join("1.1.0").exists()); + assert!(!root.join(&name).join(".tmp-1.1.0").exists()); + + // Uninstall. + store.remove_store_app(ID).unwrap(); + assert!(!root.join(&name).exists()); + assert!(fs::symlink_metadata(root.join("store/apps").join(ID)).is_err()); + fs::remove_dir_all(&root).unwrap(); + } + + #[test] + fn plan_holds_back_new_permissions() { + use sf_ipc::store::{Catalog, CatalogApp, Wanted, WantedApp}; + let (root, store) = setup("plan"); + let app = |perms: Vec<Permission>| CatalogApp { + id: ID.into(), + name: "Hello".into(), + version: "2.0.0".into(), + permissions: perms, + source: "https://github.com/fox/hello".into(), + ..Default::default() + }; + let mut wanted = Wanted::default(); + wanted.apps.insert(ID.into(), WantedApp { source: "github.com/fox/hello".into(), permissions: vec![Permission::Network] }); + let mut cat = Catalog { apps: vec![app(vec![Permission::Network])], ..Default::default() }; + assert_eq!(crate::appstore::plan(&store, &wanted, &mut cat).len(), 1); + let mut cat = Catalog { apps: vec![app(vec![Permission::Network, Permission::Gpu])], ..Default::default() }; + assert!(crate::appstore::plan(&store, &wanted, &mut cat).is_empty()); + assert_eq!(cat.apps[0].blocked.as_deref(), Some("permissions")); + // Not wanted: nothing to do. + let mut cat = Catalog { apps: vec![app(vec![])], ..Default::default() }; + assert!(crate::appstore::plan(&store, &Wanted::default(), &mut cat).is_empty()); + fs::remove_dir_all(&root).unwrap(); + } +} diff --git a/docs/sf-ui.md b/docs/sf-ui.md new file mode 100644 index 0000000..3e5f1f9 --- /dev/null +++ b/docs/sf-ui.md @@ -0,0 +1,442 @@ +# sf-ui: Liquid Glass és TV-komponensek Fennec OS appokhoz + +Az **sf-ui** a Fennec OS UI-készlete Rust + [Slint](https://slint.dev) appokhoz. Ugyanazt a Liquid Glass-t adja, amit a launcher használ: valódi fénytörést, fagyasztott (frosted) üveget, élfényt, árnyékot és cseppszerűen összeolvadó paneleket. Mellé jönnek a TV-s komponensek (gomb, panel, menü, billentyűzet...), egy képbetöltő és egy hardveres videólejátszó. + +Ez a fájl önállóan is használható. Másold be az app repójába a [store-app-guide.md](store-app-guide.md) mellé (például `AGENTS.md`-be fűzve), és egy fejlesztő vagy egy AI ebből meg tudja írni a felületet. Élő példák: +- `crates/sf-ui/gallery`: minden komponens egy képernyőn; +- `apps/netflex-tv`: egy teljes app. + +--- + +## 1. A modell: két réteg + +``` + ┌──────────────────────────────────────────────┐ + │ 2. Slint: szöveg, ikonok, képek (felül) │ + ├──────────────────────────────────────────────┤ + │ 1. Glass réteg (Rust, OpenGL), előbb rajzol: │ + │ háttér (gradient / kép / videó) + üveg │ + └──────────────────────────────────────────────┘ +``` + +- A **glass réteget** az sf-ui rajzolja OpenGL-lel, minden képkockában a Slint előtt: előbb a hátteret, rá az üveglapokat. Az üveg a **hátteret** töri meg és fagyasztja. +- A **Slint** csak szöveget, ikont és képet rajzol, a glass réteg *fölé*. +- A Slint maga nem rajzol üveget. Minden glass-komponens egy `out property <GlassRect> glass` tulajdonságban adja meg, hol van és hogyan néz ki. A gyökérkomponensed ezeket exportált `[GlassRect]` tömbökbe gyűjti, a Rust pedig minden képkockában átadja őket a glass rétegnek. + +Ebből jön a legfontosabb szabály: + +> **Semmi, amit a Slint rajzol, nem kerülhet egy glass lap *alá*.** Az üveg nem a Slint tartalmát töri meg (az fölötte van), hanem a hátteret. Ami egy felbukkanó lap alá esne, annak előbb teljesen el kell tűnnie (opacity 0), és csak utána jöhet a lap. + +Az üveg *alatt* tehát csak háttér lehet: gradient, háttérkép (`Backdrop`) vagy videó. A tartalom (szöveg, poszter) mindig az üvegen *van*. + +--- + +## 2. Bekötés lépésről lépésre + +### Cargo.toml + +```toml +[dependencies] +sf-ui = { path = "../../crates/sf-ui" } # a Fennec OS checkouton belül (apps/<app>) +# vagy: sf-ui = { git = "https://gitea.bluefox.support/bluefox/fox-in-the-box" } +slint = "1.18" +anyhow = "1" + +# Videó csak Linuxon (a TV-n); Windowson/macOS-en a UI videó nélkül fejleszthető. +[target.'cfg(target_os = "linux")'.dependencies] +sf-ui = { path = "../../crates/sf-ui", features = ["video"] } + +[build-dependencies] +slint-build = "1.18" +``` + +Feature-ök: + +| Feature | Alapból | Mit ad | +|---|---|---| +| `images` | be | `sf_ui::images::Images`: HTTP(S) képek, háttérszálon dekódolva, gyorsítótárral | +| `video` | ki | `sf_ui::video::Player`: GStreamer lejátszó (Linux, GStreamer 1.22+ és a dev csomagok kellenek a buildhez: `libgstreamer1.0-dev libgstreamer-plugins-base1.0-dev`) | + +**Hozzáférés:** az sf-ui most a privát `fox-in-the-box` repóban van. Ezért két út van: +- az app a Fennec OS checkout `apps/<app>/` mappájában él (saját git repóként; a Fennec OS a `.git`-et tartalmazó mappákat kihagyja az image-ből), és path-függőséggel hivatkozik rá; +- git-függőség, olyan buildkörnyezetben, amelynek van olvasási joga. + +A release CI-nak mindkét esetben olvasási jog kell. Példa: `apps/netflex-tv/.gitea/workflows/release.yml`. + +### build.rs + +Az sf-ui build scriptje megadja a Slint könyvtára helyét (`DEP_SF_UI_UI_DIR`). Ezt `@sf-ui` néven kell bekötni: + +```rust +fn main() { + 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"); +} +``` + +### ui/app.slint + +```slint +import { TvWindow, Tv, SfText, GlassRect, GlassPane, GlassButton, Title, Body } from "@sf-ui/sf-ui.slint"; + +// Kötelező: a Rust oldal ezt a két globált használja. +export { Tv, SfText } + +export component App inherits TvWindow { + title: "Az appom"; + forward-focus: keys; + in-out property <int> focused: 0; + callback activated(int); + + keys := FocusScope { + key-pressed(event) => { + if event.text == Key.LeftArrow { root.focused = max(0, root.focused - 1); return accept; } + if event.text == Key.RightArrow { root.focused = min(1, root.focused + 1); return accept; } + if event.text == Key.Return { root.activated(root.focused); return accept; } + reject + } + } + + pane := GlassPane { + x: Tv.safe-x; + y: 200 * Tv.u; + width: 1000 * Tv.u; + height: 420 * Tv.u; + VerticalLayout { + padding: 56 * Tv.u; + spacing: 24 * Tv.u; + Title { text: "Szia!"; } + Body { text: "Ez egy üveglap. A gombok is üvegből vannak."; } + HorizontalLayout { + spacing: 24 * Tv.u; + alignment: start; + b0 := GlassButton { text: "Indítás"; icon: "play"; primary: true; nested: true; focused: root.focused == 0; } + b1 := GlassButton { text: "Beállítások"; icon: "settings"; nested: true; focused: root.focused == 1; } + } + } + } + + // Rajzolási sorrendben: ami később jön, az van felül. + out property <[GlassRect]> glass: [pane.glass, b0.glass, b1.glass]; +} +``` + +### src/main.rs + +```rust +slint::include_modules!(); +sf_ui::glue!(App); // a GlassRect -> Panel konverzió és az App::sf_ui_setup() + +fn main() -> anyhow::Result<()> { + sf_ui::init()?; // OpenGL (FemtoVG) renderer: az ablak létrehozása ELŐTT + let ui = App::new()?; + ui.sf_ui_setup(); // SfText (billentyűzet szövegkezelése) + ui.window().set_fullscreen(true); + + let glass = sf_ui::Glass::install(&ui, |ui, panels| { + panels.extend(ui.get_glass().iter()); // minden exportált [GlassRect] tömb + })?; + glass.set_palette(sf_ui::Palette::from_hex(["#ffb27a", "#8a3d12", "#120805"])); // az app.toml palette-je + + ui.run()?; + Ok(()) +} +``` + +Ennyi elég egy működő, glass-os TV apphoz. + +--- + +## 3. Méretek, tokenek, betűk + +- **Dizájnrács:** 1920×1080. Minden hosszt `N * Tv.u` alakban adj meg; a `TvWindow` tartja karban a `Tv.u` értékét: `min(width/1920, height/1080)`. 4K-n ez magától kétszeres. +- **Biztonsági sáv:** `Tv.safe-x` (96) és `Tv.safe-y` (64). Ennél közelebb ne kerüljön tartalom a képernyő széléhez. +- **Betű:** Onest (400/500/600/700, teljes magyar ékezetkészlettel). Az sf-ui betölti, és a `TvWindow` alapértelmezett fontja. +- **Animáció:** `cubic-bezier(0.22, 1, 0.36, 1)`, 200–600 ms. Felbukkanó, „csepp” elemeknél: `cubic-bezier(0.3, 1.18, 0.4, 1)`. + +`Tv` színek: + +| Token | Érték | Mire | +|---|---|---| +| `Tv.text` / `text-secondary` / `text-tertiary` | fehér 100 / 72 / 56% | címek / leírások / súgók | +| `Tv.ink` | `#121317` | szöveg és ikon a fehér fókusz-platteren | +| `Tv.platter` | fehér ~88% | fókuszált sor/gomb üvegének tintája | +| `Tv.smoke` | `#0b0c12` | csoportosító üveg tintája, 30–48% alfával | +| `Tv.hairline` | fehér 12% | elválasztók | +| `Tv.orange` / `orange-ink` | `#ff7a35` / `#ff9a5c` | **csak** rendszer-akció (billentyűzet beküldés, mezőfókusz) | +| `Tv.ok`, `warn`, `danger` (+ `-ink`) | zöld / borostyán / piros | állapotok; üvegen a telített, háttéren az `-ink` változat | + +Szövegstílusok (mind `Text`, felülírható): + +| Komponens | Méret/súly | Mire | +|---|---|---| +| `Display` | 96/700, −2 betűköz | a képernyő egyetlen nagy neve | +| `Headline` | 56/700 | képernyőcím | +| `Title` | 40/700 | szakasz- és oldalcím | +| `SectionTitle` | 36/600 | sorcím | +| `Body` | 28/400, tördel | leírás | +| `Item` | 26/600 | lista- és menüelem | +| `Label` | 24/500 | címkék, tények; **ennél kisebb olvasandó szöveg ne legyen** | +| `Caption` | 22/500 | súgók, részletek | + +--- + +## 4. Az üveg: `GlassRect` + +```slint +export struct GlassRect { + x: length, y: length, w: length, h: length, // ablak-koordináta (logikai px) + r: length, // sarokkerekítés + focus: float, // 0..1: belső fény, erősebb él, akcentus-ragyogás + alpha: float, // 0..1: megjelenés (az üveg "materializálódik": a fénytörés is vele nő) + blur: float, // fagyasztás (a háttér elmosása); negatív = beágyazott üveg + glow: brush, // akcentusfény színe (egyszínű) + tint: brush, // tinta színe; az alfája a mértéke (0 = tiszta üveg) + group: int, // > 0: az egymást követő azonos csoportú lapok folyékonyan összeolvadnak +} +``` + +Ajánlott értékek szerep szerint (a launcherből): + +| Szerep | `r` | `blur` | `tint` | `focus` | +|---|---|---|---|---| +| Kis vezérlő, kapszula, kártya | magasság/2 vagy 36 | 1.2–1.6 | fehér 4–10% vagy akcentus 38% | 0, fókuszban 1 | +| Csoportosító platter (lista) | 32 | 2.2–3.0 | smoke 30–46% | 0–0.1 | +| Oldalsó panel (sheet) | 48 | 3.0–3.4 | smoke 38–44% | 0 | +| Modális lap | 56 | 3.8 | smoke 48% | 0–0.2 | +| Fókuszpirula egy lapon | magasság/2 | **−1** (beágyazott) | fehér 86–88% | 0.6 | +| Lapon ülő gomb, sáv | magasság/2 | **−1** (`nested: true`) | | | + +A **beágyazott üveg** (`blur < 0`) egy másik lapon ül: nem fagyaszt újra, csak megvilágítja, ami alatta van. Lapon lévő gombokat és pirulákat így használj (`nested: true`). + +--- + +## 5. Komponensek + +Minden glass-komponensnek `glass` kimenete van. **Mindet sorold fel** egy exportált tömbben, különben a Slint rajzol, de üveg nem lesz alatta. A nem látszó elemek `alpha`-ja legyen 0: a 0 alfájú lapokat a réteg kihagyja. + +### `TvWindow` +Az app gyökere (`export component App inherits TvWindow`): éjfekete alap, Onest, `Tv.u` karbantartása, 1600×900 kezdőméret asztalon. + +### `GlassPane` +Üveglap, tartalommal benne. + +| Tulajdonság | Alap | | +|---|---|---| +| `radius` | 48u | | +| `frost` | 3.0 | blur | +| `tint` | smoke 38% | | +| `glow` | fehér | | +| `lit` | 0 | fókusz-fény 0..1 | +| `alpha` | 1 | **a tartalmat ez nem halványítja**: annak a `opacity`-jét magad állítsd ugyanarra | +| `group` | 0 | | +| `nested` | false | | + +### `GlassButton` +Kapszulagomb ikonnal és/vagy szöveggel. Ha nincs szöveg, kerek ikongomb. + +| Tulajdonság | | +|---|---| +| `text`, `icon` | ikonnevek: lásd lent | +| `focused` | **te kezeled**; fókuszban fehér platter sötét tintával, ×1.05 emelés | +| `primary` | akcentus-üveg nyugalmi állapotban is (`accent`, alap: narancs) | +| `nested` | lapon ül | +| `enabled`, `alpha`, `size` | `size` = magasság, alap 72u | + +### `GlassMenu` +Lista egy smoke platteren, fehér fókuszpirulával. Sávválasztóhoz és opciólistához. + +| Tulajdonság | | +|---|---| +| `items: [MenuItem { text, detail, checked }]` | | +| `focused-index` | a fókusz, és ide görget; −1 = nincs | +| `active` | false: megtartja a görgetést, de nincs pirula (más lista fókuszos) | +| `title`, `row-h` (72u), `visible-rows` (7), `alpha`, `accent`, `width` (560u) | | + +A `glass` kimenete **két** lap: a platter és a pirula. + +### `ProgressBar` +Üvegsín, rajta a Slint rajzolja a kitöltést. Tulajdonságok: `value`, `buffered` (0..1), `fill`, `alpha`, `nested` (alapból true). + +### `ArtworkCard` +Poszter, still vagy logó lekerekítve, fókusz-emeléssel (×1.08) és árnyékkal. **Nincs alatta üveg**: képeknél az árnyék a Slint dolga. + +| Tulajdonság | | +|---|---| +| `image`, `placeholder` | szöveg kép helyett, amíg tölt | +| `focused`, `progress` | 0..1 sáv alul; negatív = nincs | +| `badge` | kis felirat a bal felső sarokban | +| `radius`, `lift`, `accent` | a sáv színe | + +### `Keyboard` +tvOS-stílusú billentyűzet: egysoros billentyűsor gördülő fókuszlencsével, magyar ékezetekkel, mód-chipekkel (abc, ABC, .?123, #+=, Törlés/Megjelenítés, beküldés). +- **Billentyűk:** amíg nyitva van, a gyökér `FocusScope`-ból add át neki: `return kb.key(event);`. +- **Tulajdonságok:** `title`, `subtitle`, `placeholder`, `secret`, `submit-label`, `min-length`, `max-length`, `text` (in-out), `error` (in-out, piros, gépelésre eltűnik), `active`, `compact` (cím nélkül: 1920×432; alapból 1920×572), `alpha`. +- **Callbackek:** `submitted(string)`, `cancelled()` (Vissza), `exit-up()` és `exit-down()` (kilépés a billentyűzetből, például a találatokra). +- **Függvény:** `reset()`. +- A `glass` kimenete **9 lap**. Az `SfText` globál kell hozzá (`ui.sf_ui_setup()`). +- A `width` lehet kisebb is (például egy lap szélessége); a geometria igazodik. + +### `Spinner`, `Icon` +- **`Spinner`:** forgó ív (`size`, `ink`). +- **`Icon { name, ink, size }`:** vonalikonok 32-es rácson: `play pause back forward up down plus check close search info rewind fast-forward next previous subtitles audio list star home film tv user settings warning space delete refresh`. + +--- + +## 6. Saját glass-elemek + +**a) Saját komponens.** Számold ki az abszolút helyét az `absolute-position` segítségével, és tedd ki `glass`-ként: + +```slint +export component Chip inherits Rectangle { + in property <string> text; + in property <bool> focused; + out property <float> f: self.focused ? 1 : 0; + animate f { duration: 220ms; easing: cubic-bezier(0.22, 1, 0.36, 1); } + height: 64 * Tv.u; + Text { x: 24 * Tv.u; vertical-alignment: center; height: parent.height; text: root.text; color: Tv.ink.mix(Tv.text, root.f); } + out property <GlassRect> glass: { + x: self.absolute-position.x, y: self.absolute-position.y, w: self.width, h: self.height, + r: self.height / 2, focus: self.f, alpha: 1, blur: 1.4, + glow: #ffffff, tint: #ffffff.with-alpha(0.06 + 0.82 * self.f), group: 0, + }; +} +``` + +**b) Ismétlődő elemek (`for`).** Ezek `glass`-ára id-vel nem lehet hivatkozni. Két jó minta: +- **Egy fókuszlencse:** egyetlen glass rect, amely a fókuszált elem mögé siklik. Az index alapján a gyökérben számolod ki (lásd a `GlassMenu` pirulát vagy a Netflex navigációs sávját). +- **Rustból:** `panels.push(sf_ui::Panel { x, y, w, h, radius, focus, alpha, blur, glow, group, tint })`. Logikai pixelben add meg (mint a Slintben); a réteg skáláz. A launcher kártyasora így készül. + +**c) Folyékony összeolvadás („csepp”).** Ha két lap egymás után jön a listában, és ugyanaz a `group` értékük (> 0), összeolvadnak. Egy csoportban legfeljebb 4 lap lehet. Így „bimbózik ki” egy menü egy kártyából vagy egy toast egy kapszulából: animáld a gyerek-lap méretét 0-ról. + +**Sorrend:** ami később kerül a listába, az van felül, és annak az árnyéka esik a korábbiakra. + +**Korlátok:** legfeljebb 48 lap képkockánként (mindegyik egy kis draw call). A láthatatlan (alpha ≈ 0) lapokat a réteg kihagyja. + +--- + +## 7. A háttér + +A `Glass` handle-lel (olcsón klónozható, a UI szálon használd): + +| Hívás | Mit csinál | +|---|---| +| `set_palette(Palette)` | az animált sötét gradient három színe (highlight, mid, deep). Áttűnik (0.35 s). Az app.toml `palette`-je jó kiindulás. `Palette::from_color(c)`: egyetlen színből, például egy poszter átlagszínéből | +| `set_brightness(0..1)` | a gradient fényereje (sűrű tartalom mögött legyen kisebb) | +| `set_backdrop(Some(Backdrop))` | egy kép a gradient fölött, amit az üveg megtör. Az előzőből áttűnik; `None`: vissza a gradienthez | +| `set_video(Some(source))` | videó a háttérben: az OSD üvege a filmet töri meg. `None`: kihalványul | +| `set_light(rad)` | a fő fényforrás iránya (kis értékek, például ±0.3; követheti a fókuszt) | +| `set_zoom(k)` | a gradient nagyítása (indítási „berepülés”) | + +```rust +let px = images_pixels; // SharedPixelBuffer<Rgba8Pixel> +glass.set_backdrop(Some( + sf_ui::Backdrop::new(px) + .dim(0.3) // az egész sötétebb (0..1) + .fade_left(1.0) // balra sötétedik: ott a cím + .fade_bottom(1.0) // alul sötétedik: ott a sorok + .align(0.6, 0.2) // vágáskor mi maradjon látható +)); +// .soft(): csak elmosva (tapéta, például a lejátszás előkészítése alatt) +``` + +A világos képekhez erős `dim`/`fade` kell, hogy a szöveg olvasható maradjon. A Netflex 0.25–0.3-at és 1.0-t használ. + +--- + +## 8. Képek (`images` feature) + +```rust +let images = sf_ui::images::Images::new(384 << 20); // ennyi bájt dekódolt kép marad a memóriában +let px = /* fizikai px per dizájn px */ (win.width as f32 / 1920.0).min(win.height as f32 / 1080.0); +images.load(&url, ((196.0 * px) as u32, (294.0 * px) as u32), move |img| model_set_image(img)); +images.load_pixels(&url, size, move |pixels| glass.set_backdrop(Some(sf_ui::Backdrop::new(pixels.clone())))); +let colour = sf_ui::images::average_color(&pixels); // -> Palette::from_color +images.cancel_pending(); // képernyőváltáskor +``` + +- A méret az a doboz **fizikai** pixelben, amiben megjelenik. A kép ezt fedi le (cover), és sosem nagyítja fel. Így 4K-n éles, 1080p-n kevesebb memóriát eszik. +- A callback a UI szálon fut, gyorsítótár-találatnál **azonnal**. Ezért ne tarts benne `RefCell`-kölcsönzést, amit a hívó is tart. Csak a modellt (például `Rc<VecModel>`) érintsd. +- A legújabb kérés kerül sorra elsőként (azt nézi most a felhasználó). Csak a fókusz körüli képeket kérd le. + +--- + +## 9. Videó (`video` feature, Linux) + +```rust +sf_ui::video::init()?; // egyszer; a VA-API dekódereket előre sorolja +let mut player = sf_ui::video::Player::new(&uri, sf_ui::video::PlayerOptions { + start: 754.0, audio_offset_ms: 0, subtitles: true, user_agent: None, ..Default::default() +})?; +glass.set_video(Some(player.video())); +// 50–200 ms-onként a UI szálon (slint::Timer): +for ev in player.poll() { + match ev { + Event::Ready { duration } => { /* sávok: player.audio_tracks(), text_tracks() */ } + Event::Buffering(pct) => {} Event::Playing(on) => {} Event::Seeked => {} + Event::Eos => {} Event::Error(msg) => {} + } +} +player.toggle(); player.seek(t, false); player.position(); player.duration(); +player.set_audio(i); player.set_text(Some(i) /* None = ki */); player.set_audio_offset_ms(ms); +``` + +- **Lejátszási lánc:** GStreamer `playbin` → VA-API dekóder (H.264, HEVC 10 bit, VP9, AV1) → `vapostproc` (GPU-s színkonverzió, HDR→SDR tónusleképezés) → NV12 → glass réteg. Ha nincs GPU vagy VA-API, FFmpeg szoftveres dekóderre vált. +- **Feliratok:** az MKV-be ágyazott ASS/SRT/PGS feliratokat a GStreamer rajzolja a képre. +- **Hálózat:** HTTP(S) stream Range-kérésekkel; az éppen töltődő fájl is megy. +- **Engedélyek:** `gpu`, `audio`, `network`. +- **A TV-n kell** (az image-ben megvan): gstreamer base/good/bad/libav, gstreamer1.0-pipewire, glib-networking (HTTPS). + +--- + +## 10. Fókusz és billentyűk + +- **A fókusz a te állapotod.** Indexek: `focused-index`, `focused: root.x == 2`. A Slint fókuszrendszere egyetlen gyökér `FocusScope`-ot ad, ez fogad minden billentyűt. Térbeli navigáció nincs; a nyilakat te képezed le. +- **Két jó felosztás:** + 1. kis appban Slintben, a `FocusScope.key-pressed`-ben; + 2. nagyobb appban Rustban: `callback key(string, bool) -> bool`, és a Rust állítja a fókusz-tulajdonságokat. A Netflex így működik; tesztelhető, és az adatokhoz is közel van. +- **Billentyűk:** `Key.UpArrow / DownArrow / LeftArrow / RightArrow`, `Key.Return` (OK), `Key.Escape` (Vissza; vedd hozzá a `Key.Backspace`-t és a `Key.Back`-et is), `" "` (szóköz, billentyűzetről lejátszás/szünet). Ismétlődéskor `event.repeat` igaz: így gyorsíthatsz (tekerés, görgetés). +- **Amit az app nem kap meg:** a Home és a hangerő gombokat a TV kezeli. A távirányító lejátszás/szünet gombja Slint 1.18-ban nem érkezik meg (nincs rá Key kód), ezért az OK gomb legyen a lejátszás/szünet. +- **A fókuszt lifttel és fénnyel jelezd** (`focused` / `lit` / `focus` a rectben, ×1.05–1.12 emelés), soha ne kerettel. + +--- + +## 11. Fejlesztői eszközök + +Minden `Glass`-os ablakba be van építve: + +| Változó | | +|---|---| +| `SF_UI_SIZE=1920x1080` | ablakméret fizikai pixelben (`3840x2160` a 4K-hoz) | +| `SF_UI_KEYS="wait down down enter d u n e esc"` | billentyűk sorban, 1.5 s után, 0.6 s-onként. Elemek: `left right up down enter esc back backspace space wait hold` és egy karakter = gépelés | +| `SF_UI_SNAPSHOT=kep.png` | PNG az ablakról, majd kilépés (az utolsó billentyű után 1.5 s-mal, vagy `SF_UI_SNAPSHOT_MS` ms-nál) | + +Így egy képernyő ember nélkül is ellenőrizhető, CI-ban vagy egy AI-nak is: + +```sh +SF_UI_SIZE=1920x1080 SF_UI_KEYS="down right enter" SF_UI_SNAPSHOT=detail.png cargo run +``` + +- **Galéria:** `cargo run -p sf-ui-gallery` (Linuxon `--features video` és `SF_UI_VIDEO=file:///…mkv`: videó a glass alatt). +- **Mock szerver:** érdemes adni egyet az apphoz, ami a szerveredet helyettesíti (a Netflexé: `apps/netflex-tv/tools/mock_server.py`). + +--- + +## 12. Buktatók (mind valódi hibákból) + +- **`x`/`y` nélkül a Slint középre teszi az elemet** egy nem-layout szülőben. Hero-szövegeknél és képeknél mindig adj `x: 0;`-t. +- **Foglalt nevek** egy `Rectangle` alapú komponensen: `focus` (függvény), `row`/`col` (GridLayout). Ezeket ne használd tulajdonságnévként. +- **A `GlassRect` `tint` és `glow` mezője `brush`**, nem `color`. A Slint 1.18 egy structon belül a `#fff.with-alpha(x)`-ből brusht csinál. +- **Az `absolute-position` nem számol a szülők `transform-*` tulajdonságaival.** Glass-elemet ne tegyél transzformált szülőbe (a lift a komponensen belül van megoldva). +- **Minden `glass` tömböt sorolj fel** a `Glass::install` callbackjében. Ami kimarad, az üveg nélkül jelenik meg. +- **Egy rejtett képernyő lapjainak `alpha`-ja legyen 0** (a képernyő átlátszóságával szorozva). A `visible: false` a Slint-tartalmat elrejti, a glass rectet nem. +- **`sf_ui::init()` a `App::new()` előtt**, különben nincs OpenGL, és nincs üveg (a napló jelzi). +- **`RefCell` újrabelépés:** ha képbetöltő vagy háttérfeladat callbackje gyorsítótárból azonnal visszahív, ne tartsd közben kölcsönözve az állapotot. + +--- + +## 13. Licenc + +A Slint királyimentes licence nem fedi le a beágyazott eszközöket (TV doboz), ezért az sf-ui és a rá épülő appok **GPL-3.0** alatt állnak. diff --git a/docs/store-app-guide.md b/docs/store-app-guide.md new file mode 100644 index 0000000..ba4ca84 --- /dev/null +++ b/docs/store-app-guide.md @@ -0,0 +1,501 @@ +# SmartFox store app: fejlesztői útmutató + +Ez a fájl önállóan is használható. Másold be az app repójába (pl. `SMARTFOX.md`, `AGENTS.md` vagy `CLAUDE.md` néven), és egy fejlesztő vagy egy AI ebből meg tudja írni, be tudja csomagolni és ki tudja adni az appot. A SmartFox forráskódja nem kell hozzá. + +A SmartFox egy Linuxos (Debian trixie) TV-rendszer. Az appok teljes képernyőn futnak, sandboxban, és távirányítóval kezelik őket. Egy **store app** egy nyilvános Git-repóban él (GitHub, Gitea/Forgejo, pl. Codeberg, vagy GitLab). A TV a repó **release-eiből** telepíti és frissíti. + +--- + +## 1. Kötelező szabályok (röviden) + +Ha ezek közül bármelyik sérül, a TV nem telepíti az appot. + +1. Az `app.toml` a repó gyökerében van, és a csomag gyökerébe is bekerül. +2. Az `id` **fordított domain név**, legalább egy ponttal, és az első tagja csak kisbetű és szám: `io.github.<user>.<app>`. Megengedett karakterek: `a-z A-Z 0-9 - _`, legfeljebb 128 karakter. Ha publikáltad, ne változtasd meg. +3. A `version` csak számokból áll, pontokkal elválasztva, legfeljebb 4 taggal: `1.2.3`. `-beta`, `+build` és hasonló utótag nem lehet. Minden release-nél emeld. +4. A `kind` értéke `"exec"` (natív program) vagy `"web"` (weboldal a beépített Chromiumban). +5. `exec` app: az `exec[0]` relatív út a csomagon belül (pl. `bin/app`), és a fájl futtatható. +6. `web` app: az `url` `https://`-sel kezdődik. +8. Tilos: `kind = "builtin"`, `service = true`, `[dial]`, `[sandbox] enabled = false`. +9. Csak Wayland van, X11 nincs. Az app ablaka mindig teljes képernyős. +10. Az app csak a saját `$HOME`-jába írhat tartósan. Hálózat, hang, GPU stb. csak akkor elérhető, ha a `[sandbox] permissions` listában szerepel. +11. A release két fájlt tartalmaz: `app.toml`, `<id>-<version>.tar.zst`. Ezeket az `sf-pack build` készíti el. +12. A release nem lehet draft vagy pre-release, és a repónak nyilvánosnak kell lennie. + +--- + +## 2. A repó felépítése + +Ajánlott szerkezet egy Rust apphoz (más nyelvnél ugyanez, csak a build lépés más): + +``` +my-app/ +├── app.toml a manifest (a gyökérben!) +├── icon.png négyzetes PNG, legalább 256×256 (nem kötelező) +├── Cargo.toml / Cargo.lock vagy package.json, CMakeLists.txt, ... +├── src/main.rs +├── package.sh build → pkg/ → sf-pack build pkg dist +├── .gitignore /target /pkg /dist +├── .github/workflows/release.yml GitHub CI +├── .gitea/workflows/release.yml Gitea / Forgejo CI +└── .gitlab-ci.yml GitLab CI +``` + +Elég annak a forge-nak a CI-fájlja, ahol a repó van. + +**A csomag tartalma** (`pkg/` mappa, ebből lesz a `.tar.zst`): + +``` +pkg/ +├── app.toml kötelező +├── icon.png ha az app.toml-ban szerepel +├── bin/my-app a futtatható fájl (a bin/ alatt minden futtathatóként kerül be) +└── ... bármi más, amit az app olvas: assetek, fontok, libek +``` + +A TV-n ez a mappa a sandboxban **csak olvashatóan** jelenik meg a `/app` alatt (`$SMARTFOX_APP_DIR`). + +A csomagban csak sima fájl, mappa és olyan symlink lehet, ami a csomagon belülre mutat. Setuid bit nem lehet benne. Korlátok: a letöltött csomag legfeljebb 1 GiB, kibontva legfeljebb 8 GiB, és legfeljebb 200 000 fájl. + +--- + +## 3. `app.toml`: a mezők + +```toml +# --- kötelező --- +id = "io.github.example.hello" # fordított domain név, nem változik +name = "Hello" # a csempe címe +version = "1.0.0" # minden release-nél emeld +kind = "exec" # "exec" vagy "web" + +# --- exec app --- +exec = ["bin/hello", "--flag", "${app}/data"] +# exec[0]: relatív út a csomagon belül (bin/...) → /app/bin/hello +# vagy egy név a PATH-ból (/usr/bin), de ott csak a TV rendszere van +# ${app}: a csomag mappája (/app) + +# --- web app --- +# url = "https://example.com/tv" + +# --- ajánlott --- +description = "Egy-két mondat a Store-ba és a csempe alá." +category = "Játék" # rövid címke a cím fölött +author = "Példa Péter" +license = "MIT" +homepage = "https://github.com/example/hello" +icon = "icon.png" # a csomagban lévő PNG/SVG/JPG; ha nincs, a név kezdőbetűje látszik +accent = "#FF9A5C" # kiemelőszín (fókusz, gombok) +palette = ["#ffb27a", "#8a3d12", "#120805"] # háttér a kezdőképernyőn: világos, közép, sötét + +# --- környezeti változók az app folyamatának --- +[env] +RUST_LOG = "info" + +# --- web app beállításai --- +[web] +user_agent_suffix = "MyApp/1.0" # a Chromium user agentjéhez fűzi +# user_agent = "..." # vagy teljes felülírás +# extensions = ["ext/my-extension"] # kicsomagolt Chromium bővítmények (a csomagon belül) + +# --- engedélyek --- +[sandbox] +permissions = ["network", "gpu", "audio"] +``` + +Ismeretlen mezőt a TV figyelmen kívül hagy. Más mezőt ne használj. + +### Engedélyek + +Telepítés előtt a TV megmutatja a felhasználónak a listát. Ha egy frissítés **új** engedélyt kér, a frissítés vár, amíg a felhasználó a Store-ban jóvá nem hagyja. Ezért csak azt kérd, ami tényleg kell. + +| Kulcs | Mit nyit meg | Mikor kell | +|---|---|---| +| `network` | internet, helyi hálózat, DNS | bármilyen hálózati forgalomhoz | +| `gpu` | `/dev/dri`, `/sys` | OpenGL/Vulkan, hardveres videódekódolás. Gyakorlatilag minden grafikus apphoz kell | +| `audio` | PipeWire- és PulseAudio-socket | hang lejátszásához | +| `gamepad` | `/dev/input`, `/dev/hidraw*`, `/dev/uinput`, udev | játékvezérlőkhöz (SDL, gilrs) | +| `dbus-session` | munkamenet D-Bus, szűretlenül | **kockázatos**, kerüld | +| `dbus-system` | rendszer D-Bus, szűretlenül | **kockázatos**, kerüld | +| `devices` | az egész `/dev` | **kockázatos**, kerüld | + +A `web` appok mindig megkapják a `network`, `gpu` és `audio` engedélyt. Ezeket nem kell felsorolni. + +--- + +## 4. Futási környezet (sandbox) + +Az app egy bubblewrap konténerben fut (ugyanaz, amire a Flatpak épül). + +| Mi | Hol / hogyan | +|---|---| +| Az app saját fájljai | `/app`, csak olvasható. Env: `SMARTFOX_APP_DIR=/app` | +| Az app adatai | `$HOME` (a TV-n `~/.local/share/smartfox/apps/<id>`). **Csak ez írható tartósan.** Ide jöjjön a config, a cache és a mentések: `$HOME/.config`, `$HOME/.cache`, `$HOME/.local/share` | +| Ideiglenes | `/tmp`, `/run`, `/var`: üres és írható, kilépéskor törlődik | +| Rendszer | `/usr`, `/etc` csak olvasható (Debian trixie). Csak arra a libre számíts, ami a TV-n biztosan megvan (lásd lent), a többit vidd a csomagban | +| Kép | Wayland socket (`WAYLAND_DISPLAY`, `XDG_RUNTIME_DIR`). `XDG_SESSION_TYPE=wayland` | +| Env | `PATH`, `HOME`, `USER`, `LANG`, `TZ`, `SMARTFOX_APP=<id>`, `SMARTFOX_APP_DIR=/app`, plusz az `[env]` | +| Nincs | X11, más appok és a felhasználó fájljai, a rendszer-socketek, hálózat/hang/eszközök engedély nélkül, root, `sudo`, csomagtelepítés | + +**Az életciklus** +- Az app a launcher csempéjéről indul. A TV az ablakát mindig teljes képernyősre méretezi, a kijelző **fizikai** felbontására (1920×1080 vagy 3840×2160), 1-es skálával. +- **Home gomb:** a TV visszavált a launcherre, és kb. 0,6 s múlva **lefagyasztja** az appot (SIGSTOP). Amikor a felhasználó visszatér, folytatódik (SIGCONT), és az ablaka azonnal újra látszik. Az app ilyenkor nem kap értesítést. Az időzítőknek és a hálózati kapcsolatoknak bírniuk kell, hogy hirtelen „ugrik az idő”. +- A háttérben legfeljebb 2 app lehet. Ha több van, vagy kevés a memória, a TV a legrégebbit leállítja: SIGTERM, majd 3 s múlva SIGKILL. **Az állapotot ezért menet közben mentsd** (pl. minden fontos változáskor), ne csak kilépéskor. A SIGTERM-et kezeld: ments, és lépj ki. +- **Vissza (Escape)** a fő képernyőn: az app lépjen ki (exit code 0). Ekkor a launcher jön vissza. +- Ha az app összeomlik, a launcher jön vissza. Hibaüzenetet magadnak kell kiírni a képernyőre, a stdout/stderr-t a felhasználó nem látja. + +### Bemenet: a távirányító + +A távirányító (Siri Remote) gombjai **billentyűleütésként** érkeznek, mintha egy billentyűzet lenne. Egér és érintés nincs. + +| Távirányító | Billentyű (evdev / Wayland) | Mit tegyen az app | +|---|---|---| +| Nyilak / érintőfelület-húzás | `Up` `Down` `Left` `Right` | fókusz mozgatása | +| Középső gomb (kattintás) | `Enter` (Return) | kiválasztás / aktiválás | +| Vissza (Menu / `<`) | `Escape` | vissza egy szintet; a gyökérben kilépés | +| Lejátszás/szünet | `XF86AudioPlay` / `KEY_PLAYPAUSE` | média lejátszása/szüneteltetése | +| Siri gomb | `XF86AudioMic` / `KEY_VOICECOMMAND` | nem kötelező | +| Home | az app **nem kapja meg** | (a TV kezeli) | +| Hangerő +/−, némítás | az app **nem kapja meg** | (a TV kezeli, és kiírja a hangerőt) | + +Ha a felhasználó gyorsan húz, egymás után több nyíl-leütés érkezik, ezért a fókuszmozgás legyen gyors, és ne akadjon meg. Szöveg beírása távirányítóval nehéz: kerüld. Ha mégis kell, rajzolj saját képernyő-billentyűzetet (nyilakkal és Enterrel kezelhetőt). Fizikai billentyűzet és gamepad (`gamepad` engedéllyel) is lehet, de ne számíts rá. + +### Megjelenés (TV, „10 láb” UI) + +- **Skálázz a kijelző magasságához:** tervezz 1080p-re, és szorozz `window_height / 1080`-nal. Egy 4K TV 2160 px magas ablakot ad, 1-es skálával. +- **Mindig látszódjon, mi van fókuszban:** nagyítás, világos háttér vagy keret. A fókusz soha ne vesszen el, induláskor is legyen egy kiválasztott elem. +- Szöveg: törzsszöveg legalább 28 px, cím 40 px vagy több (1080p-n). Sötét háttér, magas kontraszt. +- **Biztonsági sáv:** a képernyő szélén hagyj legalább 5% margót (kb. 96 px oldalt és 54 px fent/lent 1080p-n), mert egyes TV-k levágják a szélét. +- Kevés, nagy elem, rácsban vagy sorban, hogy a nyilakkal kiszámíthatóan lehessen lépkedni. +- A TV felülete magyar, de a rendszer locale-ja `C.UTF-8`, így a `LANG`-ból nem derül ki a nyelv. Az app alapból magyarul szóljon (vagy legyen benne nyelvválasztó). + +### Mi van a TV-n + +A TV rendszere Debian trixie, x86_64 (Intel N100 kategória, Intel GPU, Mesa: OpenGL ES / Vulkan). Biztosan megvan: glibc, libwayland-client és libwayland-egl, libxkbcommon, Mesa (libEGL, libGLESv2, libgbm, libvulkan + Intel Vulkan driver), fontconfig, freetype, fontok (Noto, DejaVu), PipeWire (pulse-kompatibilis szerverrel), GStreamer (base/good/bad/libav pluginekkel: videó- és audiódekódolás). Minden mást (pl. SDL2, ffmpeg-libek, GTK4, Qt6) **vidd a csomagban** a `lib/` mappában, és állíts be `LD_LIBRARY_PATH`-t az `[env]`-ben (`LD_LIBRARY_PATH = "/app/lib"`), vagy linkeld statikusan. A legbiztosabb: Rust + statikus függőségek. + +- **Debian trixie-n vagy régebbin fordíts**, különben a binárisnak újabb glibc kellhet, mint ami a TV-n van. A CI-sablonok `debian:trixie` konténert használnak. +- Az architektúra x86_64 (`x86_64-unknown-linux-gnu`). +- AppImage FUSE nélkül nem indul a sandboxban: csomagold ki (`--appimage-extract`), és a kibontott mappát tedd a csomagba. + +--- + +## 5. Toolkitok + +**Ajánlott: Rust + Slint + [sf-ui](sf-ui.md).** Az sf-ui a launcher Liquid Glass-a és TV-komponensei egy könyvtárban: üveglapok, gombok, menük, képernyő-billentyűzet, képbetöltő, hardveres videólejátszó. Ezzel az app pontosan úgy néz ki és úgy viselkedik, mint a rendszer. A teljes leírása a [sf-ui.md](sf-ui.md)-ben van; azt is másold az app repójába. Példák: `crates/sf-ui/gallery` és `apps/netflex-tv`. + +**Az app helye fejlesztés közben:** a Fennec OS checkout `apps/<app>/` mappája lehet, saját git repóként. A `.git`-et tartalmazó mappákat a Fennec OS image build, a csomagoló és a launcher kihagyja, a gyökér `.gitignore`-ba pedig vedd fel. Így az sf-ui path-függőség (`../../crates/sf-ui`) helyben működik. + +Ha nem kell a rendszer kinézete, bármi jó, ami natívan beszél Waylanddel. + +| Nyelv / toolkit | Megjegyzés | +|---|---| +| **Rust + Slint** (ajánlott, a sablon ezt használja) | `ui.window().set_fullscreen(true)`; `FocusScope` + `key-pressed` a távirányítóhoz. Build-függőség: `libfontconfig1-dev libfreetype-dev libxkbcommon-dev` | +| Rust + egui/eframe, iced, winit + wgpu | a winit Waylanddel működik; az X11 feature-t kikapcsolhatod | +| Rust/C + SDL2/SDL3 | `SDL_VIDEODRIVER=wayland` az `[env]`-ben; az SDL-t vidd magaddal; a hanghoz `audio` engedély; a játékvezérlőhöz `gamepad` | +| C++ + Qt6 | `QT_QPA_PLATFORM=wayland`; a Qt-t vidd magaddal | +| GTK4 | `GDK_BACKEND=wayland`; a GTK-t vidd magaddal | +| Godot 4 | Linux export, `--display-driver wayland`; a `.pck`-ot és a binárist tedd a `bin/`-be | +| Web technológia | inkább `kind = "web"` egy `https://` oldallal; Electron/Tauri helyett | + +### Minimális Rust + Slint app + +`Cargo.toml`: +```toml +[package] +name = "hello-smartfox" +version = "1.0.0" +edition = "2024" +publish = false + +[dependencies] +slint = "1.18" + +[profile.release] +lto = "thin" +strip = true +``` + +`src/main.rs`: +```rust +//! Full screen, driven by the remote: arrows move, Enter clicks, Escape exits. +//! $HOME is the app's own data folder; its files are read-only in /app. + +slint::slint! { + export component Main inherits Window { + in-out property <int> selected: 0; + in-out property <int> clicks: 0; + callback quit(); + property <[string]> items: ["Hello", "SmartFox", "Rust"]; + // Design for 1080p, scale to the real height (4K TVs give 2160). + property <float> k: self.height / 1080px; + background: #0b0d12; + default-font-size: 40px * k; + + FocusScope { + key-pressed(event) => { + if event.text == Key.LeftArrow { root.selected = max(0, root.selected - 1); return accept; } + if event.text == Key.RightArrow { root.selected = min(root.items.length - 1, root.selected + 1); return accept; } + if event.text == Key.Return { root.clicks += 1; return accept; } + if event.text == Key.Escape { root.quit(); return accept; } + reject + } + HorizontalLayout { + alignment: center; + spacing: 40px * k; + for item[i] in root.items: Rectangle { + width: 360px * k; + height: 220px * k; + y: (root.height - self.height) / 2; + border-radius: 32px * k; + background: i == root.selected ? #ffffff : #ffffff18; + animate background { duration: 150ms; } + Text { + text: item; + color: i == root.selected ? #121317 : #ffffff; + font-weight: 700; + } + } + } + } + } +} + +fn main() -> Result<(), slint::PlatformError> { + let ui = Main::new()?; + ui.window().set_fullscreen(true); + ui.on_quit(|| { + let _ = slint::quit_event_loop(); + }); + ui.run() +} +``` + +Ha a toolkit nem állítja be magától: az adatfájlokat a `std::env::var("HOME")` alá írd (a `dirs`/`directories` crate is ezt használja), a saját assetjeidet pedig a `std::env::var("SMARTFOX_APP_DIR")` (= `/app`) alól olvasd. Ne a futtatható fájlhoz képesti relatív útról. + +--- + +## 6. Csomagolás: `sf-pack` + +Telepítés (Linuxon, Rust kell hozzá): +```sh +cargo install --locked --git https://gitea.bluefox.support/bluefox/fox-in-the-box sf-pack +``` + +| Parancs | Mit csinál | +|---|---| +| `sf-pack build <pkg-mappa> [dist]` | ellenőrzi a szabályokat, majd elkészíti a 2 release-fájlt a `dist/`-be | +| `sf-pack verify [dist]` | ellenőrzi a csomag tartalmát | +| `sf-pack run <pkg-mappa>` | úgy indítja az appot, mint a TV: ugyanaz a sandbox, ugyanazok az engedélyek (bubblewrap kell hozzá: `apt install bubblewrap`) | + +A `build` hibát ad, ha az `exec` fájl hiányzik vagy nem futtatható, ha a `version` nem release-verzió, vagy ha a megadott `icon` hiányzik. + +### `package.sh` + +```sh +#!/usr/bin/env bash +# Builds the two store release assets into dist/. +set -euo pipefail +cd "$(dirname "$0")" + +cargo build --release --locked +rm -rf pkg dist +mkdir -p pkg/bin +cp app.toml pkg/ +[ -f icon.png ] && cp icon.png pkg/ +install -m755 target/release/hello-smartfox pkg/bin/hello-smartfox +# Assets, bundled libraries: cp -r assets pkg/ ; cp lib/*.so* pkg/lib/ +sf-pack build pkg dist +sf-pack verify dist +``` + +A fájl legyen futtatható (`git update-index --chmod=+x package.sh`). + +--- + +## 7. Kiadás (release) + +Folyamat: +1. Emeld a `version` mezőt az `app.toml`-ban (és ha kell, a `Cargo.toml`-ban is), majd commitold. +2. Tageld: `git tag v1.2.3 && git push --tags`. +3. A CI megépíti az appot, és létrehoz egy release-t a 2 fájllal. + +A tag a `v` prefixtől eltekintve egyezzen a `version` mezővel. A TV mindig a **legújabb**, nem draft, nem pre-release release-t nézi, amelyben van `app.toml`. + +### GitHub: `.github/workflows/release.yml` + +```yaml +name: release +on: + push: + tags: ["v*"] +permissions: + contents: write +jobs: + release: + runs-on: ubuntu-latest + container: debian:trixie + env: + SF_PACK_GIT: https://gitea.bluefox.support/bluefox/fox-in-the-box + steps: + - uses: actions/checkout@v4 + - name: Toolchain + run: | + apt-get update -qq + apt-get install -y -qq --no-install-recommends build-essential pkg-config curl ca-certificates git \ + libfontconfig1-dev libfreetype-dev libxkbcommon-dev gh >/dev/null + curl -sSf https://sh.rustup.rs | sh -s -- -y -q --profile minimal + echo "$HOME/.cargo/bin" >> "$GITHUB_PATH" + - name: sf-pack + run: cargo install -q --locked --git "$SF_PACK_GIT" sf-pack + - name: Build + run: ./package.sh + - name: Release + env: + GH_TOKEN: ${{ github.token }} + run: | + git config --global --add safe.directory "$PWD" + gh release create "$GITHUB_REF_NAME" dist/* --title "$GITHUB_REF_NAME" --notes "SmartFox store release" +``` + +### Gitea / Forgejo (Codeberg): `.gitea/workflows/release.yml` + +```yaml +name: release +on: + push: + tags: ["v*"] +jobs: + release: + runs-on: ubuntu-latest + container: + image: debian:trixie + env: + SF_PACK_GIT: https://gitea.bluefox.support/bluefox/fox-in-the-box + steps: + - name: Checkout + run: | + apt-get update -qq + apt-get install -y -qq --no-install-recommends build-essential pkg-config curl ca-certificates git jq \ + libfontconfig1-dev libfreetype-dev libxkbcommon-dev >/dev/null + git clone --depth 1 --branch "$GITHUB_REF_NAME" \ + "${GITHUB_SERVER_URL%%://*}://oauth2:${{ secrets.GITHUB_TOKEN }}@${GITHUB_SERVER_URL#*://}/${GITHUB_REPOSITORY}.git" src + - name: Build + run: | + curl -sSf https://sh.rustup.rs | sh -s -- -y -q --profile minimal + export PATH="$HOME/.cargo/bin:$PATH" + cargo install -q --locked --git "$SF_PACK_GIT" sf-pack + cd src && ./package.sh + - name: Release + env: + TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + api="$GITHUB_SERVER_URL/api/v1/repos/$GITHUB_REPOSITORY/releases" + id=$(curl -fsS -H "Authorization: token $TOKEN" -H "Content-Type: application/json" \ + -d "{\"tag_name\":\"$GITHUB_REF_NAME\",\"name\":\"$GITHUB_REF_NAME\"}" "$api" | jq -r .id) + for f in src/dist/*; do + curl -fsS -H "Authorization: token $TOKEN" -F "attachment=@$f" "$api/$id/assets?name=$(basename "$f")" >/dev/null + done +``` + +### GitLab: `.gitlab-ci.yml` + +A GitLab a release-fájlokat a projekt generic package registryjébe teszi, és a release linkekkel hivatkozik rájuk. A projektnek nyilvánosnak kell lennie. + +```yaml +release: + image: debian:trixie + rules: + - if: $CI_COMMIT_TAG =~ /^v/ + variables: + SF_PACK_GIT: https://gitea.bluefox.support/bluefox/fox-in-the-box + script: + - apt-get update -qq + - apt-get install -y -qq --no-install-recommends build-essential pkg-config curl ca-certificates git jq libfontconfig1-dev libfreetype-dev libxkbcommon-dev >/dev/null + - curl -sSf https://sh.rustup.rs | sh -s -- -y -q --profile minimal + - export PATH="$HOME/.cargo/bin:$PATH" + - cargo install -q --locked --git "$SF_PACK_GIT" sf-pack + - ./package.sh + - VERSION="${CI_COMMIT_TAG#v}" + - PKG="$CI_API_V4_URL/projects/$CI_PROJECT_ID/packages/generic/smartfox/$VERSION" + - links="[]" + - | + for f in dist/*; do + n=$(basename "$f") + curl -fsS --header "JOB-TOKEN: $CI_JOB_TOKEN" --upload-file "$f" "$PKG/$n" >/dev/null + links=$(echo "$links" | jq --arg n "$n" --arg u "$PKG/$n" '. + [{name: $n, url: $u, link_type: "package"}]') + done + - | + jq -n --arg t "$CI_COMMIT_TAG" --argjson l "$links" '{tag_name: $t, name: $t, assets: {links: $l}}' | + curl -fsS --header "JOB-TOKEN: $CI_JOB_TOKEN" --header "Content-Type: application/json" --data @- \ + "$CI_API_V4_URL/projects/$CI_PROJECT_ID/releases" >/dev/null +``` + +Ha a projektnek más build-függősége van (SDL, ffmpeg-dev stb.), az `apt-get install` sorba kerüljön. + +--- + +## 8. Telepítés a TV-n + +Store app → **Források** → „Forrás hozzáadása” → a repó címe: +- `github.com/user/app`, `github:user/app`, `https://github.com/user/app` +- `codeberg.org/user/app` +- `gitlab.com/csoport/alcsoport/projekt` +- saját szerver: `https://git.pelda.hu/user/app`, vagy kifejezetten `gitea:git.pelda.hu/user/app`, `gitlab:git.pelda.hu/csoport/projekt` + +Az app a **Felfedezés** alatt jelenik meg, és telepítés után saját csempét kap a kezdőképernyőn. A frissítéseket a TV 6 óránként keresi, és a következő induláskor élesíti őket. A Beállítások → Rendszer → Frissítések → „Telepítés most” azonnal telepít. + +**Katalógus-repó** (több app egy forrásként): egy repó, amelynek az alapértelmezett ágán egy `smartfox-store.toml` van: +```toml +name = "Családi katalógus" +apps = [ + "https://github.com/valaki/app", + "codeberg.org/masvalaki/jatek", +] +``` + +--- + +## 9. Web app + +Csak egy `app.toml` (és egy ikon) kell, program nem: + +```toml +id = "io.github.example.mytv" +name = "My TV" +version = "1.0.0" +kind = "web" +url = "https://example.com/tv" +description = "..." +icon = "icon.png" +accent = "#3d7bff" + +[web] +user_agent_suffix = "SMART-TV SmartFox" +``` + +`package.sh` web apphoz: +```sh +set -euo pipefail +rm -rf pkg dist && mkdir pkg +cp app.toml pkg/ && [ -f icon.png ] && cp icon.png pkg/ +sf-pack build pkg dist && sf-pack verify dist +``` + +Az oldal a beépített Chromiumban fut, teljes képernyőn (kiosk). Az oldal kezelje a nyilakat, az Entert és az Escape-et `keydown` eseményből (`ArrowUp`/`ArrowDown`/`ArrowLeft`/`ArrowRight`, `Enter`, `Escape`, `MediaPlayPause`), és mindig legyen egy fókuszban lévő elem. A sütik és a bejelentkezés megmaradnak (saját Chromium-profil az app adatmappájában). + +--- + +## 10. Ellenőrzőlista release előtt + +- [ ] `id` fordított domain név, nem változott az előző release óta +- [ ] `version` emelve, egyezik a taggel, csak számok +- [ ] `permissions`: csak ami kell; új engedély = a felhasználónak jóvá kell hagynia +- [ ] Debian trixie-n (vagy régebbin) fordult, x86_64 +- [ ] Minden nem rendszer-lib a csomagban van, vagy statikusan linkelt +- [ ] Wayland-only, teljes képernyő, a felbontáshoz skáláz (1080p és 4K) +- [ ] Nyilakkal, Enterrel és Escape-pel minden elérhető; mindig van látható fókusz +- [ ] Escape a gyökérképernyőn → kilépés +- [ ] Csak a `$HOME`-ba ír; az állapotot menet közben menti; a SIGTERM-et kezeli +- [ ] Bírja a SIGSTOP/SIGCONT-ot (háttérbe kerülés) +- [ ] `sf-pack run pkg` alatt működik (sandbox, ugyanazok az engedélyek) +- [ ] `sf-pack verify dist` OK +- [ ] A repó nyilvános, a release nem draft és nem pre-release diff --git a/docs/store.md b/docs/store.md new file mode 100644 index 0000000..1d22018 --- /dev/null +++ b/docs/store.md @@ -0,0 +1,143 @@ +# App Store és sandbox + +A Fennec OS appjai két helyről jönnek: +- **Hivatalos appok:** a gyári appok (az image-ben) és azok csomagjai (`sf-app-<id>`, a Fennec OS kulcsával aláírva, a Gitea registryből). Ide tartozik a Steam is. Lásd: [updates.md](updates.md). +- **Store appok:** külső, nyílt forrású appok. Mindegyik a saját GitHub-, Gitea/Forgejo- (pl. Codeberg) vagy GitLab-repójában él, és a release-eiből települ. + +Minden app **sandboxban** fut (bubblewrap, a Flatpak építőköve). Kivételek, mert ezek rendszer-szolgáltatások: az AirPlay és a Miracast vevő. Ezek gyári appok, és az `app.toml`-jukban `[sandbox] enabled = false` áll. Store app ezt nem teheti meg. + +## A sandbox +Amit egy app lát (`crates/sf-ipc/src/sandbox.rs`): + +| Mit | Hogyan | +|---|---| +| A rendszer | `/usr`, `/etc` csak olvasva | +| Az app saját fájljai | `/app`, csak olvasva (`$SMARTFOX_APP_DIR`) | +| Az app adatai | `$HOME` = a TV-n `~/.local/share/smartfox/apps/<id>`; csak ez írható tartósan | +| Kép | a Wayland socket | +| Ideiglenes | saját `/tmp`, `/run`, `/var`; saját PID-, IPC- és UTS-névtér | +| Ami nincs | más appok és a felhasználó fájljai, a launcher / sf-core / kompozitor socketje, hálózat, hang, eszközök, D-Bus (engedély nélkül) | + +**Engedélyek** (`[sandbox] permissions`): ezeket a TV telepítés előtt megmutatja. + +| Engedély | Mit nyit meg | +|---|---| +| `network` | internet és helyi hálózat (DNS is) | +| `gpu` | `/dev/dri`, `/sys`: hardveres grafika és videódekódolás | +| `audio` | PipeWire / PulseAudio socket | +| `gamepad` | `/dev/input`, `/dev/hidraw*`, `/dev/uinput`, udev: játékvezérlők | +| `dbus-session` | a munkamenet D-Bus-a (szűretlen, **kockázatos**) | +| `dbus-system` | a rendszer D-Bus-a (szűretlen, **kockázatos**) | +| `devices` | minden eszköz `/dev` alatt (**kockázatos**) | + +A web appok (Chromium) mindig megkapják a `network`, `gpu` és `audio` engedélyt. A Chromium profilja is a sandboxba költözik (`<adat>/chromium`). A régi profil (`~/.config/smartfox/profiles/<id>`) az első indításkor átköltözik, így a bejelentkezések megmaradnak. + +**Hibakeresés:** a `SMARTFOX_SANDBOX=off` (a `/var/lib/smartfox/session.env` fájlban) a hivatalos appokat sandbox nélkül indítja. A store appokra nem hat: azok bubblewrap nélkül el sem indulnak. + +**Korlátok:** +- nincs seccomp-szűrő és D-Bus-proxy (a Flatpak mindkettőt használja). A D-Bus engedélyek ezért teljes hozzáférést adnak. +- `/etc` egésze olvasható; a titkos fájlok (`shadow`, kulcsok) amúgy is csak a rootnak olvashatók. + +## Store források +A Store app (a launcherben) → **Források** → „Forrás hozzáadása”. Egy forrás kétféle lehet: +- **App-repó:** egyetlen app, pl. `github.com/valaki/app`. +- **Katalógus-repó:** sok app listája. Az alapértelmezett ágon egy `smartfox-store.toml` fájl: + ```toml + name = "Családi katalógus" + apps = [ + "https://github.com/valaki/app", + "https://codeberg.org/masvalaki/jatek", + "gitlab.com/csoport/alcsoport/projekt", + ] + ``` + +**Elfogadott címek:** +- `https://github.com/o/r`, `github.com/o/r`, `github:o/r`; +- `gitlab.com/csoport/projekt` (alcsoportokkal is); +- `codeberg.org/o/r`; +- saját szerver: `https://git.pelda.hu/o/r` (a TV kitalálja, Gitea-e vagy GitLab), vagy kifejezetten `gitea:git.pelda.hu/o/r`, `gitlab:git.pelda.hu/csoport/projekt`. + +Csak `https://` engedett. A repónak nyilvánosnak kell lennie: a TV bejelentkezés nélkül tölt, és a Fennec OS registry-tokenje sosem megy külső szerverre. + +**Egy release** a legújabb nem-draft, nem-prerelease kiadás, amelyben van `app.toml`. Két fájl (asset) kell bele: + +| Fájl | Mi | +|---|---| +| `app.toml` | a manifest: név, leírás, engedélyek | +| `<id>-<verzió>.tar.zst` | a csomag | + +## Biztonság +- **Az app azonosítója** fordított domain név legalább egy ponttal (`io.github.valaki.app`). A hivatalos appok azonosítójában nincs pont, így store app sosem léphet egy hivatalos app helyére. Két forrás ugyanazzal az azonosítóval: az nyer, ahonnan telepítve van. +- **Forrás:** a TV a felhasználó által kiválasztott repó release-eiből frissít. A repó tulajdonosában és tartalmában a felhasználó bízik meg. +- **Engedélyek:** csak a jóváhagyott engedélyekkel települ. Ha egy frissítés többet kér, vár, amíg a Store-ban jóvá nem hagyod. A TV a letöltött csomagban lévő `app.toml`-t is ellenőrzi, nem csak a release-ét. +- **Kibontás:** csak sima fájl, mappa és csomagon belül maradó symlink lehet benne. Setuid/setgid bitek és mások által írható fájlok nincsenek; méret- és fájlszám-korlát van. +- **Szabályok** (`check_store_rules`): store app nem lehet `builtin` vagy háttérszolgáltatás, nem kapcsolhatja ki a sandboxot, nem regisztrálhat DIAL-ra; web app csak `https://` címmel. + +## A TV-n +``` +/var/lib/smartfox/store.toml amit a felhasználó kért (a launcher írja, tv) +/var/lib/sf-pkg/store/catalog.json amit a források kínálnak (sf-update, root) +/var/lib/sf-pkg/store-<id>/ a telepített verziók, mint bármely csomagnál + <verzió>/ current previous staged bad + source a repó, ahonnan jött +/var/lib/sf-pkg/store/apps/<id> -> ../../store-<id>/current (ezt olvassa a launcher és az sf-core) +~/.local/share/smartfox/apps/<id>/ az app adatai ($HOME a sandboxban) +``` + +**`store.toml`:** +```toml +sources = ["https://github.com/valaki/katalogus"] + +[apps."io.github.valaki.app"] +source = "https://github.com/valaki/app" +permissions = ["network", "audio"] # amit jóváhagytál +``` + +**Folyamat:** +1. A Store képernyő átírja a `store.toml`-t, és `store` kérést tesz az `update-requests` mappába. +2. Az `sf-update store` (root) lekérdezi a forrásokat, és megírja a `catalog.json`-t. +3. Ezután letölti, ellenőrzi és azonnal élesíti az új vagy jóváhagyott appokat, a kivetteket pedig eltávolítja. +4. Amikor kilépsz a Store-ból, a launcher újraindítja magát ugyanabban a folyamatban, és így megjelenik az új csempe. A futó appok és az sf-core közben futnak tovább. + +A `store.toml`-t a root óvatosan olvassa: symlinket nem követ, csak sima fájlt fogad el, méretkorláttal. + +**Frissítés:** pontosan úgy, mint a hivatalos csomagoknál. +- A 6 óránkénti `sf-update auto` a store appok új verzióit is letölti, és a következő induláskor élesednek. +- A Beállítások → Rendszer → Frissítések „Telepítés most” gombja azonnal telepít. + +**Eltávolítás:** az app fájljai törlődnek. Az adatai csak akkor, ha a Store-ban azt választod. + +## App készítése +**Teljes, önálló útmutató:** [store-app-guide.md](store-app-guide.md). Másold be az app repójába, és abból egy fejlesztő vagy egy AI meg tudja írni az appot. + +Rust app sablon: [`templates/rust-app`](../templates/rust-app). Benne van a manifest, a csomagoló script, és release pipeline GitHubra, Giteára/Forgejóra és GitLabra. + +1. **Csomagoló:** + ```sh + cargo install --git https://gitea.bluefox.support/bluefox/fox-in-the-box sf-pack + ``` +2. **Kipróbálás a sandboxban,** Linuxon, bubblewrappel: `sf-pack run <app-mappa>`. Ugyanúgy indítja, mint a TV: ugyanaz a sandbox, ugyanazok az engedélyek. +3. **Csomag:** `sf-pack build <app-mappa> dist`. A `dist/` mappába kerül a két release-fájl; ellenőrzés: `sf-pack verify dist`. +4. **Kiadás:** tag (`v1.2.3`) → a CI megépíti, és release-t csinál a két fájllal. +5. **A TV-n:** Store → Források → a repó címe → az app megjelenik a Felfedezés alatt. + +**Natív app (Rust vagy bármi más):** +- `kind = "exec"`, `exec = ["bin/app"]`: a relatív út a csomagon belül van, a `${app}` helyére a csomag mappája kerül. +- Csak Wayland van, X11 nincs. Slint, egui, iced, winit vagy GTK4/Qt6 Waylanddel jó. +- Debian trixie-n vagy régebbin fordíts, hogy a glibc ne legyen újabb a TV-énél. +- **Távirányító:** nyilak, Enter (kattintás), Escape (Vissza). A Home gombot a TV kezeli: az app megáll a háttérben, és onnan folytatódik. + +**Web app:** `kind = "web"`, `url = "https://..."`; a csomagban elég az `app.toml` (és egy ikon). + +**Ikon:** `icon = "icon.png"` (négyzetes PNG, legalább 256 px). Ha nincs, a csempén az app nevének kezdőbetűje látszik. + +## Steam +A Steam gyári app, nem store app: előtelepítve jön, és a hivatalos frissítési rendszer frissíti (`sf-app-steam`). +- **Forrás:** Valve hivatalos `steam-launcher` csomagja a `repo.steampowered.com`-ról (`tools/pkg/steam/package.sh`). +- **Ellenőrzés:** az `InRelease` Valve kulcsával aláírt (`tools/pkg/steam/valve-archive-keyring.gpg`; ugyanaz a kulcs, ami a csomagban van, ujjlenyomat: `BA18 16EF 8E75 005F CF5E 27A1 F24A EA9F B054 98B7`). A `Packages` és a `.deb` SHA256-ja is egyezik. +- **Verzió:** a Valve-é (pl. `1.0.0.87`). A CI hetente és minden pushkor megnézi, és ha van új, megépíti és feltölti az `sf-app-steam` csomagot. +- **Image:** az `image/build.sh` ugyanezzel a scripttel teszi a gyári példányt a `/usr/share/smartfox/apps/steam` mappába. A 32 bites függőségek (`steam-libs-i386`) a Valve repójából jönnek (`mkosi.postinst.chroot`), a kontroller udev-szabályok a Valve csomagjából. +- **Futás:** `apps/steam/bin/smartfox-steam`. A `gamescope` (Valve kompozitora, mint a Steam Decken) X szervert ad a Steam kliensnek és a játékoknak, és egy Wayland-ablakként mutatja őket. A Steam a kontrolleres felületével indul (`-gamepadui`). A játékok legfeljebb 1080p-ben renderelnek, a gamescope skálázza fel őket a TV felbontására. +- **Sandbox:** a Steam a saját konténerében (pressure-vessel) futtatja a játékokat, ez a mi sandboxunkba ágyazva fut. Engedélyei: `network`, `gpu`, `audio`, `gamepad`, `dbus-session`. Adatai és a játékok: `~/.local/share/smartfox/apps/steam`. +- **Két szint frissül:** a Steam kliens maga is frissíti magát az adatmappájában (ezt a Valve kezeli). A mi csomagunk a launchert (bootstrap) hozza. +- **Még nincs kipróbálva valódi TV-n:** gamescope beágyazott (nested) módban, Intel N100 Vulkannal, kontrollerrel. diff --git a/docs/updates.md b/docs/updates.md index f3c4cc9..1abe3e2 100644 --- a/docs/updates.md +++ b/docs/updates.md @@ -1,15 +1,17 @@ # Frissítések (csomagok) A TV nem image-et frissít, hanem csomagokat: -- `sf-shell`: a felület (`sf-launcher`, `sf-remote`, `sf-pair`); -- `sf-app-<id>`: egy-egy app (`apps/<id>/` tartalma). +- `sf-shell`: a felület és a frissítő (`sf-launcher`, `sf-remote`, `sf-update`, `sf-pair`); +- `sf-app-<id>`: egy-egy app (`apps/<id>/` tartalma); +- `store-<id>`: store appok a saját repójukból, aláírás nélkül. Ugyanez a rendszer frissíti őket; lásd [store.md](store.md). -Az image (rendszer, scriptek, unitok, `sf-update`) csak újratelepítéssel változik. A gyári shell és a gyári appok az image-ben maradnak, és tartalékként mindig elérhetők. +Az image rendszere, scriptjei és unitjai csak újratelepítéssel változnak. Az új `sf-update` a shell csomaggal érkezik az új rendszerképet használó TV-kre; a gyári példány tartalékként marad meg. ## Kiadás Egy csomag akkor jelenik meg, ha a verziója még nincs fent a registryben. Kiadáshoz emeld a verziót, és pushold a `main` ágat: - shell: `Cargo.toml` → `[workspace.package] version`; -- app: `apps/<id>/app.toml` → `version`. +- app: `apps/<id>/app.toml` → `version`; +- Steam: a Valve verziója. A `tools/pkg/steam/package.sh` mondja meg, a CI hetente is ránéz. A `.gitea/workflows/packages.yml` workflow a `build` runneren lefordítja, aláírja és feltölti a csomagot (`tools/pkg/packages.sh --upload`). Ugyanez kézzel, a WSL-ből: ```sh @@ -40,7 +42,7 @@ Registry: Gitea generic packages, `https://gitea.bluefox.support`, tulajdonos: ` - A privát kulcs: a `SF_SIGNING_KEY` CI-secret (a PEM fájl base64-ben, egy sorban, így a CI-napló maszkolja), és egy példány a fejlesztő gépén (`%USERPROFILE%\.smartfox\signing-key.pem`). - Aláírás nélküli vagy hibásan aláírt csomagot a TV nem telepít. Azt sem, amelyiknek a `pkg.toml`-ja más nevet vagy verziót mond. -**Csak release verzió települ** (`1.2.3`), előzetes verzió (`1.2.3-rc1`) nem. A TV csak a meglévőnél (a gyári és a telepített közül a nagyobbnál) újabbat tölt le. +**Csak release verzió települ** (`1.2.3`, legfeljebb négy tag: a Steam `1.0.0.87`), előzetes verzió (`1.2.3-rc1`) nem. A TV csak a meglévőnél (a gyári és a telepített közül a nagyobbnál) újabbat tölt le. **Belépés:** a `fox-tv` felhasználó tokenje, csak `read:package` joggal. Az image építésekor az `image/secrets/update-token` fájlból kerül a `/usr/share/smartfox/update-token` fájlba (`fox-tv:<token>`; a fájl nincs a gitben). Egy adott TV-n felülírható a `/var/lib/sf-pkg/update.toml` fájllal (`token_file`, `server` stb.). diff --git a/image/build-iso.sh b/image/build-iso.sh index 41be58f..81b5d5c 100644 --- a/image/build-iso.sh +++ b/image/build-iso.sh @@ -1,5 +1,5 @@ #!/usr/bin/env bash -# Builds the SmartFox installer ISO (UEFI, x86-64) for a USB stick. +# Builds the Fennec OS installer ISO (UEFI, x86-64) for a USB stick. # Run as root inside WSL Debian: # sudo bash /mnt/g/source/smartfox/image/build-iso.sh # Writes image/out/smartfox-installer.iso (in the source tree, so Rufus on @@ -7,7 +7,7 @@ # Raw writers (Etcher, dd) work too: the ISO carries a GPT with an ESP holding # the UKI, so UEFI firmware sees the stick as bootable. # -# SKIP_BUILD=1 reuses the last SmartFox image instead of running build.sh. +# SKIP_BUILD=1 reuses the last Fennec OS image instead of running build.sh. # Don't do that after booting it in run-qemu.sh: the VM writes into that file. set -euo pipefail @@ -43,7 +43,7 @@ rm -rf "$STAGE" mkdir -p "$STAGE/tree/EFI/BOOT" "$STAGE/tree/smartfox" cp "$UKI" "$STAGE/tree/EFI/BOOT/BOOTX64.EFI" stat -c %s "$RAW" >"$STAGE/tree/smartfox/smartfox.size" -echo "SmartFox $(grep -m1 '^version' "$WORK/Cargo.toml" | cut -d'"' -f2) · $(date +%Y-%m-%d)" >"$STAGE/tree/smartfox/version" +echo "Fennec OS $(grep -m1 '^version' "$WORK/Cargo.toml" | cut -d'"' -f2) · $(date +%Y-%m-%d)" >"$STAGE/tree/smartfox/version" zstd -T0 -10 -q "$RAW" -o "$STAGE/tree/smartfox/smartfox.raw.zst" # Rufus puts the files on FAT32: no single file may reach 4 GiB. [ "$(stat -c %s "$STAGE/tree/smartfox/smartfox.raw.zst")" -lt 4294967296 ] || { echo "payload too big for FAT32"; exit 1; } @@ -59,7 +59,7 @@ echo "== iso" ISO="$STAGE/smartfox-installer.iso" xorriso -as mkisofs \ -iso-level 3 -full-iso9660-filenames -joliet -joliet-long -rational-rock \ - -volid SMARTFOX -appid "SmartFox installer" \ + -volid FENNEC_OS -appid "Fennec OS installer" \ -partition_offset 16 \ -append_partition 2 C12A7328-F81F-11D2-BA4B-00A0C93EC93B "$EFI_IMG" -appended_part_as_gpt \ -e --interval:appended_partition_2:all:: -no-emul-boot \ diff --git a/image/build.sh b/image/build.sh index dbdd7c7..934d72c 100644 --- a/image/build.sh +++ b/image/build.sh @@ -1,5 +1,5 @@ #!/usr/bin/env bash -# Builds the SmartFox binaries and the OS disk image. +# Builds the Fennec OS binaries and the OS disk image. # Run as root inside WSL Debian (or any Debian/Ubuntu host): # sudo bash /mnt/g/source/smartfox/image/build.sh set -euo pipefail @@ -11,7 +11,7 @@ echo "== sync $SRC -> $WORK" mkdir -p "$WORK" # Files on NTFS show up as 0777; normalize, the image must not get world-writable files. rsync -a --delete --chmod=Du=rwx,Dgo=rx,Fu=rw,Fgo=r \ - --exclude /target --exclude /image/mkosi.output --exclude /image/mkosi.cache --exclude /image/stage --exclude /image/ovmf-vars.fd \ + --exclude /target --exclude '*/target' --exclude /image/mkosi.output --exclude /image/mkosi.cache --exclude /image/stage --exclude /image/ovmf-vars.fd \ --exclude /image/installer/mkosi.output --exclude /image/installer/mkosi.cache --exclude /image/iso --exclude /image/out \ "$SRC/" "$WORK/" cd "$WORK" @@ -21,7 +21,7 @@ if ! command -v cargo >/dev/null; then [ -x "$HOME/.cargo/bin/cargo" ] || curl -sSf https://sh.rustup.rs | sh -s -- -y --profile minimal export PATH="$HOME/.cargo/bin:$PATH" fi -cargo build --release -p sf-launcher -p sf-remote -p sf-update +cargo build --release -p sf-launcher -p sf-remote -p sf-update -p sf-core -p sf-miracast -p sf-compositor echo "== stage" STAGE="$WORK/image/stage" @@ -30,6 +30,9 @@ install -Dm755 target/release/sf-launcher "$STAGE/usr/bin/sf-launcher" install -Dm755 target/release/sf-remote "$STAGE/usr/bin/sf-remote" install -Dm755 tools/siri-remote/fastpair.py "$STAGE/usr/bin/sf-pair" install -Dm755 target/release/sf-update "$STAGE/usr/bin/sf-update" +for b in sf-core sf-miracast sf-compositor; do + install -Dm755 "target/release/$b" "$STAGE/usr/bin/$b" +done # Registry login for sf-update (read:package only). Kept out of git; without it # the TV can only update if the registry allows anonymous downloads. if [ -f image/secrets/update-token ]; then @@ -38,17 +41,37 @@ else echo "warning: image/secrets/update-token is missing, sf-update will log in anonymously" fi mkdir -p "$STAGE/usr/share/smartfox" -cp -r apps "$STAGE/usr/share/smartfox/apps" +# Official apps only: a folder with its own .git is a store app developed in +# place (docs/store-app-guide.md), not part of the image. +mkdir -p "$STAGE/usr/share/smartfox/apps" +for d in apps/*/; do + [ -e "$d/.git" ] && continue + cp -r "$d" "$STAGE/usr/share/smartfox/apps/" +done +# Apps with a packaging hook (Steam: the official steam-launcher from Valve). +for hook in tools/pkg/*/package.sh; do + id=$(basename "$(dirname "$hook")") + [ -d "$STAGE/usr/share/smartfox/apps/$id" ] || continue + echo "== $id $(bash "$hook" "$STAGE/usr/share/smartfox/apps/$id" | tail -1)" +done +chmod -R a+x "$STAGE"/usr/share/smartfox/apps/*/bin 2>/dev/null || true +# Steam's controller rules (uinput, Steam Controller, DualSense...) and the +# key of Valve's repository (mkosi.postinst.chroot: the 32-bit libraries). +if [ -d "$STAGE/usr/share/smartfox/apps/steam/udev" ]; then + mkdir -p "$STAGE/usr/lib/udev/rules.d" + cp "$STAGE"/usr/share/smartfox/apps/steam/udev/*.rules "$STAGE/usr/lib/udev/rules.d/" + install -Dm644 tools/pkg/steam/valve-archive-keyring.gpg "$STAGE/usr/share/keyrings/valve-archive-keyring.gpg" +fi # Versions of the factory copies: sf-update only installs newer packages. { echo "sf-shell = \"$(sed -n '/^\[workspace.package\]/,/^\[/ s/^version *= *"\(.*\)"/\1/p' Cargo.toml)\"" - for d in apps/*/; do + for d in "$STAGE"/usr/share/smartfox/apps/*/; do v=$(sed -n 's/^version *= *"\(.*\)".*/\1/p' "$d/app.toml" | head -1) [ -n "$v" ] && echo "sf-app-$(basename "$d") = \"$v\"" done } >"$STAGE/usr/share/smartfox/factory-versions.toml" mkdir -p "$STAGE/usr/share/doc/smartfox" -cp docs/updates.md "$STAGE/usr/share/doc/smartfox/updates.md" +cp docs/updates.md docs/store.md "$STAGE/usr/share/doc/smartfox/" chmod +x image/mkosi.postinst.chroot image/mkosi.extra/usr/bin/sf-session image/mkosi.extra/usr/bin/sf-launcher-start image/mkosi.extra/usr/bin/sf-remote-debug image/mkosi.extra/usr/bin/sf-diag image/mkosi.extra/usr/bin/sf-shell-exec image/*.sh tools/vm/*.sh tools/siri-remote/*.sh tools/siri-remote/*.py echo "== mkosi" diff --git a/image/installer/mkosi.conf b/image/installer/mkosi.conf index 8a08d10..f64faa5 100644 --- a/image/installer/mkosi.conf +++ b/image/installer/mkosi.conf @@ -1,5 +1,5 @@ -# SmartFox installer: a tiny Debian that runs entirely from RAM (packed as a -# UKI) and writes the SmartFox disk image from the install stick to a disk. +# Fennec OS installer: a tiny Debian that runs entirely from RAM (packed as a +# UKI) and writes the Fennec OS disk image from the install stick to a disk. # Built by ../build-iso.sh; not meant to be built on its own. [Distribution] diff --git a/image/installer/mkosi.extra/usr/bin/sf-install b/image/installer/mkosi.extra/usr/bin/sf-install index 097d4e5..cb63f34 100644 --- a/image/installer/mkosi.extra/usr/bin/sf-install +++ b/image/installer/mkosi.extra/usr/bin/sf-install @@ -1,5 +1,5 @@ #!/bin/bash -# SmartFox installer: writes the SmartFox disk image from the install stick +# Fennec OS installer: writes the Fennec OS disk image from the install stick # onto an internal disk. The disk is wiped completely. # # The stick (written by Rufus in ISO mode, or dd) carries: @@ -19,7 +19,7 @@ say() { printf '%s\n' "$*"; } banner() { clear say "" - say " SmartFox telepítő" + say " Fennec OS telepítő" say " =================" say "" } @@ -101,7 +101,7 @@ banner [ -n "$VERSION" ] && say " Verzió: $VERSION" && say "" [ "${#DISKS[@]}" -gt 0 ] || die "Nincs olyan belső lemez, amire telepíteni lehetne (legalább $(human $((NEED + 1024 * 1024 * 1024))) kell)." -say " Melyik lemezre telepítsem a SmartFoxot?" +say " Melyik lemezre telepítsem a Fennec OS-t?" say "" for i in "${!DISKS[@]}"; do say " $((i + 1))) $(describe "${DISKS[$i]}")" @@ -161,14 +161,14 @@ fi # Boot entry, so firmware that ignores the fallback path still finds it. ESP=$(lsblk -rpno NAME,PARTN "$TARGET" | awk '$2 == 1 { print $1 }') if [ -d /sys/firmware/efi/efivars ] && [ -n "$ESP" ]; then - efibootmgr -q -c -d "$TARGET" -p 1 -L SmartFox -l '\EFI\systemd\systemd-bootx64.efi' 2>/dev/null || + efibootmgr -q -c -d "$TARGET" -p 1 -L "Fennec OS" -l '\EFI\systemd\systemd-bootx64.efi' 2>/dev/null || say " (A UEFI boot bejegyzés nem jött létre, a gép a tartalék útvonalról indul.)" fi sync umount "$SRC" 2>/dev/null banner -say " Kész! A SmartFox telepítve: $TARGET" +say " Kész! A Fennec OS telepítve: $TARGET" say "" say " Húzd ki a pendrive-ot, majd nyomj Entert az újraindításhoz." say " Az első indításkor a rendszer létrehozza az adatpartíciót, ez néhány másodperc." diff --git a/image/installer/mkosi.extra/usr/lib/systemd/system/sf-install.service b/image/installer/mkosi.extra/usr/lib/systemd/system/sf-install.service index c905cd2..d8fbb87 100644 --- a/image/installer/mkosi.extra/usr/lib/systemd/system/sf-install.service +++ b/image/installer/mkosi.extra/usr/lib/systemd/system/sf-install.service @@ -1,5 +1,5 @@ [Unit] -Description=SmartFox installer +Description=Fennec OS installer After=systemd-udevd.service systemd-udev-trigger.service Conflicts=getty@tty1.service diff --git a/image/mkosi.conf b/image/mkosi.conf index 4ce29c7..2055dd9 100644 --- a/image/mkosi.conf +++ b/image/mkosi.conf @@ -1,4 +1,4 @@ -# SmartFox OS image (dev build). Build with image/build.sh inside WSL/Linux. +# Fennec OS image (dev build). Build with image/build.sh inside WSL/Linux. [Distribution] Distribution=debian @@ -6,6 +6,11 @@ Release=trixie Architecture=x86-64 Repositories=main,contrib,non-free,non-free-firmware +[Build] +# mkosi.postinst.chroot adds i386 and Valve's repository for Steam's 32-bit +# libraries (mkosi itself installs one architecture only). +WithNetwork=yes + [Output] Format=disk ImageId=smartfox @@ -26,6 +31,7 @@ ExtraTrees=mkosi.extra ExtraTrees=stage Packages= systemd + apt systemd-sysv systemd-boot systemd-boot-efi @@ -81,5 +87,26 @@ Packages= pipewire pipewire-pulse wireplumber + libspa-0.2-bluetooth + pulseaudio-utils avahi-daemon uxplay + dbus-user-session + libpam-systemd + libseat1 + libinput10 + gstreamer1.0-tools + gstreamer1.0-plugins-base + gstreamer1.0-plugins-good + gstreamer1.0-plugins-bad + gstreamer1.0-libav + gstreamer1.0-pipewire + # TLS for GStreamer's HTTP source (HTTPS video streams, sf-ui video). + glib-networking + # App sandbox (sf_ipc::sandbox, docs/store.md). + bubblewrap + # Steam: gamescope hosts the X11 client and games; Vulkan for both. + gamescope/trixie-backports + mesa-vulkan-drivers + libvulkan1 + xdg-user-dirs diff --git a/image/mkosi.extra/etc/skel/.bash_profile b/image/mkosi.extra/etc/skel/.bash_profile index cd6c3fd..e02d251 100644 --- a/image/mkosi.extra/etc/skel/.bash_profile +++ b/image/mkosi.extra/etc/skel/.bash_profile @@ -1,4 +1,4 @@ -# Start the SmartFox session on the first console. +# Start the Fennec OS session on the first console. if [ "$(tty)" = "/dev/tty1" ]; then exec /usr/bin/sf-session fi diff --git a/image/mkosi.extra/usr/bin/sf-launcher-start b/image/mkosi.extra/usr/bin/sf-launcher-start index 2754d84..be8de17 100644 --- a/image/mkosi.extra/usr/bin/sf-launcher-start +++ b/image/mkosi.extra/usr/bin/sf-launcher-start @@ -1,5 +1,6 @@ #!/bin/sh -# Runs inside cage: apply the output mode, then start the launcher. +# Runs inside the compositor (sf-compositor, or cage as a fallback): apply +# the output mode, start sf-core, then the launcher. if [ -n "${SMARTFOX_MODE:-}" ]; then OUT=$(wlr-randr | awk 'NR==1 {print $1}') wlr-randr --output "$OUT" --custom-mode "$SMARTFOX_MODE" || @@ -31,4 +32,10 @@ if [ -x "$PKG/current/bin/sf-launcher" ]; then rm -f "$TRIES" fi fi -exec "$LAUNCHER" --fullscreen --apps /usr/share/smartfox/apps --apps /var/lib/sf-pkg/apps +# sf-core starts and freezes apps, runs DIAL (YouTube cast) and the AirPlay / +# Miracast receivers. It quits by itself when this Wayland session ends. +pkill -u "$(id -u)" -x sf-core 2>/dev/null +# Store apps (sandboxed, docs/store.md): /var/lib/sf-pkg/store/apps. +/usr/bin/sf-shell-exec sf-core --apps /usr/share/smartfox/apps --apps /var/lib/sf-pkg/apps --store-apps /var/lib/sf-pkg/store/apps & + +exec "$LAUNCHER" --fullscreen --apps /usr/share/smartfox/apps --apps /var/lib/sf-pkg/apps --store-apps /var/lib/sf-pkg/store/apps diff --git a/image/mkosi.extra/usr/bin/sf-session b/image/mkosi.extra/usr/bin/sf-session index 772b37c..0814378 100644 --- a/image/mkosi.extra/usr/bin/sf-session +++ b/image/mkosi.extra/usr/bin/sf-session @@ -1,5 +1,5 @@ #!/bin/sh -# SmartFox session: kiosk compositor (cage) with the launcher. +# Fennec OS session: kiosk compositor (cage) with the launcher. # Apps the launcher starts (Chromium etc.) appear full screen on top of it. CONF="$HOME/.config/smartfox" @@ -32,4 +32,15 @@ if [ -z "${SMARTFOX_MODE:-}" ] && systemd-detect-virt -q; then fi export SMARTFOX_MODE +# The compositor: sf-compositor (app switching, volume OSD). If it can't start +# (or crashes right away), fall back to cage so the TV still works. +# SMARTFOX_COMPOSITOR=cage in /etc/default/smartfox or session.env forces cage. +if [ "${SMARTFOX_COMPOSITOR:-sf-compositor}" != cage ]; then + start=$(date +%s) + /usr/bin/sf-shell-exec sf-compositor --drm -- /usr/bin/sf-launcher-start >>"$LOG" 2>&1 && exit 0 + if [ $(($(date +%s) - start)) -gt 20 ]; then + exit 1 # ran for a while: a normal exit/crash, getty restarts the session + fi + echo "sf-session: sf-compositor failed, falling back to cage" >>"$LOG" +fi exec cage -d -s -- /usr/bin/sf-launcher-start >>"$LOG" 2>&1 diff --git a/image/mkosi.extra/usr/lib/systemd/system/sf-data-init.service b/image/mkosi.extra/usr/lib/systemd/system/sf-data-init.service index e522ccc..f097d10 100644 --- a/image/mkosi.extra/usr/lib/systemd/system/sf-data-init.service +++ b/image/mkosi.extra/usr/lib/systemd/system/sf-data-init.service @@ -1,5 +1,5 @@ [Unit] -Description=SmartFox: fill the new data partition (/var) with the factory defaults +Description=Fennec OS: fill the new data partition (/var) with the factory defaults Documentation=file:/usr/lib/repart.d/50-sf-data.conf DefaultDependencies=no RequiresMountsFor=/var diff --git a/image/mkosi.extra/usr/lib/systemd/system/sf-remote-debug-boot.service b/image/mkosi.extra/usr/lib/systemd/system/sf-remote-debug-boot.service index f2bfcc4..4a25545 100644 --- a/image/mkosi.extra/usr/lib/systemd/system/sf-remote-debug-boot.service +++ b/image/mkosi.extra/usr/lib/systemd/system/sf-remote-debug-boot.service @@ -1,5 +1,5 @@ [Unit] -Description=SmartFox: remote debugging (ssh) off after boot +Description=Fennec OS: remote debugging (ssh) off after boot After=network.target [Service] diff --git a/image/mkosi.extra/usr/lib/systemd/system/sf-remote-debug.path b/image/mkosi.extra/usr/lib/systemd/system/sf-remote-debug.path index d94cb51..5bcd9fd 100644 --- a/image/mkosi.extra/usr/lib/systemd/system/sf-remote-debug.path +++ b/image/mkosi.extra/usr/lib/systemd/system/sf-remote-debug.path @@ -1,5 +1,5 @@ [Unit] -Description=SmartFox: watch the remote debugging switch +Description=Fennec OS: watch the remote debugging switch [Path] PathModified=/var/lib/smartfox/remote-debug diff --git a/image/mkosi.extra/usr/lib/systemd/system/sf-remote-debug.service b/image/mkosi.extra/usr/lib/systemd/system/sf-remote-debug.service index b6d2313..52785fc 100644 --- a/image/mkosi.extra/usr/lib/systemd/system/sf-remote-debug.service +++ b/image/mkosi.extra/usr/lib/systemd/system/sf-remote-debug.service @@ -1,5 +1,5 @@ [Unit] -Description=SmartFox: remote debugging (ssh) on or off +Description=Fennec OS: remote debugging (ssh) on or off After=network.target [Service] diff --git a/image/mkosi.extra/usr/lib/systemd/system/sf-remote.service b/image/mkosi.extra/usr/lib/systemd/system/sf-remote.service index d1ad63b..1a8f7ea 100644 --- a/image/mkosi.extra/usr/lib/systemd/system/sf-remote.service +++ b/image/mkosi.extra/usr/lib/systemd/system/sf-remote.service @@ -1,5 +1,5 @@ [Unit] -Description=SmartFox Siri Remote driver +Description=Fennec OS Siri Remote driver After=bluetooth.service Wants=bluetooth.service diff --git a/image/mkosi.extra/usr/lib/systemd/system/sf-update-apply.service b/image/mkosi.extra/usr/lib/systemd/system/sf-update-apply.service index 9968260..7675374 100644 --- a/image/mkosi.extra/usr/lib/systemd/system/sf-update-apply.service +++ b/image/mkosi.extra/usr/lib/systemd/system/sf-update-apply.service @@ -1,5 +1,5 @@ [Unit] -Description=SmartFox: switch downloaded packages live before the TV starts +Description=Fennec OS: switch downloaded packages live before the TV starts DefaultDependencies=no RequiresMountsFor=/var After=local-fs.target sf-data-init.service @@ -9,7 +9,7 @@ ConditionPathIsMountPoint=/var [Service] Type=oneshot RemainAfterExit=yes -ExecStart=/usr/bin/sf-update apply +ExecStart=/usr/bin/sf-shell-exec sf-update apply [Install] WantedBy=multi-user.target diff --git a/image/mkosi.extra/usr/lib/systemd/system/sf-update-auto.service b/image/mkosi.extra/usr/lib/systemd/system/sf-update-auto.service index 693b62a..03999dd 100644 --- a/image/mkosi.extra/usr/lib/systemd/system/sf-update-auto.service +++ b/image/mkosi.extra/usr/lib/systemd/system/sf-update-auto.service @@ -1,10 +1,10 @@ [Unit] -Description=SmartFox: download new shell and app packages (live at next boot) +Description=Fennec OS: download new shell and app packages (live at next boot) Wants=network-online.target After=network-online.target sf-update-apply.service [Service] Type=oneshot -ExecStart=/usr/bin/sf-update auto +ExecStart=/usr/bin/sf-shell-exec sf-update auto Nice=10 IOSchedulingClass=idle diff --git a/image/mkosi.extra/usr/lib/systemd/system/sf-update-auto.timer b/image/mkosi.extra/usr/lib/systemd/system/sf-update-auto.timer index 2da177b..f66302a 100644 --- a/image/mkosi.extra/usr/lib/systemd/system/sf-update-auto.timer +++ b/image/mkosi.extra/usr/lib/systemd/system/sf-update-auto.timer @@ -1,5 +1,5 @@ [Unit] -Description=SmartFox: look for package updates a few times a day +Description=Fennec OS: look for package updates a few times a day [Timer] OnBootSec=10min diff --git a/image/mkosi.extra/usr/lib/systemd/system/sf-update-requests.path b/image/mkosi.extra/usr/lib/systemd/system/sf-update-requests.path index c1680fa..3fdb572 100644 --- a/image/mkosi.extra/usr/lib/systemd/system/sf-update-requests.path +++ b/image/mkosi.extra/usr/lib/systemd/system/sf-update-requests.path @@ -1,5 +1,5 @@ [Unit] -Description=SmartFox: watch for update requests from the launcher +Description=Fennec OS: watch for update requests from the launcher Documentation=file:/usr/share/doc/smartfox/updates.md [Path] diff --git a/image/mkosi.extra/usr/lib/systemd/system/sf-update-requests.service b/image/mkosi.extra/usr/lib/systemd/system/sf-update-requests.service index a0b1d4f..1ee0e1a 100644 --- a/image/mkosi.extra/usr/lib/systemd/system/sf-update-requests.service +++ b/image/mkosi.extra/usr/lib/systemd/system/sf-update-requests.service @@ -1,7 +1,7 @@ [Unit] -Description=SmartFox: handle update requests (check, install, confirm, rollback) +Description=Fennec OS: handle update requests (check, install, confirm, rollback) After=network-online.target sf-update-apply.service [Service] Type=oneshot -ExecStart=/usr/bin/sf-update requests +ExecStart=/usr/bin/sf-shell-exec sf-update requests diff --git a/image/mkosi.extra/usr/lib/tmpfiles.d/smartfox.conf b/image/mkosi.extra/usr/lib/tmpfiles.d/smartfox.conf index ba505be..b47fe70 100644 --- a/image/mkosi.extra/usr/lib/tmpfiles.d/smartfox.conf +++ b/image/mkosi.extra/usr/lib/tmpfiles.d/smartfox.conf @@ -4,3 +4,6 @@ d /var/lib/smartfox 0755 tv tv - # request files (check, install, confirm, rollback; see docs/updates.md). d /var/lib/sf-pkg 0755 root root - d /var/lib/smartfox/update-requests 0755 tv tv - +# Store: installed store apps (root) and their links (docs/store.md). +d /var/lib/sf-pkg/store 0755 root root - +d /var/lib/sf-pkg/store/apps 0755 root root - diff --git a/image/mkosi.postinst.chroot b/image/mkosi.postinst.chroot index 657432c..0dc01a1 100644 --- a/image/mkosi.postinst.chroot +++ b/image/mkosi.postinst.chroot @@ -10,7 +10,7 @@ if [ ! -L /home ]; then ln -s var/home /home fi -# The TV user (uid 1000): auto-login on tty1 starts the SmartFox session. +# The TV user (uid 1000): auto-login on tty1 starts the Fennec OS session. if ! id tv >/dev/null 2>&1; then useradd -m -d /var/home/tv -u 1000 -s /bin/bash -G video,render,input,audio,bluetooth tv fi @@ -18,6 +18,24 @@ fi getent group netdev >/dev/null || groupadd -r netdev usermod -aG netdev tv +# Steam (apps/steam, docs/store.md): the client is 32-bit. Valve's metapackages +# pull in the i386 graphics and system libraries it needs; the launcher itself +# is the sf-app-steam package (factory copy in /usr/share/smartfox/apps/steam). +if [ -f /usr/share/keyrings/valve-archive-keyring.gpg ]; then + dpkg --add-architecture i386 + cat >/etc/apt/sources.list.d/steam.sources <<'EOF' +Types: deb +URIs: https://repo.steampowered.com/steam/ +Suites: stable +Components: steam +Architectures: amd64 i386 +Signed-By: /usr/share/keyrings/valve-archive-keyring.gpg +EOF + apt-get update -q + DEBIAN_FRONTEND=noninteractive apt-get install -y -q --no-install-recommends steam-libs-amd64 steam-libs-i386:i386 mesa-vulkan-drivers:i386 libvulkan1:i386 + apt-get clean +fi + systemctl enable systemd-networkd systemd-resolved iwd bluetooth sf-remote.service sf-data-init.service sf-remote-debug-boot.service sf-remote-debug.path sf-update-apply.service sf-update-requests.path sf-update-auto.timer # sshd only runs when remote debugging is on (Settings > System, sf-remote-debug). systemctl disable ssh.service ssh.socket 2>/dev/null || true diff --git a/image/run-qemu.sh b/image/run-qemu.sh index ed44b11..375b659 100644 --- a/image/run-qemu.sh +++ b/image/run-qemu.sh @@ -1,5 +1,5 @@ #!/usr/bin/env bash -# Boots the SmartFox image in QEMU (KVM). Under WSL the window shows up via WSLg. +# Boots the Fennec OS image in QEMU (KVM). Under WSL the window shows up via WSLg. # sudo bash image/run-qemu.sh [--no-gl] [--bt VID:PID] # ssh into the VM: ssh -p 2222 root@localhost (password: smartfox) set -euo pipefail @@ -43,7 +43,7 @@ if [ -n "${PULSE_SERVER:-}" ] || [ -S /mnt/wslg/PulseServer ]; then fi exec qemu-system-x86_64 \ - -name SmartFox -machine q35,accel=kvm -cpu host -smp 4 -m 4096 \ + -name "Fennec OS" -machine q35,accel=kvm -cpu host -smp 4 -m 4096 \ -drive if=pflash,format=raw,readonly=on,file="$CODE" \ -drive if=pflash,format=raw,file="$VARS" \ -drive file="$IMG",format=raw,if=virtio \ diff --git a/templates/rust-app/.gitea/workflows/release.yml b/templates/rust-app/.gitea/workflows/release.yml new file mode 100644 index 0000000..2641387 --- /dev/null +++ b/templates/rust-app/.gitea/workflows/release.yml @@ -0,0 +1,40 @@ +# Gitea / Forgejo (Codeberg): on a tag (v1.2.3), build, sign and publish a +# release with the three store assets. Secret: SF_SIGNING_KEY (base64 of +# key.pem on one line). The job token creates the release. +name: release +on: + push: + tags: ["v*"] +jobs: + release: + runs-on: ubuntu-latest + container: + image: debian:trixie + env: + SF_PACK_GIT: https://gitea.bluefox.support/bluefox/fox-in-the-box + steps: + - name: Checkout + run: | + apt-get update -qq + apt-get install -y -qq --no-install-recommends build-essential pkg-config curl ca-certificates git jq \ + libfontconfig1-dev libfreetype-dev libxkbcommon-dev >/dev/null + git clone --depth 1 --branch "$GITHUB_REF_NAME" \ + "${GITHUB_SERVER_URL%%://*}://oauth2:${{ secrets.GITHUB_TOKEN }}@${GITHUB_SERVER_URL#*://}/${GITHUB_REPOSITORY}.git" src + - name: Build and sign + env: + SF_SIGNING_KEY: ${{ secrets.SF_SIGNING_KEY }} + run: | + curl -sSf https://sh.rustup.rs | sh -s -- -y -q --profile minimal + export PATH="$HOME/.cargo/bin:$PATH" + cargo install -q --locked --git "$SF_PACK_GIT" sf-pack + cd src && ./package.sh + - name: Release + env: + TOKEN: ${{ secrets.GITHUB_TOKEN }} + run: | + api="$GITHUB_SERVER_URL/api/v1/repos/$GITHUB_REPOSITORY/releases" + id=$(curl -fsS -H "Authorization: token $TOKEN" -H "Content-Type: application/json" \ + -d "{\"tag_name\":\"$GITHUB_REF_NAME\",\"name\":\"$GITHUB_REF_NAME\"}" "$api" | jq -r .id) + for f in src/dist/*; do + curl -fsS -H "Authorization: token $TOKEN" -F "attachment=@$f" "$api/$id/assets?name=$(basename "$f")" >/dev/null + done diff --git a/templates/rust-app/.github/workflows/release.yml b/templates/rust-app/.github/workflows/release.yml new file mode 100644 index 0000000..64e6b5e --- /dev/null +++ b/templates/rust-app/.github/workflows/release.yml @@ -0,0 +1,36 @@ +# GitHub: on a tag (v1.2.3), build in Debian trixie, sign, and publish a +# release with the three store assets. Secret: SF_SIGNING_KEY (base64 of +# key.pem on one line: `base64 -w0 key.pem`). +name: release +on: + push: + tags: ["v*"] +permissions: + contents: write +jobs: + release: + runs-on: ubuntu-latest + container: debian:trixie + env: + SF_PACK_GIT: https://gitea.bluefox.support/bluefox/fox-in-the-box + steps: + - uses: actions/checkout@v4 + - name: Toolchain + run: | + apt-get update -qq + apt-get install -y -qq --no-install-recommends build-essential pkg-config curl ca-certificates git \ + libfontconfig1-dev libfreetype-dev libxkbcommon-dev gh >/dev/null + curl -sSf https://sh.rustup.rs | sh -s -- -y -q --profile minimal + echo "$HOME/.cargo/bin" >> "$GITHUB_PATH" + - name: sf-pack + run: cargo install -q --locked --git "$SF_PACK_GIT" sf-pack + - name: Build and sign + env: + SF_SIGNING_KEY: ${{ secrets.SF_SIGNING_KEY }} + run: ./package.sh + - name: Release + env: + GH_TOKEN: ${{ github.token }} + run: | + git config --global --add safe.directory "$PWD" + gh release create "$GITHUB_REF_NAME" dist/* --title "$GITHUB_REF_NAME" --notes "Fennec OS store release" diff --git a/templates/rust-app/.gitignore b/templates/rust-app/.gitignore new file mode 100644 index 0000000..4d7fb51 --- /dev/null +++ b/templates/rust-app/.gitignore @@ -0,0 +1,4 @@ +/target +/pkg +/dist +key.pem diff --git a/templates/rust-app/.gitlab-ci.yml b/templates/rust-app/.gitlab-ci.yml new file mode 100644 index 0000000..d9f6ea7 --- /dev/null +++ b/templates/rust-app/.gitlab-ci.yml @@ -0,0 +1,30 @@ +# GitLab: on a tag (v1.2.3), build, sign, put the three store assets into the +# project's generic package registry and make a release that links them. +# CI/CD variable: SF_SIGNING_KEY (base64 of key.pem on one line, masked). +# The project must be public, so TVs can download without a login. +release: + image: debian:trixie + rules: + - if: $CI_COMMIT_TAG =~ /^v/ + variables: + SF_PACK_GIT: https://gitea.bluefox.support/bluefox/fox-in-the-box + script: + - apt-get update -qq + - apt-get install -y -qq --no-install-recommends build-essential pkg-config curl ca-certificates git jq libfontconfig1-dev libfreetype-dev libxkbcommon-dev >/dev/null + - curl -sSf https://sh.rustup.rs | sh -s -- -y -q --profile minimal + - export PATH="$HOME/.cargo/bin:$PATH" + - cargo install -q --locked --git "$SF_PACK_GIT" sf-pack + - ./package.sh + - VERSION="${CI_COMMIT_TAG#v}" + - PKG="$CI_API_V4_URL/projects/$CI_PROJECT_ID/packages/generic/smartfox/$VERSION" + - links="[]" + - | + for f in dist/*; do + n=$(basename "$f") + curl -fsS --header "JOB-TOKEN: $CI_JOB_TOKEN" --upload-file "$f" "$PKG/$n" >/dev/null + links=$(echo "$links" | jq --arg n "$n" --arg u "$PKG/$n" '. + [{name: $n, url: $u, link_type: "package"}]') + done + - | + jq -n --arg t "$CI_COMMIT_TAG" --argjson l "$links" '{tag_name: $t, name: $t, assets: {links: $l}}' | + curl -fsS --header "JOB-TOKEN: $CI_JOB_TOKEN" --header "Content-Type: application/json" --data @- \ + "$CI_API_V4_URL/projects/$CI_PROJECT_ID/releases" >/dev/null diff --git a/templates/rust-app/Cargo.lock b/templates/rust-app/Cargo.lock new file mode 100644 index 0000000..4875784 --- /dev/null +++ b/templates/rust-app/Cargo.lock @@ -0,0 +1,5768 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "ab_glyph" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01c0457472c38ea5bd1c3b5ada5e368271cb550be7a4ca4a0b4634e9913f6cc2" +dependencies = [ + "ab_glyph_rasterizer", + "owned_ttf_parser", +] + +[[package]] +name = "ab_glyph_rasterizer" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "366ffbaa4442f4684d91e2cd7c5ea7c4ed8add41959a31447066e279e432b618" + +[[package]] +name = "accesskit" +version = "0.24.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3b7f7f85a7e5f68090000ed7622545829afd484d210358702ae4cb97dd0c320" +dependencies = [ + "uuid", +] + +[[package]] +name = "accesskit_atspi_common" +version = "0.19.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "023da0e5097f46df7092d5280b02efb9bbf8d93298daeced42652463e357d636" +dependencies = [ + "accesskit", + "accesskit_consumer", + "atspi-common", + "phf", + "serde", + "zvariant", +] + +[[package]] +name = "accesskit_consumer" +version = "0.38.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d10a236f96f87d70732e44520046785431ef01d5bcd6b041317bfadd2f88245" +dependencies = [ + "accesskit", + "hashbrown 0.16.1", +] + +[[package]] +name = "accesskit_ios" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "750c4e9f6ce888dfe8a10c0f1b5ceb646a7854fd46579d74919219d1bb314083" +dependencies = [ + "accesskit", + "accesskit_consumer", + "hashbrown 0.16.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", + "objc2-ui-kit 0.2.2", +] + +[[package]] +name = "accesskit_macos" +version = "0.26.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce02dc63b43f0c9296af9ac946312a2dc8814427d7a64d2d600971dac55b6076" +dependencies = [ + "accesskit", + "accesskit_consumer", + "hashbrown 0.16.1", + "objc2 0.5.3", + "objc2-app-kit 0.2.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "accesskit_unix" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03e156ed3802e35eefe894ef2671bc6c889303d8a7e110b5e1b48f504b91362f" +dependencies = [ + "accesskit", + "accesskit_atspi_common", + "async-channel", + "async-executor", + "async-task", + "atspi", + "futures-lite", + "futures-util", + "serde", + "zbus", +] + +[[package]] +name = "accesskit_windows" +version = "0.34.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "106c2b961215864d1c2e703ee63269c25c4e80a577ffb2c1017b9c17dcdf83a1" +dependencies = [ + "accesskit", + "accesskit_consumer", + "hashbrown 0.16.1", + "static_assertions", + "windows", + "windows-core", +] + +[[package]] +name = "accesskit_winit" +version = "0.33.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5b41e63a69f36d9f1f41e70464c7e5f72eee485ef26aab19f0b4f86e6c0a84c" +dependencies = [ + "accesskit", + "accesskit_ios", + "accesskit_macos", + "accesskit_unix", + "accesskit_windows", + "raw-window-handle", + "winit", +] + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "ahash" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a15f179cd60c4584b8a8c596927aadc462e27f2ca70c04e0071964a73ba7a75" +dependencies = [ + "cfg-if", + "getrandom 0.3.4", + "once_cell", + "version_check", + "zerocopy", +] + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "allocator-api2" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923" + +[[package]] +name = "android-activity" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f2a1bb052857d5dd49572219344a7332b31b76405648eabac5bc68978251bcd" +dependencies = [ + "android-properties", + "bitflags 2.13.2", + "cc", + "jni", + "libc", + "log", + "ndk", + "ndk-context", + "ndk-sys", + "num_enum", + "thiserror 2.0.21", +] + +[[package]] +name = "android-properties" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc7eb209b1518d6bb87b283c20095f5228ecda460da70b44f0802523dea6da04" + +[[package]] +name = "android_system_properties" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc" +dependencies = [ + "libc", +] + +[[package]] +name = "annotate-snippets" +version = "0.12.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a5b0a5ab8561c603f16c3b78c24a386b1f70e7fc1b1b1e8c15738828e4a176" +dependencies = [ + "anstyle", + "memchr", + "unicode-width", +] + +[[package]] +name = "anstyle" +version = "1.0.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000" + +[[package]] +name = "arboard" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aeb9553e62312c8756a5979254fc6d7da8bbeb5986a1e17037fab932f7037917" +dependencies = [ + "clipboard-win", + "log", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "parking_lot", + "percent-encoding", + "windows-sys 0.61.2", + "wl-clipboard-rs", + "x11rb", +] + +[[package]] +name = "arc-swap" +version = "1.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "380962b3d93b99642e50b9febf72c071e97e8b32d86eae9cf4ef582bb960ae6e" +dependencies = [ + "rustversion", +] + +[[package]] +name = "arrayref" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76a2e8124351fda1ef8aaaa3bbd7ebbcb486bbcd4225aca0aa0d84bb2db8fecb" + +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + +[[package]] +name = "as-raw-xcb-connection" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "175571dd1d178ced59193a6fc02dde1b972eb0bc56c892cde9beeceac5bf0f6b" + +[[package]] +name = "ash" +version = "0.38.0+1.3.281" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb44936d800fea8f016d7f2311c6a4f97aebd5dc86f09906139ec848cf3a46f" +dependencies = [ + "libloading", +] + +[[package]] +name = "async-broadcast" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "435a87a52755b8f27fcf321ac4f04b2802e337c8c4872923137471ec39c37532" +dependencies = [ + "event-listener", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-channel" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "924ed96dd52d1b75e9c1a3e6275715fd320f5f9439fb5a4a11fa51f4221158d2" +dependencies = [ + "concurrent-queue", + "event-listener-strategy", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-executor" +version = "1.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96bf972d85afc50bf5ab8fe2d54d1586b4e0b46c97c50a0c9e71e2f7bcd812a" +dependencies = [ + "async-task", + "concurrent-queue", + "fastrand", + "futures-lite", + "pin-project-lite", + "slab", +] + +[[package]] +name = "async-io" +version = "2.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "456b8a8feb6f42d237746d4b3e9a178494627745c3c56c6ea55d92ba50d026fc" +dependencies = [ + "autocfg", + "cfg-if", + "concurrent-queue", + "futures-io", + "futures-lite", + "parking", + "polling", + "rustix 1.1.5", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-lock" +version = "3.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "290f7f2596bd5b78a9fec8088ccd89180d7f9f55b94b0576823bbbdc72ee8311" +dependencies = [ + "event-listener", + "event-listener-strategy", + "pin-project-lite", +] + +[[package]] +name = "async-process" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc50921ec0055cdd8a16de48773bfeec5c972598674347252c0399676be7da75" +dependencies = [ + "async-channel", + "async-io", + "async-lock", + "async-signal", + "async-task", + "blocking", + "cfg-if", + "event-listener", + "futures-lite", + "rustix 1.1.5", +] + +[[package]] +name = "async-recursion" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f8abc12baad266b1c8cec146854c195b5864b4221d4b2ca7296a7ae82d9e451" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "async-signal" +version = "0.2.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52b5aaafa020cf5053a01f2a60e8ff5dccf550f0f77ec54a4e47285ac2bab485" +dependencies = [ + "async-io", + "async-lock", + "atomic-waker", + "cfg-if", + "futures-core", + "futures-io", + "rustix 1.1.5", + "signal-hook-registry", + "slab", + "windows-sys 0.61.2", +] + +[[package]] +name = "async-task" +version = "4.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b75356056920673b02621b35afd0f7dda9306d03c79a30f5c56c44cf256e3de" + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "atspi" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c77886257be21c9cd89a4ae7e64860c6f0eefca799bb79127913052bd0eefb3d" +dependencies = [ + "atspi-common", + "atspi-proxies", +] + +[[package]] +name = "atspi-common" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20c5617155740c98003016429ad13fe43ce7a77b007479350a9f8bf95a29f63d" +dependencies = [ + "enumflags2", + "serde", + "static_assertions", + "zbus", + "zbus-lockstep", + "zbus-lockstep-macros", + "zbus_names", + "zvariant", +] + +[[package]] +name = "atspi-proxies" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2230e48787ed3eb4088996eab66a32ca20c0b67bbd4fd6cdfe79f04f1f04c9fc" +dependencies = [ + "atspi-common", + "serde", + "zbus", +] + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bincode" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36eaf5d7b090263e8150820482d5d93cd964a81e4019913c972f4edcc6edb740" +dependencies = [ + "serde", + "unty", +] + +[[package]] +name = "bindgen" +version = "0.72.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "993776b509cfb49c750f11b8f07a46fa23e0a1386ffc01fb1e7d343efc387895" +dependencies = [ + "bitflags 2.13.2", + "cexpr", + "clang-sys", + "itertools 0.13.0", + "log", + "prettyplease", + "proc-macro2", + "quote", + "regex", + "rustc-hash 2.1.3", + "shlex 1.3.0", + "syn 2.0.119", +] + +[[package]] +name = "bit-set" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2f926cc3060f09db9ebc5b52823d85268d24bb917e472c0c4bea35780a7d" +dependencies = [ + "bit-vec", +] + +[[package]] +name = "bit-vec" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b71798fca2c1fe1086445a7258a4bc81e6e49dcd24c8d0dd9a1e57395b603f51" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +dependencies = [ + "serde_core", +] + +[[package]] +name = "block2" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c132eebf10f5cad5289222520a4a058514204aed6d791f1cf4fe8088b82d15f" +dependencies = [ + "objc2 0.5.3", +] + +[[package]] +name = "block2" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5" +dependencies = [ + "objc2 0.6.5", +] + +[[package]] +name = "blocking" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a70e4329df6cb94385eed412ec92375c3cdd8a6e502493d1229b6414e4036dfa" +dependencies = [ + "async-channel", + "async-task", + "futures-io", + "futures-lite", + "piper", +] + +[[package]] +name = "borsh" +version = "1.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a" +dependencies = [ + "bytes", + "cfg_aliases", +] + +[[package]] +name = "bumpalo" +version = "3.20.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" + +[[package]] +name = "by_address" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64fa3c856b712db6612c019f14756e64e4bcea13337a6b33b696333a9eaa2d06" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" +dependencies = [ + "bytemuck_derive", +] + +[[package]] +name = "bytemuck_derive" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a1f896587b6f2c069c73d2f0913e2d590c3990285cd2f0b6aa02b786b4c679c" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + +[[package]] +name = "bytes" +version = "1.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" + +[[package]] +name = "calloop" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b99da2f8558ca23c71f4fd15dc57c906239752dd27ff3c00a1d56b685b7cbfec" +dependencies = [ + "bitflags 2.13.2", + "log", + "polling", + "rustix 0.38.44", + "slab", + "thiserror 1.0.69", +] + +[[package]] +name = "calloop" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43b32313e937c8721c9d17ee9bf60699a6402b4b7c2cb6ac1bee0ffcaa4b4e5e" +dependencies = [ + "bitflags 2.13.2", + "polling", + "rustix 1.1.5", + "tracing", +] + +[[package]] +name = "calloop-wayland-source" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95a66a987056935f7efce4ab5668920b5d0dac4a7c99991a67395f13702ddd20" +dependencies = [ + "calloop 0.13.0", + "rustix 0.38.44", + "wayland-backend", + "wayland-client", +] + +[[package]] +name = "cc" +version = "1.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86e055fa6e3e40ad6187ba25b6855eeb635d5271f8e0f0e1e9a5826b8d75bea0" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex 2.0.1", +] + +[[package]] +name = "cexpr" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fac387a98bb7c37292057cffc56d62ecb629900026402633ae9160df93a8766" +dependencies = [ + "nom 7.1.3", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "cgl" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ced0551234e87afee12411d535648dd89d2e7f34c78b753395567aff3d447ff" +dependencies = [ + "libc", +] + +[[package]] +name = "chrono" +version = "0.4.45" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327" +dependencies = [ + "iana-time-zone", + "js-sys", + "num-traits", + "wasm-bindgen", + "windows-link", +] + +[[package]] +name = "clang-sys" +version = "1.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "157a8ba7b480713b56f4c09fd13fc3e0a22a5dfab8097ba61cbc5feef950788a" +dependencies = [ + "glob", + "libc", + "libloading", +] + +[[package]] +name = "clipboard-win" +version = "5.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "052af7878466feccda12ba7a6a67d019d712f296809559b47c12c8cc196d3a9a" +dependencies = [ + "error-code", +] + +[[package]] +name = "clru" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "197fd99cb113a8d5d9b6376f3aa817f32c1078f2343b714fff7d2ca44fdf67d5" +dependencies = [ + "hashbrown 0.16.1", +] + +[[package]] +name = "codespan-reporting" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af491d569909a7e4dee0ad7db7f5341fef5c614d5b8ec8cf765732aba3cff681" +dependencies = [ + "unicode-width", +] + +[[package]] +name = "color_quant" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" + +[[package]] +name = "combine" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "concurrent-queue" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "const-field-offset" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d535c69e75b4e3c69e17205b5b37a91936c54086cecd339b70071500786acb9c" +dependencies = [ + "const-field-offset-macro", + "field-offset", +] + +[[package]] +name = "const-field-offset-macro" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93d5848843a221ac268cfdd6bfd14e68d5d3dfa79d52c880aafab93f9517fb74" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "convert_case" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9" +dependencies = [ + "unicode-segmentation", +] + +[[package]] +name = "core-foundation" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "91e195e091a93c46f7102ec7818a2aa394e1e1771c3ab4825963fa03e45afb8f" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "core-graphics" +version = "0.23.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c07782be35f9e1140080c6b96f0d44b739e2278479f64e02fdab4e32dfd8b081" +dependencies = [ + "bitflags 1.3.2", + "core-foundation", + "core-graphics-types", + "foreign-types", + "libc", +] + +[[package]] +name = "core-graphics-types" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "45390e6114f68f718cc7a830514a96f903cccd70d02a8f6d9f643ac4ba45afaf" +dependencies = [ + "bitflags 1.3.2", + "core-foundation", + "libc", +] + +[[package]] +name = "countme" +version = "3.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7704b5fdd17b18ae31c4c1da5a2e0305a2bf17b5249300a9ee9ed7b72114c636" + +[[package]] +name = "crc32fast" +version = "1.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ba106e844045ddc02c20768ac4b0b7cb45f2cc2ecbd833ac9f5dacb183c2055" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "critical-section" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "790eea4361631c5e7d22598ecd5723ff611904e3344ce8720784c93e3d83d40b" + +[[package]] +name = "crossbeam-channel" +version = "0.5.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-queue" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03e8bd762f7479489c70ed6c768ddca99d7296857de437a68dcb2a94365b3fae" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "ctor" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83cf0d42651b16c6dfe68685716d18480d18a9c39c62d76e8cf3eb6ed5d8bcbf" +dependencies = [ + "dtor", +] + +[[package]] +name = "cursor-icon" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f27ae1dd37df86211c42e150270f82743308803d90a6f6e6651cd730d5e1732f" + +[[package]] +name = "data-url" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "be1e0bca6c3637f992fc1cc7cbc52a78c1ef6db076dbf1059c4323d6a2048376" + +[[package]] +name = "derive_more" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134" +dependencies = [ + "derive_more-impl", +] + +[[package]] +name = "derive_more-impl" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" +dependencies = [ + "convert_case", + "proc-macro2", + "quote", + "rustc_version", + "syn 2.0.119", + "unicode-xid", +] + +[[package]] +name = "dispatch" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bd0c93bb4b0c6d9b77f4435b0ae98c24d17f1c45b2ff844c6151a07256ca923b" + +[[package]] +name = "dispatch2" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", +] + +[[package]] +name = "displaydoc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6232dd377dcc64799954cbd3a9bb882e9cdc1308ccd87b1c098f1fb2eaf82a8" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "dlib" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab8ecd87370524b461f8557c119c405552c396ed91fc0a8eec68679eab26f94a" +dependencies = [ + "libloading", +] + +[[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] + +[[package]] +name = "downcast-rs" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75b325c5dbd37f80359721ad39aca5a29fb04c89279657cffdda8736d0c0b9d2" + +[[package]] +name = "dpi" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" + +[[package]] +name = "drm" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80bc8c5c6c2941f70a55c15f8d9f00f9710ebda3ffda98075f996a0e6c92756f" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "drm-ffi", + "drm-fourcc", + "libc", + "rustix 0.38.44", +] + +[[package]] +name = "drm-ffi" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51a91c9b32ac4e8105dec255e849e0d66e27d7c34d184364fb93e469db08f690" +dependencies = [ + "drm-sys", + "rustix 1.1.5", +] + +[[package]] +name = "drm-fourcc" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0aafbcdb8afc29c1a7ee5fbe53b5d62f4565b35a042a662ca9fecd0b54dae6f4" + +[[package]] +name = "drm-sys" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ecc8e1361066d91f5ffccff060a3c3be9c3ecde15be2959c1937595f7a82a9f8" +dependencies = [ + "libc", + "linux-raw-sys 0.9.4", +] + +[[package]] +name = "dtor" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edf234dd1594d6dd434a8fb8cada51ddbbc593e40e4a01556a0b31c62da2775b" + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "endi" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099" + +[[package]] +name = "enumflags2" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1027f7680c853e056ebcec683615fb6fbbc07dbaa13b4d5d9442b146ded4ecef" +dependencies = [ + "enumflags2_derive", + "serde", +] + +[[package]] +name = "enumflags2_derive" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67c78a4d8fdf9953a5c9d458f9efe940fd97a0cab0941c075a813ac594733827" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "error-code" +version = "3.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5343afd4a8365a643ac588dab4cf234a190c7f6c88c9f6dd6ffe00837661b7" + +[[package]] +name = "euclid" +version = "0.22.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06" +dependencies = [ + "num-traits", +] + +[[package]] +name = "event-listener" +version = "5.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a23add41df1562121a9393cb065eab5146a1242410f23a644851e90cfd669d2" +dependencies = [ + "parking", + "pin-project-lite", +] + +[[package]] +name = "event-listener-strategy" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8be9f3dfaaffdae2972880079a491a1a8bb7cbed0b8dd7a347f668b4150a3b93" +dependencies = [ + "event-listener", + "pin-project-lite", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "femtovg" +version = "0.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31eebf3ab1b76359ccd5f850c07a7c6b2722c64d9127c40e02358e83f3ff9b1a" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "fnv", + "glow", + "imgref", + "itertools 0.15.0", + "log", + "rgb", + "slotmap", + "swash", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "field-offset" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38e2275cc4e4fc009b0669731a1e5ab7ebf11f469eaede2bab9309a5b4d6057f" +dependencies = [ + "memoffset", + "rustc_version", +] + +[[package]] +name = "filetime" +version = "0.2.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c287a33c7f0a620c38e641e7f60827713987b3c0f26e8ddc9462cc69cf75759" +dependencies = [ + "cfg-if", + "libc", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "fixed_decimal" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2214fb00f669ee96bee5bb29dfb1ddabe058b2bc426817efc79afa03c9bc55ae" +dependencies = [ + "displaydoc", + "smallvec", + "writeable", +] + +[[package]] +name = "fixedbitset" +version = "0.5.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d674e81391d1e1ab681a28d99df07927c6d4aa5b027d7da16ba32d1d21ecd99" + +[[package]] +name = "flate2" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e634e2e0ebac1ee034020da1ca582e17ffe4e0f5e985823721e168928136dcb" +dependencies = [ + "crc32fast", + "miniz_oxide 0.9.1", + "zlib-rs", +] + +[[package]] +name = "float-cmp" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98de4bbd547a563b716d8dfa9aad1cb19bfab00f4fa09a6a4ed21dbcf44ce9c4" + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foldhash" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2" + +[[package]] +name = "foldhash" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb" + +[[package]] +name = "font-types" +version = "0.12.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "835ae9d781464a79026cde387f9cbc650c9a4909d7cf7e658b127e3c35d2f35d" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "fontdb" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2660c5e9157bf76d2db1294e4a9feba604ef610819a3b591088d0d8392a3290f" +dependencies = [ + "log", + "slotmap", + "tinyvec", +] + +[[package]] +name = "fontique" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6688bc1294fe7117d788937b6c53480169b29c566954af490830d4c09da9516a" +dependencies = [ + "hashbrown 0.17.1", + "linebender_resource_handle", + "memmap2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-text", + "objc2-foundation 0.3.2", + "parlance", + "read-fonts", + "roxmltree", + "smallvec", + "windows", + "windows-core", + "yeslogic-fontconfig-sys", +] + +[[package]] +name = "foreign-types" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965" +dependencies = [ + "foreign-types-macros", + "foreign-types-shared", +] + +[[package]] +name = "foreign-types-macros" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "foreign-types-shared" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" + +[[package]] +name = "form_urlencoded" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf" +dependencies = [ + "percent-encoding", +] + +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-lite" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f78e10609fe0e0b3f4157ffab1876319b5b0db102a2c60dc4626306dc46b44ad" +dependencies = [ + "fastrand", + "futures-core", + "futures-io", + "parking", + "pin-project-lite", +] + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[package]] +name = "futures-task" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd417de3d1d015fc3bfd2b1ea46dfc7bab72ef86f1cc7cc9c78e728b34a6d1fd" + +[[package]] +name = "futures-util" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d50a92467f8ba5dd6e3ee5d4bd04d73ab2e4e1c44474a0674821dfce14b79bc" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "gbm" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce852e998d3ca5e4a97014fb31c940dc5ef344ec7d364984525fd11e8a547e6a" +dependencies = [ + "bitflags 2.13.2", + "drm", + "drm-fourcc", + "gbm-sys", + "libc", +] + +[[package]] +name = "gbm-sys" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c13a5f2acc785d8fb6bf6b7ab6bfb0ef5dad4f4d97e8e70bb8e470722312f76f" +dependencies = [ + "libc", +] + +[[package]] +name = "gethostname" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" +dependencies = [ + "rustix 1.1.5", + "windows-link", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "libc", + "r-efi 6.0.0", +] + +[[package]] +name = "gif" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159" +dependencies = [ + "color_quant", + "weezl", +] + +[[package]] +name = "gl_generator" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a95dfc23a2b4a9a2f5ab41d194f8bfda3cabec42af4e39f08c339eb2a0c124d" +dependencies = [ + "khronos_api", + "log", + "xml-rs", +] + +[[package]] +name = "glob" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b" + +[[package]] +name = "glow" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "263218b0ba2b0715c3370fb04674f5f8aa331594b521c94ff0a8e4a8472d1386" +dependencies = [ + "js-sys", + "slotmap", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "glutin" +version = "0.32.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "12124de845cacfebedff80e877bb37b5b75c34c5a4c89e47e1cdd67fb6041325" +dependencies = [ + "bitflags 2.13.2", + "cfg_aliases", + "cgl", + "dispatch2", + "glutin_egl_sys", + "glutin_glx_sys", + "glutin_wgl_sys", + "libloading", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "once_cell", + "raw-window-handle", + "wayland-sys", + "windows-sys 0.52.0", + "x11-dl", +] + +[[package]] +name = "glutin-winit" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85edca7075f8fc728f28cb8fbb111a96c3b89e930574369e3e9c27eb75d3788f" +dependencies = [ + "cfg_aliases", + "glutin", + "raw-window-handle", + "winit", +] + +[[package]] +name = "glutin_egl_sys" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c4680ba6195f424febdc3ba46e7a42a0e58743f2edb115297b86d7f8ecc02d2" +dependencies = [ + "gl_generator", + "windows-sys 0.52.0", +] + +[[package]] +name = "glutin_glx_sys" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7bb2938045a88b612499fbcba375a77198e01306f52272e692f8c1f3751185" +dependencies = [ + "gl_generator", + "x11-dl", +] + +[[package]] +name = "glutin_wgl_sys" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c4ee00b289aba7a9e5306d57c2d05499b2e5dc427f84ac708bd2c090212cf3e" +dependencies = [ + "gl_generator", +] + +[[package]] +name = "gpu-allocator" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51255ea7cfaadb6c5f1528d43e92a82acb2b96c43365989a28b2d44ee38f8795" +dependencies = [ + "ash", + "hashbrown 0.16.1", + "log", + "presser", + "thiserror 2.0.21", + "windows", +] + +[[package]] +name = "grid" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b40ca9252762c466af32d0b1002e91e4e1bc5398f77455e55474deb466355ff5" + +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "num-traits", + "zerocopy", +] + +[[package]] +name = "harfrust" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c03d949a14aa089bbb282f7dd76a498a7f684428e4257202efc119ec010376f9" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "read-fonts", + "smallvec", +] + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" + +[[package]] +name = "hashbrown" +version = "0.15.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1" +dependencies = [ + "foldhash 0.1.5", +] + +[[package]] +name = "hashbrown" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100" +dependencies = [ + "allocator-api2", + "equivalent", + "foldhash 0.2.0", +] + +[[package]] +name = "hashbrown" +version = "0.17.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +dependencies = [ + "foldhash 0.2.0", +] + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "hello-fennec" +version = "1.0.0" +dependencies = [ + "slint", +] + +[[package]] +name = "hermit-abi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d231dfb89cfffdbc30e7fc41579ed6066ad03abda9e567ccafae602b97ec5024" + +[[package]] +name = "hermit-abi" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e17592d60ebacc7d5e169f4663c5f84f9161cc90328abcfe8456f41e4dfcb284" + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "htmlparser" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48ce8546b993eaf241d69ded33b1be6d205dd9857ec879d9d18bd05d3676e144" + +[[package]] +name = "i-slint-backend-linuxkms" +version = "1.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f519a8611a4982921e46e391015e5e40ceac5cc63813333ef91ada77df180d8" +dependencies = [ + "bytemuck", + "calloop 0.14.5", + "cfg_aliases", + "drm", + "gbm", + "glutin", + "i-slint-common", + "i-slint-core", + "i-slint-renderer-femtovg", + "i-slint-renderer-software", + "input", + "libseat", + "memmap2", + "nix", + "raw-window-handle", + "xkbcommon", +] + +[[package]] +name = "i-slint-backend-selector" +version = "1.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb974705d61ba56034f6129ff61f3e6282a2c0c07752f25e6cb417d81c0f0958" +dependencies = [ + "cfg-if", + "cfg_aliases", + "i-slint-backend-linuxkms", + "i-slint-backend-testing", + "i-slint-backend-winit", + "i-slint-common", + "i-slint-core", + "i-slint-core-macros", + "i-slint-renderer-femtovg", +] + +[[package]] +name = "i-slint-backend-testing" +version = "1.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01943d6c5ea5bc913d497bdaa423c309e7627afff47a6794bfd13be5c564209f" +dependencies = [ + "cfg_aliases", + "i-slint-common", + "i-slint-core", + "i-slint-renderer-software", + "vtable", +] + +[[package]] +name = "i-slint-backend-winit" +version = "1.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dae4fcf1b19e9cb109984d2af87d2b9485388c619265bff71dd523133888bee2" +dependencies = [ + "accesskit", + "accesskit_winit", + "arboard", + "block2 0.6.2", + "bytemuck", + "cfg-if", + "cfg_aliases", + "futures", + "glutin", + "glutin-winit", + "i-slint-common", + "i-slint-core", + "i-slint-core-macros", + "i-slint-renderer-femtovg", + "i-slint-renderer-skia", + "i-slint-renderer-software", + "imgref", + "lyon_path", + "muda", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", + "objc2-ui-kit 0.3.2", + "pin-weak", + "raw-window-handle", + "rgb", + "scoped-tls-hkt", + "scopeguard", + "softbuffer", + "strum", + "vtable", + "wasm-bindgen", + "web-sys", + "webbrowser", + "windows", + "winit", + "zbus", +] + +[[package]] +name = "i-slint-common" +version = "1.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68a578f3e4b681b2b9cbd326d3be19716e2fac51d00a8a5b00c0ef4ae923b5e6" +dependencies = [ + "derive_more", + "fontique", + "htmlparser", + "icu_decimal", + "icu_locale_core", + "icu_provider", + "pulldown-cmark", + "resvg", + "skrifa", +] + +[[package]] +name = "i-slint-compiler" +version = "1.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f55d48ebef05e2bf09ba5a1fc67bcb11033b9e12a2a50ed3105c7d25e2b539d0" +dependencies = [ + "annotate-snippets", + "by_address", + "data-url", + "derive_more", + "i-slint-common", + "icu_normalizer", + "icu_properties", + "indexmap", + "itertools 0.15.0", + "lyon_extra", + "lyon_path", + "num_enum", + "proc-macro2", + "quote", + "rowan", + "smol_str 0.3.7", + "strum", + "typed-index-collections", + "unicode-segmentation", + "url", +] + +[[package]] +name = "i-slint-core" +version = "1.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2ea15059d70bc31b1a8b1eb4c34f2c5df04cb7e53f36179b43c0261231d646" +dependencies = [ + "accesskit", + "async-channel", + "bitflags 2.13.2", + "cfg-if", + "chrono", + "clru", + "const-field-offset", + "derive_more", + "euclid", + "i-slint-common", + "i-slint-core-macros", + "icu_normalizer", + "image", + "js-sys", + "ksni", + "lyon_algorithms", + "lyon_extra", + "lyon_geom", + "lyon_path", + "num-traits", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "once_cell", + "parley", + "pin-project", + "pin-weak", + "portable-atomic", + "raw-window-handle", + "resvg", + "rgb", + "scopeguard", + "skrifa", + "slab", + "strum", + "swash", + "sys-locale", + "taffy", + "unicode-linebreak", + "unicode-script", + "unicode-segmentation", + "vtable", + "wasm-bindgen", + "web-sys", + "web-time", + "wgpu", + "windows", +] + +[[package]] +name = "i-slint-core-macros" +version = "1.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73f5a8a076de52f53be80caa826599ed2107b54c9d4a421e66dc06cf893a984c" +dependencies = [ + "quote", + "serde_json", + "syn 3.0.9", +] + +[[package]] +name = "i-slint-renderer-femtovg" +version = "1.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb0de504d57cdadf80c2abf7bcb8b7135a3716aee1f41b6ebb90ea93e3649d7c" +dependencies = [ + "cfg-if", + "const-field-offset", + "femtovg", + "glow", + "i-slint-common", + "i-slint-core", + "i-slint-core-macros", + "imgref", + "lyon_path", + "pin-weak", + "rgb", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "i-slint-renderer-skia" +version = "1.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc9c1cf02385f1d26fc1f423544e52390a8e5c2d89420a8042aa94b4fe109d1f" +dependencies = [ + "bytemuck", + "cfg-if", + "cfg_aliases", + "clru", + "const-field-offset", + "glow", + "glutin", + "i-slint-common", + "i-slint-core", + "i-slint-core-macros", + "lyon_path", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", + "objc2-quartz-core 0.3.2", + "pin-weak", + "raw-window-handle", + "read-fonts", + "scoped-tls-hkt", + "skia-safe", + "softbuffer", + "spin_on", + "unicode-segmentation", + "vtable", + "wgpu", + "wgpu-hal", + "windows", + "windows-core", + "write-fonts", +] + +[[package]] +name = "i-slint-renderer-software" +version = "1.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f8c641e138a2cc96537cac4481f5c7c8bb8dcc66d09acaed269329c8738628a" +dependencies = [ + "bytemuck", + "clru", + "derive_more", + "euclid", + "i-slint-common", + "i-slint-core", + "lyon_path", + "num-traits", + "skrifa", + "swash", + "zeno", +] + +[[package]] +name = "iana-time-zone" +version = "0.1.65" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470" +dependencies = [ + "android_system_properties", + "core-foundation-sys", + "iana-time-zone-haiku", + "js-sys", + "log", + "wasm-bindgen", + "windows-core", +] + +[[package]] +name = "iana-time-zone-haiku" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" +dependencies = [ + "cc", +] + +[[package]] +name = "icu_collections" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe090a42a0d3140fed8c63263ed1fecc02422cb2f4bfe55cd8de2de1b8e105dd" +dependencies = [ + "displaydoc", + "potential_utf", + "utf8_iter", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "icu_decimal" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1150ad5e272740670464934ee76facda43ef2e11f85c27b7ba76ccb33edf2d05" +dependencies = [ + "displaydoc", + "fixed_decimal", + "icu_decimal_data", + "icu_locale_core", + "icu_locale_fallback", + "icu_plurals", + "icu_provider", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_decimal_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5595ab78370d48abd24a062f3db115d5108dd0b65634352036cae532aebb0df8" + +[[package]] +name = "icu_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "serde", + "tinystr", + "writeable", + "zerovec", +] + +[[package]] +name = "icu_locale_fallback" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "406e9ae5b95d8aa37db6293405931b766a6172d1848daee22d70eb44aa78a43c" +dependencies = [ + "icu_locale_core", + "icu_locale_fallback_data", + "icu_provider", + "potential_utf", + "tinystr", + "zerovec", +] + +[[package]] +name = "icu_locale_fallback_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3632ebbd0c5c3637ba1a40bdf8288f2cb9d2268e73441a69d5fc73d7cfbaa87c" + +[[package]] +name = "icu_normalizer" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "404a3b8c486f205c87fe7f23ab6894d84a4ad76d6e4671ae1981ba7def87c599" +dependencies = [ + "icu_collections", + "icu_normalizer_data", + "icu_properties", + "icu_provider", + "smallvec", + "zerovec", +] + +[[package]] +name = "icu_normalizer_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20f0088bfb7441f7a37fa0c9e20cb1e9cba1cac6b9ce8cd2a6dc44294f8e8cbc" + +[[package]] +name = "icu_plurals" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ef046647b445acf95ce0f8083fa292467d3df649959fa9a20f3f8abfd957c5d" +dependencies = [ + "fixed_decimal", + "icu_locale_fallback", + "icu_plurals_data", + "icu_provider", + "zerovec", +] + +[[package]] +name = "icu_plurals_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d43ff7df2c1a1d41588a6ddcba354d513d4a3e10eec22c06fe56d13c12a848ea" + +[[package]] +name = "icu_properties" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ea83d991c56158f7cf898bf86436c1dfe7c07ee82fe88951f2695c9f37a379f" +dependencies = [ + "displaydoc", + "icu_collections", + "icu_locale_core", + "icu_properties_data", + "icu_provider", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_properties_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b98f29af82d02b163fe50161388350e743bb3107cc8e8c2f7314cb505faddfcf" + +[[package]] +name = "icu_provider" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413099315636c588ee8f011190b329b971a09a8fae9d157e01dcae8379468514" +dependencies = [ + "displaydoc", + "icu_locale_core", + "serde", + "stable_deref_trait", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_segmenter" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61b195dc605f81aa181bec9b3bd14e26cc71b903e4644f6af578ca9772c7a710" +dependencies = [ + "icu_collections", + "icu_locale_fallback", + "icu_provider", + "icu_segmenter_data", + "potential_utf", + "smallvec", + "utf8_iter", + "zerotrie", + "zerovec", +] + +[[package]] +name = "icu_segmenter_data" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "913a7d294ad056474749152107309fdee3ec17d2482d1ab70fdc61a81c64b9a3" + +[[package]] +name = "idna" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de" +dependencies = [ + "idna_adapter", + "smallvec", + "utf8_iter", +] + +[[package]] +name = "idna_adapter" +version = "1.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "image" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +dependencies = [ + "bytemuck", + "byteorder-lite", + "moxcms", + "num-traits", + "png", + "zune-core", + "zune-jpeg", +] + +[[package]] +name = "image-webp" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" +dependencies = [ + "byteorder-lite", + "quick-error", +] + +[[package]] +name = "imagesize" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65b27460c2c92b037f3f94c538ed9a3342f3fdf923606781629ccb35f82d042a" + +[[package]] +name = "imgref" +version = "1.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e44b0a4eaa4c82f441d50a963f2d5f05a787240aeee097597033e72accfd22f" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown 0.17.1", +] + +[[package]] +name = "input" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9793345a65d71317763a33066b5d8351f8760dde8d4930fe9e39b5f14a7959d" +dependencies = [ + "bitflags 2.13.2", + "input-sys", + "libc", + "log", + "udev", +] + +[[package]] +name = "input-sys" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36eee07d8e02bd95bf52b2e642cf13d33701b94c6e4b04fbf1d1fb07e9cb19e7" + +[[package]] +name = "io-lifetimes" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eae7b9aee968036d54dce06cebaefd919e4472e753296daccd6d344e3e2df0c2" +dependencies = [ + "hermit-abi 0.3.9", + "libc", + "windows-sys 0.48.0", +] + +[[package]] +name = "itertools" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186" +dependencies = [ + "either", +] + +[[package]] +name = "itertools" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b4baf93f58d4425749ca49a51c50ebab072c5df6994d08fed93541c331481dc" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" + +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys 0.4.1", + "log", + "simd_cesu8", + "thiserror 2.0.21", + "walkdir", + "windows-link", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258" +dependencies = [ + "jni-sys 0.4.1", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[package]] +name = "js-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7883d941dae510fb2d978fc3fe018c71c9e2892fd38854de3e8b92c2e5ad9cc5" +dependencies = [ + "cfg-if", + "futures-util", + "wasm-bindgen", +] + +[[package]] +name = "keyboard-types" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b750dcadc39a09dbadd74e118f6dd6598df77fa01df0cfcdc52c28dece74528a" +dependencies = [ + "bitflags 2.13.2", + "serde", + "unicode-segmentation", +] + +[[package]] +name = "khronos_api" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e2db585e1d738fc771bf08a151420d3ed193d9d895a36df7f6f8a9456b911ddc" + +[[package]] +name = "ksni" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bcc1cb43797140f74b711f1c4a49f48a7a7429f211c5fb78264e7bcd1e99caf" +dependencies = [ + "arc-swap", + "async-executor", + "async-io", + "async-lock", + "crossbeam-queue", + "futures-channel", + "futures-lite", + "futures-util", + "pastey", + "serde", + "task-local", + "zbus", +] + +[[package]] +name = "kurbo" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b60dfc32f652b926df6192e55525b16d186c69d47876c3ead4da5cc9f8450e2" +dependencies = [ + "arrayvec", + "euclid", + "polycool", + "smallvec", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libloading" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" +dependencies = [ + "cfg-if", + "windows-link", +] + +[[package]] +name = "libm" +version = "0.2.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6d2cec3eae94f9f509c767b45932f1ada8350c4bdb85af2fcab4a3c14807981" + +[[package]] +name = "libredox" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" +dependencies = [ + "bitflags 2.13.2", + "libc", + "plain", + "redox_syscall 0.9.5", +] + +[[package]] +name = "libseat" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6656c69b6e0366ffb83faa232f3e4fda5fc91161722d140f2c95ce2e90b1ef31" +dependencies = [ + "errno", + "libseat-sys", + "log", +] + +[[package]] +name = "libseat-sys" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8a484fa48be5f62a8d3ffed767779d0ab808cfead91de98ef4362d469097dfb" +dependencies = [ + "pkg-config", +] + +[[package]] +name = "libudev-sys" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c8469b4a23b962c1396b9b451dda50ef5b283e8dd309d69033475fa9b334324" +dependencies = [ + "libc", + "pkg-config", +] + +[[package]] +name = "linebender_resource_handle" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" + +[[package]] +name = "linux-raw-sys" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d26c52dbd32dccf2d10cac7725f8eae5296885fb5703b261f7d0a0739ec807ab" + +[[package]] +name = "linux-raw-sys" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd945864f07fe9f5371a27ad7b52a172b4b499999f1d97574c9fa68373937e12" + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "litrs" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4744e383959f0db86ede514b809b1c53251889093803c05267acc7d4e7030d70" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f9f8bd3e56ce4dfc153cf470fffbfa98c7620958b312ca5c3a4b8d5181fd13c6" + +[[package]] +name = "lyon_algorithms" +version = "1.0.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3a6b9d4e8b48acd531fbf1241ad9b270df6e60b6b92bdea1469f4f40899d805" +dependencies = [ + "lyon_path", + "num-traits", +] + +[[package]] +name = "lyon_extra" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7755f08423275157ad1680aaecc9ccb7e0cc633da3240fea2d1522935cc15c72" +dependencies = [ + "lyon_path", + "thiserror 2.0.21", +] + +[[package]] +name = "lyon_geom" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d82dd26aa4dc0b5b70b9115de59824842bcb43cf4a28e1b1e6d0ad148c93f93e" +dependencies = [ + "arrayvec", + "euclid", + "num-traits", +] + +[[package]] +name = "lyon_path" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c463f9c428b7fc5ec885dcd39ce4aa61e29111d0e33483f6f98c74e89d8621e" +dependencies = [ + "lyon_geom", + "num-traits", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memmap2" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" +dependencies = [ + "libc", +] + +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "minimal-lexical" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a" + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "moxcms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" +dependencies = [ + "num-traits", + "pxfm", +] + +[[package]] +name = "muda" +version = "0.19.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1dd04e60bc0b07438a6771710ee1698f98f6ebbc7f89b61264af1563b8aeb878" +dependencies = [ + "crossbeam-channel", + "dpi", + "keyboard-types", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "once_cell", + "png", + "thiserror 2.0.21", + "windows-sys 0.61.2", +] + +[[package]] +name = "naga" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a616d2fb8c89516ac2723a581f69d6c18576046bed761bd6b305e5618e6ae130" +dependencies = [ + "arrayvec", + "bit-set", + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "codespan-reporting", + "half", + "hashbrown 0.17.1", + "indexmap", + "libm", + "log", + "naga-types", + "num-traits", + "once_cell", + "rustc-hash 1.1.0", + "spirv", + "thiserror 2.0.21", + "unicode-ident", +] + +[[package]] +name = "naga-types" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "590afbf58a6f4f62873cd5cff4468061844bafa1cdf399cc954537c22d768d49" +dependencies = [ + "hashbrown 0.17.1", + "indexmap", + "rustc-hash 1.1.0", + "thiserror 2.0.21", +] + +[[package]] +name = "ndk" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4" +dependencies = [ + "bitflags 2.13.2", + "jni-sys 0.3.1", + "log", + "ndk-sys", + "num_enum", + "raw-window-handle", + "thiserror 1.0.69", +] + +[[package]] +name = "ndk-context" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" + +[[package]] +name = "ndk-sys" +version = "0.6.0+11769913" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873" +dependencies = [ + "jni-sys 0.3.1", +] + +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "libc", +] + +[[package]] +name = "nom" +version = "7.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d273983c5a657a70a3e8f2a01329822f3b8c8172b73826411a55751e404a0a4a" +dependencies = [ + "memchr", + "minimal-lexical", +] + +[[package]] +name = "nom" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" +dependencies = [ + "memchr", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", + "libm", +] + +[[package]] +name = "num_enum" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26" +dependencies = [ + "num_enum_derive", + "rustversion", +] + +[[package]] +name = "num_enum_derive" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "objc-sys" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb91bdd390c7ce1a8607f35f3ca7151b65afc0ff5ff3b34fa350f7d7c7e4310" + +[[package]] +name = "objc2" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19d5490aaf8f1d7cf7688dfa9b0ce07900e168852c45cd2c03f534dfd27cfd0b" +dependencies = [ + "objc-sys", + "objc2-encode", +] + +[[package]] +name = "objc2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8" +dependencies = [ + "objc2-encode", +] + +[[package]] +name = "objc2-app-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4e89ad9e3d7d297152b17d39ed92cd50ca8063a89a9fa569046d41568891eff" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "libc", + "objc2 0.5.3", + "objc2-core-data", + "objc2-core-image", + "objc2-foundation 0.2.2", + "objc2-quartz-core 0.2.2", +] + +[[package]] +name = "objc2-app-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", +] + +[[package]] +name = "objc2-cloud-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "74dd3b56391c7a0596a295029734d3c1c5e7e510a4cb30245f8221ccea96b009" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-core-location", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-contacts" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5ff520e9c33812fd374d8deecef01d4a840e7b41862d849513de77e44aa4889" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-core-data" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "617fbf49e071c178c0b24c080767db52958f716d9eabdf0890523aeae54773ef" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags 2.13.2", + "dispatch2", + "objc2 0.6.5", +] + +[[package]] +name = "objc2-core-graphics" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" +dependencies = [ + "bitflags 2.13.2", + "dispatch2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-io-surface", +] + +[[package]] +name = "objc2-core-image" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "55260963a527c99f1819c4f8e3b47fe04f9650694ef348ffd2227e8196d34c80" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", + "objc2-metal 0.2.2", +] + +[[package]] +name = "objc2-core-location" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "000cfee34e683244f284252ee206a27953279d370e309649dc3ee317b37e5781" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-contacts", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-core-text" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d" +dependencies = [ + "bitflags 2.13.2", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-encode" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" + +[[package]] +name = "objc2-foundation" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "dispatch", + "libc", + "objc2 0.5.3", +] + +[[package]] +name = "objc2-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "objc2 0.6.5", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-io-surface" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-link-presentation" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1a1ae721c5e35be65f01a03b6d2ac13a54cb4fa70d8a5da293d7b0020261398" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-app-kit 0.2.2", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-metal" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd0cba1276f6023976a406a14ffa85e1fdd19df6b0f737b063b95f6c8c7aadd6" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-metal" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0125f776a10d00af4152d74616409f0d4a2053a6f57fa5b7d6aa2854ac04794" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "objc2 0.6.5", + "objc2-foundation 0.3.2", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e42bee7bff906b14b167da2bac5efe6b6a07e6f7c0a21a7308d40c960242dc7a" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", + "objc2-metal 0.2.2", +] + +[[package]] +name = "objc2-quartz-core" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f" +dependencies = [ + "bitflags 2.13.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", +] + +[[package]] +name = "objc2-symbols" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0a684efe3dec1b305badae1a28f6555f6ddd3bb2c2267896782858d5a78404dc" +dependencies = [ + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-ui-kit" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8bb46798b20cd6b91cbd113524c490f1686f4c4e8f49502431415f3512e2b6f" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-cloud-kit", + "objc2-core-data", + "objc2-core-image", + "objc2-core-location", + "objc2-foundation 0.2.2", + "objc2-link-presentation", + "objc2-quartz-core 0.2.2", + "objc2-symbols", + "objc2-uniform-type-identifiers", + "objc2-user-notifications", +] + +[[package]] +name = "objc2-ui-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22" +dependencies = [ + "bitflags 2.13.2", + "block2 0.6.2", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", +] + +[[package]] +name = "objc2-uniform-type-identifiers" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44fa5f9748dbfe1ca6c0b79ad20725a11eca7c2218bceb4b005cb1be26273bfe" +dependencies = [ + "block2 0.5.1", + "objc2 0.5.3", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "objc2-user-notifications" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76cfcbf642358e8689af64cee815d139339f3ed8ad05103ed5eaf73db8d84cb3" +dependencies = [ + "bitflags 2.13.2", + "block2 0.5.1", + "objc2 0.5.3", + "objc2-core-location", + "objc2-foundation 0.2.2", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" +dependencies = [ + "critical-section", + "portable-atomic", +] + +[[package]] +name = "orbclient" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5df339f526ea9a60e371768d50efc2f2508c7203290731565d1f7a6f71d21747" +dependencies = [ + "libc", + "libredox", +] + +[[package]] +name = "ordered-float" +version = "5.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c7c9e0d9b23589f26070720bac724174bfec1083e82f7854cdd0267518343c0" +dependencies = [ + "num-traits", +] + +[[package]] +name = "ordered-stream" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aa2b01e1d916879f73a53d01d1d6cee68adbb31d6d9177a8cfce093cced1d50" +dependencies = [ + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "os_pipe" +version = "1.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7d8fae84b431384b68627d0f9b3b1245fcf9f46f6c0e3dc902e9dce64edd1967" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "owned_ttf_parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36820e9051aca1014ddc75770aab4d68bc1e9e632f0f5627c4086bc216fb583b" +dependencies = [ + "ttf-parser", +] + +[[package]] +name = "parking" +version = "2.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba" + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall 0.5.18", + "smallvec", + "windows-link", +] + +[[package]] +name = "parlance" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73072a9470554c8e794778acece2312661218aaabb635600957d952cf01c716e" + +[[package]] +name = "parley" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22d2ff88bd3f7d68d1d9b09c7e6209f9a8e8c05088295140a2bcf2e9b17038c5" +dependencies = [ + "accesskit", + "fontique", + "harfrust", + "hashbrown 0.17.1", + "icu_normalizer", + "icu_properties", + "icu_segmenter", + "linebender_resource_handle", + "parlance", + "parley_data", + "skrifa", +] + +[[package]] +name = "parley_data" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1567535334d6ba2d3cde19221ba9a7bd0fabb3cbd99046ddfb10ae061cfcc889" +dependencies = [ + "icu_properties", +] + +[[package]] +name = "pastey" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ee67f1008b1ba2321834326597b8e186293b049a023cdef258527550b9935b4" + +[[package]] +name = "percent-encoding" +version = "2.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" + +[[package]] +name = "petgraph" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455" +dependencies = [ + "fixedbitset", + "hashbrown 0.15.5", + "indexmap", +] + +[[package]] +name = "phf" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" +dependencies = [ + "phf_macros", + "phf_shared", + "serde", +] + +[[package]] +name = "phf_generator" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" +dependencies = [ + "fastrand", + "phf_shared", +] + +[[package]] +name = "phf_macros" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" +dependencies = [ + "phf_generator", + "phf_shared", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "phf_shared" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" +dependencies = [ + "siphasher", +] + +[[package]] +name = "pico-args" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5be167a7af36ee22fe3115051bc51f6e6c7054c9348e28deb4f49bd6f705a315" + +[[package]] +name = "pin-project" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2466b2336ed02bcdca6b294417127b90ec92038d1d5c4fbeac971a922e0e0924" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c96395f0a926bc13b1c17622aaddda1ecb55d49c8f1bf9777e4d877800a43f8b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd" + +[[package]] +name = "pin-utils" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13bee6c73da26345c729282832b60b0363cf3dd9f4bfd81d8551b7a1c889a113" + +[[package]] +name = "pin-weak" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b330c9d1b92dfe68442ca20b009c717d5f0b1e3cf4965e62f704c3c6e95a1305" + +[[package]] +name = "piper" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c835479a4443ded371d6c535cbfd8d31ad92c5d23ae9770a61bc155e4992a3c1" +dependencies = [ + "atomic-waker", + "fastrand", + "futures-io", +] + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "plain" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6" + +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags 2.13.2", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + +[[package]] +name = "polling" +version = "3.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0e4f59085d47d8241c88ead0f274e8a0cb551f3625263c05eb8dd897c34218" +dependencies = [ + "cfg-if", + "concurrent-queue", + "hermit-abi 0.5.3", + "pin-project-lite", + "rustix 1.1.5", + "windows-sys 0.61.2", +] + +[[package]] +name = "polycool" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50596ddc09eb5ad5f75cacd40209568e66df71baf86e1499a0e99c4cff12a5a6" +dependencies = [ + "arrayvec", +] + +[[package]] +name = "portable-atomic" +version = "1.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85" +dependencies = [ + "critical-section", +] + +[[package]] +name = "portable-atomic-util" +version = "0.2.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715" +dependencies = [ + "portable-atomic", +] + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "serde_core", + "writeable", + "zerovec", +] + +[[package]] +name = "presser" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa" + +[[package]] +name = "prettyplease" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b" +dependencies = [ + "proc-macro2", + "syn 2.0.119", +] + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit", +] + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "profiling" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5" + +[[package]] +name = "pulldown-cmark" +version = "0.13.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "278e9268c93b9e498a2da46c34d90ba93a3255eb99009646398f34bc73ab36eb" +dependencies = [ + "bitflags 2.13.2", + "memchr", + "unicase", +] + +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + +[[package]] +name = "quick-xml" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e660451e55124f798a69a5af3f49ccfbefbd41910eefd25caf2393e1f3473ec1" +dependencies = [ + "memchr", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "range-alloc" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca45419789ae5a7899559e9512e58ca889e41f04f1f2445e9f4b290ceccd1d08" + +[[package]] +name = "raw-window-handle" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" + +[[package]] +name = "raw-window-metal" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40d213455a5f1dc59214213c7330e074ddf8114c9a42411eb890c767357ce135" +dependencies = [ + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", +] + +[[package]] +name = "read-fonts" +version = "0.41.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "046a7d674daf459825b32f5062056d6882db0d2f5a479fbd76ccfc870ac18709" +dependencies = [ + "bytemuck", + "font-types", + "once_cell", +] + +[[package]] +name = "redox_syscall" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4722d768eff46b75989dd134e5c353f0d6296e5aaa3132e776cbdb56be7731aa" +dependencies = [ + "bitflags 1.3.2", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "redox_syscall" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "580c875845b41ecb1564ad1ae4703044cef774145e3d7a94dc2b3fa7c97868fd" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "regex" +version = "1.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d" +dependencies = [ + "aho-corasick", + "memchr", + "regex-automata", + "regex-syntax", +] + +[[package]] +name = "regex-automata" +version = "0.4.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4" + +[[package]] +name = "renderdoc-sys" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19b30a45b0cd0bcca8037f3d0dc3421eaf95327a17cad11964fb8179b4fc4832" + +[[package]] +name = "resvg" +version = "0.48.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67e3803f97b999e80cbf7c6ecdd07a8102204d92e1633cf48783720c521196bd" +dependencies = [ + "bytemuck", + "gif", + "image-webp", + "log", + "pico-args", + "rgb", + "svgtypes", + "tiny-skia 0.12.0", + "usvg", + "zune-jpeg", +] + +[[package]] +name = "rgb" +version = "0.8.53" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "rowan" +version = "0.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14b574c58582fa59fa43a2feb6608b8744184659f08a2e0117e4b8224d95ed61" +dependencies = [ + "countme", + "hashbrown 0.14.5", + "memoffset", + "rustc-hash 1.1.0", + "text-size", +] + +[[package]] +name = "roxmltree" +version = "0.21.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9da7f59328b09405b181fee1018925fad50f157afb43c0c0f5c522c256dd5907" +dependencies = [ + "memchr", +] + +[[package]] +name = "rustc-hash" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "0.38.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fdb5bc1ae2baa591800df16c9ca78619bf65c0488b41b96ccec5d11220d8c154" +dependencies = [ + "bitflags 2.13.2", + "errno", + "libc", + "linux-raw-sys 0.4.15", + "windows-sys 0.59.0", +] + +[[package]] +name = "rustix" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +dependencies = [ + "bitflags 2.13.2", + "errno", + "libc", + "linux-raw-sys 0.12.1", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "scoped-tls" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" + +[[package]] +name = "scoped-tls-hkt" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e9603871ffe5df3ac39cb624790c296dbd47a400d202f56bf3e414045099524d" + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "sctk-adwaita" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6277f0217056f77f1d8f49f2950ac6c278c0d607c45f5ee99328d792ede24ec" +dependencies = [ + "ab_glyph", + "log", + "memmap2", + "smithay-client-toolkit", + "tiny-skia 0.11.4", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "serde" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4148590afebada386688f18773da617792bf2ef03ffc1e4cbd2b1d45b023e0ba" +dependencies = [ + "serde_core", + "serde_derive", +] + +[[package]] +name = "serde_core" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67dca2c9c51e58a4791a4b1ed58308b39c64224d349a935ab5039aa360942a48" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.229" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7a5d71263a5a7d47b41f6b3f06ba276f10cc18b0931f1799f710578e2309348" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_json" +version = "1.0.154" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" +dependencies = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_repr" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "serde_spanned" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7523beb55eece201a2356bee0bbca0d1ab466c14c07703b2e0ee6d42cb0c2c" +dependencies = [ + "serde_core", +] + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "simplecss" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a9c6883ca9c3c7c90e888de77b7a5c849c779d25d74a1269b0218b14e8b136c" +dependencies = [ + "log", +] + +[[package]] +name = "siphasher" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256" + +[[package]] +name = "skia-bindings" +version = "0.153.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb325787c91b3f6c34a7c6f2b8a2297b20292d733ca53a08c233e5028aec49af" +dependencies = [ + "bindgen", + "cc", + "flate2", + "heck", + "pkg-config", + "regex", + "serde_json", + "tar", + "toml", +] + +[[package]] +name = "skia-safe" +version = "0.153.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c61cb643dac43067f3eb76c866635a74377ac0abca0ff2590674e1e295514c3d" +dependencies = [ + "bitflags 2.13.2", + "skia-bindings", + "windows", +] + +[[package]] +name = "skrifa" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "819ab7d62b1d3e72d9d9dea5650bac30424f9111364bb94928dbf5ecad1baa68" +dependencies = [ + "bytemuck", + "read-fonts", +] + +[[package]] +name = "slab" +version = "0.4.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5" + +[[package]] +name = "slint" +version = "1.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15e477d5ff6fec20909100ff8f7062432ebfbda7a62a0f37d0252aa126f38c83" +dependencies = [ + "const-field-offset", + "i-slint-backend-linuxkms", + "i-slint-backend-selector", + "i-slint-common", + "i-slint-core", + "i-slint-core-macros", + "i-slint-renderer-femtovg", + "i-slint-renderer-software", + "num-traits", + "once_cell", + "pin-weak", + "slint-macros", + "unicode-segmentation", + "vtable", +] + +[[package]] +name = "slint-macros" +version = "1.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35e74b13d20884dc480ce37d0fabbf02cb4bc0df2a595434feac96ca7c2a0f15" +dependencies = [ + "i-slint-compiler", + "proc-macro2", + "quote", + "spin_on", +] + +[[package]] +name = "slotmap" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038" +dependencies = [ + "version_check", +] + +[[package]] +name = "smallvec" +version = "1.16.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d0d5d4b1981b8bbbb7aed204cae5726d683d5d6ac7e74ec54122ea28f315e7c8" + +[[package]] +name = "smithay-client-toolkit" +version = "0.19.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3457dea1f0eb631b4034d61d4d8c32074caa6cd1ab2d59f2327bd8461e2c0016" +dependencies = [ + "bitflags 2.13.2", + "calloop 0.13.0", + "calloop-wayland-source", + "cursor-icon", + "libc", + "log", + "memmap2", + "rustix 0.38.44", + "thiserror 1.0.69", + "wayland-backend", + "wayland-client", + "wayland-csd-frame", + "wayland-cursor", + "wayland-protocols", + "wayland-protocols-wlr", + "wayland-scanner", + "xkeysym", +] + +[[package]] +name = "smol_str" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dd538fb6910ac1099850255cf94a94df6551fbdd602454387d0adb2d1ca6dead" +dependencies = [ + "serde", +] + +[[package]] +name = "smol_str" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eeb7109d23f319619d4cc0de5464613c8b7b1a09db2774a58101459cf6be2f10" +dependencies = [ + "borsh", + "serde_core", +] + +[[package]] +name = "softbuffer" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aac18da81ebbf05109ab275b157c22a653bb3c12cf884450179942f81bcbf6c3" +dependencies = [ + "as-raw-xcb-connection", + "bytemuck", + "fastrand", + "js-sys", + "memmap2", + "ndk", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "objc2-quartz-core 0.3.2", + "raw-window-handle", + "redox_syscall 0.5.18", + "rustix 1.1.5", + "tiny-xlib", + "tracing", + "wasm-bindgen", + "wayland-backend", + "wayland-client", + "wayland-sys", + "web-sys", + "windows-sys 0.61.2", + "x11rb", +] + +[[package]] +name = "spin_on" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "076e103ed41b9864aa838287efe5f4e3a7a0362dd00671ae62a212e5e4612da2" +dependencies = [ + "pin-utils", +] + +[[package]] +name = "spirv" +version = "0.4.0+sdk-1.4.341.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9571ea910ebd84c86af4b3ed27f9dbdc6ad06f17c5f96146b2b671e2976744f" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "static_assertions" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" + +[[package]] +name = "strict-num" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6637bab7722d379c8b41ba849228d680cc12d0a45ba1fa2b48f2a30577a06731" +dependencies = [ + "float-cmp", +] + +[[package]] +name = "strum" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9628de9b8791db39ceda2b119bbe13134770b56c138ec1d3af810d045c04f9bd" +dependencies = [ + "strum_macros", +] + +[[package]] +name = "strum_macros" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ab85eea0270ee17587ed4156089e10b9e6880ee688791d45a905f5b1ca36f664" +dependencies = [ + "heck", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "svgtypes" +version = "0.16.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "695b5790b3131dafa99b3bbfd25a216edb3d216dad9ca208d4657bfb8f2abc3d" +dependencies = [ + "kurbo", + "siphasher", +] + +[[package]] +name = "swash" +version = "0.2.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c2499c2d826531388872b2268718aed907a39bd785ab0dcfe57fab26283f92e" +dependencies = [ + "skrifa", + "yazi", + "zeno", +] + +[[package]] +name = "syn" +version = "2.0.119" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "syn" +version = "3.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d78c8dee4c7bf0e14673097256fed6142ce9d3b85a408189d07482442145823b" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "synstructure" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "901704edd0dfe137f1987838ee4f259e4e063c31371bdb423f7ae38ec6f77f02" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "sys-locale" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8eab9a99a024a169fe8a903cf9d4a3b3601109bcc13bd9e3c6fff259138626c4" +dependencies = [ + "js-sys", + "libc", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "taffy" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aea22054047c16c3f34d3ac473a2170be1424b1115b2a3adcf28cfb067c88859" +dependencies = [ + "arrayvec", + "grid", + "serde", + "slotmap", +] + +[[package]] +name = "tar" +version = "0.4.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f6221d9a6003c78398e3b239969f352578258df48c8eb051caadae0015bc840" +dependencies = [ + "filetime", + "libc", + "xattr", +] + +[[package]] +name = "task-local" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2972044a9e5e448a506a7ff6f0d03b566d8ef4cd6918a58fc59835a0f8666626" +dependencies = [ + "pin-project-lite", +] + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix 1.1.5", + "windows-sys 0.61.2", +] + +[[package]] +name = "text-size" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f18aa187839b2bdb1ad2fa35ead8c4c2976b64e4363c386d45ac0f7ee85c9233" + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl 2.0.21", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "tiny-skia" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83d13394d44dae3207b52a326c0c85a8bf87f1541f23b0d143811088497b09ab" +dependencies = [ + "arrayref", + "arrayvec", + "bytemuck", + "cfg-if", + "log", + "tiny-skia-path 0.11.4", +] + +[[package]] +name = "tiny-skia" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47ffee5eaaf5527f630fb0e356b90ebdec84d5d18d937c5e440350f88c5a91ea" +dependencies = [ + "arrayref", + "arrayvec", + "bytemuck", + "cfg-if", + "log", + "png", + "tiny-skia-path 0.12.0", +] + +[[package]] +name = "tiny-skia-path" +version = "0.11.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c9e7fc0c2e86a30b117d0462aa261b72b7a99b7ebd7deb3a14ceda95c5bdc93" +dependencies = [ + "arrayref", + "bytemuck", + "strict-num", +] + +[[package]] +name = "tiny-skia-path" +version = "0.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "edca365c3faccca67d06593c5980fa6c57687de727a03131735bb85f01fdeeb9" +dependencies = [ + "arrayref", + "bytemuck", + "strict-num", +] + +[[package]] +name = "tiny-xlib" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a90a0ca3ee6a69f2ad28fd11621a4c3f03b371f366be500b64df260c4ffbafb4" +dependencies = [ + "as-raw-xcb-connection", + "ctor", + "libloading", + "pkg-config", + "tracing", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "serde_core", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "pin-project-lite", +] + +[[package]] +name = "toml" +version = "1.1.8+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20489e00e4d8741d6be680764cc12e270655e375a20d1011e844a9c3379e678d" +dependencies = [ + "indexmap", + "serde_core", + "serde_spanned", + "toml_datetime", + "toml_parser", + "toml_writer", + "winnow", +] + +[[package]] +name = "toml_datetime" +version = "1.1.2+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b86d767906c6c42421dcba507eb9d203e779497710a47782a224bb871653053" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.25.17+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3641d5bbb5349a79e1020a242d251efbc546ad8048d133958323ce9c40a9c9c" +dependencies = [ + "indexmap", + "toml_datetime", + "toml_parser", + "winnow", +] + +[[package]] +name = "toml_parser" +version = "1.1.5+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c" +dependencies = [ + "winnow", +] + +[[package]] +name = "toml_writer" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "log", + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "tree_magic_mini" +version = "3.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8765b90061cba6c22b5831f675da109ae5561588290f9fa2317adab2714d5a6" +dependencies = [ + "memchr", + "nom 8.0.0", + "petgraph", +] + +[[package]] +name = "ttf-parser" +version = "0.25.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2df906b07856748fa3f6e0ad0cbaa047052d4a7dd609e231c4f72cee8c36f31" + +[[package]] +name = "typed-index-collections" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "898160f1dfd383b4e92e17f0512a7d62f3c51c44937b23b6ffc3a1614a8eaccd" +dependencies = [ + "bincode", + "serde", +] + +[[package]] +name = "udev" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af4e37e9ea4401fc841ff54b9ddfc9be1079b1e89434c1a6a865dd68980f7e9f" +dependencies = [ + "io-lifetimes", + "libc", + "libudev-sys", + "pkg-config", +] + +[[package]] +name = "uds_windows" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f6fb2847f6742cd76af783a2a2c49e9375d0a111c7bef6f71cd9e738c72d6e" +dependencies = [ + "memoffset", + "tempfile", + "windows-sys 0.61.2", +] + +[[package]] +name = "unicase" +version = "2.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f" + +[[package]] +name = "unicode-bidi" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-linebreak" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b09c83c3c29d37506a3e260c08c03743a6bb66a9cd432c6934ab501a190571f" + +[[package]] +name = "unicode-script" +version = "0.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "383ad40bb927465ec0ce7720e033cb4ca06912855fc35db31b5755d0de75b1ee" + +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "unicode-vo" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1d386ff53b415b7fe27b50bb44679e2cc4660272694b7b6f3326d8480823a94" + +[[package]] +name = "unicode-width" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "unty" +version = "0.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d49784317cd0d1ee7ec5c716dd598ec5b4483ea832a2dced265471cc0f690ae" + +[[package]] +name = "url" +version = "2.5.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" +dependencies = [ + "form_urlencoded", + "idna", + "percent-encoding", + "serde", +] + +[[package]] +name = "usvg" +version = "0.48.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "977d0a4abdef933f424a99fe09f95576e089b90aebc6f016a3bc813762493e91" +dependencies = [ + "base64", + "data-url", + "flate2", + "fontdb", + "harfrust", + "imagesize", + "kurbo", + "log", + "pico-args", + "roxmltree", + "simplecss", + "siphasher", + "skrifa", + "strict-num", + "svgtypes", + "tiny-skia-path 0.12.0", + "unicode-bidi", + "unicode-script", + "unicode-vo", + "xmlwriter", +] + +[[package]] +name = "utf8_iter" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be" + +[[package]] +name = "uuid" +version = "1.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a0e2d11620c50695fe12bbbfde96b3477fe606e7284c22d505c12ce51214514" +dependencies = [ + "js-sys", + "serde_core", + "wasm-bindgen", +] + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "vtable" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "515a4b5b1399cc46fb0dc4081436cb40a3852a2d3e94fd1fa50bb68a334896eb" +dependencies = [ + "const-field-offset", + "portable-atomic", + "stable_deref_trait", + "vtable-macro", +] + +[[package]] +name = "vtable-macro" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8191d73ececf73fc94e65809bf0e667525a0bcff9aeeb8d042a4173a508332a1" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "walkdir" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[package]] +name = "wasm-bindgen" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9bb54f33acc68fd454578d9820b0bde1a1a3d17aa17bb7b6595806d02886d409" +dependencies = [ + "cfg-if", + "once_cell", + "rustversion", + "wasm-bindgen-macro", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-futures" +version = "0.4.79" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3cbab34de2d982e9b48e18d216d04c4a6f641066ff19ffb699980f591ee3610e" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[package]] +name = "wasm-bindgen-macro" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e29d0c35b16e224a7eeb5cd2d25e3e1968fbd65604117b44d3b789d00ee8535" +dependencies = [ + "quote", + "wasm-bindgen-macro-support", +] + +[[package]] +name = "wasm-bindgen-macro-support" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f501a8bc3719dba86ef8ae4728879c08001bea749eb1333ac5b91e040e2a6b7" +dependencies = [ + "bumpalo", + "proc-macro2", + "quote", + "syn 3.0.9", + "wasm-bindgen-shared", +] + +[[package]] +name = "wasm-bindgen-shared" +version = "0.2.129" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23f0c9c52aa7cd7d77769a4cfe2a9adb1b331f489a41d912ce14513d5ab995c6" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "wayland-backend" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078" +dependencies = [ + "cc", + "downcast-rs", + "rustix 1.1.5", + "scoped-tls", + "smallvec", + "wayland-sys", +] + +[[package]] +name = "wayland-client" +version = "0.31.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073" +dependencies = [ + "bitflags 2.13.2", + "rustix 1.1.5", + "wayland-backend", + "wayland-scanner", +] + +[[package]] +name = "wayland-csd-frame" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "625c5029dbd43d25e6aa9615e88b829a5cad13b2819c4ae129fdbb7c31ab4c7e" +dependencies = [ + "bitflags 2.13.2", + "cursor-icon", + "wayland-backend", +] + +[[package]] +name = "wayland-cursor" +version = "0.31.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a52d18780be9b1314328a3de5f930b73d2200112e3849ca6cb11822793fb34d" +dependencies = [ + "rustix 1.1.5", + "wayland-client", + "xcursor", +] + +[[package]] +name = "wayland-protocols" +version = "0.32.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23d0c813de3daa2ed6520af85a3bd49b0e722a3078506899aa9686fea58dc4b6" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-plasma" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b6d8cf1eb2c1c31ed1f5643c88a6e53538129d4af80030c8cabd1f9fa884d91" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-protocols-wlr" +version = "0.3.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb04e52f7836d7c7976c78ca0250d61e33873c34156a2a1fc9474828ec268234" +dependencies = [ + "bitflags 2.13.2", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-scanner", +] + +[[package]] +name = "wayland-scanner" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "338e30461b3a2b67d70eb30a6d89f8e0c93a833e07d2ae89085cd070c4a00ac0" +dependencies = [ + "proc-macro2", + "quick-xml", + "quote", +] + +[[package]] +name = "wayland-sys" +version = "0.31.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8eab23fefc9e41f8e841df4a9c707e8a8c4ed26e944ef69297184de2785e3be" +dependencies = [ + "dlib", + "log", + "once_cell", + "pkg-config", +] + +[[package]] +name = "web-sys" +version = "0.3.106" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88261b9deccee56594c11a3460c462c41f58d148598fe70ad77070126a68aba4" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "web-time" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "webbrowser" +version = "1.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2c8ddfbbf66e501434657400268cefe51b95140a0266236415cda7627732df7" +dependencies = [ + "jni", + "log", + "ndk-context", + "objc2 0.6.5", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", + "url", + "web-sys", +] + +[[package]] +name = "weezl" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" + +[[package]] +name = "wgpu" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527ccdf43dd5b2e8676eed9984ce00e2bbb0a1b85b70c1969dcb6cd2eb55ab9e" +dependencies = [ + "arrayvec", + "bitflags 2.13.2", + "bytemuck", + "cfg-if", + "cfg_aliases", + "document-features", + "hashbrown 0.17.1", + "log", + "portable-atomic", + "profiling", + "raw-window-handle", + "smallvec", + "static_assertions", + "wgpu-core", + "wgpu-hal", + "wgpu-types", +] + +[[package]] +name = "wgpu-core" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "14c018fce9b6270aa203c2fdd56f3cce996713534bd757e4ea58c8560b121f14" +dependencies = [ + "arrayvec", + "bit-set", + "bit-vec", + "bitflags 2.13.2", + "bytemuck", + "cfg_aliases", + "document-features", + "hashbrown 0.17.1", + "indexmap", + "log", + "naga", + "naga-types", + "once_cell", + "parking_lot", + "portable-atomic", + "profiling", + "raw-window-handle", + "rustc-hash 1.1.0", + "smallvec", + "thiserror 2.0.21", + "wgpu-core-deps-apple", + "wgpu-core-deps-windows-linux-android", + "wgpu-hal", + "wgpu-naga-bridge", + "wgpu-types", +] + +[[package]] +name = "wgpu-core-deps-apple" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "061f3d319a40d39d00b1ecc2c33b89fe21d4e6fe01859df3500a3a8ecccd6b68" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-core-deps-windows-linux-android" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7586165fd5f6d881cb9ce4bb71f40d6caab2c0f1837e3fc1d9788a197fb6004f" +dependencies = [ + "wgpu-hal", +] + +[[package]] +name = "wgpu-hal" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6b7fb58561a792bc237628ba0792e332de418fefe145f13b5ed8201e6d52f58" +dependencies = [ + "android_system_properties", + "arrayvec", + "ash", + "bit-set", + "bitflags 2.13.2", + "block2 0.6.2", + "bytemuck", + "cfg-if", + "cfg_aliases", + "gpu-allocator", + "hashbrown 0.17.1", + "libc", + "libloading", + "log", + "naga", + "naga-types", + "objc2 0.6.5", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation 0.3.2", + "objc2-metal 0.3.2", + "objc2-quartz-core 0.3.2", + "once_cell", + "ordered-float", + "parking_lot", + "portable-atomic", + "portable-atomic-util", + "profiling", + "range-alloc", + "raw-window-handle", + "raw-window-metal", + "renderdoc-sys", + "smallvec", + "static_assertions", + "thiserror 2.0.21", + "wgpu-naga-bridge", + "wgpu-types", + "windows", + "windows-core", +] + +[[package]] +name = "wgpu-naga-bridge" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f62e73117bb7a62bfd9c5a5841438a823f6566c6442a808ee269d2d055c081" +dependencies = [ + "naga", + "wgpu-types", +] + +[[package]] +name = "wgpu-types" +version = "30.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "99dad6f1fbdbbdb4c278a6508b059d44688f5cebddf78d005a46a31340269286" +dependencies = [ + "bitflags 2.13.2", + "bytemuck", + "log", + "naga-types", + "raw-window-handle", + "static_assertions", +] + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "windows" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580" +dependencies = [ + "windows-collections", + "windows-core", + "windows-future", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610" +dependencies = [ + "windows-core", +] + +[[package]] +name = "windows-core" +version = "0.62.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-future" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb" +dependencies = [ + "windows-core", + "windows-link", + "windows-threading", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-numerics" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26" +dependencies = [ + "windows-core", + "windows-link", +] + +[[package]] +name = "windows-result" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-strings" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-sys" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +dependencies = [ + "windows-targets 0.48.5", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows-targets" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" +dependencies = [ + "windows_aarch64_gnullvm 0.48.5", + "windows_aarch64_msvc 0.48.5", + "windows_i686_gnu 0.48.5", + "windows_i686_msvc 0.48.5", + "windows_x86_64_gnu 0.48.5", + "windows_x86_64_gnullvm 0.48.5", + "windows_x86_64_msvc 0.48.5", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows-threading" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37" +dependencies = [ + "windows-link", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_i686_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "winit" +version = "0.30.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6755fa58a9f8350bd1e472d4c3fcc25f824ec358933bba33306d0b63df5978d" +dependencies = [ + "ahash", + "android-activity", + "atomic-waker", + "bitflags 2.13.2", + "block2 0.5.1", + "bytemuck", + "calloop 0.13.0", + "cfg_aliases", + "concurrent-queue", + "core-foundation", + "core-graphics", + "cursor-icon", + "dpi", + "js-sys", + "libc", + "memmap2", + "ndk", + "objc2 0.5.3", + "objc2-app-kit 0.2.2", + "objc2-foundation 0.2.2", + "objc2-ui-kit 0.2.2", + "orbclient", + "percent-encoding", + "pin-project", + "raw-window-handle", + "redox_syscall 0.4.1", + "rustix 0.38.44", + "sctk-adwaita", + "smithay-client-toolkit", + "smol_str 0.2.2", + "tracing", + "unicode-segmentation", + "wasm-bindgen", + "wasm-bindgen-futures", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-protocols-plasma", + "web-sys", + "web-time", + "windows-sys 0.52.0", + "x11-dl", + "x11rb", + "xkbcommon-dl", +] + +[[package]] +name = "winnow" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" +dependencies = [ + "memchr", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "wl-clipboard-rs" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d7888ccd4896447b2d14d3a9350a85df2aeb6f181e2e7a31349d104ac46cac1" +dependencies = [ + "libc", + "log", + "os_pipe", + "rustix 1.1.5", + "thiserror 2.0.21", + "tree_magic_mini", + "wayland-backend", + "wayland-client", + "wayland-protocols", + "wayland-protocols-wlr", +] + +[[package]] +name = "write-fonts" +version = "0.50.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cae90d1d9f6d1d36ef116b0b1e651a6d7c12ba925439d4d06ff9adc94662a3d8" +dependencies = [ + "font-types", + "indexmap", + "kurbo", + "log", + "read-fonts", +] + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "x11-dl" +version = "2.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f" +dependencies = [ + "libc", + "once_cell", + "pkg-config", +] + +[[package]] +name = "x11rb" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414" +dependencies = [ + "as-raw-xcb-connection", + "gethostname", + "libc", + "libloading", + "once_cell", + "rustix 1.1.5", + "x11rb-protocol", +] + +[[package]] +name = "x11rb-protocol" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" + +[[package]] +name = "xattr" +version = "1.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156" +dependencies = [ + "libc", + "rustix 1.1.5", +] + +[[package]] +name = "xcursor" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "163b33ed8786455e2fa5d72f554057ce3f3182425434f756cd39c99839d88e23" + +[[package]] +name = "xkbcommon" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7a974f48060a14e95705c01f24ad9c3345022f4d97441b8a36beb7ed5c4a02d" +dependencies = [ + "libc", + "memmap2", + "xkeysym", +] + +[[package]] +name = "xkbcommon-dl" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d039de8032a9a8856a6be89cea3e5d12fdd82306ab7c94d74e6deab2460651c5" +dependencies = [ + "bitflags 2.13.2", + "dlib", + "log", + "once_cell", + "xkeysym", +] + +[[package]] +name = "xkeysym" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56" + +[[package]] +name = "xml-rs" +version = "0.8.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e450f9b2ed1dff33c94c12589a87338689467b9c4f5d8a5710bd09a847d2c8a7" + +[[package]] +name = "xmlwriter" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec7a2a501ed189703dba8b08142f057e887dfc4b2cc4db2d343ac6376ba3e0b9" + +[[package]] +name = "yazi" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e01738255b5a16e78bbb83e7fbba0a1e7dd506905cfc53f4622d89015a03fbb5" + +[[package]] +name = "yeslogic-fontconfig-sys" +version = "6.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d8b8abf912b9a29ff112e1671c97c33636903d13a69712037190e6805af4f76" +dependencies = [ + "dlib", + "once_cell", + "pkg-config", +] + +[[package]] +name = "yoke" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3" +dependencies = [ + "stable_deref_trait", + "yoke-derive", + "zerofrom", +] + +[[package]] +name = "yoke-derive" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zbus" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5db4be7c075cb421e4b7ee645541604239bd243ba7c357511f4ff3a74b555907" +dependencies = [ + "async-broadcast", + "async-executor", + "async-io", + "async-lock", + "async-process", + "async-recursion", + "async-task", + "async-trait", + "blocking", + "enumflags2", + "event-listener", + "futures-core", + "futures-lite", + "hex", + "libc", + "ordered-stream", + "rustix 1.1.5", + "serde", + "serde_repr", + "tracing", + "uds_windows", + "uuid", + "windows-sys 0.61.2", + "winnow", + "zbus_macros", + "zbus_names", + "zvariant", +] + +[[package]] +name = "zbus-lockstep" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6998de05217a084b7578728a9443d04ea4cd80f2a0839b8d78770b76ccd45863" +dependencies = [ + "zbus_xml", + "zvariant", +] + +[[package]] +name = "zbus-lockstep-macros" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10da05367f3a7b7553c8cdf8fa91aee6b64afebe32b51c95177957efc47ca3a0" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "zbus-lockstep", + "zbus_xml", + "zvariant", +] + +[[package]] +name = "zbus_macros" +version = "5.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2990635d09ade6df1868f72f8cac69a876a90981e8bd3c40b1be413f8dc88f40" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.9", + "zbus_names", + "zvariant", + "zvariant_utils", +] + +[[package]] +name = "zbus_names" +version = "4.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812a12be4ead7a59e18ea8f047d08add0066b73bc62fc1467066a2472ae088dd" +dependencies = [ + "serde", + "winnow", + "zvariant", +] + +[[package]] +name = "zbus_xml" +version = "5.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1586c021a01ca0a9216dcd874e546382e156a5cbab5fab6cb5f10087e22682a" +dependencies = [ + "serde", + "winnow", + "zbus_names", + "zvariant", +] + +[[package]] +name = "zcheapstr" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1afec51604565183aeb5c54c20aeab286120d4e4460f7f76e3e8bb8c0d99473" +dependencies = [ + "serde", +] + +[[package]] +name = "zeno" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6df3dc4292935e51816d896edcd52aa30bc297907c26167fec31e2b0c6a32524" + +[[package]] +name = "zerocopy" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5fe1f8f1b06191a00962174c61aa5005e0bb391a6d80d07e24d115c01a92ed8" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.63" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "863ad3ac83293fb4d740aedbfdc9240dd8d1a50c1099acd76ce80ce7c7230c7f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "zerofrom" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272" +dependencies = [ + "zerofrom-derive", +] + +[[package]] +name = "zerofrom-derive" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", + "synstructure", +] + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", + "zerovec", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "serde", + "yoke", + "zerofrom", + "zerovec-derive", +] + +[[package]] +name = "zerovec-derive" +version = "0.11.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3743ddbf47738d929cd1ae2e199d40d0162979dfe31aef8ae646d2bf00bf97a" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.9", +] + +[[package]] +name = "zlib-rs" +version = "0.6.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zune-core" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" + +[[package]] +name = "zune-jpeg" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" +dependencies = [ + "zune-core", +] + +[[package]] +name = "zvariant" +version = "5.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "80bf6d6cd6a4b601acb64cfb8284cdc643fcfa75ef26ae3c46ec8aa4e8a1fbb7" +dependencies = [ + "endi", + "enumflags2", + "serde", + "winnow", + "zcheapstr", + "zvariant_derive", + "zvariant_utils", +] + +[[package]] +name = "zvariant_derive" +version = "5.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef2672456ba1cb54b5eaec136e63135b3c7495fb938e53b28a62e633496d486d" +dependencies = [ + "proc-macro-crate", + "proc-macro2", + "quote", + "syn 3.0.9", + "zvariant_utils", +] + +[[package]] +name = "zvariant_utils" +version = "4.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bad0294361a320b694a328460dc73add56c306150f5cb6bfafc44446120008a3" +dependencies = [ + "proc-macro2", + "quote", + "serde", + "syn 3.0.9", + "winnow", +] diff --git a/templates/rust-app/Cargo.toml b/templates/rust-app/Cargo.toml new file mode 100644 index 0000000..4eef53a --- /dev/null +++ b/templates/rust-app/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "hello-fennec" +version = "1.0.0" +edition = "2024" +license = "MIT" +publish = false + +[dependencies] +# Any toolkit that speaks Wayland works (Slint, egui/eframe, iced, winit...). +# The sandbox only has the Wayland socket: no X11. +slint = "1.18" + +[profile.release] +lto = "thin" +strip = true + +# Not part of the Fennec OS workspace: this folder is a template to copy. +[workspace] diff --git a/templates/rust-app/app.toml b/templates/rust-app/app.toml new file mode 100644 index 0000000..698fda9 --- /dev/null +++ b/templates/rust-app/app.toml @@ -0,0 +1,29 @@ +# Fennec OS store app manifest (docs/store.md in the Fennec OS repo). +# The id is a reverse domain name you control: io.github.<user>.<app>, +# io.gitlab.<user>.<app>, org.codeberg.<user>.<app>, or your own domain. +id = "io.github.example.hello" +name = "Hello" +# Release versions only (1.2.3). Bump it for every release. +version = "1.0.0" +kind = "exec" +category = "Példa" +description = "Egy Fennec OS app Rustban: a távirányító nyilaival lépkedsz, a középső gombbal kattintasz." +author = "Example" +license = "MIT" +homepage = "https://github.com/example/hello-fennec" +# Relative to the package: bin/ holds the binary built by the release job. +exec = ["bin/hello-fennec"] +# Your own icon (PNG, square, 256x256 or more) in the package, or leave it out. +# icon = "icon.png" +accent = "#FF9A5C" +palette = ["#ffb27a", "#8a3d12", "#120805"] + +# Your signing key's public half: `sf-pack keygen` prints it. Every release +# must be signed with the same key, or TVs won't update. + +[sandbox] +# What the app may use besides its own files and the screen. The TV shows +# this list before installing; an update that asks for more waits for the +# user to approve it. network, gpu, audio, gamepad, dbus-session, +# dbus-system, devices. +permissions = ["gpu"] diff --git a/templates/rust-app/package.sh b/templates/rust-app/package.sh new file mode 100644 index 0000000..fb40e22 --- /dev/null +++ b/templates/rust-app/package.sh @@ -0,0 +1,18 @@ +#!/usr/bin/env bash +# Builds the release assets into dist/: app.toml and <id>-<version>.tar.zst. +# Upload both files to a release of this repo; that's all the +# store needs. The CI files here do it on every tag. +# +# Build on Debian trixie (what the TV runs) or older, so the binary's glibc +# isn't newer than the TV's. +set -euo pipefail +cd "$(dirname "$0")" + +cargo build --release --locked +rm -rf pkg dist +mkdir -p pkg/bin +cp app.toml pkg/ +[ -f icon.png ] && cp icon.png pkg/ +install -m755 target/release/hello-fennec pkg/bin/hello-fennec +sf-pack build pkg dist +sf-pack verify dist diff --git a/templates/rust-app/src/main.rs b/templates/rust-app/src/main.rs new file mode 100644 index 0000000..1756ba8 --- /dev/null +++ b/templates/rust-app/src/main.rs @@ -0,0 +1,60 @@ +//! A Fennec OS store app in Rust: full screen, driven by the remote. +//! +//! The Siri Remote arrives as keys: arrows, Enter (click), Escape (Back). +//! Home is handled by the TV itself (the app is paused in the background). +//! Files: $HOME is the app's own data folder and the only writable place +//! that lasts; the app's own files are read-only in $SMARTFOX_APP_DIR (/app). + +slint::slint! { + export component Main inherits Window { + in-out property <int> selected: 0; + in-out property <int> clicks: 0; + callback quit(); + property <[string]> items: ["Hello", "Fennec OS", "Rust"]; + background: #0b0d12; + default-font-size: 40px; + + FocusScope { + key-pressed(event) => { + if event.text == Key.LeftArrow { root.selected = max(0, root.selected - 1); return accept; } + if event.text == Key.RightArrow { root.selected = min(root.items.length - 1, root.selected + 1); return accept; } + if event.text == Key.Return { root.clicks += 1; return accept; } + if event.text == Key.Escape { root.quit(); return accept; } + reject + } + HorizontalLayout { + alignment: center; + spacing: 40px; + for item[i] in root.items: Rectangle { + width: 360px; + height: 220px; + y: (root.height - self.height) / 2; + border-radius: 32px; + background: i == root.selected ? #ffffff : #ffffff18; + animate background { duration: 150ms; } + Text { + text: item; + color: i == root.selected ? #121317 : #ffffff; + font-weight: 700; + } + } + } + Text { + y: root.height - 140px; + text: "Enter: " + root.clicks + " · Back: exit"; + color: #ffffff99; + font-size: 28px; + } + } + } +} + +fn main() -> Result<(), slint::PlatformError> { + let ui = Main::new()?; + ui.window().set_fullscreen(true); + // Back on the remote = Escape: leave the app (the launcher comes back). + ui.on_quit(|| { + let _ = slint::quit_event_loop(); + }); + ui.run() +} diff --git a/tools/pkg/packages.sh b/tools/pkg/packages.sh index 5bdb5f3..0a329d2 100644 --- a/tools/pkg/packages.sh +++ b/tools/pkg/packages.sh @@ -1,12 +1,14 @@ #!/usr/bin/env bash -# Builds, signs and uploads SmartFox packages (protocol: docs/updates.md). +# Builds, signs and uploads Fennec OS packages (protocol: docs/updates.md). # # tools/pkg/packages.sh [--upload] [shell] [app:<id>...] [apps] # # With no package names it does the shell and every app. A package whose # version is already in the registry is skipped (bump the version to publish): # shell version = [workspace.package] version in Cargo.toml -# app:<id> version = "version" in apps/<id>/app.toml +# app:<id> version = "version" in apps/<id>/app.toml, or what the app's +# hook says (tools/pkg/<id>/package.sh: Steam follows Valve's +# official steam-launcher package) # # Environment: # SF_SIGNING_KEY Ed25519 private key: the PEM file base64-encoded on one @@ -22,7 +24,7 @@ GITEA="${SF_GITEA:-https://gitea.bluefox.support}" OWNER="${SF_OWNER:-bluefox}" OUT="${SF_OUT:-$ROOT/target/packages}" # Binaries in the shell package (built with cargo --release). -SHELL_BINS=(sf-launcher sf-remote) +SHELL_BINS=(sf-launcher sf-remote sf-core sf-miracast sf-compositor sf-update) UPLOAD=0 WANT=() @@ -98,10 +100,17 @@ do_shell() { pack sf-shell "$version" "$dir" } +# An app with a hook (tools/pkg/<id>/package.sh, e.g. Steam from Valve's +# official package) gets its files and version from it: `--version` prints +# the upstream version, `<dir>` fills the app folder. do_app() { - local id=$1 src="$ROOT/apps/$1" version + local id=$1 src="$ROOT/apps/$1" version hook="$ROOT/tools/pkg/$1/package.sh" [ -f "$src/app.toml" ] || { echo "no app $id" >&2; return 1; } - version=$(toml_version "$src/app.toml") + if [ -f "$hook" ]; then + version=$(bash "$hook" --version) + else + version=$(toml_version "$src/app.toml") + fi [ -n "$version" ] || { echo "apps/$id/app.toml has no version, skipped"; return; } if published "sf-app-$id" "$version"; then echo "sf-app-$id $version: already published" @@ -110,14 +119,20 @@ do_app() { local dir="$TMP/sf-app-$id" rm -rf "$dir" cp -r "$src" "$dir" + if [ -f "$hook" ]; then + [ "$(bash "$hook" "$dir" | tail -1)" = "$version" ] || { echo "$id: the hook built another version than $version" >&2; return 1; } + fi chmod -R u=rwX,go=rX "$dir" + # Git on Windows loses the x bit: programs live in bin/. + [ -d "$dir/bin" ] && chmod -R a+x "$dir/bin" pack "sf-app-$id" "$version" "$dir" } for w in "${WANT[@]}"; do case "$w" in shell) do_shell ;; - apps) for d in "$ROOT"/apps/*/; do do_app "$(basename "$d")"; done ;; + # A folder with its own .git is a store app developed in place: skipped. + apps) for d in "$ROOT"/apps/*/; do [ -e "$d/.git" ] || do_app "$(basename "$d")"; done ;; app:*) do_app "${w#app:}" ;; esac done diff --git a/tools/pkg/steam/package.sh b/tools/pkg/steam/package.sh new file mode 100644 index 0000000..5adcace --- /dev/null +++ b/tools/pkg/steam/package.sh @@ -0,0 +1,81 @@ +#!/usr/bin/env bash +# The Steam app from Valve's official package: downloads the newest +# steam-launcher .deb from repo.steampowered.com, checks it against Valve's +# signed repository index, and puts the launcher into an app folder. +# +# package.sh --version prints the newest official version (1.0.0.87) +# package.sh <app-dir> fills <app-dir> (a copy of apps/steam) and sets the +# version in its app.toml +# +# Used by tools/pkg/packages.sh (the sf-app-steam package, so Steam updates +# like every other app) and image/build.sh (the preinstalled factory copy). +# +# Trust: valve-archive-keyring.gpg is the keyring from the steam-launcher +# package itself (Valve Corporation, BA18 16EF 8E75 005F CF5E 27A1 F24A EA9F +# B054 98B7, and the 2025 repository key). InRelease must be signed by it, the +# Packages index must match its SHA256, the .deb must match the index. +set -euo pipefail + +HERE="$(cd "$(dirname "$0")" && pwd)" +REPO="${STEAM_REPO:-https://repo.steampowered.com/steam}" +KEYRING="$HERE/valve-archive-keyring.gpg" +TMP=$(mktemp -d) +trap 'rm -rf "$TMP"' EXIT + +curl -fsSL -o "$TMP/InRelease" "$REPO/dists/stable/InRelease" +if ! gpgv --keyring "$KEYRING" --output "$TMP/Release" "$TMP/InRelease" 2>"$TMP/gpgv.log"; then + cat "$TMP/gpgv.log" >&2 + echo "steam: InRelease is not signed by Valve's key" >&2 + exit 1 +fi +want=$(awk '/^SHA256:/ {f = 1; next} /^[^ ]/ {f = 0} f && $3 == "steam/binary-amd64/Packages" {print $1}' "$TMP/Release") +[ -n "$want" ] || { echo "steam: no Packages checksum in Release" >&2; exit 1; } +curl -fsSL -o "$TMP/Packages" "$REPO/dists/stable/steam/binary-amd64/Packages" +echo "$want $TMP/Packages" | sha256sum -c --quiet - || { echo "steam: Packages checksum mismatch" >&2; exit 1; } + +# The newest steam-launcher in the index: "version<TAB>filename<TAB>sha256". +best=$(awk -v RS= -v FS='\n' ' + $0 ~ /(^|\n)Package: steam-launcher(\n|$)/ { + v = f = s = "" + for (i = 1; i <= NF; i++) { + if ($i ~ /^Version: /) v = substr($i, 10) + if ($i ~ /^Filename: /) f = substr($i, 11) + if ($i ~ /^SHA256: /) s = substr($i, 9) + } + sub(/^[0-9]+:/, "", v) + print v "\t" f "\t" s + }' "$TMP/Packages" | sort -t "$(printf '\t')" -k1,1V | tail -1) +IFS=$'\t' read -r version file sha <<<"$best" +case "$version" in + "" | *[!0-9.]*) echo "steam: unexpected version '$version'" >&2; exit 1 ;; +esac +case "$file" in + pool/*.deb) ;; + *) echo "steam: unexpected file '$file'" >&2; exit 1 ;; +esac + +if [ "${1:-}" = --version ]; then + echo "$version" + exit 0 +fi +DIR="${1:?usage: package.sh --version | <app-dir>}" +[ -f "$DIR/app.toml" ] || { echo "steam: $DIR/app.toml is missing" >&2; exit 1; } + +curl -fsSL -o "$TMP/steam.deb" "$REPO/$file" +echo "$sha $TMP/steam.deb" | sha256sum -c --quiet - || { echo "steam: .deb checksum mismatch" >&2; exit 1; } +mkdir "$TMP/x" +dpkg-deb -x "$TMP/steam.deb" "$TMP/x" + +# The launcher script finds its bootstrap next to itself, and must be called +# "steam" (it uses its own name as the package name). +L="$TMP/x/usr/lib/steam" +install -Dm755 "$L/bin_steam.sh" "$DIR/steam/steam" +install -Dm644 "$L/bootstraplinux_ubuntu12_32.tar.xz" "$DIR/steam/bootstraplinux_ubuntu12_32.tar.xz" +# Controller access (uinput, Steam Controller, DualSense...): the image +# installs these rules (image/build.sh). +for r in "$TMP"/x/lib/udev/rules.d/*.rules; do + install -Dm644 "$r" "$DIR/udev/$(basename "$r")" +done +install -Dm644 "$TMP/x/usr/share/doc/steam-launcher/copyright" "$DIR/steam/COPYRIGHT" +sed -i "s/^version = .*/version = \"$version\"/" "$DIR/app.toml" +echo "$version" diff --git a/tools/pkg/steam/valve-archive-keyring.gpg b/tools/pkg/steam/valve-archive-keyring.gpg new file mode 100644 index 0000000..986e9bf Binary files /dev/null and b/tools/pkg/steam/valve-archive-keyring.gpg differ diff --git a/tools/siri-remote/setup-host.sh b/tools/siri-remote/setup-host.sh index 278eaf6..b5f298e 100644 --- a/tools/siri-remote/setup-host.sh +++ b/tools/siri-remote/setup-host.sh @@ -22,7 +22,7 @@ echo "== device access for group 'smartfox'" groupadd -f smartfox usermod -aG smartfox,input "$USER_NAME" cat >/etc/udev/rules.d/70-smartfox.rules <<'EOF' -# SmartFox: remote daemon reads raw HID and writes virtual key events. +# Fennec OS: remote daemon reads raw HID and writes virtual key events. KERNEL=="hidraw*", SUBSYSTEM=="hidraw", GROUP="smartfox", MODE="0660" KERNEL=="uinput", SUBSYSTEM=="misc", GROUP="smartfox", MODE="0660", OPTIONS+="static_node=uinput" EOF diff --git a/tools/vm/hotswap.sh b/tools/vm/hotswap.sh index 638ecb2..7b31703 100644 --- a/tools/vm/hotswap.sh +++ b/tools/vm/hotswap.sh @@ -1,5 +1,5 @@ #!/usr/bin/env bash -# Rebuilds SmartFox binaries in WSL and swaps them into the running VM (no image rebuild). +# Rebuilds Fennec OS binaries in WSL and swaps them into the running VM (no image rebuild). # hotswap.sh sf-remote sf-launcher set -euo pipefail SRC=/mnt/g/source/smartfox diff --git a/tools/vm/start-vm.ps1 b/tools/vm/start-vm.ps1 index 8429b70..afc052d 100644 --- a/tools/vm/start-vm.ps1 +++ b/tools/vm/start-vm.ps1 @@ -1,4 +1,4 @@ -# Starts the SmartFox OS VM (QEMU in WSL Debian). The window appears via WSLg. +# Starts the Fennec OS VM (QEMU in WSL Debian). The window appears via WSLg. # powershell -File tools\vm\start-vm.ps1 # boot the last built image # powershell -File tools\vm\start-vm.ps1 -Build # rebuild image first param([switch]$Build, [string]$Bt = "") diff --git a/tools/vm/vmcp.sh b/tools/vm/vmcp.sh index 2e8a4f2..b41e553 100644 --- a/tools/vm/vmcp.sh +++ b/tools/vm/vmcp.sh @@ -1,5 +1,5 @@ #!/usr/bin/env bash -# Copies files to/from the SmartFox VM. Use "vm:" prefix for the remote side. +# Copies files to/from the Fennec OS VM. Use "vm:" prefix for the remote side. # vmcp.sh local vm:/remote vmcp.sh vm:/remote local OPTS=(-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o LogLevel=ERROR -P 2222) args=() diff --git a/tools/vm/vmssh.sh b/tools/vm/vmssh.sh index 07c3bb2..23e8fbb 100644 --- a/tools/vm/vmssh.sh +++ b/tools/vm/vmssh.sh @@ -1,5 +1,5 @@ #!/usr/bin/env bash -# Runs a command in the SmartFox QEMU VM (dev image, root/smartfox). +# Runs a command in the Fennec OS QEMU VM (dev image, root/smartfox). # usage: vmssh.sh [--wait] 'command' OPTS=(-o StrictHostKeyChecking=no -o UserKnownHostsFile=/dev/null -o LogLevel=ERROR -p 2222) if [ "$1" = "--wait" ]; then