Add Store support and unsigned app releases
This commit is contained in:
442
docs/sf-ui.md
Normal file
442
docs/sf-ui.md
Normal file
@@ -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.
|
||||
501
docs/store-app-guide.md
Normal file
501
docs/store-app-guide.md
Normal file
@@ -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
|
||||
283
sf-app/src/launch.rs
Normal file
283
sf-app/src/launch.rs
Normal file
@@ -0,0 +1,283 @@
|
||||
//! How apps are started: the command line for a web app (Chromium in kiosk or
|
||||
//! app mode with its own profile) or an exec app. Shared by the launcher
|
||||
//! (local testing on a desktop) and sf-core (the TV).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
|
||||
use crate::{AppKind, AppManifest, Settings, paths, sandbox};
|
||||
|
||||
/// Environment variable carrying the app id into the app's processes. The
|
||||
/// compositor reads it from `/proc/<pid>/environ` to tell windows apart.
|
||||
pub const APP_ENV: &str = "SMARTFOX_APP";
|
||||
|
||||
pub struct Browser {
|
||||
pub exe: PathBuf,
|
||||
/// Full version, used to build a realistic user agent.
|
||||
pub version: String,
|
||||
}
|
||||
|
||||
pub fn find_browser() -> Option<Browser> {
|
||||
let mut candidates: Vec<PathBuf> = Vec::new();
|
||||
if let Ok(p) = std::env::var("SMARTFOX_BROWSER") {
|
||||
candidates.push(p.into());
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
for base in ["ProgramFiles", "ProgramFiles(x86)", "LOCALAPPDATA"] {
|
||||
if let Some(b) = std::env::var_os(base) {
|
||||
let b = PathBuf::from(b);
|
||||
candidates.push(b.join(r"Google\Chrome\Application\chrome.exe"));
|
||||
candidates.push(b.join(r"Chromium\Application\chrome.exe"));
|
||||
candidates.push(b.join(r"Microsoft\Edge\Application\msedge.exe"));
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
for name in ["chromium", "chromium-browser", "google-chrome-stable", "google-chrome"] {
|
||||
for dir in ["/usr/bin", "/usr/local/bin", "/snap/bin"] {
|
||||
candidates.push(Path::new(dir).join(name));
|
||||
}
|
||||
}
|
||||
}
|
||||
let exe = candidates.into_iter().find(|p| p.is_file())?;
|
||||
let version = browser_version(&exe).unwrap_or_else(|| "141.0.0.0".into());
|
||||
Some(Browser { exe, version })
|
||||
}
|
||||
|
||||
fn browser_version(exe: &Path) -> Option<String> {
|
||||
// Windows installs keep a folder named after the version next to the exe.
|
||||
if cfg!(windows) {
|
||||
let dir = exe.parent()?;
|
||||
let mut versions: Vec<String> = std::fs::read_dir(dir)
|
||||
.ok()?
|
||||
.flatten()
|
||||
.filter_map(|e| e.file_name().into_string().ok())
|
||||
.filter(|n| n.split('.').count() == 4 && n.split('.').all(|p| p.parse::<u32>().is_ok()))
|
||||
.collect();
|
||||
versions.sort_by_key(|v| v.split('.').map(|p| p.parse::<u32>().unwrap_or(0)).collect::<Vec<_>>());
|
||||
return versions.pop();
|
||||
}
|
||||
let out = Command::new(exe).arg("--version").output().ok()?;
|
||||
String::from_utf8_lossy(&out.stdout)
|
||||
.split_whitespace()
|
||||
.find(|w| w.chars().next().is_some_and(|c| c.is_ascii_digit()) && w.contains('.'))
|
||||
.map(str::to_string)
|
||||
}
|
||||
|
||||
fn default_user_agent(version: &str) -> String {
|
||||
let platform = if cfg!(windows) { "Windows NT 10.0; Win64; x64" } else { "X11; Linux x86_64" };
|
||||
let major = version.split('.').next().unwrap_or("141");
|
||||
format!("Mozilla/5.0 ({platform}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{major}.0.0.0 Safari/537.36")
|
||||
}
|
||||
|
||||
pub struct LaunchOptions<'a> {
|
||||
/// Per-app browser profiles live in `<data_dir>/profiles/<id>`.
|
||||
pub data_dir: &'a Path,
|
||||
pub fullscreen: bool,
|
||||
/// Windowed mode: open the app exactly over the launcher (x, y, w, h).
|
||||
pub bounds: Option<(i32, i32, u32, u32)>,
|
||||
/// Extra query string for the start URL (DIAL launch parameters).
|
||||
pub query: Option<&'a str>,
|
||||
}
|
||||
|
||||
/// A program with its arguments and environment, before it is (maybe) put
|
||||
/// into the sandbox.
|
||||
struct Inner {
|
||||
program: String,
|
||||
args: Vec<String>,
|
||||
env: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
/// The bwrap binary if `app` runs sandboxed (`sandbox` module). Store apps
|
||||
/// never run without it. Official apps run unsandboxed when bwrap is missing
|
||||
/// (an older image under a newer shell) or with `SMARTFOX_SANDBOX=off`
|
||||
/// (debugging), with a warning.
|
||||
fn sandbox_for(app: &AppManifest) -> Result<Option<PathBuf>> {
|
||||
if app.origin == crate::Origin::Store {
|
||||
anyhow::ensure!(cfg!(target_os = "linux"), "store apps only run on the TV (Linux)");
|
||||
return sandbox::bwrap_path().context("bubblewrap (bwrap) is not installed, and store apps only run sandboxed").map(Some);
|
||||
}
|
||||
if !cfg!(target_os = "linux") || !app.sandboxed() {
|
||||
return Ok(None);
|
||||
}
|
||||
if std::env::var("SMARTFOX_SANDBOX").is_ok_and(|v| v == "off") {
|
||||
log::warn!("{}: SMARTFOX_SANDBOX=off, running without a sandbox", app.id);
|
||||
return Ok(None);
|
||||
}
|
||||
let bwrap = sandbox::bwrap_path();
|
||||
if bwrap.is_none() {
|
||||
log::warn!("{}: bubblewrap is not installed, running without a sandbox", app.id);
|
||||
}
|
||||
Ok(bwrap)
|
||||
}
|
||||
|
||||
/// The command that starts `app`. Not spawned yet, so callers can wrap it
|
||||
/// (sf-core runs it inside a systemd scope).
|
||||
pub fn command(app: &AppManifest, settings: &Settings, opts: &LaunchOptions) -> Result<Command> {
|
||||
let bwrap = sandbox_for(app)?;
|
||||
// Where the app's files are, as the app sees them.
|
||||
let root = if bwrap.is_some() { PathBuf::from(sandbox::APP_DIR) } else { app.dir.clone() };
|
||||
let data = paths::app_data_dir(&app.id);
|
||||
let inner = match app.kind {
|
||||
AppKind::Web => web_command(app, settings, opts, &root, bwrap.is_some().then_some(data.as_path()))?,
|
||||
AppKind::Exec => {
|
||||
let line = app.resolved_exec(&root);
|
||||
let (prog, args) = line.split_first().context("empty exec command")?;
|
||||
Inner { program: prog.clone(), args: args.to_vec(), env: Vec::new() }
|
||||
}
|
||||
AppKind::Builtin => bail!("built-in app has no process"),
|
||||
};
|
||||
let mut env = inner.env;
|
||||
env.extend(app.env.iter().map(|(k, v)| (k.clone(), settings.expand(v))));
|
||||
|
||||
let mut cmd = match bwrap {
|
||||
Some(bwrap) => {
|
||||
std::fs::create_dir_all(&data).with_context(|| format!("creating {}", data.display()))?;
|
||||
// Store apps sit behind symlinks (store/apps/<id> -> ../store-<id>/current).
|
||||
let app_dir = std::fs::canonicalize(&app.dir).unwrap_or_else(|_| app.dir.clone());
|
||||
let permissions = app.permissions();
|
||||
let spec = sandbox::Spec {
|
||||
app_id: &app.id,
|
||||
app_dir: &app_dir,
|
||||
data_dir: &data,
|
||||
extra_rw: Vec::new(),
|
||||
permissions: &permissions,
|
||||
env,
|
||||
program: inner.program,
|
||||
args: inner.args,
|
||||
};
|
||||
let cmd = sandbox::command(&bwrap, &spec, &sandbox::Host::current());
|
||||
log::info!("{}: sandboxed, permissions: {:?}", app.id, permissions.iter().map(|p| p.key()).collect::<Vec<_>>());
|
||||
cmd
|
||||
}
|
||||
None => {
|
||||
let mut cmd = Command::new(&inner.program);
|
||||
cmd.args(&inner.args).envs(env).env("SMARTFOX_APP_DIR", &app.dir);
|
||||
cmd
|
||||
}
|
||||
};
|
||||
cmd.env(APP_ENV, &app.id);
|
||||
// Own process group, so stopping the app also ends its helper processes.
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::process::CommandExt;
|
||||
cmd.process_group(0);
|
||||
}
|
||||
Ok(cmd)
|
||||
}
|
||||
|
||||
/// Adds `query` to `url`, before any `#fragment`.
|
||||
pub fn with_query(url: &str, query: Option<&str>) -> String {
|
||||
let Some(q) = query.map(|q| q.trim_start_matches(['?', '&'])).filter(|q| !q.is_empty()) else {
|
||||
return url.to_string();
|
||||
};
|
||||
let (base, frag) = match url.find('#') {
|
||||
Some(i) => (&url[..i], &url[i..]),
|
||||
None => (url, ""),
|
||||
};
|
||||
let sep = if base.contains('?') { '&' } else { '?' };
|
||||
format!("{base}{sep}{q}{frag}")
|
||||
}
|
||||
|
||||
/// First-run preferences for an app profile: no translate prompt, Hungarian
|
||||
/// content language. Existing profiles are left alone.
|
||||
fn seed_profile(profile: &Path) -> Result<()> {
|
||||
let prefs = profile.join("Default").join("Preferences");
|
||||
if prefs.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
std::fs::create_dir_all(prefs.parent().unwrap())?;
|
||||
std::fs::write(
|
||||
&prefs,
|
||||
r#"{"translate":{"enabled":false},"intl":{"accept_languages":"hu-HU,hu,en"},"browser":{"has_seen_welcome_page":true}}"#,
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The browser command for a web app. `sandbox_home`: the app's data folder
|
||||
/// when it runs sandboxed; its Chromium profile then lives in there.
|
||||
fn web_command(app: &AppManifest, settings: &Settings, opts: &LaunchOptions, root: &Path, sandbox_home: Option<&Path>) -> Result<Inner> {
|
||||
let browser = find_browser().context("no Chromium/Chrome/Edge found (set SMARTFOX_BROWSER)")?;
|
||||
let url = app.resolved_url(settings).filter(|u| !u.is_empty()).context("app has no URL")?;
|
||||
if url.starts_with('/') {
|
||||
bail!("URL is not set (check settings: {url})");
|
||||
}
|
||||
let url = with_query(&url, opts.query);
|
||||
let old_profile = opts.data_dir.join("profiles").join(&app.id);
|
||||
let profile = match sandbox_home {
|
||||
Some(home) => {
|
||||
let profile = home.join("chromium");
|
||||
// Profiles from before the sandbox (logins, settings) move along.
|
||||
if old_profile.is_dir() && !profile.exists() {
|
||||
std::fs::create_dir_all(home)?;
|
||||
if let Err(e) = std::fs::rename(&old_profile, &profile) {
|
||||
log::warn!("{}: moving the browser profile: {e}", app.id);
|
||||
}
|
||||
}
|
||||
profile
|
||||
}
|
||||
None => old_profile,
|
||||
};
|
||||
seed_profile(&profile)?;
|
||||
|
||||
let ua = match (&app.web.user_agent, &app.web.user_agent_suffix) {
|
||||
(Some(ua), _) => ua.clone(),
|
||||
(None, Some(suffix)) => format!("{} {suffix}", default_user_agent(&browser.version)),
|
||||
(None, None) => default_user_agent(&browser.version),
|
||||
};
|
||||
|
||||
let mut args: Vec<String> = vec![
|
||||
format!("--user-data-dir={}", profile.display()),
|
||||
format!("--user-agent={ua}"),
|
||||
"--no-first-run".into(),
|
||||
"--no-default-browser-check".into(),
|
||||
"--disable-session-crashed-bubble".into(),
|
||||
"--hide-crash-restore-bubble".into(),
|
||||
"--disable-features=Translate,TranslateUI,MediaRouter,LocalNetworkAccessChecks".into(),
|
||||
"--lang=hu".into(),
|
||||
"--accept-lang=hu-HU,hu,en".into(),
|
||||
// Dark first paint instead of a white flash before the page draws.
|
||||
"--force-dark-mode".into(),
|
||||
"--autoplay-policy=no-user-gesture-required".into(),
|
||||
"--overscroll-history-navigation=0".into(),
|
||||
];
|
||||
if opts.fullscreen {
|
||||
args.extend(["--kiosk".into(), url]);
|
||||
} else {
|
||||
args.push(format!("--app={url}"));
|
||||
match opts.bounds {
|
||||
Some((x, y, w, h)) => args.extend([format!("--window-position={x},{y}"), format!("--window-size={w},{h}")]),
|
||||
None => args.push("--window-size=1600,900".into()),
|
||||
}
|
||||
}
|
||||
let mut env = Vec::new();
|
||||
if cfg!(target_os = "linux") {
|
||||
// Chromium on Linux picks its UI language from the environment, not --lang.
|
||||
env.push(("LANGUAGE".to_string(), "hu".to_string()));
|
||||
args.push("--enable-features=VaapiVideoDecoder,VaapiIgnoreDriverChecks,PlatformHEVCDecoderSupport".into());
|
||||
if std::env::var_os("WAYLAND_DISPLAY").is_some() {
|
||||
args.push("--ozone-platform=wayland".into());
|
||||
}
|
||||
}
|
||||
for ext in &app.web.extensions {
|
||||
args.push(format!("--load-extension={}", root.join(ext).display()));
|
||||
}
|
||||
Ok(Inner { program: browser.exe.to_string_lossy().into_owned(), args, env })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn adds_query() {
|
||||
assert_eq!(with_query("https://www.youtube.com/tv", Some("a=1&b=2")), "https://www.youtube.com/tv?a=1&b=2");
|
||||
assert_eq!(with_query("https://x/tv?x=1#f", Some("?a=1")), "https://x/tv?x=1&a=1#f");
|
||||
assert_eq!(with_query("https://x/", None), "https://x/");
|
||||
assert_eq!(with_query("https://x/", Some("")), "https://x/");
|
||||
}
|
||||
}
|
||||
@@ -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-<id>`, signed
|
||||
//! with the Fennec OS key);
|
||||
//! - the store: third-party apps from their own GitHub/Gitea/GitLab repos,
|
||||
//! published in their own repo (docs/store.md). These always run sandboxed and
|
||||
//! can never replace an official app.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use 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> {
|
||||
Permission::ALL.into_iter().find(|p| p.key() == key)
|
||||
}
|
||||
|
||||
/// Hungarian label for the store screen.
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Permission::Network => "Internet és helyi hálózat",
|
||||
Permission::Gpu => "Grafikus gyorsítás",
|
||||
Permission::Audio => "Hang",
|
||||
Permission::Gamepad => "Játékvezérlők",
|
||||
Permission::DbusSession => "Munkamenet D-Bus",
|
||||
Permission::DbusSystem => "Rendszer D-Bus",
|
||||
Permission::Devices => "Minden eszköz (/dev)",
|
||||
}
|
||||
}
|
||||
|
||||
/// Worth a warning: the app can reach far outside its sandbox.
|
||||
pub fn risky(self) -> bool {
|
||||
matches!(self, Permission::DbusSession | Permission::DbusSystem | Permission::Devices)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SandboxOptions {
|
||||
/// Run in a bubblewrap sandbox. Only official apps may turn it off
|
||||
/// (system receivers like AirPlay); store apps are always sandboxed.
|
||||
/// Unset: on, except for official background services.
|
||||
#[serde(default)]
|
||||
pub enabled: Option<bool>,
|
||||
#[serde(default)]
|
||||
pub permissions: Vec<Permission>,
|
||||
}
|
||||
|
||||
impl Default for SandboxOptions {
|
||||
fn default() -> Self {
|
||||
SandboxOptions { enabled: None, permissions: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
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<String, String>,
|
||||
/// Legacy store manifest field. Older signed releases may still contain it.
|
||||
#[serde(default)]
|
||||
pub public_key: Option<String>,
|
||||
/// Store apps: source code / home page, shown on the store screen.
|
||||
#[serde(default)]
|
||||
pub homepage: Option<String>,
|
||||
#[serde(default)]
|
||||
pub author: Option<String>,
|
||||
#[serde(default)]
|
||||
pub license: Option<String>,
|
||||
/// Folder the manifest was loaded from (not serialized).
|
||||
#[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<String> {
|
||||
self.url.as_ref().map(|u| settings.expand(u))
|
||||
}
|
||||
|
||||
/// The command line with `${app}` replaced by `app_root` (where the app's
|
||||
/// files are: its folder, or /app inside the sandbox). A relative program
|
||||
/// path with a slash (`bin/hello`) is inside the app folder too; a bare
|
||||
/// name (`uxplay`) is looked up in PATH.
|
||||
pub fn resolved_exec(&self, app_root: &Path) -> Vec<String> {
|
||||
let root = app_root.to_string_lossy();
|
||||
let mut line: Vec<String> = self.exec.iter().flatten().map(|a| a.replace("${app}", &root)).collect();
|
||||
if let Some(first) = line.first_mut() {
|
||||
if first.contains('/') && !first.starts_with('/') {
|
||||
*first = format!("{}/{}", root.trim_end_matches('/'), first.trim_start_matches("./"));
|
||||
}
|
||||
}
|
||||
line
|
||||
}
|
||||
|
||||
/// What the app may reach from its sandbox. Web apps always get what a
|
||||
/// browser needs.
|
||||
pub fn permissions(&self) -> Vec<Permission> {
|
||||
let mut p = self.sandbox.permissions.clone();
|
||||
if self.kind == AppKind::Web {
|
||||
p.extend([Permission::Network, Permission::Gpu, Permission::Audio]);
|
||||
}
|
||||
p.sort();
|
||||
p.dedup();
|
||||
p
|
||||
}
|
||||
|
||||
/// Store apps always run sandboxed; official ones unless they opt out.
|
||||
pub fn sandboxed(&self) -> bool {
|
||||
self.origin == Origin::Store || self.sandbox.enabled.unwrap_or(!self.service)
|
||||
}
|
||||
|
||||
/// An image file shipped with the app (`icon = "icon.png"`), if `icon`
|
||||
/// isn't one of the launcher's built-in icon names.
|
||||
pub fn icon_file(&self) -> Option<PathBuf> {
|
||||
let lower = self.icon.to_ascii_lowercase();
|
||||
if ![".png", ".svg", ".jpg", ".jpeg"].iter().any(|ext| lower.ends_with(ext)) {
|
||||
return None;
|
||||
}
|
||||
if self.icon.contains("..") || Path::new(&self.icon).is_absolute() {
|
||||
return None;
|
||||
}
|
||||
let path = self.dir.join(&self.icon);
|
||||
path.is_file().then_some(path)
|
||||
}
|
||||
|
||||
/// Rules a store app must follow (checked by sf-update before installing
|
||||
/// and by the launcher when loading).
|
||||
pub fn check_store_rules(&self) -> Result<()> {
|
||||
anyhow::ensure!(is_store_id(&self.id), "store app id {:?} must be a reverse domain name (io.github.user.app)", self.id);
|
||||
anyhow::ensure!(self.kind != AppKind::Builtin, "store apps can't be built-in");
|
||||
anyhow::ensure!(!self.service, "store apps can't be background services");
|
||||
anyhow::ensure!(self.dial.is_none(), "store apps can't register for DIAL");
|
||||
anyhow::ensure!(self.sandbox.enabled != Some(false), "store apps can't turn off the sandbox");
|
||||
match self.kind {
|
||||
AppKind::Exec => anyhow::ensure!(!self.resolved_exec(Path::new("/app")).is_empty(), "exec is missing"),
|
||||
AppKind::Web => anyhow::ensure!(self.url.as_deref().is_some_and(|u| u.starts_with("https://")), "web apps need an https:// url"),
|
||||
AppKind::Builtin => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Store app ids are reverse domain names with at least one dot
|
||||
/// (`io.github.user.app`). Official app ids never have a dot, so a store app
|
||||
/// can't take the place of one.
|
||||
pub fn is_store_id(id: &str) -> bool {
|
||||
let parts: Vec<&str> = id.split('.').collect();
|
||||
id.len() <= 128
|
||||
&& parts.len() >= 2
|
||||
&& parts.iter().all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_'))
|
||||
&& parts[0].bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
|
||||
}
|
||||
|
||||
/// Loads every `*/app.toml` under `dir`, sorted by `order` then name.
|
||||
@@ -128,6 +321,12 @@ pub fn load_apps_from(dirs: &[PathBuf]) -> Result<Vec<AppManifest>> {
|
||||
}
|
||||
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<Vec<AppManifest>> {
|
||||
Ok(apps)
|
||||
}
|
||||
|
||||
/// Official apps from `dirs` (see `load_apps_from`), plus store apps from
|
||||
/// `store`. A store app is skipped if it breaks the store rules or has the id
|
||||
/// of an official app.
|
||||
pub fn load_all(dirs: &[PathBuf], store: Option<&Path>) -> Result<Vec<AppManifest>> {
|
||||
let mut apps = load_apps_from(dirs)?;
|
||||
if let Some(store) = store.filter(|d| d.is_dir()) {
|
||||
for mut app in load_apps(store)? {
|
||||
app.origin = Origin::Store;
|
||||
if let Err(e) = app.check_store_rules() {
|
||||
log::warn!("skipping store app {}: {e:#}", app.dir.display());
|
||||
} else if apps.iter().any(|a| a.id == app.id) {
|
||||
log::warn!("skipping store app {}: an app with this id is already installed", app.id);
|
||||
} else {
|
||||
apps.push(app);
|
||||
}
|
||||
}
|
||||
sort_apps(&mut apps);
|
||||
}
|
||||
Ok(apps)
|
||||
}
|
||||
|
||||
fn sort_apps(apps: &mut [AppManifest]) {
|
||||
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<u64> { v.split(['.', '-', '+']).take(3).map(|p| p.parse().unwrap_or(0)).collect() };
|
||||
let parts = |v: &str| -> Vec<u64> { v.split(['.', '-', '+']).take(4).map(|p| p.parse().unwrap_or(0)).collect() };
|
||||
let (a, b) = (parts(a), parts(b));
|
||||
(0..3).map(|i| a.get(i).unwrap_or(&0).cmp(b.get(i).unwrap_or(&0))).find(|o| o.is_ne()).unwrap_or(std::cmp::Ordering::Equal)
|
||||
(0..4).map(|i| a.get(i).unwrap_or(&0).cmp(b.get(i).unwrap_or(&0))).find(|o| o.is_ne()).unwrap_or(std::cmp::Ordering::Equal)
|
||||
}
|
||||
|
||||
fn load_one(path: &Path) -> Result<AppManifest> {
|
||||
@@ -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"]);
|
||||
}
|
||||
}
|
||||
|
||||
78
sf-app/src/paths.rs
Normal file
78
sf-app/src/paths.rs
Normal file
@@ -0,0 +1,78 @@
|
||||
//! Where the Fennec OS sockets and files live.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// `$XDG_RUNTIME_DIR`, or the temp dir.
|
||||
pub fn runtime_dir() -> PathBuf {
|
||||
std::env::var_os("XDG_RUNTIME_DIR").map(PathBuf::from).unwrap_or_else(std::env::temp_dir)
|
||||
}
|
||||
|
||||
fn from_env(var: &str, default: &str) -> PathBuf {
|
||||
match std::env::var_os(var) {
|
||||
Some(p) => p.into(),
|
||||
None => runtime_dir().join(default),
|
||||
}
|
||||
}
|
||||
|
||||
/// Launcher command socket (`home`, `remote <state>`, `power`, `wake`).
|
||||
pub fn launcher_socket() -> PathBuf {
|
||||
from_env("SMARTFOX_SOCKET", "smartfox.sock")
|
||||
}
|
||||
|
||||
/// sf-core: app lifecycle (JSON lines, see `message`).
|
||||
pub fn core_socket() -> PathBuf {
|
||||
from_env("SMARTFOX_CORE_SOCKET", "smartfox-core.sock")
|
||||
}
|
||||
|
||||
/// sf-compositor control socket (`focus launcher`, `focus <app-id>`).
|
||||
pub fn wm_socket() -> PathBuf {
|
||||
from_env("SMARTFOX_WM_SOCKET", "smartfox-wm.sock")
|
||||
}
|
||||
|
||||
/// The settings file: `$SMARTFOX_SETTINGS`, else `<config>/smartfox/settings.toml`.
|
||||
pub fn settings_file() -> PathBuf {
|
||||
if let Ok(p) = std::env::var("SMARTFOX_SETTINGS") {
|
||||
return p.into();
|
||||
}
|
||||
let base = std::env::var_os("XDG_CONFIG_HOME")
|
||||
.map(PathBuf::from)
|
||||
.or_else(|| std::env::var_os("APPDATA").map(PathBuf::from))
|
||||
.or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")))
|
||||
.unwrap_or_else(|| PathBuf::from("."));
|
||||
base.join("smartfox").join("settings.toml")
|
||||
}
|
||||
|
||||
/// An app's private data folder; its `$HOME` inside the sandbox:
|
||||
/// `$XDG_DATA_HOME/smartfox/apps/<id>` (default `~/.local/share/...`).
|
||||
pub fn app_data_dir(id: &str) -> PathBuf {
|
||||
let base = std::env::var_os("XDG_DATA_HOME")
|
||||
.map(PathBuf::from)
|
||||
.or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".local").join("share")))
|
||||
.or_else(|| std::env::var_os("LOCALAPPDATA").map(PathBuf::from))
|
||||
.unwrap_or_else(|| PathBuf::from("."));
|
||||
base.join("smartfox").join("apps").join(id)
|
||||
}
|
||||
|
||||
/// Installed store apps (`/var/lib/sf-pkg/store/apps/<id>`), written by sf-update.
|
||||
pub const STORE_APPS: &str = "/var/lib/sf-pkg/store/apps";
|
||||
|
||||
/// Looks for an `apps` folder next to the binary or above the cwd (dev
|
||||
/// checkout), else the installed one.
|
||||
pub fn apps_dir() -> PathBuf {
|
||||
let mut starts = vec![];
|
||||
if let Ok(cwd) = std::env::current_dir() {
|
||||
starts.push(cwd);
|
||||
}
|
||||
if let Ok(exe) = std::env::current_exe() {
|
||||
starts.extend(exe.parent().map(Path::to_path_buf));
|
||||
}
|
||||
for start in starts {
|
||||
for dir in start.ancestors() {
|
||||
let candidate = dir.join("apps");
|
||||
if candidate.join("netflex").is_dir() {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
}
|
||||
PathBuf::from("/usr/share/smartfox/apps")
|
||||
}
|
||||
350
sf-app/src/sandbox.rs
Normal file
350
sf-app/src/sandbox.rs
Normal file
@@ -0,0 +1,350 @@
|
||||
//! App sandbox: every app runs in its own bubblewrap (`bwrap`) container,
|
||||
//! the same building block Flatpak uses.
|
||||
//!
|
||||
//! Inside the sandbox an app sees:
|
||||
//! - the system read-only (`/usr`, `/etc`), no other user's or app's files;
|
||||
//! - its own files read-only at `/app`;
|
||||
//! - its own data folder as `$HOME` (on the host:
|
||||
//! `~/.local/share/smartfox/apps/<id>`), the only writable place that lasts;
|
||||
//! - the Wayland socket (it can show a window), nothing else from
|
||||
//! `$XDG_RUNTIME_DIR` (no launcher, sf-core or compositor sockets);
|
||||
//! - fresh /tmp, /run, /var and its own PID, IPC and UTS namespaces;
|
||||
//! - and only what its permissions allow (`Permission`): network, GPU,
|
||||
//! sound, game controllers, D-Bus, devices.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
use crate::manifest::Permission;
|
||||
|
||||
/// Where the app's own files are inside the sandbox.
|
||||
pub const APP_DIR: &str = "/app";
|
||||
|
||||
/// Environment variables passed through from the session when set.
|
||||
const PASS_ENV: [&str; 7] = ["LANG", "LANGUAGE", "LC_ALL", "TZ", "XCURSOR_THEME", "XCURSOR_SIZE", "RUST_LOG"];
|
||||
|
||||
/// What a host path is, for building the mount list (a function so tests
|
||||
/// can fake the file system).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Entry {
|
||||
Missing,
|
||||
Dir,
|
||||
Other,
|
||||
Symlink(PathBuf),
|
||||
/// There, but we may not read it (bwrap's `--*-bind-try` fails on that).
|
||||
Denied,
|
||||
}
|
||||
|
||||
pub fn probe(path: &Path) -> Entry {
|
||||
if let Err(e) = std::fs::metadata(path) {
|
||||
if e.kind() == std::io::ErrorKind::PermissionDenied {
|
||||
return Entry::Denied;
|
||||
}
|
||||
}
|
||||
match std::fs::symlink_metadata(path) {
|
||||
Err(_) => Entry::Missing,
|
||||
Ok(m) if m.file_type().is_symlink() => std::fs::read_link(path).map(Entry::Symlink).unwrap_or(Entry::Missing),
|
||||
Ok(m) if m.is_dir() => Entry::Dir,
|
||||
Ok(_) => Entry::Other,
|
||||
}
|
||||
}
|
||||
|
||||
/// The session the app is started from.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Host {
|
||||
pub uid: u32,
|
||||
pub user: String,
|
||||
pub home: PathBuf,
|
||||
pub runtime_dir: PathBuf,
|
||||
pub wayland_display: Option<String>,
|
||||
pub hostname: Option<String>,
|
||||
/// Allowed variables from the session (`PASS_ENV`).
|
||||
pub env: Vec<(String, String)>,
|
||||
/// /dev/hidraw* (controllers that talk raw HID, like DualSense).
|
||||
pub hidraw: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
impl Host {
|
||||
pub fn current() -> Host {
|
||||
let var = |k: &str| std::env::var(k).ok().filter(|v| !v.is_empty());
|
||||
let home = var("HOME").map(PathBuf::from).unwrap_or_else(|| PathBuf::from("/tmp"));
|
||||
let hidraw = std::fs::read_dir("/dev")
|
||||
.map(|d| d.flatten().map(|e| e.path()).filter(|p| p.file_name().is_some_and(|n| n.to_string_lossy().starts_with("hidraw"))).collect())
|
||||
.unwrap_or_default();
|
||||
Host {
|
||||
uid: current_uid(),
|
||||
user: var("USER").unwrap_or_else(|| "tv".into()),
|
||||
home,
|
||||
runtime_dir: crate::paths::runtime_dir(),
|
||||
wayland_display: var("WAYLAND_DISPLAY"),
|
||||
hostname: std::fs::read_to_string("/etc/hostname").ok().map(|h| h.trim().to_string()).filter(|h| !h.is_empty()),
|
||||
env: PASS_ENV.iter().filter_map(|k| var(k).map(|v| (k.to_string(), v))).collect(),
|
||||
hidraw,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn current_uid() -> u32 {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
// The owner of our own /proc entry is our uid (no libc needed).
|
||||
std::fs::metadata("/proc/self").map(|m| m.uid()).unwrap_or(1000)
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn current_uid() -> u32 {
|
||||
1000
|
||||
}
|
||||
|
||||
/// One sandboxed process.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Spec<'a> {
|
||||
pub app_id: &'a str,
|
||||
/// The app's files (host path), read-only at `/app`.
|
||||
pub app_dir: &'a Path,
|
||||
/// The app's private data (host path), mounted as `$HOME`.
|
||||
pub data_dir: &'a Path,
|
||||
/// More writable folders, at the same path inside (a browser profile).
|
||||
pub extra_rw: Vec<PathBuf>,
|
||||
pub permissions: &'a [Permission],
|
||||
/// Extra environment for the app.
|
||||
pub env: Vec<(String, String)>,
|
||||
pub program: String,
|
||||
pub args: Vec<String>,
|
||||
}
|
||||
|
||||
pub fn bwrap_path() -> Option<PathBuf> {
|
||||
if let Ok(p) = std::env::var("SMARTFOX_BWRAP") {
|
||||
return Some(p.into());
|
||||
}
|
||||
["/usr/bin/bwrap", "/usr/local/bin/bwrap"].iter().map(PathBuf::from).find(|p| p.is_file())
|
||||
}
|
||||
|
||||
/// The bwrap command for `spec`.
|
||||
pub fn command(bwrap: &Path, spec: &Spec, host: &Host) -> Command {
|
||||
let mut cmd = Command::new(bwrap);
|
||||
cmd.args(args(spec, host, &probe));
|
||||
cmd
|
||||
}
|
||||
|
||||
/// The bwrap arguments. Mount order matters: later mounts go on top.
|
||||
pub fn args(spec: &Spec, host: &Host, fs: &dyn Fn(&Path) -> Entry) -> Vec<String> {
|
||||
let has = |p: Permission| spec.permissions.contains(&p);
|
||||
let mut a: Vec<String> = Vec::new();
|
||||
let mut push = |items: &[&str]| a.extend(items.iter().map(|s| s.to_string()));
|
||||
|
||||
push(&["--die-with-parent", "--unshare-all"]);
|
||||
if has(Permission::Network) {
|
||||
push(&["--share-net"]);
|
||||
}
|
||||
if host.uid == 0 {
|
||||
// Unprivileged bwrap drops every capability by itself; as root
|
||||
// (development) do it explicitly.
|
||||
push(&["--cap-drop", "ALL"]);
|
||||
}
|
||||
if let Some(h) = &host.hostname {
|
||||
push(&["--hostname", h]);
|
||||
}
|
||||
|
||||
// The system, read-only. /bin, /lib... are symlinks into /usr on Debian.
|
||||
push(&["--ro-bind", "/usr", "/usr"]);
|
||||
for top in ["/bin", "/sbin", "/lib", "/lib32", "/lib64", "/libx32"] {
|
||||
match fs(Path::new(top)) {
|
||||
Entry::Symlink(t) => push(&["--symlink", &t.to_string_lossy(), top]),
|
||||
Entry::Dir => push(&["--ro-bind", top, top]),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
push(&["--ro-bind", "/etc", "/etc", "--proc", "/proc"]);
|
||||
|
||||
// Devices.
|
||||
if has(Permission::Devices) {
|
||||
push(&["--dev-bind", "/dev", "/dev"]);
|
||||
} else {
|
||||
push(&["--dev", "/dev", "--tmpfs", "/dev/shm"]);
|
||||
if has(Permission::Gpu) {
|
||||
push(&["--dev-bind-try", "/dev/dri", "/dev/dri"]);
|
||||
}
|
||||
if has(Permission::Gamepad) {
|
||||
push(&["--dev-bind-try", "/dev/input", "/dev/input", "--dev-bind-try", "/dev/uinput", "/dev/uinput"]);
|
||||
for h in &host.hidraw {
|
||||
let h = h.to_string_lossy();
|
||||
push(&["--dev-bind-try", &h, &h]);
|
||||
}
|
||||
}
|
||||
}
|
||||
if has(Permission::Gpu) || has(Permission::Gamepad) || has(Permission::Devices) {
|
||||
push(&["--ro-bind", "/sys", "/sys"]);
|
||||
}
|
||||
|
||||
// Fresh writable scratch space.
|
||||
push(&["--tmpfs", "/tmp", "--tmpfs", "/var", "--tmpfs", "/run", "--dir", "/var/tmp", "--symlink", "../run", "/var/run"]);
|
||||
push(&["--ro-bind-try", "/var/cache/fontconfig", "/var/cache/fontconfig"]);
|
||||
if has(Permission::Gamepad) || has(Permission::Devices) {
|
||||
// Hotplug of controllers (SDL, Steam) goes through udev.
|
||||
push(&["--ro-bind-try", "/run/udev", "/run/udev"]);
|
||||
}
|
||||
if has(Permission::Network) {
|
||||
// /etc/resolv.conf points at systemd-resolved's stub file on the TV;
|
||||
// elsewhere (WSL: /mnt/wsl/resolv.conf) bind whatever it points at.
|
||||
push(&["--ro-bind-try", "/run/systemd/resolve", "/run/systemd/resolve"]);
|
||||
if let Entry::Symlink(t) = fs(Path::new("/etc/resolv.conf")) {
|
||||
let target = Path::new("/etc").join(t);
|
||||
let target = target.to_string_lossy();
|
||||
if !target.starts_with("/run/systemd/resolve/") && !target.starts_with("/etc/") && !target.starts_with("/usr/") {
|
||||
push(&["--ro-bind-try", &target, &target]);
|
||||
}
|
||||
}
|
||||
}
|
||||
if has(Permission::DbusSystem) {
|
||||
push(&["--ro-bind-try", "/run/dbus/system_bus_socket", "/run/dbus/system_bus_socket"]);
|
||||
}
|
||||
|
||||
// The session's runtime dir: only the sockets the app may use.
|
||||
let rt = host.runtime_dir.to_string_lossy().to_string();
|
||||
push(&["--perms", "0700", "--dir", &rt]);
|
||||
let mut socket = |name: &str| {
|
||||
let p = format!("{rt}/{name}");
|
||||
if fs(Path::new(&p)) != Entry::Denied {
|
||||
push(&["--ro-bind-try", &p, &p]);
|
||||
}
|
||||
};
|
||||
if let Some(wl) = &host.wayland_display {
|
||||
socket(wl);
|
||||
}
|
||||
if has(Permission::Audio) {
|
||||
socket("pipewire-0");
|
||||
socket("pulse/native");
|
||||
}
|
||||
if has(Permission::DbusSession) {
|
||||
socket("bus");
|
||||
}
|
||||
|
||||
// $HOME is the app's own data folder (at the real home path, so programs
|
||||
// that remember absolute paths keep working).
|
||||
let home = host.home.to_string_lossy().to_string();
|
||||
if let Entry::Symlink(t) = fs(Path::new("/home")) {
|
||||
push(&["--symlink", &t.to_string_lossy(), "/home"]);
|
||||
}
|
||||
push(&["--bind", &spec.data_dir.to_string_lossy(), &home]);
|
||||
for p in &spec.extra_rw {
|
||||
let p = p.to_string_lossy();
|
||||
push(&["--bind", &p, &p]);
|
||||
}
|
||||
push(&["--ro-bind", &spec.app_dir.to_string_lossy(), APP_DIR, "--chdir", &home]);
|
||||
|
||||
// A clean environment.
|
||||
push(&["--clearenv"]);
|
||||
let mut env: Vec<(String, String)> = vec![
|
||||
("PATH".into(), "/usr/local/bin:/usr/bin:/bin:/usr/games".into()),
|
||||
("HOME".into(), home.clone()),
|
||||
("USER".into(), host.user.clone()),
|
||||
("LOGNAME".into(), host.user.clone()),
|
||||
("SHELL".into(), "/bin/sh".into()),
|
||||
("XDG_RUNTIME_DIR".into(), rt.clone()),
|
||||
("XDG_SESSION_TYPE".into(), "wayland".into()),
|
||||
("SMARTFOX_APP".into(), spec.app_id.into()),
|
||||
("SMARTFOX_APP_DIR".into(), APP_DIR.into()),
|
||||
];
|
||||
if let Some(wl) = &host.wayland_display {
|
||||
env.push(("WAYLAND_DISPLAY".into(), wl.clone()));
|
||||
}
|
||||
if has(Permission::DbusSession) {
|
||||
env.push(("DBUS_SESSION_BUS_ADDRESS".into(), format!("unix:path={rt}/bus")));
|
||||
}
|
||||
env.extend(host.env.iter().cloned());
|
||||
env.extend(spec.env.iter().cloned());
|
||||
for (k, v) in env {
|
||||
push(&["--setenv", &k, &v]);
|
||||
}
|
||||
|
||||
push(&["--", &spec.program]);
|
||||
a.extend(spec.args.iter().cloned());
|
||||
a
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn host() -> Host {
|
||||
Host {
|
||||
uid: 1000,
|
||||
user: "tv".into(),
|
||||
home: "/var/home/tv".into(),
|
||||
runtime_dir: "/run/user/1000".into(),
|
||||
wayland_display: Some("wayland-1".into()),
|
||||
hostname: Some("smartfox".into()),
|
||||
env: vec![("LANG".into(), "C.UTF-8".into())],
|
||||
hidraw: vec!["/dev/hidraw0".into()],
|
||||
}
|
||||
}
|
||||
|
||||
fn fake_fs(p: &Path) -> Entry {
|
||||
match p.to_str().unwrap() {
|
||||
"/bin" => Entry::Symlink("usr/bin".into()),
|
||||
"/lib" => Entry::Symlink("usr/lib".into()),
|
||||
"/lib64" => Entry::Symlink("usr/lib64".into()),
|
||||
"/home" => Entry::Symlink("var/home".into()),
|
||||
_ => Entry::Missing,
|
||||
}
|
||||
}
|
||||
|
||||
fn has_seq(args: &[String], seq: &[&str]) -> bool {
|
||||
args.windows(seq.len()).any(|w| w.iter().zip(seq).all(|(a, b)| a == b))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn minimal_sandbox() {
|
||||
let spec = Spec {
|
||||
app_id: "io.github.fox.hello",
|
||||
app_dir: Path::new("/var/lib/sf-pkg/store-io.github.fox.hello/1.0.0"),
|
||||
data_dir: Path::new("/var/home/tv/.local/share/smartfox/apps/io.github.fox.hello"),
|
||||
extra_rw: vec![],
|
||||
permissions: &[],
|
||||
env: vec![("FOO".into(), "bar".into())],
|
||||
program: "/app/bin/hello".into(),
|
||||
args: vec!["--x".into()],
|
||||
};
|
||||
let a = args(&spec, &host(), &fake_fs);
|
||||
assert!(has_seq(&a, &["--unshare-all"]));
|
||||
assert!(!a.contains(&"--share-net".to_string()));
|
||||
assert!(!a.iter().any(|s| s == "/dev/dri" || s == "/sys"));
|
||||
assert!(!a.iter().any(|s| s.contains("pipewire") || s.ends_with("/bus")));
|
||||
assert!(has_seq(&a, &["--symlink", "usr/bin", "/bin"]));
|
||||
assert!(has_seq(&a, &["--ro-bind-try", "/run/user/1000/wayland-1", "/run/user/1000/wayland-1"]));
|
||||
assert!(has_seq(&a, &["--bind", "/var/home/tv/.local/share/smartfox/apps/io.github.fox.hello", "/var/home/tv"]));
|
||||
assert!(has_seq(&a, &["--ro-bind", "/var/lib/sf-pkg/store-io.github.fox.hello/1.0.0", "/app"]));
|
||||
assert!(has_seq(&a, &["--setenv", "SMARTFOX_APP", "io.github.fox.hello"]));
|
||||
assert!(has_seq(&a, &["--setenv", "FOO", "bar"]));
|
||||
assert!(has_seq(&a, &["--", "/app/bin/hello", "--x"]));
|
||||
assert_eq!(a.last().unwrap(), "--x");
|
||||
// /run must be fresh before the runtime dir and sockets go in.
|
||||
let run = a.iter().position(|s| s == "/run").unwrap();
|
||||
let sock = a.iter().position(|s| s == "/run/user/1000/wayland-1").unwrap();
|
||||
assert!(run < sock);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn permissions_open_doors() {
|
||||
let perms = [Permission::Network, Permission::Gpu, Permission::Audio, Permission::Gamepad, Permission::DbusSession];
|
||||
let spec = Spec {
|
||||
app_id: "steam",
|
||||
app_dir: Path::new("/usr/share/smartfox/apps/steam"),
|
||||
data_dir: Path::new("/d"),
|
||||
extra_rw: vec!["/var/home/tv/.config/smartfox/profiles/steam".into()],
|
||||
permissions: &perms,
|
||||
env: vec![],
|
||||
program: "/app/x".into(),
|
||||
args: vec![],
|
||||
};
|
||||
let a = args(&spec, &host(), &fake_fs);
|
||||
assert!(a.contains(&"--share-net".to_string()));
|
||||
assert!(has_seq(&a, &["--dev-bind-try", "/dev/dri", "/dev/dri"]));
|
||||
assert!(has_seq(&a, &["--dev-bind-try", "/dev/hidraw0", "/dev/hidraw0"]));
|
||||
assert!(has_seq(&a, &["--ro-bind", "/sys", "/sys"]));
|
||||
assert!(has_seq(&a, &["--ro-bind-try", "/run/user/1000/pipewire-0", "/run/user/1000/pipewire-0"]));
|
||||
assert!(has_seq(&a, &["--setenv", "DBUS_SESSION_BUS_ADDRESS", "unix:path=/run/user/1000/bus"]));
|
||||
assert!(has_seq(&a, &["--bind", "/var/home/tv/.config/smartfox/profiles/steam", "/var/home/tv/.config/smartfox/profiles/steam"]));
|
||||
}
|
||||
}
|
||||
14
sf-pack/Cargo.toml
Normal file
14
sf-pack/Cargo.toml
Normal file
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "sf-pack"
|
||||
description = "Fennec OS store app packaging (docs/store.md)"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
sf-ipc.workspace = true
|
||||
anyhow.workspace = true
|
||||
serde.workspace = true
|
||||
toml.workspace = true
|
||||
tar = "0.4"
|
||||
ruzstd = "0.8"
|
||||
220
sf-pack/src/main.rs
Normal file
220
sf-pack/src/main.rs
Normal file
@@ -0,0 +1,220 @@
|
||||
//! sf-pack: builds Fennec OS store packages (docs/store.md).
|
||||
//!
|
||||
//! sf-pack build <app-dir> [out-dir] app.toml + <id>-<version>.tar.zst
|
||||
//! sf-pack verify <out-dir> checks what `build` made
|
||||
//! sf-pack run <app-dir> runs the app the way the TV does: in the
|
||||
//! store sandbox (Linux, needs bwrap)
|
||||
//!
|
||||
//! The two files in out-dir are the release assets: upload them to a
|
||||
//! release of the app's repo (GitHub, Gitea or GitLab).
|
||||
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use sf_ipc::AppManifest;
|
||||
|
||||
fn main() {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
if let Err(e) = run(&args) {
|
||||
eprintln!("sf-pack: {e:#}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
fn run(args: &[String]) -> Result<()> {
|
||||
let arg = |i: usize| args.get(i).map(String::as_str);
|
||||
match arg(0) {
|
||||
Some("build") => {
|
||||
let dir = arg(1).context("usage: sf-pack build <app-dir> [out-dir]")?;
|
||||
build(Path::new(dir), Path::new(arg(2).unwrap_or("dist")))
|
||||
}
|
||||
Some("verify") => verify(Path::new(arg(1).unwrap_or("dist"))),
|
||||
Some("run") => run_app(Path::new(arg(1).context("usage: sf-pack run <app-dir>")?)),
|
||||
_ => bail!("usage: sf-pack build <app-dir> [out-dir] | verify [out-dir] | run <app-dir>"),
|
||||
}
|
||||
}
|
||||
|
||||
fn read_manifest(dir: &Path) -> Result<AppManifest> {
|
||||
let path = dir.join("app.toml");
|
||||
let text = std::fs::read_to_string(&path).with_context(|| format!("reading {}", path.display()))?;
|
||||
let mut app: AppManifest = toml::from_str(&text).with_context(|| format!("parsing {}", path.display()))?;
|
||||
app.dir = dir.to_path_buf();
|
||||
Ok(app)
|
||||
}
|
||||
|
||||
fn is_release(v: &str) -> bool {
|
||||
!v.is_empty() && v.split('.').count() <= 4 && v.split('.').all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()))
|
||||
}
|
||||
|
||||
fn build(dir: &Path, out: &Path) -> Result<()> {
|
||||
let app = read_manifest(dir)?;
|
||||
app.check_store_rules().context("app.toml")?;
|
||||
if !is_release(&app.version) {
|
||||
bail!("version {:?} must be a release version like 1.2.3", app.version);
|
||||
}
|
||||
if app.icon.contains('.') && app.icon_file().is_none() {
|
||||
bail!("icon {} is missing from {}", app.icon, dir.display());
|
||||
}
|
||||
if let Some(exe) = app.resolved_exec(Path::new("/app")).first().and_then(|p| p.strip_prefix("/app/")) {
|
||||
let path = dir.join(exe);
|
||||
if !path.is_file() {
|
||||
bail!("exec {} is missing from {}", exe, dir.display());
|
||||
}
|
||||
check_executable(&path)?;
|
||||
}
|
||||
|
||||
std::fs::create_dir_all(out)?;
|
||||
let file = format!("{}-{}.tar.zst", app.id, app.version);
|
||||
let tar = pack_tar(dir, &app)?;
|
||||
let zst = ruzstd::encoding::compress_to_vec(&tar[..], ruzstd::encoding::CompressionLevel::Fastest);
|
||||
std::fs::write(out.join(&file), &zst)?;
|
||||
std::fs::copy(dir.join("app.toml"), out.join("app.toml"))?;
|
||||
println!("{}: {} ({} KiB)", app.id, out.join(&file).display(), zst.len() / 1024);
|
||||
println!("Release assets: app.toml, {file}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn check_executable(path: &Path) -> Result<()> {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
if std::fs::metadata(path)?.permissions().mode() & 0o111 == 0 {
|
||||
bail!("{} is not executable (chmod +x)", path.display());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn check_executable(_path: &Path) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The package: the app folder plus pkg.toml, reproducible (sorted, no
|
||||
/// owners, fixed time).
|
||||
fn pack_tar(dir: &Path, app: &AppManifest) -> Result<Vec<u8>> {
|
||||
let mut files = Vec::new();
|
||||
collect(dir, Path::new(""), &mut files)?;
|
||||
files.sort();
|
||||
let mut b = tar::Builder::new(Vec::new());
|
||||
b.follow_symlinks(false);
|
||||
let pkg = format!("name = \"{}\"\nversion = \"{}\"\n", app.id, app.version);
|
||||
let mut h = header(tar::EntryType::Regular, 0o644, pkg.len() as u64);
|
||||
b.append_data(&mut h, "pkg.toml", pkg.as_bytes())?;
|
||||
for rel in files {
|
||||
let path = dir.join(&rel);
|
||||
let meta = std::fs::symlink_metadata(&path)?;
|
||||
let mode = file_mode(&meta);
|
||||
if meta.file_type().is_symlink() {
|
||||
let mut h = header(tar::EntryType::Symlink, 0o777, 0);
|
||||
b.append_link(&mut h, &rel, std::fs::read_link(&path)?)?;
|
||||
} else if meta.is_dir() {
|
||||
let mut h = header(tar::EntryType::Directory, 0o755, 0);
|
||||
b.append_data(&mut h, &rel, std::io::empty())?;
|
||||
} else {
|
||||
// Windows has no x bit: whatever is under bin/ is executable.
|
||||
let exec = mode & 0o111 != 0 || rel.starts_with("bin");
|
||||
let mut h = header(tar::EntryType::Regular, if exec { 0o755 } else { 0o644 }, meta.len());
|
||||
b.append_data(&mut h, &rel, std::fs::File::open(&path)?)?;
|
||||
}
|
||||
}
|
||||
Ok(b.into_inner()?)
|
||||
}
|
||||
|
||||
fn header(kind: tar::EntryType, mode: u32, size: u64) -> tar::Header {
|
||||
let mut h = tar::Header::new_gnu();
|
||||
h.set_entry_type(kind);
|
||||
h.set_mode(mode);
|
||||
h.set_size(size);
|
||||
h.set_mtime(0);
|
||||
h.set_uid(0);
|
||||
h.set_gid(0);
|
||||
h
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn file_mode(meta: &std::fs::Metadata) -> u32 {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
meta.permissions().mode()
|
||||
}
|
||||
|
||||
/// On Windows nothing is executable; binaries under bin/ are.
|
||||
#[cfg(not(unix))]
|
||||
fn file_mode(_meta: &std::fs::Metadata) -> u32 {
|
||||
0o644
|
||||
}
|
||||
|
||||
fn collect(root: &Path, rel: &Path, out: &mut Vec<PathBuf>) -> Result<()> {
|
||||
for e in std::fs::read_dir(root.join(rel))? {
|
||||
let e = e?;
|
||||
let name = e.file_name();
|
||||
if name == "pkg.toml" && rel.as_os_str().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let r = rel.join(&name);
|
||||
out.push(r.clone());
|
||||
if e.file_type()?.is_dir() {
|
||||
collect(root, &r, out)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn verify(out: &Path) -> Result<()> {
|
||||
let app = read_manifest(out)?;
|
||||
app.check_store_rules()?;
|
||||
let file = out.join(format!("{}-{}.tar.zst", app.id, app.version));
|
||||
let data = std::fs::read(&file).with_context(|| format!("reading {}", file.display()))?;
|
||||
let mut tar = Vec::new();
|
||||
ruzstd::decoding::StreamingDecoder::new(&data[..]).map_err(|e| anyhow::anyhow!("zstd: {e}"))?.read_to_end(&mut tar)?;
|
||||
let mut archive = tar::Archive::new(&tar[..]);
|
||||
let names: Vec<String> = archive.entries()?.filter_map(|e| e.ok()?.path().ok().map(|p| p.to_string_lossy().into_owned())).collect();
|
||||
if !names.iter().any(|n| n == "pkg.toml") || !names.iter().any(|n| n == "app.toml") {
|
||||
bail!("pkg.toml or app.toml missing from the package");
|
||||
}
|
||||
println!("{} {}: package OK, {} files", app.id, app.version, names.len());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn builds_and_verifies() {
|
||||
let tmp = std::env::temp_dir().join(format!("sf-pack-test-{}", std::process::id()));
|
||||
let app = tmp.join("app");
|
||||
std::fs::create_dir_all(app.join("bin")).unwrap();
|
||||
std::fs::write(
|
||||
app.join("app.toml"),
|
||||
"id = \"io.github.fox.hello\"\nname = \"Hello\"\nversion = \"1.2.3\"\nkind = \"exec\"\nexec = [\"bin/hello\"]\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(app.join("bin/hello"), "#!/bin/sh\necho hi\n").unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(app.join("bin/hello"), std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
let out = tmp.join("dist");
|
||||
build(&app, &out).unwrap();
|
||||
verify(&out).unwrap();
|
||||
std::fs::remove_dir_all(&tmp).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs an app folder as a store app: same sandbox, same permissions.
|
||||
fn run_app(dir: &Path) -> Result<()> {
|
||||
let mut app = read_manifest(dir)?;
|
||||
app.check_store_rules().context("app.toml")?;
|
||||
app.origin = sf_ipc::Origin::Store;
|
||||
let settings = sf_ipc::Settings::default();
|
||||
let data = std::env::temp_dir().join("sf-pack-run");
|
||||
let opts = sf_ipc::launch::LaunchOptions { data_dir: &data, fullscreen: false, bounds: None, query: None };
|
||||
let mut cmd = sf_ipc::launch::command(&app, &settings, &opts)?;
|
||||
eprintln!("data folder ($HOME inside): {}", sf_ipc::paths::app_data_dir(&app.id).display());
|
||||
if std::env::var_os("SF_PACK_SHOW").is_some() {
|
||||
eprintln!("{} {}", cmd.get_program().to_string_lossy(), cmd.get_args().map(|a| a.to_string_lossy()).collect::<Vec<_>>().join(" "));
|
||||
}
|
||||
let status = cmd.status().context("starting the app")?;
|
||||
std::process::exit(status.code().unwrap_or(1));
|
||||
}
|
||||
30
sf-ui/Cargo.toml
Normal file
30
sf-ui/Cargo.toml
Normal file
@@ -0,0 +1,30 @@
|
||||
[package]
|
||||
name = "sf-ui"
|
||||
description = "SmartFox TV UI kit: Liquid Glass for Slint apps, TV components, artwork loading, video playback"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
# Slint is used under GPL-3.0 (its royalty-free license does not cover embedded
|
||||
# devices like a TV box), so apps built on sf-ui are GPL-3.0 too.
|
||||
license = "GPL-3.0-only"
|
||||
# Lets the build script of an app read DEP_SF_UI_UI_DIR (the Slint library).
|
||||
links = "sf_ui"
|
||||
build = "build.rs"
|
||||
|
||||
[features]
|
||||
default = ["images"]
|
||||
# Artwork over HTTP(S), decoded and scaled off the UI thread (images::Images).
|
||||
images = ["dep:ureq", "dep:image"]
|
||||
# Video playback with GStreamer (video::Player). Linux; needs GStreamer 1.22+.
|
||||
video = ["dep:gstreamer", "dep:gstreamer-app", "dep:gstreamer-video"]
|
||||
|
||||
[dependencies]
|
||||
anyhow.workspace = true
|
||||
log.workspace = true
|
||||
slint = { version = "1.18", default-features = false, features = ["std", "backend-default", "renderer-femtovg", "compat-1-2", "image-default-formats"] }
|
||||
glow = "0.16"
|
||||
png = "0.18"
|
||||
ureq = { version = "3", optional = true }
|
||||
image = { version = "0.25", optional = true, default-features = false, features = ["jpeg", "png", "webp"] }
|
||||
gstreamer = { version = "0.25", optional = true }
|
||||
gstreamer-app = { version = "0.25", optional = true }
|
||||
gstreamer-video = { version = "0.25", optional = true }
|
||||
7
sf-ui/build.rs
Normal file
7
sf-ui/build.rs
Normal file
@@ -0,0 +1,7 @@
|
||||
// Tells the build scripts of apps that depend on sf-ui where its Slint
|
||||
// library is: they read it as DEP_SF_UI_UI_DIR and map it to "@sf-ui".
|
||||
fn main() {
|
||||
let dir = std::path::Path::new(&std::env::var("CARGO_MANIFEST_DIR").unwrap()).join("ui");
|
||||
println!("cargo:ui_dir={}", dir.display());
|
||||
println!("cargo:rerun-if-changed=build.rs");
|
||||
}
|
||||
21
sf-ui/gallery/Cargo.toml
Normal file
21
sf-ui/gallery/Cargo.toml
Normal file
@@ -0,0 +1,21 @@
|
||||
[package]
|
||||
name = "sf-ui-gallery"
|
||||
description = "Every sf-ui component on one screen (example and visual test)"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license = "GPL-3.0-only"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
sf-ui = { path = ".." }
|
||||
slint = "1.18"
|
||||
anyhow.workspace = true
|
||||
log.workspace = true
|
||||
env_logger.workspace = true
|
||||
|
||||
[features]
|
||||
# SF_UI_VIDEO=<uri>: plays a video as the backdrop (Linux, GStreamer).
|
||||
video = ["sf-ui/video"]
|
||||
|
||||
[build-dependencies]
|
||||
slint-build = "1.18"
|
||||
7
sf-ui/gallery/build.rs
Normal file
7
sf-ui/gallery/build.rs
Normal file
@@ -0,0 +1,7 @@
|
||||
fn main() {
|
||||
// sf-ui's build script publishes where its Slint library is.
|
||||
let sf_ui = std::env::var("DEP_SF_UI_UI_DIR").expect("sf-ui must be a direct dependency");
|
||||
let config = slint_build::CompilerConfiguration::new()
|
||||
.with_library_paths(std::collections::HashMap::from([("sf-ui".to_string(), sf_ui.into())]));
|
||||
slint_build::compile_with_config("ui/gallery.slint", config).expect("compiling ui/gallery.slint");
|
||||
}
|
||||
101
sf-ui/gallery/src/main.rs
Normal file
101
sf-ui/gallery/src/main.rs
Normal file
@@ -0,0 +1,101 @@
|
||||
//! sf-ui gallery: every component on one screen.
|
||||
//!
|
||||
//! cargo run -p sf-ui-gallery
|
||||
//! SF_UI_SIZE=1920x1080 SF_UI_KEYS="down right" SF_UI_SNAPSHOT=shot.png cargo run -p sf-ui-gallery
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use slint::{ComponentHandle, Model, Rgba8Pixel, SharedPixelBuffer, VecModel};
|
||||
|
||||
slint::include_modules!();
|
||||
sf_ui::glue!(Gallery);
|
||||
|
||||
/// Stand-in artwork: a soft two-colour gradient with a light blob.
|
||||
fn artwork(a: [u8; 3], b: [u8; 3], w: u32, h: u32) -> SharedPixelBuffer<Rgba8Pixel> {
|
||||
let mut px = SharedPixelBuffer::<Rgba8Pixel>::new(w, h);
|
||||
let (cw, ch) = (w as f32, h as f32);
|
||||
for (i, p) in px.make_mut_slice().iter_mut().enumerate() {
|
||||
let (x, y) = ((i as u32 % w) as f32 / cw, (i as u32 / w) as f32 / ch);
|
||||
let t = (x * 0.6 + y * 0.4).clamp(0.0, 1.0);
|
||||
let d = ((x - 0.7).powi(2) + (y - 0.3).powi(2)).sqrt();
|
||||
let glow = (1.0 - d * 2.2).max(0.0).powi(2) * 0.55;
|
||||
let c = |k: usize| ((a[k] as f32 * (1.0 - t) + b[k] as f32 * t) * (1.0 - glow) + 255.0 * glow) as u8;
|
||||
*p = Rgba8Pixel { r: c(0), g: c(1), b: c(2), a: 255 };
|
||||
}
|
||||
px
|
||||
}
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
|
||||
sf_ui::init()?;
|
||||
let ui = Gallery::new()?;
|
||||
ui.sf_ui_setup();
|
||||
|
||||
let colours = [
|
||||
([190, 70, 40], [30, 10, 40]),
|
||||
([30, 110, 160], [10, 20, 40]),
|
||||
([60, 140, 80], [10, 30, 20]),
|
||||
([170, 140, 40], [40, 20, 10]),
|
||||
([120, 60, 170], [20, 10, 40]),
|
||||
];
|
||||
let pictures: Vec<SharedPixelBuffer<Rgba8Pixel>> = colours.iter().map(|(a, b)| artwork(*a, *b, 640, 360)).collect();
|
||||
let images: Vec<slint::Image> = pictures.iter().map(|p| slint::Image::from_rgba8(p.clone())).collect();
|
||||
ui.set_art(slint::ModelRc::new(VecModel::from(images)));
|
||||
let weak = ui.as_weak();
|
||||
ui.on_search(move |text| {
|
||||
if let Some(ui) = weak.upgrade() {
|
||||
ui.set_typed(text);
|
||||
}
|
||||
});
|
||||
|
||||
let glass = sf_ui::Glass::install(&ui, |ui, panels| {
|
||||
panels.extend(ui.get_glass().iter());
|
||||
panels.extend(ui.get_glass_menu().iter());
|
||||
panels.extend(ui.get_glass_modal().iter());
|
||||
panels.extend(ui.get_glass_keyboard().iter());
|
||||
})?;
|
||||
glass.set_palette(sf_ui::Palette::from_hex(["#ffb27a", "#8a3d12", "#120805"]));
|
||||
|
||||
// SF_UI_VIDEO=<uri> (feature "video"): the film plays under the glass.
|
||||
#[cfg(feature = "video")]
|
||||
let _video = match std::env::var("SF_UI_VIDEO") {
|
||||
Ok(uri) => {
|
||||
sf_ui::video::init()?;
|
||||
log::info!("hardware decoding: {}", sf_ui::video::hardware_decoding());
|
||||
let player = std::rc::Rc::new(std::cell::RefCell::new(sf_ui::video::Player::new(&uri, Default::default())?));
|
||||
glass.set_video(Some(player.borrow().video()));
|
||||
let p = player.clone();
|
||||
let poll = slint::Timer::default();
|
||||
poll.start(slint::TimerMode::Repeated, Duration::from_millis(100), move || {
|
||||
let mut p = p.borrow_mut();
|
||||
for ev in p.poll() {
|
||||
log::info!("video: {ev:?}");
|
||||
if let sf_ui::video::Event::Ready { .. } = ev {
|
||||
log::info!("audio: {:?}", p.audio_tracks());
|
||||
log::info!("text: {:?}", p.text_tracks());
|
||||
}
|
||||
}
|
||||
});
|
||||
Some((player, poll))
|
||||
}
|
||||
Err(_) => None,
|
||||
};
|
||||
|
||||
// The focused card's artwork becomes the backdrop (crossfades), and the
|
||||
// light follows the focus.
|
||||
let weak = ui.as_weak();
|
||||
let mut shown: Option<usize> = None;
|
||||
let timer = slint::Timer::default();
|
||||
timer.start(slint::TimerMode::Repeated, Duration::from_millis(100), move || {
|
||||
let Some(ui) = weak.upgrade() else { return };
|
||||
let want = (ui.get_area() == 2).then(|| ui.get_card() as usize);
|
||||
if want != shown {
|
||||
shown = want;
|
||||
glass.set_backdrop(want.map(|i| sf_ui::Backdrop::new(pictures[i].clone()).dim(0.2)));
|
||||
}
|
||||
glass.set_light((ui.get_card() as f32 - 2.0) * 0.08);
|
||||
});
|
||||
|
||||
ui.run()?;
|
||||
Ok(())
|
||||
}
|
||||
181
sf-ui/gallery/ui/gallery.slint
Normal file
181
sf-ui/gallery/ui/gallery.slint
Normal file
@@ -0,0 +1,181 @@
|
||||
// sf-ui gallery: every component on one screen. Also the smallest complete
|
||||
// example of an sf-ui app: TvWindow root, one FocusScope that owns the
|
||||
// focus state, glass exported as [GlassRect] arrays for the Rust side.
|
||||
|
||||
import { TvWindow, Tv, SfText, GlassRect, GlassPane, GlassButton, GlassMenu, MenuItem, ProgressBar, ArtworkCard, Spinner, Keyboard, Icon, Headline, Title, Body, Label, Caption, SectionTitle } from "@sf-ui/sf-ui.slint";
|
||||
|
||||
// Rust needs these two globals (sf_ui::glue! wires SfText).
|
||||
export { Tv, SfText }
|
||||
|
||||
export component Gallery inherits TvWindow {
|
||||
title: "sf-ui gallery";
|
||||
forward-focus: keys;
|
||||
|
||||
in property <[image]> art;
|
||||
in-out property <float> progress: 0.36;
|
||||
in property <string> typed;
|
||||
callback search(string);
|
||||
|
||||
// Focus: 0 = buttons, 1 = menu, 2 = cards.
|
||||
in-out property <int> area: 0;
|
||||
in-out property <int> button: 0;
|
||||
in-out property <int> item: 1;
|
||||
in-out property <int> card: 0;
|
||||
in-out property <bool> kb-open;
|
||||
out property <float> kb-t: self.kb-open ? 1 : 0;
|
||||
animate kb-t { duration: 480ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
|
||||
// Content under the keyboard pane goes away completely before it arrives.
|
||||
property <float> dim: max(0, 1 - 1.6 * self.kb-t);
|
||||
|
||||
keys := FocusScope {
|
||||
key-pressed(event) => {
|
||||
if root.kb-open {
|
||||
return kb.key(event);
|
||||
}
|
||||
if event.text == Key.UpArrow {
|
||||
if root.area == 1 { root.item = max(0, root.item - 1); }
|
||||
if root.area == 2 { root.area = 0; }
|
||||
} else if event.text == Key.DownArrow {
|
||||
if root.area == 1 { if root.item < 4 { root.item += 1; } else { root.area = 2; } }
|
||||
if root.area == 0 { root.area = 2; }
|
||||
} else if event.text == Key.LeftArrow {
|
||||
if root.area == 0 { root.button = max(0, root.button - 1); }
|
||||
if root.area == 2 { root.card = max(0, root.card - 1); }
|
||||
if root.area == 1 { root.area = 0; }
|
||||
} else if event.text == Key.RightArrow {
|
||||
if root.area == 0 { if root.button < 2 { root.button += 1; } else { root.area = 1; } }
|
||||
if root.area == 2 { root.card = min(4, root.card + 1); }
|
||||
} else if event.text == Key.Return {
|
||||
if root.area == 0 && root.button == 1 {
|
||||
kb.reset();
|
||||
root.kb-open = true;
|
||||
} else if root.area == 0 && root.button == 0 {
|
||||
root.progress = root.progress > 0.9 ? 0 : root.progress + 0.1;
|
||||
}
|
||||
} else {
|
||||
return reject;
|
||||
}
|
||||
accept
|
||||
}
|
||||
}
|
||||
|
||||
// ---- heading ----
|
||||
Headline {
|
||||
x: Tv.safe-x;
|
||||
y: Tv.safe-y;
|
||||
text: "sf-ui";
|
||||
opacity: root.dim;
|
||||
}
|
||||
Caption {
|
||||
x: Tv.safe-x;
|
||||
y: Tv.safe-y + 72 * Tv.u;
|
||||
text: "Nyilak: mozgás · OK: kiválasztás · Keresés: billentyűzet";
|
||||
opacity: root.dim;
|
||||
}
|
||||
|
||||
// ---- a details pane with buttons ----
|
||||
pane := GlassPane {
|
||||
x: Tv.safe-x;
|
||||
y: 200 * Tv.u;
|
||||
width: 1040 * Tv.u;
|
||||
height: 520 * Tv.u;
|
||||
alpha: root.dim;
|
||||
VerticalLayout {
|
||||
padding: 56 * Tv.u;
|
||||
spacing: 20 * Tv.u;
|
||||
opacity: root.dim;
|
||||
Label { text: "Film · 2024 · 2 ó 16 p"; }
|
||||
Title { text: "A dűne második része"; }
|
||||
Body {
|
||||
text: "Paul Atreides egyesül Chanival és a fremenekkel, miközben bosszút áll a családját elpusztító összeesküvőkön.";
|
||||
vertical-stretch: 1;
|
||||
}
|
||||
HorizontalLayout {
|
||||
spacing: 24 * Tv.u;
|
||||
alignment: start;
|
||||
b0 := GlassButton { text: "Lejátszás"; icon: "play"; primary: true; nested: true; focused: root.area == 0 && root.button == 0; alpha: root.dim; }
|
||||
b1 := GlassButton { text: "Keresés"; icon: "search"; nested: true; focused: root.area == 0 && root.button == 1; alpha: root.dim; }
|
||||
b2 := GlassButton { icon: "plus"; nested: true; focused: root.area == 0 && root.button == 2; alpha: root.dim; }
|
||||
}
|
||||
bar := ProgressBar { value: root.progress; buffered: root.progress + 0.2; alpha: root.dim; }
|
||||
}
|
||||
}
|
||||
|
||||
// ---- a menu ----
|
||||
menu := GlassMenu {
|
||||
x: 1264 * Tv.u;
|
||||
y: 200 * Tv.u;
|
||||
title: "Hang";
|
||||
alpha: root.dim;
|
||||
focused-index: root.area == 1 ? root.item : -1;
|
||||
items: [
|
||||
{ text: "Magyar", detail: "5.1", checked: root.item == 0 },
|
||||
{ text: "Angol", detail: "Atmos", checked: root.item == 1 },
|
||||
{ text: "Angol — Kommentár", detail: "Sztereó", checked: root.item == 2 },
|
||||
{ text: "Német", detail: "5.1", checked: root.item == 3 },
|
||||
{ text: "Francia", detail: "Sztereó", checked: root.item == 4 },
|
||||
];
|
||||
}
|
||||
|
||||
// ---- artwork ----
|
||||
SectionTitle {
|
||||
x: Tv.safe-x;
|
||||
y: 760 * Tv.u;
|
||||
text: root.typed == "" ? "Népszerű" : "Keresés: " + root.typed;
|
||||
opacity: root.dim;
|
||||
}
|
||||
for i in 5: ArtworkCard {
|
||||
x: Tv.safe-x + i * 344 * Tv.u;
|
||||
y: 830 * Tv.u;
|
||||
width: 312 * Tv.u;
|
||||
height: 176 * Tv.u;
|
||||
image: i < root.art.length ? root.art[i] : @image-url("");
|
||||
placeholder: "Kártya \{i + 1}";
|
||||
progress: i == 1 ? 0.4 : -1;
|
||||
badge: i == 0 ? "Új rész" : "";
|
||||
focused: root.area == 2 && root.card == i;
|
||||
opacity: root.dim;
|
||||
}
|
||||
Spinner {
|
||||
x: 1264 * Tv.u + 560 * Tv.u - self.width;
|
||||
y: Tv.safe-y;
|
||||
opacity: root.dim;
|
||||
}
|
||||
|
||||
// ---- keyboard on a modal pane ----
|
||||
modal := GlassPane {
|
||||
x: (root.width - self.width) / 2;
|
||||
y: (root.height - self.height) / 2;
|
||||
width: 1720 * Tv.u;
|
||||
height: 760 * Tv.u;
|
||||
radius: 56 * Tv.u;
|
||||
frost: 3.8;
|
||||
tint: Tv.smoke.with-alpha(0.48);
|
||||
glow: Tv.orange;
|
||||
alpha: root.kb-t;
|
||||
kb := Keyboard {
|
||||
x: 0;
|
||||
y: 96 * Tv.u;
|
||||
width: parent.width;
|
||||
title: "Keresés";
|
||||
subtitle: "Filmek és sorozatok címe";
|
||||
placeholder: "Cím";
|
||||
submit-label: "Keresés";
|
||||
min-length: 2;
|
||||
alpha: root.kb-t;
|
||||
submitted(text) => {
|
||||
root.kb-open = false;
|
||||
root.search(text);
|
||||
}
|
||||
cancelled => {
|
||||
root.kb-open = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- glass, in drawing order ----
|
||||
out property <[GlassRect]> glass: [pane.glass, b0.glass, b1.glass, b2.glass, bar.glass];
|
||||
out property <[GlassRect]> glass-menu: menu.glass;
|
||||
out property <[GlassRect]> glass-modal: [modal.glass];
|
||||
out property <[GlassRect]> glass-keyboard: kb.glass;
|
||||
}
|
||||
103
sf-ui/src/dev.rs
Normal file
103
sf-ui/src/dev.rs
Normal file
@@ -0,0 +1,103 @@
|
||||
//! Dev helper, built into every [`crate::Glass`] window: scripted key presses
|
||||
//! and a PNG snapshot of the window, so a UI can be checked (by you, a CI job
|
||||
//! or an AI) without anyone at the screen.
|
||||
//!
|
||||
//! - `SF_UI_SIZE=1920x1080`: physical window size.
|
||||
//! - `SF_UI_KEYS="down down right enter wait esc"`: keys sent one by one
|
||||
//! (left, right, up, down, enter, esc, back = esc, backspace, space;
|
||||
//! a single character types it, `wait` = pause,
|
||||
//! `hold` = enter held 0.8 s), starting after 1.5 s, every 0.6 s.
|
||||
//! - `SF_UI_SNAPSHOT=out.png`: saves the frame and quits, 1.5 s after the
|
||||
//! last key (or after `SF_UI_SNAPSHOT_MS` milliseconds).
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::path::PathBuf;
|
||||
use std::rc::Rc;
|
||||
use std::time::Duration;
|
||||
|
||||
use slint::ComponentHandle;
|
||||
use slint::platform::{Key, WindowEvent};
|
||||
|
||||
const FIRST_KEY_MS: u64 = 1500;
|
||||
const KEY_STEP_MS: u64 = 600;
|
||||
|
||||
/// A snapshot waiting to be taken (shared with the rendering notifier).
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Snapshot {
|
||||
pub(crate) path: RefCell<Option<PathBuf>>,
|
||||
pub(crate) due: Cell<bool>,
|
||||
}
|
||||
|
||||
pub(crate) fn setup<C: ComponentHandle + 'static>(ui: &C) -> Rc<Snapshot> {
|
||||
let snap = Rc::new(Snapshot::default());
|
||||
if let Some((w, h)) = std::env::var("SF_UI_SIZE").ok().and_then(|s| {
|
||||
let (w, h) = s.split_once('x')?;
|
||||
Some((w.trim().parse().ok()?, h.trim().parse().ok()?))
|
||||
}) {
|
||||
ui.window().set_size(slint::PhysicalSize::new(w, h));
|
||||
}
|
||||
|
||||
let keys: Vec<String> =
|
||||
std::env::var("SF_UI_KEYS").map(|s| s.split_whitespace().map(str::to_string).collect()).unwrap_or_default();
|
||||
let mut at = FIRST_KEY_MS;
|
||||
for k in &keys {
|
||||
let hold = k == "hold";
|
||||
let text: Option<slint::SharedString> = match k.to_lowercase().as_str() {
|
||||
"hold" | "enter" => Some(Key::Return.into()),
|
||||
"left" => Some(Key::LeftArrow.into()),
|
||||
"right" => Some(Key::RightArrow.into()),
|
||||
"up" => Some(Key::UpArrow.into()),
|
||||
"down" => Some(Key::DownArrow.into()),
|
||||
"esc" | "back" => Some(Key::Escape.into()),
|
||||
"backspace" => Some(Key::Backspace.into()),
|
||||
"space" => Some(" ".into()),
|
||||
"wait" => None,
|
||||
_ if k.chars().count() == 1 => Some(k.as_str().into()),
|
||||
_ => None,
|
||||
};
|
||||
let start = at;
|
||||
at += if hold { 2 * KEY_STEP_MS } else { KEY_STEP_MS };
|
||||
let Some(text) = text else { continue };
|
||||
let weak = ui.as_weak();
|
||||
let t = text.clone();
|
||||
slint::Timer::single_shot(Duration::from_millis(start), move || {
|
||||
if let Some(ui) = weak.upgrade() {
|
||||
ui.window().dispatch_event(WindowEvent::KeyPressed { text: t.clone() });
|
||||
if !hold {
|
||||
ui.window().dispatch_event(WindowEvent::KeyReleased { text: t });
|
||||
}
|
||||
}
|
||||
});
|
||||
if hold {
|
||||
let weak = ui.as_weak();
|
||||
slint::Timer::single_shot(Duration::from_millis(start + 800), move || {
|
||||
if let Some(ui) = weak.upgrade() {
|
||||
ui.window().dispatch_event(WindowEvent::KeyReleased { text });
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(path) = std::env::var_os("SF_UI_SNAPSHOT").map(PathBuf::from) {
|
||||
let ms = std::env::var("SF_UI_SNAPSHOT_MS").ok().and_then(|s| s.parse().ok()).unwrap_or(at + 1500);
|
||||
*snap.path.borrow_mut() = Some(path);
|
||||
let s = snap.clone();
|
||||
slint::Timer::single_shot(Duration::from_millis(ms), move || s.due.set(true));
|
||||
}
|
||||
snap
|
||||
}
|
||||
|
||||
/// Writes top-down RGBA8 pixels as a PNG.
|
||||
pub(crate) fn save_png(path: &std::path::Path, w: u32, h: u32, rgba: &[u8]) -> anyhow::Result<()> {
|
||||
let file = std::io::BufWriter::new(std::fs::File::create(path)?);
|
||||
let mut enc = png::Encoder::new(file, w, h);
|
||||
enc.set_color(png::ColorType::Rgba);
|
||||
enc.set_depth(png::BitDepth::Eight);
|
||||
// The window has no meaningful alpha: make every pixel opaque.
|
||||
let mut data = rgba.to_vec();
|
||||
for px in data.chunks_exact_mut(4) {
|
||||
px[3] = 255;
|
||||
}
|
||||
enc.write_header()?.write_image_data(&data)?;
|
||||
Ok(())
|
||||
}
|
||||
386
sf-ui/src/glass.rs
Normal file
386
sf-ui/src/glass.rs
Normal file
@@ -0,0 +1,386 @@
|
||||
//! The Liquid Glass layer for a Slint window: install it once, then tell it
|
||||
//! each frame which panels to draw (usually the `[GlassRect]` arrays your
|
||||
//! .slint file exports), and set the backdrop (palette, picture, video).
|
||||
//!
|
||||
//! ```ignore
|
||||
//! sf_ui::init()?; // before creating the window
|
||||
//! let ui = App::new()?;
|
||||
//! ui.sf_ui_setup(); // from sf_ui::glue!(App)
|
||||
//! let glass = sf_ui::Glass::install(&ui, |ui, panels| {
|
||||
//! panels.extend(ui.get_glass().iter());
|
||||
//! })?;
|
||||
//! glass.set_palette(sf_ui::Palette::from_hex(["#ffb27a", "#8a3d12", "#120805"]));
|
||||
//! ui.run()?;
|
||||
//! ```
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
use std::time::Instant;
|
||||
|
||||
use slint::{ComponentHandle, Rgba8Pixel, SharedPixelBuffer};
|
||||
|
||||
use crate::render::{Frame, GlassRenderer, ImageDraw, ImageId, Nv12Frame, Panel, Quality, VideoDraw};
|
||||
use crate::Palette;
|
||||
|
||||
/// Time constant of palette and brightness changes (seconds).
|
||||
const EASE: f32 = 0.35;
|
||||
/// Crossfade time of pictures and video (seconds).
|
||||
const FADE: f32 = 0.45;
|
||||
|
||||
/// A picture for the backdrop (artwork behind a details page, a hero...).
|
||||
/// Glass panels refract and frost it like the gradient.
|
||||
#[derive(Clone)]
|
||||
pub struct Backdrop {
|
||||
pixels: SharedPixelBuffer<Rgba8Pixel>,
|
||||
dim: f32,
|
||||
fade_left: f32,
|
||||
fade_bottom: f32,
|
||||
align: [f32; 2],
|
||||
sharp: bool,
|
||||
}
|
||||
|
||||
impl Backdrop {
|
||||
/// Defaults: slightly dimmed, darker towards the left and bottom (room
|
||||
/// for titles), sharp, cropped around the centre.
|
||||
pub fn new(pixels: SharedPixelBuffer<Rgba8Pixel>) -> Backdrop {
|
||||
Backdrop { pixels, dim: 0.12, fade_left: 0.75, fade_bottom: 0.6, align: [0.5, 0.35], sharp: true }
|
||||
}
|
||||
/// Darkens the whole picture: 0 = as is, 1 = black.
|
||||
pub fn dim(mut self, v: f32) -> Self {
|
||||
self.dim = v.clamp(0.0, 1.0);
|
||||
self
|
||||
}
|
||||
/// Darkening towards the left edge, 0..1.
|
||||
pub fn fade_left(mut self, v: f32) -> Self {
|
||||
self.fade_left = v.clamp(0.0, 1.0);
|
||||
self
|
||||
}
|
||||
/// Darkening towards the bottom edge, 0..1.
|
||||
pub fn fade_bottom(mut self, v: f32) -> Self {
|
||||
self.fade_bottom = v.clamp(0.0, 1.0);
|
||||
self
|
||||
}
|
||||
/// Which part stays visible when cropped (0..1 per axis, 0.5 = centre).
|
||||
pub fn align(mut self, x: f32, y: f32) -> Self {
|
||||
self.align = [x.clamp(0.0, 1.0), y.clamp(0.0, 1.0)];
|
||||
self
|
||||
}
|
||||
/// Soft: only the blurred low-resolution copy shows (a frosted wallpaper).
|
||||
pub fn soft(mut self) -> Self {
|
||||
self.sharp = false;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Where video frames come from (see `sf_ui::video::Player`, or your own
|
||||
/// decoder). Called once per rendered frame on the UI thread.
|
||||
pub trait VideoSource {
|
||||
/// The newest frame since the last call, if any.
|
||||
fn take_frame(&self) -> Option<Box<dyn Nv12Frame + '_>>;
|
||||
}
|
||||
|
||||
/// Collects the glass panels of one frame, in logical pixels (the units of
|
||||
/// your .slint file). Draw order is push order: later panels lie on top.
|
||||
pub struct Panels {
|
||||
scale: f32,
|
||||
out: Vec<Panel>,
|
||||
}
|
||||
|
||||
impl Panels {
|
||||
/// One panel (logical px).
|
||||
pub fn push(&mut self, panel: impl Into<Panel>) {
|
||||
let p = panel.into();
|
||||
if p.alpha > 0.002 && p.w > 0.0 && p.h > 0.0 {
|
||||
self.out.push(p.scaled(self.scale));
|
||||
}
|
||||
}
|
||||
|
||||
/// Many panels, e.g. `panels.extend(ui.get_glass().iter())`.
|
||||
pub fn extend<T: Into<Panel>>(&mut self, panels: impl IntoIterator<Item = T>) {
|
||||
for p in panels {
|
||||
self.push(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Slot {
|
||||
backdrop: Backdrop,
|
||||
id: Option<ImageId>,
|
||||
alpha: f32,
|
||||
target: f32,
|
||||
}
|
||||
|
||||
struct State {
|
||||
palette: [f32; 9],
|
||||
palette_target: [f32; 9],
|
||||
brightness: f32,
|
||||
brightness_target: f32,
|
||||
images: Vec<Slot>,
|
||||
free: Vec<ImageId>,
|
||||
video: Option<Rc<dyn VideoSource>>,
|
||||
video_alpha: f32,
|
||||
video_on: bool,
|
||||
clear_video: bool,
|
||||
light: f32,
|
||||
zoom: f32,
|
||||
last: f32,
|
||||
quality: Quality,
|
||||
}
|
||||
|
||||
/// Handle to an installed glass layer (cheap to clone).
|
||||
#[derive(Clone)]
|
||||
pub struct Glass {
|
||||
state: Rc<RefCell<State>>,
|
||||
}
|
||||
|
||||
impl Glass {
|
||||
/// Draws the glass layer under `ui`'s window. `panels` runs before every
|
||||
/// frame and adds that frame's panels. The backdrop animates, so frames
|
||||
/// keep coming (vsync-limited).
|
||||
///
|
||||
/// Call [`crate::init`] before creating the window: the layer needs the
|
||||
/// OpenGL (FemtoVG) renderer.
|
||||
pub fn install<C: ComponentHandle + 'static>(
|
||||
ui: &C,
|
||||
mut panels: impl FnMut(&C, &mut Panels) + 'static,
|
||||
) -> anyhow::Result<Glass> {
|
||||
let neutral = Palette::NEUTRAL.to_floats();
|
||||
let state = Rc::new(RefCell::new(State {
|
||||
palette: neutral,
|
||||
palette_target: neutral,
|
||||
brightness: 1.0,
|
||||
brightness_target: 1.0,
|
||||
images: Vec::new(),
|
||||
free: Vec::new(),
|
||||
video: None,
|
||||
video_alpha: 0.0,
|
||||
video_on: false,
|
||||
clear_video: false,
|
||||
light: 0.0,
|
||||
zoom: 1.0,
|
||||
last: 0.0,
|
||||
quality: Quality::Full,
|
||||
}));
|
||||
let glass = Glass { state: state.clone() };
|
||||
let snapshot = crate::dev::setup(ui);
|
||||
let renderer: Rc<RefCell<Option<GlassRenderer>>> = Rc::default();
|
||||
let start = Instant::now();
|
||||
let weak = ui.as_weak();
|
||||
ui.window()
|
||||
.set_rendering_notifier(move |rs, api| match rs {
|
||||
slint::RenderingState::RenderingSetup => {
|
||||
let slint::GraphicsAPI::NativeOpenGL { get_proc_address } = api else {
|
||||
log::error!("sf-ui: the glass layer needs OpenGL (call sf_ui::init() first)");
|
||||
return;
|
||||
};
|
||||
let gl = unsafe { glow::Context::from_loader_function_cstr(|s| get_proc_address(s)) };
|
||||
match unsafe { GlassRenderer::new(gl) } {
|
||||
Ok(r) => *renderer.borrow_mut() = Some(r),
|
||||
Err(e) => log::error!("sf-ui: glass layer disabled: {e:#}"),
|
||||
}
|
||||
}
|
||||
slint::RenderingState::BeforeRendering => {
|
||||
let mut guard = renderer.borrow_mut();
|
||||
let (Some(ui), Some(r)) = (weak.upgrade(), guard.as_mut()) else { return };
|
||||
let time = start.elapsed().as_secs_f32();
|
||||
let size = ui.window().size();
|
||||
let scale = ui.window().scale_factor();
|
||||
let mut list = Panels { scale, out: Vec::new() };
|
||||
panels(&ui, &mut list);
|
||||
|
||||
let mut st = state.borrow_mut();
|
||||
let dt = (time - st.last).clamp(0.0, 0.25);
|
||||
st.last = time;
|
||||
st.step(dt);
|
||||
// SAFETY: the rendering notifier runs with the GL context current.
|
||||
unsafe { st.sync_images(r) };
|
||||
if std::mem::take(&mut st.clear_video) {
|
||||
r.clear_video();
|
||||
}
|
||||
let draws: Vec<ImageDraw> = st
|
||||
.images
|
||||
.iter()
|
||||
.filter_map(|s| {
|
||||
Some(ImageDraw {
|
||||
image: s.id?,
|
||||
alpha: s.alpha,
|
||||
dim: s.backdrop.dim,
|
||||
fade_left: s.backdrop.fade_left,
|
||||
fade_bottom: s.backdrop.fade_bottom,
|
||||
align: s.backdrop.align,
|
||||
sharp: s.backdrop.sharp,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let video = st.video.clone();
|
||||
let frame_box = video.as_ref().and_then(|v| v.take_frame());
|
||||
let angle = -2.25 + 0.10 * (time * 0.35).sin() + st.light;
|
||||
let frame = Frame {
|
||||
width: size.width,
|
||||
height: size.height,
|
||||
scale,
|
||||
time,
|
||||
palette: st.palette,
|
||||
brightness: st.brightness,
|
||||
light: [angle.cos(), angle.sin()],
|
||||
zoom: st.zoom,
|
||||
images: &draws,
|
||||
video: (st.video_alpha > 0.002 || frame_box.is_some())
|
||||
.then(|| VideoDraw { frame: frame_box.as_deref(), alpha: st.video_alpha }),
|
||||
rects: list.out,
|
||||
quality: st.quality,
|
||||
};
|
||||
drop(st);
|
||||
// SAFETY: as above.
|
||||
unsafe { r.render(&frame) };
|
||||
}
|
||||
slint::RenderingState::AfterRendering => {
|
||||
let Some(ui) = weak.upgrade() else { return };
|
||||
if snapshot.due.get() {
|
||||
if let (Some(path), Some(r)) = (snapshot.path.borrow_mut().take(), renderer.borrow().as_ref()) {
|
||||
let size = ui.window().size();
|
||||
// SAFETY: after Slint rendered, context current.
|
||||
let px = unsafe { r.read_pixels(size.width, size.height) };
|
||||
match crate::dev::save_png(&path, size.width, size.height, &px) {
|
||||
Ok(()) => log::info!("sf-ui: snapshot {}", path.display()),
|
||||
Err(e) => log::error!("sf-ui: snapshot {}: {e:#}", path.display()),
|
||||
}
|
||||
let _ = slint::quit_event_loop();
|
||||
}
|
||||
}
|
||||
ui.window().request_redraw();
|
||||
}
|
||||
slint::RenderingState::RenderingTeardown => {
|
||||
if let Some(mut r) = renderer.borrow_mut().take() {
|
||||
unsafe { r.destroy() };
|
||||
}
|
||||
// Textures died with the context: upload again if it comes back.
|
||||
for s in state.borrow_mut().images.iter_mut() {
|
||||
s.id = None;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
})
|
||||
.map_err(|e| anyhow::anyhow!("sf-ui: rendering notifier: {e:?}"))?;
|
||||
Ok(glass)
|
||||
}
|
||||
|
||||
/// The backdrop gradient's colours; eases over from the current ones.
|
||||
pub fn set_palette(&self, palette: Palette) {
|
||||
self.state.borrow_mut().palette_target = palette.to_floats();
|
||||
}
|
||||
|
||||
/// Backdrop brightness, 0..1 (1 = full). Lower it to calm the backdrop
|
||||
/// behind dense content.
|
||||
pub fn set_brightness(&self, v: f32) {
|
||||
self.state.borrow_mut().brightness_target = v.clamp(0.0, 1.0);
|
||||
}
|
||||
|
||||
/// A picture over the gradient (crossfades from the previous one), or
|
||||
/// `None` to fade back to the gradient.
|
||||
pub fn set_backdrop(&self, backdrop: Option<Backdrop>) {
|
||||
let mut st = self.state.borrow_mut();
|
||||
match backdrop {
|
||||
Some(b) => {
|
||||
// Already showing this very picture: keep it.
|
||||
if let Some(last) = st.images.last_mut() {
|
||||
if last.backdrop.pixels.as_bytes().as_ptr() == b.pixels.as_bytes().as_ptr() {
|
||||
last.backdrop = b;
|
||||
last.target = 1.0;
|
||||
return;
|
||||
}
|
||||
}
|
||||
st.images.push(Slot { backdrop: b, id: None, alpha: 0.0, target: 1.0 });
|
||||
}
|
||||
None => {
|
||||
for s in st.images.iter_mut() {
|
||||
s.target = 0.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Video as the backdrop (glass refracts the film), or `None` to fade it
|
||||
/// out. The source is polled once per frame.
|
||||
pub fn set_video(&self, source: Option<Rc<dyn VideoSource>>) {
|
||||
let mut st = self.state.borrow_mut();
|
||||
st.video_on = source.is_some();
|
||||
if source.is_some() {
|
||||
st.video = source;
|
||||
st.clear_video = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Turns the key light (radians, small values like ±0.3), e.g. to follow
|
||||
/// the focus across the screen.
|
||||
pub fn set_light(&self, offset: f32) {
|
||||
self.state.borrow_mut().light = offset;
|
||||
}
|
||||
|
||||
/// How much of the glass effect to draw ([`Quality::Light`] or
|
||||
/// [`Quality::Flat`] on weaker hardware).
|
||||
pub fn set_quality(&self, q: Quality) {
|
||||
self.state.borrow_mut().quality = q;
|
||||
}
|
||||
|
||||
/// Zooms the backdrop gradient (1 = none).
|
||||
pub fn set_zoom(&self, zoom: f32) {
|
||||
self.state.borrow_mut().zoom = zoom.max(0.1);
|
||||
}
|
||||
}
|
||||
|
||||
impl State {
|
||||
fn step(&mut self, dt: f32) {
|
||||
let k = 1.0 - (-dt / EASE).exp();
|
||||
for (c, t) in self.palette.iter_mut().zip(self.palette_target) {
|
||||
*c += (t - *c) * k;
|
||||
}
|
||||
self.brightness += (self.brightness_target - self.brightness) * k;
|
||||
|
||||
let fade = dt / FADE;
|
||||
for s in self.images.iter_mut() {
|
||||
s.alpha = if s.target > s.alpha { (s.alpha + fade).min(s.target) } else { (s.alpha - fade).max(s.target) };
|
||||
}
|
||||
// A picture fully covered by a newer, opaque one is no longer needed;
|
||||
// faded-out ones neither.
|
||||
let covered = self.images.iter().rposition(|s| s.alpha >= 0.999).unwrap_or(0);
|
||||
let mut i = 0;
|
||||
self.images.retain(|s| {
|
||||
let keep = i >= covered && !(s.target == 0.0 && s.alpha <= 0.0);
|
||||
i += 1;
|
||||
if !keep {
|
||||
if let Some(id) = s.id {
|
||||
self.free.push(id);
|
||||
}
|
||||
}
|
||||
keep
|
||||
});
|
||||
|
||||
let target = if self.video_on { 1.0 } else { 0.0 };
|
||||
self.video_alpha = if target > self.video_alpha {
|
||||
(self.video_alpha + dt / 0.3).min(1.0)
|
||||
} else {
|
||||
(self.video_alpha - dt / 0.3).max(0.0)
|
||||
};
|
||||
if !self.video_on && self.video_alpha <= 0.0 {
|
||||
self.video = None;
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn sync_images(&mut self, r: &mut GlassRenderer) {
|
||||
for id in self.free.drain(..) {
|
||||
unsafe { r.free_image(id) };
|
||||
}
|
||||
for s in self.images.iter_mut().filter(|s| s.id.is_none()) {
|
||||
let px = &s.backdrop.pixels;
|
||||
match unsafe { r.upload_image(px.width(), px.height(), px.as_bytes()) } {
|
||||
Ok(id) => s.id = Some(id),
|
||||
Err(e) => {
|
||||
log::warn!("sf-ui: backdrop picture: {e:#}");
|
||||
s.target = 0.0;
|
||||
s.alpha = 0.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
259
sf-ui/src/images.rs
Normal file
259
sf-ui/src/images.rs
Normal file
@@ -0,0 +1,259 @@
|
||||
//! Artwork over HTTP(S): downloaded, decoded and scaled on worker threads,
|
||||
//! kept in a memory cache, handed to you on the UI thread.
|
||||
//!
|
||||
//! ```ignore
|
||||
//! let images = sf_ui::images::Images::new(256 << 20);
|
||||
//! images.load(&poster_url, (240, 360), move |img| card.set_image(img));
|
||||
//! ```
|
||||
//!
|
||||
//! Sizes are the size you show the picture at, in *physical* pixels (design
|
||||
//! px × the window's scale): the picture is scaled down to cover that box
|
||||
//! (never up), so a 4K TV gets sharper artwork and a 1080p one uses less memory.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::io::Read;
|
||||
use std::rc::{Rc, Weak};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::mpsc;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
use slint::{Rgba8Pixel, SharedPixelBuffer};
|
||||
|
||||
/// Bigger downloads are refused.
|
||||
const MAX_DOWNLOAD: u64 = 24 << 20;
|
||||
const WORKERS: usize = 4;
|
||||
|
||||
type Pixels = SharedPixelBuffer<Rgba8Pixel>;
|
||||
type Key = (String, u32, u32);
|
||||
type Waiter = Box<dyn FnOnce(&Pixels)>;
|
||||
|
||||
struct Job {
|
||||
owner: u64,
|
||||
key: Key,
|
||||
}
|
||||
|
||||
struct Inner {
|
||||
id: u64,
|
||||
budget: usize,
|
||||
used: RefCell<usize>,
|
||||
cache: RefCell<HashMap<Key, Pixels>>,
|
||||
order: RefCell<VecDeque<Key>>,
|
||||
waiting: RefCell<HashMap<Key, Vec<Waiter>>>,
|
||||
jobs: Mutex<Option<mpsc::Sender<()>>>,
|
||||
queue: Arc<Mutex<VecDeque<Job>>>,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static OWNERS: RefCell<HashMap<u64, Weak<Inner>>> = RefCell::new(HashMap::new());
|
||||
}
|
||||
|
||||
static NEXT_ID: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
/// The image loader and cache (cheap to clone; use it on the UI thread).
|
||||
#[derive(Clone)]
|
||||
pub struct Images {
|
||||
inner: Rc<Inner>,
|
||||
}
|
||||
|
||||
impl Images {
|
||||
/// `budget`: bytes of decoded pixels to keep (e.g. `256 << 20`).
|
||||
pub fn new(budget: usize) -> Images {
|
||||
let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
|
||||
let queue: Arc<Mutex<VecDeque<Job>>> = Arc::default();
|
||||
let (tx, rx) = mpsc::channel::<()>();
|
||||
let rx = Arc::new(Mutex::new(rx));
|
||||
let agent: ureq::Agent = ureq::Agent::config_builder()
|
||||
.timeout_global(Some(Duration::from_secs(30)))
|
||||
.user_agent("SmartFox sf-ui")
|
||||
.build()
|
||||
.into();
|
||||
for _ in 0..WORKERS {
|
||||
let rx = rx.clone();
|
||||
let queue = queue.clone();
|
||||
let agent = agent.clone();
|
||||
std::thread::spawn(move || {
|
||||
// Wake-ups come over the channel; the newest request is served first
|
||||
// (what the user looks at now), from the shared queue.
|
||||
while rx.lock().unwrap().recv().is_ok() {
|
||||
let Some(job) = queue.lock().unwrap().pop_back() else { continue };
|
||||
let result = fetch(&agent, &job.key.0, job.key.1, job.key.2);
|
||||
if let Err(e) = &result {
|
||||
log::debug!("image {}: {e:#}", job.key.0);
|
||||
}
|
||||
let (owner, key) = (job.owner, job.key);
|
||||
let _ = slint::invoke_from_event_loop(move || deliver(owner, key, result.ok()));
|
||||
}
|
||||
});
|
||||
}
|
||||
let inner = Rc::new(Inner {
|
||||
id,
|
||||
budget,
|
||||
used: RefCell::new(0),
|
||||
cache: RefCell::default(),
|
||||
order: RefCell::default(),
|
||||
waiting: RefCell::default(),
|
||||
jobs: Mutex::new(Some(tx)),
|
||||
queue,
|
||||
});
|
||||
OWNERS.with(|o| o.borrow_mut().insert(id, Rc::downgrade(&inner)));
|
||||
Images { inner }
|
||||
}
|
||||
|
||||
/// Loads `url` scaled to cover `size` (physical px) and calls `done` with
|
||||
/// it on the UI thread: at once if cached, later otherwise. On failure
|
||||
/// `done` is not called.
|
||||
pub fn load(&self, url: &str, size: (u32, u32), done: impl FnOnce(slint::Image) + 'static) {
|
||||
self.load_pixels(url, size, move |px| done(slint::Image::from_rgba8(px.clone())));
|
||||
}
|
||||
|
||||
/// Like [`Images::load`], but hands over the pixels (for
|
||||
/// [`crate::Backdrop`] or your own processing).
|
||||
pub fn load_pixels(&self, url: &str, size: (u32, u32), done: impl FnOnce(&Pixels) + 'static) {
|
||||
if url.is_empty() {
|
||||
return;
|
||||
}
|
||||
let key: Key = (url.to_string(), size.0.max(1), size.1.max(1));
|
||||
if let Some(px) = self.inner.cache.borrow().get(&key).cloned() {
|
||||
self.touch(&key);
|
||||
done(&px);
|
||||
return;
|
||||
}
|
||||
let mut waiting = self.inner.waiting.borrow_mut();
|
||||
if let Some(list) = waiting.get_mut(&key) {
|
||||
list.push(Box::new(done));
|
||||
return;
|
||||
}
|
||||
waiting.insert(key.clone(), vec![Box::new(done)]);
|
||||
drop(waiting);
|
||||
self.inner.queue.lock().unwrap().push_back(Job { owner: self.inner.id, key });
|
||||
if let Some(tx) = self.inner.jobs.lock().unwrap().as_ref() {
|
||||
let _ = tx.send(());
|
||||
}
|
||||
}
|
||||
|
||||
/// The cached picture, if it is already loaded.
|
||||
pub fn cached(&self, url: &str, size: (u32, u32)) -> Option<slint::Image> {
|
||||
let key: Key = (url.to_string(), size.0.max(1), size.1.max(1));
|
||||
self.inner.cache.borrow().get(&key).map(|px| slint::Image::from_rgba8(px.clone()))
|
||||
}
|
||||
|
||||
/// Drops requests that have not started yet (e.g. after leaving a screen).
|
||||
pub fn cancel_pending(&self) {
|
||||
let mut q = self.inner.queue.lock().unwrap();
|
||||
let mut waiting = self.inner.waiting.borrow_mut();
|
||||
for job in q.drain(..) {
|
||||
waiting.remove(&job.key);
|
||||
}
|
||||
}
|
||||
|
||||
fn touch(&self, key: &Key) {
|
||||
let mut order = self.inner.order.borrow_mut();
|
||||
if let Some(i) = order.iter().position(|k| k == key) {
|
||||
let k = order.remove(i).unwrap();
|
||||
order.push_back(k);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Inner {
|
||||
fn insert(&self, key: Key, px: Pixels) {
|
||||
let bytes = px.as_bytes().len();
|
||||
let mut cache = self.cache.borrow_mut();
|
||||
let mut order = self.order.borrow_mut();
|
||||
let mut used = self.used.borrow_mut();
|
||||
while *used + bytes > self.budget {
|
||||
let Some(old) = order.pop_front() else { break };
|
||||
if let Some(p) = cache.remove(&old) {
|
||||
*used -= p.as_bytes().len();
|
||||
}
|
||||
}
|
||||
*used += bytes;
|
||||
order.push_back(key.clone());
|
||||
cache.insert(key, px);
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Inner {
|
||||
fn drop(&mut self) {
|
||||
// Ends the worker threads.
|
||||
self.jobs.lock().unwrap().take();
|
||||
let id = self.id;
|
||||
let _ = OWNERS.try_with(|o| o.borrow_mut().remove(&id));
|
||||
}
|
||||
}
|
||||
|
||||
fn deliver(owner: u64, key: Key, px: Option<Pixels>) {
|
||||
let Some(inner) = OWNERS.with(|o| o.borrow().get(&owner).and_then(Weak::upgrade)) else { return };
|
||||
let waiters = inner.waiting.borrow_mut().remove(&key).unwrap_or_default();
|
||||
let Some(px) = px else { return };
|
||||
inner.insert(key, px.clone());
|
||||
for w in waiters {
|
||||
w(&px);
|
||||
}
|
||||
}
|
||||
|
||||
fn fetch(agent: &ureq::Agent, url: &str, w: u32, h: u32) -> anyhow::Result<Pixels> {
|
||||
let mut resp = agent.get(url).call()?;
|
||||
let mut bytes = Vec::new();
|
||||
resp.body_mut().as_reader().take(MAX_DOWNLOAD + 1).read_to_end(&mut bytes)?;
|
||||
anyhow::ensure!((bytes.len() as u64) <= MAX_DOWNLOAD, "larger than {MAX_DOWNLOAD} bytes");
|
||||
decode(&bytes, w, h)
|
||||
}
|
||||
|
||||
/// Decodes and scales down to cover `w` x `h` (never up).
|
||||
pub fn decode(bytes: &[u8], w: u32, h: u32) -> anyhow::Result<Pixels> {
|
||||
let img = image::load_from_memory(bytes)?;
|
||||
let (iw, ih) = (img.width().max(1), img.height().max(1));
|
||||
let k = (w as f32 / iw as f32).max(h as f32 / ih as f32);
|
||||
let img = if k < 0.98 {
|
||||
let (nw, nh) = (((iw as f32 * k).round() as u32).max(1), ((ih as f32 * k).round() as u32).max(1));
|
||||
img.resize_exact(nw, nh, image::imageops::FilterType::Triangle)
|
||||
} else {
|
||||
img
|
||||
};
|
||||
let rgba = img.into_rgba8();
|
||||
Ok(SharedPixelBuffer::clone_from_slice(rgba.as_raw(), rgba.width(), rgba.height()))
|
||||
}
|
||||
|
||||
/// The average colour of a picture (for a matching [`crate::Palette`]),
|
||||
/// leaning towards its saturated parts.
|
||||
pub fn average_color(px: &Pixels) -> slint::Color {
|
||||
let (mut r, mut g, mut b, mut n) = (0f64, 0f64, 0f64, 0f64);
|
||||
let bytes = px.as_bytes();
|
||||
for p in bytes.chunks_exact(4).step_by(7) {
|
||||
let (pr, pg, pb) = (p[0] as f64, p[1] as f64, p[2] as f64);
|
||||
let max = pr.max(pg).max(pb);
|
||||
let min = pr.min(pg).min(pb);
|
||||
let wgt = 0.15 + (max - min) / 255.0 + max / 510.0;
|
||||
r += pr * wgt;
|
||||
g += pg * wgt;
|
||||
b += pb * wgt;
|
||||
n += wgt;
|
||||
}
|
||||
if n == 0.0 {
|
||||
return slint::Color::from_rgb_u8(0x2a, 0x31, 0x40);
|
||||
}
|
||||
slint::Color::from_rgb_u8((r / n) as u8, (g / n) as u8, (b / n) as u8)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn scales_to_cover() {
|
||||
let mut png = Vec::new();
|
||||
let img = image::RgbaImage::from_pixel(400, 600, image::Rgba([200, 40, 30, 255]));
|
||||
image::DynamicImage::ImageRgba8(img)
|
||||
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
|
||||
.unwrap();
|
||||
let px = decode(&png, 100, 100).unwrap();
|
||||
assert_eq!((px.width(), px.height()), (100, 150));
|
||||
let px = decode(&png, 1000, 1000).unwrap();
|
||||
assert_eq!((px.width(), px.height()), (400, 600));
|
||||
let c = average_color(&px);
|
||||
assert!(c.red() > 150 && c.green() < 80);
|
||||
}
|
||||
}
|
||||
191
sf-ui/src/lib.rs
Normal file
191
sf-ui/src/lib.rs
Normal file
@@ -0,0 +1,191 @@
|
||||
//! sf-ui: the SmartFox TV UI kit for Slint apps.
|
||||
//!
|
||||
//! - **Liquid Glass** ([`Glass`]): the refracting, frosted glass of the
|
||||
//! SmartFox launcher, drawn by an OpenGL layer under your Slint UI, over an
|
||||
//! animated palette backdrop, a picture or a playing video.
|
||||
//! - **Slint components** (`@sf-ui/sf-ui.slint`): design tokens (`Tv`), text
|
||||
//! styles, glass panes, buttons, chips, a progress bar, an on-screen
|
||||
//! keyboard, icons and the Onest font.
|
||||
//! - **Images** ([`images::Images`], feature `images`): artwork over HTTP,
|
||||
//! decoded and scaled off the UI thread, cached.
|
||||
//! - **Video** (`video::Player`, feature `video`, Linux): GStreamer playback
|
||||
//! with hardware decoding, its frames shown as the glass backdrop.
|
||||
//!
|
||||
//! Guide: `docs/sf-ui.md` in the SmartFox repository.
|
||||
|
||||
pub mod render;
|
||||
|
||||
mod dev;
|
||||
mod glass;
|
||||
#[cfg(feature = "images")]
|
||||
pub mod images;
|
||||
pub mod text;
|
||||
#[cfg(feature = "video")]
|
||||
pub mod video;
|
||||
|
||||
pub use glass::{Backdrop, Glass, Panels, VideoSource};
|
||||
pub use render::{Matrix, Nv12Frame, Panel, Quality};
|
||||
|
||||
/// Selects Slint's OpenGL renderer (FemtoVG), which the glass layer draws
|
||||
/// with. Call it first in `main`, before creating any window.
|
||||
pub fn init() -> anyhow::Result<()> {
|
||||
slint::BackendSelector::new()
|
||||
.renderer_name("femtovg".into())
|
||||
.select()
|
||||
.map_err(|e| anyhow::anyhow!("selecting the femtovg (OpenGL) renderer: {e}"))
|
||||
}
|
||||
|
||||
/// The backdrop gradient's three colours: highlight, mid, deep. Use the
|
||||
/// `palette` of your app.toml, or one per screen / per focused item.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct Palette {
|
||||
pub highlight: slint::Color,
|
||||
pub mid: slint::Color,
|
||||
pub deep: slint::Color,
|
||||
}
|
||||
|
||||
impl Palette {
|
||||
/// The neutral system palette (no app colour).
|
||||
pub const NEUTRAL: Palette = Palette {
|
||||
highlight: slint::Color::from_rgb_u8(0x9a, 0xa4, 0xb5),
|
||||
mid: slint::Color::from_rgb_u8(0x2a, 0x31, 0x40),
|
||||
deep: slint::Color::from_rgb_u8(0x06, 0x07, 0x0a),
|
||||
};
|
||||
|
||||
pub fn new(highlight: slint::Color, mid: slint::Color, deep: slint::Color) -> Palette {
|
||||
Palette { highlight, mid, deep }
|
||||
}
|
||||
|
||||
/// From three "#rrggbb" strings (as in app.toml); bad ones fall back to
|
||||
/// the neutral palette's colour.
|
||||
pub fn from_hex(hex: [&str; 3]) -> Palette {
|
||||
let n = Palette::NEUTRAL;
|
||||
Palette {
|
||||
highlight: parse_hex(hex[0]).unwrap_or(n.highlight),
|
||||
mid: parse_hex(hex[1]).unwrap_or(n.mid),
|
||||
deep: parse_hex(hex[2]).unwrap_or(n.deep),
|
||||
}
|
||||
}
|
||||
|
||||
/// A palette from one colour, e.g. the average colour of a poster:
|
||||
/// a lighter highlight, the colour itself, a near-black deep tone.
|
||||
pub fn from_color(c: slint::Color) -> Palette {
|
||||
let [r, g, b] = rgb(c);
|
||||
let mix = |k: f32, t: f32| -> slint::Color {
|
||||
let f = |v: f32| ((v * k + t * (1.0 - k)).clamp(0.0, 1.0) * 255.0) as u8;
|
||||
slint::Color::from_rgb_u8(f(r), f(g), f(b))
|
||||
};
|
||||
Palette { highlight: mix(0.7, 1.0), mid: mix(0.55, 0.0), deep: mix(0.08, 0.0) }
|
||||
}
|
||||
|
||||
/// rgb 0..1 for the renderer.
|
||||
pub fn to_floats(self) -> [f32; 9] {
|
||||
let mut out = [0.0; 9];
|
||||
for (i, c) in [self.highlight, self.mid, self.deep].into_iter().enumerate() {
|
||||
out[i * 3..i * 3 + 3].copy_from_slice(&rgb(c));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// "#rrggbb" or "rrggbb".
|
||||
pub fn parse_hex(hex: &str) -> Option<slint::Color> {
|
||||
let h = hex.trim().trim_start_matches('#');
|
||||
let v = u32::from_str_radix(h.get(..6)?, 16).ok()?;
|
||||
Some(slint::Color::from_rgb_u8((v >> 16) as u8, (v >> 8) as u8, v as u8))
|
||||
}
|
||||
|
||||
fn rgb(c: slint::Color) -> [f32; 3] {
|
||||
[c.red() as f32 / 255.0, c.green() as f32 / 255.0, c.blue() as f32 / 255.0]
|
||||
}
|
||||
|
||||
impl Panel {
|
||||
/// From the fields of a Slint `GlassRect` (used by [`glue!`]).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn from_slint(
|
||||
x: f32,
|
||||
y: f32,
|
||||
w: f32,
|
||||
h: f32,
|
||||
r: f32,
|
||||
focus: f32,
|
||||
alpha: f32,
|
||||
blur: f32,
|
||||
glow: slint::Color,
|
||||
tint: slint::Color,
|
||||
group: i32,
|
||||
) -> Panel {
|
||||
let [tr, tg, tb] = rgb(tint);
|
||||
Panel {
|
||||
x,
|
||||
y,
|
||||
w,
|
||||
h,
|
||||
radius: r,
|
||||
focus,
|
||||
alpha,
|
||||
blur,
|
||||
glow: rgb(glow),
|
||||
group: group as f32,
|
||||
tint: [tr, tg, tb, tint.alpha() as f32 / 255.0],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Connects the types Slint generated in *your* crate to sf-ui. Put it once
|
||||
/// next to `slint::include_modules!()`, with your root component's name:
|
||||
///
|
||||
/// ```ignore
|
||||
/// slint::include_modules!();
|
||||
/// sf_ui::glue!(App);
|
||||
/// ```
|
||||
///
|
||||
/// It makes `GlassRect` convertible to [`Panel`] (so `panels.extend(...)`
|
||||
/// takes your `[GlassRect]` arrays) and adds `App::sf_ui_setup()`, which
|
||||
/// wires the Slint helper callbacks (`SfText`). Your main .slint file must
|
||||
/// export the helpers: `export { Tv, SfText } from "@sf-ui/sf-ui.slint";`.
|
||||
#[macro_export]
|
||||
macro_rules! glue {
|
||||
($app:ident) => {
|
||||
impl ::core::convert::From<GlassRect> for $crate::Panel {
|
||||
fn from(g: GlassRect) -> Self {
|
||||
$crate::Panel::from_slint(g.x, g.y, g.w, g.h, g.r, g.focus, g.alpha, g.blur, g.glow.color(), g.tint.color(), g.group)
|
||||
}
|
||||
}
|
||||
|
||||
impl $app {
|
||||
/// Wires the sf-ui Slint helpers (text editing for the keyboard).
|
||||
/// Call it once after creating the window.
|
||||
#[allow(dead_code)]
|
||||
pub fn sf_ui_setup(&self) {
|
||||
use ::slint::ComponentHandle as _;
|
||||
let t = self.global::<SfText>();
|
||||
t.on_drop_last(|s| $crate::text::drop_last(&s).into());
|
||||
t.on_dots(|n| $crate::text::dots(n.max(0) as usize).into());
|
||||
t.on_truncate(|s, n| $crate::text::truncate(&s, n.max(0) as usize).into());
|
||||
t.on_typable(|s| $crate::text::typable(&s).into());
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn hex_colours() {
|
||||
assert_eq!(parse_hex("#ff7a35"), Some(slint::Color::from_rgb_u8(0xff, 0x7a, 0x35)));
|
||||
assert_eq!(parse_hex("121317"), Some(slint::Color::from_rgb_u8(0x12, 0x13, 0x17)));
|
||||
assert_eq!(parse_hex("#12"), None);
|
||||
let p = Palette::from_hex(["#ffffff", "nope", "#000000"]);
|
||||
assert_eq!(p.mid, Palette::NEUTRAL.mid);
|
||||
assert_eq!(p.to_floats()[0], 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn panel_scaling() {
|
||||
let p = Panel { x: 10.0, y: 20.0, w: 30.0, h: 40.0, radius: 5.0, alpha: 1.0, ..Panel::default() }.scaled(2.0);
|
||||
assert_eq!((p.x, p.y, p.w, p.h, p.radius), (20.0, 40.0, 60.0, 80.0, 10.0));
|
||||
}
|
||||
}
|
||||
167
sf-ui/src/render/mod.rs
Normal file
167
sf-ui/src/render/mod.rs
Normal file
@@ -0,0 +1,167 @@
|
||||
//! The low-level Liquid Glass renderer: an OpenGL pass drawn *under* the
|
||||
//! Slint UI. Most apps use [`crate::Glass`] instead, which drives this from a
|
||||
//! Slint rendering notifier; use this module directly only if you need your
|
||||
//! own notifier (the launcher does, for its dev snapshots).
|
||||
//!
|
||||
//! Per frame: the backdrop (animated gradient, optional pictures, optional
|
||||
//! video) goes into a small mipmapped texture and onto the window; then every
|
||||
//! glass panel is drawn as its own quad, refracting and frosting that texture.
|
||||
|
||||
mod renderer;
|
||||
mod shaders;
|
||||
|
||||
pub use renderer::GlassRenderer;
|
||||
|
||||
/// Panels drawn per frame at most (each one is its own small draw call).
|
||||
pub const MAX_RECTS: usize = 48;
|
||||
/// Members of one merged (liquid) group at most.
|
||||
pub const MAX_GROUP: usize = 4;
|
||||
|
||||
/// One glass panel. In [`Frame`] it is in physical pixels (top-left origin);
|
||||
/// [`crate::Panels`] takes it in logical pixels and scales it.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq)]
|
||||
pub struct Panel {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
pub w: f32,
|
||||
pub h: f32,
|
||||
pub radius: f32,
|
||||
/// 0..1, brightens the rim and adds the accent glow.
|
||||
pub focus: f32,
|
||||
pub alpha: f32,
|
||||
/// Frost: mip level of the backdrop seen through it (higher = blurrier).
|
||||
/// Negative = nested glass that sits on another pane.
|
||||
pub blur: f32,
|
||||
/// Accent light (rgb 0..1) for focus glow and rim.
|
||||
pub glow: [f32; 3],
|
||||
/// Consecutive panels with the same group (> 0) melt into one shape.
|
||||
pub group: f32,
|
||||
/// rgb + amount (0..1).
|
||||
pub tint: [f32; 4],
|
||||
}
|
||||
|
||||
impl Panel {
|
||||
/// The same panel with every length multiplied by `k` (logical → physical).
|
||||
pub fn scaled(mut self, k: f32) -> Panel {
|
||||
self.x *= k;
|
||||
self.y *= k;
|
||||
self.w *= k;
|
||||
self.h *= k;
|
||||
self.radius *= k;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// A picture uploaded with [`GlassRenderer::upload_image`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct ImageId(pub(crate) u32);
|
||||
|
||||
/// One picture on the backdrop, drawn over the gradient (and under the glass).
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct ImageDraw {
|
||||
pub image: ImageId,
|
||||
/// 0..1, for crossfades.
|
||||
pub alpha: f32,
|
||||
/// Darkens the whole picture (0 = as is).
|
||||
pub dim: f32,
|
||||
/// Darkens towards the left edge (room for a title), 0..1.
|
||||
pub fade_left: f32,
|
||||
/// Darkens towards the bottom edge, 0..1.
|
||||
pub fade_bottom: f32,
|
||||
/// Which part stays visible when the picture is cropped to the screen
|
||||
/// (0..1 per axis, 0.5 = centre).
|
||||
pub align: [f32; 2],
|
||||
/// Drawn sharp at full resolution. When false only the soft (blurred,
|
||||
/// low resolution) copy shows, like a frosted wallpaper.
|
||||
pub sharp: bool,
|
||||
}
|
||||
|
||||
/// Colour matrix of a video frame.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub enum Matrix {
|
||||
Bt601,
|
||||
#[default]
|
||||
Bt709,
|
||||
Bt2020,
|
||||
}
|
||||
|
||||
/// One decoded video frame in NV12: a full-size Y plane and a half-size
|
||||
/// plane of interleaved Cb/Cr bytes.
|
||||
pub trait Nv12Frame {
|
||||
fn width(&self) -> u32;
|
||||
fn height(&self) -> u32;
|
||||
/// Display aspect ratio (width / height, pixel aspect included).
|
||||
fn aspect(&self) -> f32 {
|
||||
self.width() as f32 / self.height().max(1) as f32
|
||||
}
|
||||
/// Plane 0 (Y) or 1 (CbCr): bytes and the stride (bytes per row).
|
||||
fn plane(&self, index: usize) -> (&[u8], usize);
|
||||
fn matrix(&self) -> Matrix {
|
||||
Matrix::Bt709
|
||||
}
|
||||
fn full_range(&self) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// The video layer of a frame. The renderer keeps the last uploaded frame,
|
||||
/// so `frame` only needs to be set when a new one arrived.
|
||||
pub struct VideoDraw<'a> {
|
||||
pub frame: Option<&'a dyn Nv12Frame>,
|
||||
/// 0..1, for fading in.
|
||||
pub alpha: f32,
|
||||
}
|
||||
|
||||
/// How much of the glass effect to draw (weaker TVs: lighter modes).
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub enum Quality {
|
||||
/// Refraction, dispersion, Fresnel: the full Liquid Glass.
|
||||
#[default]
|
||||
Full,
|
||||
/// Frosted glass with the lit rim, no lensing.
|
||||
Light,
|
||||
/// No frost: tinted panes with the rim only.
|
||||
Flat,
|
||||
}
|
||||
|
||||
/// Everything the renderer needs for one frame.
|
||||
pub struct Frame<'a> {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
/// Physical pixels per logical pixel (glass sizes depend on it).
|
||||
pub scale: f32,
|
||||
/// Seconds since start (animation clock).
|
||||
pub time: f32,
|
||||
/// Backdrop palette (highlight, mid, deep), rgb 0..1 each.
|
||||
pub palette: [f32; 9],
|
||||
/// Backdrop brightness, 0..1 (1 = full).
|
||||
pub brightness: f32,
|
||||
/// Direction towards the key light (screen space, y down).
|
||||
pub light: [f32; 2],
|
||||
/// Backdrop zoom (1 = none), e.g. for a launch fly-in.
|
||||
pub zoom: f32,
|
||||
/// Pictures over the gradient, in drawing order.
|
||||
pub images: &'a [ImageDraw],
|
||||
pub video: Option<VideoDraw<'a>>,
|
||||
pub rects: Vec<Panel>,
|
||||
pub quality: Quality,
|
||||
}
|
||||
|
||||
impl Default for Frame<'_> {
|
||||
fn default() -> Self {
|
||||
Frame {
|
||||
width: 0,
|
||||
height: 0,
|
||||
scale: 1.0,
|
||||
time: 0.0,
|
||||
palette: crate::Palette::NEUTRAL.to_floats(),
|
||||
brightness: 1.0,
|
||||
light: [-0.63, -0.78],
|
||||
zoom: 1.0,
|
||||
images: &[],
|
||||
video: None,
|
||||
rects: Vec::new(),
|
||||
quality: Quality::Full,
|
||||
}
|
||||
}
|
||||
}
|
||||
735
sf-ui/src/render/renderer.rs
Normal file
735
sf-ui/src/render/renderer.rs
Normal file
@@ -0,0 +1,735 @@
|
||||
//! OpenGL underlay drawn before Slint renders its items.
|
||||
//!
|
||||
//! Pass 1 renders the backdrop (gradient, then pictures, then video) into a
|
||||
//! small, mipmapped texture: that is what the glass refracts and frosts.
|
||||
//! Pass 2 puts the backdrop on the window: the small texture upscaled, then
|
||||
//! sharp pictures and the video at full resolution. Pass 3 draws every glass
|
||||
//! panel as its own quad, covering only the panel and its shadow. Uniform
|
||||
//! locations are looked up once; GL state is handed back to Slint untouched.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use glow::HasContext;
|
||||
|
||||
use super::shaders;
|
||||
use super::{Frame, ImageDraw, ImageId, MAX_GROUP, MAX_RECTS, Matrix, Nv12Frame, Panel};
|
||||
|
||||
/// The backdrop is blurry by design, so it never needs more than this width.
|
||||
const SCENE_MAX_W: i32 = 640;
|
||||
|
||||
type Loc = Option<glow::UniformLocation>;
|
||||
|
||||
struct SceneLocs {
|
||||
res: Loc,
|
||||
time: Loc,
|
||||
pal: Loc,
|
||||
zoom: Loc,
|
||||
bright: Loc,
|
||||
}
|
||||
|
||||
struct BlitLocs {
|
||||
scene: Loc,
|
||||
time: Loc,
|
||||
}
|
||||
|
||||
struct ImageLocs {
|
||||
image: Loc,
|
||||
img: Loc,
|
||||
res: Loc,
|
||||
align: Loc,
|
||||
dim: Loc,
|
||||
fade_left: Loc,
|
||||
fade_bottom: Loc,
|
||||
alpha: Loc,
|
||||
}
|
||||
|
||||
struct VideoLocs {
|
||||
y: Loc,
|
||||
uv: Loc,
|
||||
res: Loc,
|
||||
aspect: Loc,
|
||||
matrix: Loc,
|
||||
full: Loc,
|
||||
alpha: Loc,
|
||||
}
|
||||
|
||||
struct GlassLocs {
|
||||
box_: Loc,
|
||||
res: Loc,
|
||||
scene: Loc,
|
||||
scale: Loc,
|
||||
time: Loc,
|
||||
light: Loc,
|
||||
count: Loc,
|
||||
rect: Loc,
|
||||
param: Loc,
|
||||
glow: Loc,
|
||||
tint: Loc,
|
||||
mode: Loc,
|
||||
}
|
||||
|
||||
struct Image {
|
||||
tex: glow::Texture,
|
||||
w: i32,
|
||||
h: i32,
|
||||
}
|
||||
|
||||
/// The last uploaded video frame.
|
||||
struct Video {
|
||||
y: glow::Texture,
|
||||
uv: glow::Texture,
|
||||
size: (i32, i32),
|
||||
aspect: f32,
|
||||
matrix: Matrix,
|
||||
full: bool,
|
||||
ready: bool,
|
||||
}
|
||||
|
||||
pub struct GlassRenderer {
|
||||
gl: glow::Context,
|
||||
vao: glow::VertexArray,
|
||||
scene_prog: glow::Program,
|
||||
blit_prog: glow::Program,
|
||||
image_prog: glow::Program,
|
||||
video_prog: glow::Program,
|
||||
glass_prog: glow::Program,
|
||||
scene_locs: SceneLocs,
|
||||
blit_locs: BlitLocs,
|
||||
image_locs: ImageLocs,
|
||||
video_locs: VideoLocs,
|
||||
glass_locs: GlassLocs,
|
||||
fbo: glow::Framebuffer,
|
||||
tex: glow::Texture,
|
||||
tex_size: (i32, i32),
|
||||
/// RGBA16F if the driver can render to it (no banding in dark gradients).
|
||||
half_float: bool,
|
||||
images: HashMap<u32, Image>,
|
||||
next_image: u32,
|
||||
video: Option<Video>,
|
||||
}
|
||||
|
||||
/// GL state we touch and must hand back to the Slint renderer untouched.
|
||||
struct SavedState {
|
||||
program: i32,
|
||||
vao: i32,
|
||||
array_buffer: i32,
|
||||
framebuffer: i32,
|
||||
active_texture: i32,
|
||||
texture0: i32,
|
||||
texture1: i32,
|
||||
viewport: [i32; 4],
|
||||
blend: bool,
|
||||
blend_func: [i32; 4],
|
||||
blend_eq: [i32; 2],
|
||||
scissor: bool,
|
||||
depth: bool,
|
||||
stencil: bool,
|
||||
cull: bool,
|
||||
unpack_alignment: i32,
|
||||
unpack_row_length: i32,
|
||||
}
|
||||
|
||||
impl GlassRenderer {
|
||||
/// # Safety
|
||||
/// Must be called with the Slint OpenGL context current.
|
||||
pub unsafe fn new(gl: glow::Context) -> anyhow::Result<Self> {
|
||||
unsafe {
|
||||
let version = gl.get_parameter_string(glow::VERSION);
|
||||
let is_es = version.contains("OpenGL ES");
|
||||
log::info!("OpenGL: {version} ({})", gl.get_parameter_string(glow::RENDERER));
|
||||
let header = if is_es {
|
||||
"#version 300 es\nprecision highp float;\nprecision highp int;\n"
|
||||
} else {
|
||||
"#version 330 core\n"
|
||||
};
|
||||
|
||||
let scene_prog = link(&gl, header, shaders::VERTEX, shaders::SCENE)?;
|
||||
let blit_prog = link(&gl, header, shaders::VERTEX, shaders::BLIT)?;
|
||||
let 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 {
|
||||
res: loc(scene_prog, "uRes"),
|
||||
time: loc(scene_prog, "uTime"),
|
||||
pal: loc(scene_prog, "uPal"),
|
||||
zoom: loc(scene_prog, "uZoom"),
|
||||
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"),
|
||||
scene: loc(glass_prog, "uScene"),
|
||||
scale: loc(glass_prog, "uScale"),
|
||||
time: loc(glass_prog, "uTime"),
|
||||
light: loc(glass_prog, "uLight"),
|
||||
count: loc(glass_prog, "uCount"),
|
||||
rect: loc(glass_prog, "uRect"),
|
||||
param: loc(glass_prog, "uParam"),
|
||||
glow: loc(glass_prog, "uGlow"),
|
||||
tint: loc(glass_prog, "uTint"),
|
||||
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)?;
|
||||
let tex = gl.create_texture().map_err(anyhow::Error::msg)?;
|
||||
|
||||
Ok(Self {
|
||||
gl,
|
||||
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,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn save(&self) -> SavedState {
|
||||
let gl = &self.gl;
|
||||
unsafe {
|
||||
let mut viewport = [0; 4];
|
||||
gl.get_parameter_i32_slice(glow::VIEWPORT, &mut viewport);
|
||||
let active_texture = gl.get_parameter_i32(glow::ACTIVE_TEXTURE);
|
||||
gl.active_texture(glow::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),
|
||||
vao: gl.get_parameter_i32(glow::VERTEX_ARRAY_BINDING),
|
||||
array_buffer: gl.get_parameter_i32(glow::ARRAY_BUFFER_BINDING),
|
||||
framebuffer: gl.get_parameter_i32(glow::FRAMEBUFFER_BINDING),
|
||||
active_texture,
|
||||
texture0: gl.get_parameter_i32(glow::TEXTURE_BINDING_2D),
|
||||
texture1,
|
||||
viewport,
|
||||
blend: gl.is_enabled(glow::BLEND),
|
||||
blend_func: [
|
||||
gl.get_parameter_i32(glow::BLEND_SRC_RGB),
|
||||
gl.get_parameter_i32(glow::BLEND_DST_RGB),
|
||||
gl.get_parameter_i32(glow::BLEND_SRC_ALPHA),
|
||||
gl.get_parameter_i32(glow::BLEND_DST_ALPHA),
|
||||
],
|
||||
blend_eq: [
|
||||
gl.get_parameter_i32(glow::BLEND_EQUATION_RGB),
|
||||
gl.get_parameter_i32(glow::BLEND_EQUATION_ALPHA),
|
||||
],
|
||||
scissor: gl.is_enabled(glow::SCISSOR_TEST),
|
||||
depth: gl.is_enabled(glow::DEPTH_TEST),
|
||||
stencil: gl.is_enabled(glow::STENCIL_TEST),
|
||||
cull: gl.is_enabled(glow::CULL_FACE),
|
||||
unpack_alignment: gl.get_parameter_i32(glow::UNPACK_ALIGNMENT),
|
||||
unpack_row_length: gl.get_parameter_i32(glow::UNPACK_ROW_LENGTH),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn restore(&self, s: SavedState) {
|
||||
let gl = &self.gl;
|
||||
let nz = |v: i32| std::num::NonZeroU32::new(v as u32);
|
||||
unsafe {
|
||||
gl.use_program(nz(s.program).map(glow::NativeProgram));
|
||||
gl.bind_vertex_array(nz(s.vao).map(glow::NativeVertexArray));
|
||||
gl.bind_buffer(glow::ARRAY_BUFFER, nz(s.array_buffer).map(glow::NativeBuffer));
|
||||
gl.bind_framebuffer(glow::FRAMEBUFFER, nz(s.framebuffer).map(glow::NativeFramebuffer));
|
||||
gl.active_texture(glow::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);
|
||||
gl.viewport(s.viewport[0], s.viewport[1], s.viewport[2], s.viewport[3]);
|
||||
let [sr, dr, sa, da] = s.blend_func.map(|v| v as u32);
|
||||
gl.blend_func_separate(sr, dr, sa, da);
|
||||
gl.blend_equation_separate(s.blend_eq[0] as u32, s.blend_eq[1] as u32);
|
||||
let set = |cap, on: bool| if on { gl.enable(cap) } else { gl.disable(cap) };
|
||||
set(glow::BLEND, s.blend);
|
||||
set(glow::SCISSOR_TEST, s.scissor);
|
||||
set(glow::DEPTH_TEST, s.depth);
|
||||
set(glow::STENCIL_TEST, s.stencil);
|
||||
set(glow::CULL_FACE, s.cull);
|
||||
gl.pixel_store_i32(glow::UNPACK_ALIGNMENT, s.unpack_alignment);
|
||||
gl.pixel_store_i32(glow::UNPACK_ROW_LENGTH, s.unpack_row_length);
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn alloc_target(&self, w: i32, h: i32, half_float: bool) -> bool {
|
||||
let gl = &self.gl;
|
||||
unsafe {
|
||||
gl.bind_texture(glow::TEXTURE_2D, Some(self.tex));
|
||||
let (internal, ty) =
|
||||
if half_float { (glow::RGBA16F, glow::HALF_FLOAT) } else { (glow::RGBA8, glow::UNSIGNED_BYTE) };
|
||||
gl.tex_image_2d(
|
||||
glow::TEXTURE_2D,
|
||||
0,
|
||||
internal as i32,
|
||||
w,
|
||||
h,
|
||||
0,
|
||||
glow::RGBA,
|
||||
ty,
|
||||
glow::PixelUnpackData::Slice(None),
|
||||
);
|
||||
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);
|
||||
gl.check_framebuffer_status(glow::FRAMEBUFFER) == glow::FRAMEBUFFER_COMPLETE
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn ensure_target(&mut self, w: i32, h: i32) {
|
||||
if self.tex_size == (w, h) {
|
||||
return;
|
||||
}
|
||||
unsafe {
|
||||
if self.half_float && !self.alloc_target(w, h, true) {
|
||||
log::info!("glass: RGBA16F not renderable, using RGBA8 for the backdrop");
|
||||
self.half_float = false;
|
||||
}
|
||||
if !self.half_float {
|
||||
self.alloc_target(w, h, false);
|
||||
}
|
||||
}
|
||||
self.tex_size = (w, h);
|
||||
}
|
||||
|
||||
/// 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) {
|
||||
let (w, h) = (f.width as i32, f.height as i32);
|
||||
if w <= 0 || h <= 0 {
|
||||
return;
|
||||
}
|
||||
unsafe {
|
||||
let saved = self.save();
|
||||
let gl = &self.gl;
|
||||
gl.disable(glow::BLEND);
|
||||
gl.disable(glow::SCISSOR_TEST);
|
||||
gl.disable(glow::DEPTH_TEST);
|
||||
gl.disable(glow::STENCIL_TEST);
|
||||
gl.disable(glow::CULL_FACE);
|
||||
|
||||
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 (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);
|
||||
let gl = &self.gl;
|
||||
gl.bind_framebuffer(glow::FRAMEBUFFER, Some(self.fbo));
|
||||
gl.viewport(0, 0, sw, sh);
|
||||
let l = &self.scene_locs;
|
||||
gl.use_program(Some(self.scene_prog));
|
||||
gl.uniform_2_f32(l.res.as_ref(), sw as f32, sh as f32);
|
||||
gl.uniform_1_f32(l.time.as_ref(), f.time);
|
||||
gl.uniform_3_f32_slice(l.pal.as_ref(), &f.palette);
|
||||
gl.uniform_1_f32(l.zoom.as_ref(), f.zoom);
|
||||
gl.uniform_1_f32(l.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: 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),
|
||||
);
|
||||
gl.viewport(0, 0, w, h);
|
||||
let l = &self.blit_locs;
|
||||
gl.use_program(Some(self.blit_prog));
|
||||
gl.uniform_1_i32(l.scene.as_ref(), 0);
|
||||
gl.uniform_1_f32(l.time.as_ref(), f.time);
|
||||
gl.draw_arrays(glow::TRIANGLES, 0, 3);
|
||||
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);
|
||||
let l = &self.glass_locs;
|
||||
gl.use_program(Some(self.glass_prog));
|
||||
gl.uniform_1_i32(l.scene.as_ref(), 0);
|
||||
gl.uniform_2_f32(l.res.as_ref(), w as f32, h as f32);
|
||||
gl.uniform_1_f32(l.scale.as_ref(), f.scale);
|
||||
gl.uniform_1_f32(l.time.as_ref(), f.time);
|
||||
gl.uniform_2_f32(l.light.as_ref(), f.light[0], f.light[1]);
|
||||
let 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];
|
||||
let mut param = [0f32; MAX_GROUP * 4];
|
||||
let mut glow_c = [0f32; MAX_GROUP * 4];
|
||||
let mut tint = [0f32; MAX_GROUP * 4];
|
||||
for run in runs(rects) {
|
||||
let n = run.len();
|
||||
// Bounds plus room for the shadow (spread + downward offset).
|
||||
let margin = 132.0 * f.scale;
|
||||
let (mut x0, mut y0, mut x1, mut y1) = (f32::MAX, f32::MAX, f32::MIN, f32::MIN);
|
||||
for (i, r) in run.iter().enumerate() {
|
||||
rect[i * 4..i * 4 + 4].copy_from_slice(&[r.x, r.y, r.w, r.h]);
|
||||
param[i * 4..i * 4 + 4].copy_from_slice(&[r.radius, r.focus, r.alpha, r.blur]);
|
||||
glow_c[i * 4..i * 4 + 4].copy_from_slice(&[r.glow[0], r.glow[1], r.glow[2], 0.0]);
|
||||
tint[i * 4..i * 4 + 4].copy_from_slice(&r.tint);
|
||||
x0 = x0.min(r.x);
|
||||
y0 = y0.min(r.y);
|
||||
x1 = x1.max(r.x + r.w);
|
||||
y1 = y1.max(r.y + r.h);
|
||||
}
|
||||
let bx = [
|
||||
(x0 - margin).max(0.0),
|
||||
(y0 - margin).max(0.0),
|
||||
(x1 + margin).min(w as f32),
|
||||
(y1 + margin + 46.0 * f.scale).min(h as f32),
|
||||
];
|
||||
if bx[0] >= bx[2] || bx[1] >= bx[3] {
|
||||
continue;
|
||||
}
|
||||
gl.uniform_4_f32(l.box_.as_ref(), bx[0], bx[1], bx[2], bx[3]);
|
||||
gl.uniform_1_i32(l.count.as_ref(), n as i32);
|
||||
gl.uniform_4_f32_slice(l.rect.as_ref(), &rect[..n * 4]);
|
||||
gl.uniform_4_f32_slice(l.param.as_ref(), ¶m[..n * 4]);
|
||||
gl.uniform_4_f32_slice(l.glow.as_ref(), &glow_c[..n * 4]);
|
||||
gl.uniform_4_f32_slice(l.tint.as_ref(), &tint[..n * 4]);
|
||||
gl.draw_arrays(glow::TRIANGLE_STRIP, 0, 4);
|
||||
}
|
||||
|
||||
self.restore(saved);
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the current window framebuffer as top-down RGBA8 (dev snapshots).
|
||||
///
|
||||
/// # Safety
|
||||
/// Must be called with the context current, after Slint has rendered.
|
||||
pub unsafe fn read_pixels(&self, w: u32, h: u32) -> Vec<u8> {
|
||||
let mut buf = vec![0u8; (w * h * 4) as usize];
|
||||
unsafe {
|
||||
self.gl.pixel_store_i32(glow::PACK_ALIGNMENT, 1);
|
||||
self.gl.read_pixels(
|
||||
0,
|
||||
0,
|
||||
w as i32,
|
||||
h as i32,
|
||||
glow::RGBA,
|
||||
glow::UNSIGNED_BYTE,
|
||||
glow::PixelPackData::Slice(Some(&mut buf)),
|
||||
);
|
||||
}
|
||||
let row = (w * 4) as usize;
|
||||
let mut flipped = Vec::with_capacity(buf.len());
|
||||
for y in (0..h as usize).rev() {
|
||||
flipped.extend_from_slice(&buf[y * row..(y + 1) * row]);
|
||||
}
|
||||
flipped
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// Must be called with the context current.
|
||||
pub unsafe fn destroy(&mut self) {
|
||||
unsafe {
|
||||
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);
|
||||
self.gl.delete_texture(self.tex);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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]> {
|
||||
let mut rest = rects;
|
||||
std::iter::from_fn(move || {
|
||||
let first = rest.first()?;
|
||||
let mut n = 1;
|
||||
if first.group > 0.5 {
|
||||
while n < rest.len() && n < MAX_GROUP && (rest[n].group - first.group).abs() < 0.5 {
|
||||
n += 1;
|
||||
}
|
||||
}
|
||||
let (run, tail) = rest.split_at(n);
|
||||
rest = tail;
|
||||
Some(run)
|
||||
})
|
||||
}
|
||||
|
||||
unsafe fn link(gl: &glow::Context, header: &str, vs: &str, fs: &str) -> anyhow::Result<glow::Program> {
|
||||
unsafe {
|
||||
let program = gl.create_program().map_err(anyhow::Error::msg)?;
|
||||
let mut shaders = Vec::new();
|
||||
for (kind, src) in [(glow::VERTEX_SHADER, vs), (glow::FRAGMENT_SHADER, fs)] {
|
||||
let sh = gl.create_shader(kind).map_err(anyhow::Error::msg)?;
|
||||
gl.shader_source(sh, &format!("{header}{src}"));
|
||||
gl.compile_shader(sh);
|
||||
if !gl.get_shader_compile_status(sh) {
|
||||
anyhow::bail!("shader compile failed: {}", gl.get_shader_info_log(sh));
|
||||
}
|
||||
gl.attach_shader(program, sh);
|
||||
shaders.push(sh);
|
||||
}
|
||||
gl.link_program(program);
|
||||
if !gl.get_program_link_status(program) {
|
||||
anyhow::bail!("program link failed: {}", gl.get_program_info_log(program));
|
||||
}
|
||||
for sh in shaders {
|
||||
gl.detach_shader(program, sh);
|
||||
gl.delete_shader(sh);
|
||||
}
|
||||
Ok(program)
|
||||
}
|
||||
}
|
||||
|
||||
#[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]);
|
||||
}
|
||||
}
|
||||
471
sf-ui/src/render/shaders.rs
Normal file
471
sf-ui/src/render/shaders.rs
Normal file
@@ -0,0 +1,471 @@
|
||||
//! GLSL sources. The `#version` line is added at runtime (desktop GL 3.3 core or GLES 3.0).
|
||||
|
||||
/// Fullscreen triangle without vertex buffers.
|
||||
pub const VERTEX: &str = r#"
|
||||
out vec2 vUv;
|
||||
void main() {
|
||||
vec2 p = vec2(float((gl_VertexID << 1) & 2), float(gl_VertexID & 2));
|
||||
vUv = p;
|
||||
gl_Position = vec4(p * 2.0 - 1.0, 0.0, 1.0);
|
||||
}
|
||||
"#;
|
||||
|
||||
/// A quad over `uBox` (x0, y0, x1, y1 in px, top-left origin), drawn as a
|
||||
/// 4-vertex triangle strip. Glass panels only shade the pixels they can reach.
|
||||
pub const QUAD_VERTEX: &str = r#"
|
||||
uniform vec4 uBox;
|
||||
uniform vec2 uRes;
|
||||
void main() {
|
||||
vec2 c = vec2(float(gl_VertexID & 1), float((gl_VertexID >> 1) & 1));
|
||||
vec2 p = mix(uBox.xy, uBox.zw, c);
|
||||
gl_Position = vec4(p.x / uRes.x * 2.0 - 1.0, 1.0 - p.y / uRes.y * 2.0, 0.0, 1.0);
|
||||
}
|
||||
"#;
|
||||
|
||||
/// Backdrop: a dark, slowly flowing mesh gradient (soft colour fields in the
|
||||
/// focused app's palette), like Apple's dark dynamic wallpapers.
|
||||
///
|
||||
/// It is smooth by design, so it is rendered at low resolution and upscaled.
|
||||
/// Cost per pixel: a handful of exp() calls, no noise, no loops over shapes.
|
||||
pub const SCENE: &str = r#"
|
||||
in vec2 vUv;
|
||||
out vec4 fragColor;
|
||||
|
||||
uniform vec2 uRes;
|
||||
uniform float uTime;
|
||||
uniform vec3 uPal[3]; // highlight, mid, deep
|
||||
uniform float uZoom; // launch fly-in
|
||||
uniform float uBright; // backdrop brightness: 1 = full, lower = calmer (launcher: shelf hidden)
|
||||
|
||||
float field(vec2 d, float r) {
|
||||
return exp(-dot(d, d) / (r * r));
|
||||
}
|
||||
|
||||
// Rotates the hue around the grey axis (keeps brightness roughly the same).
|
||||
vec3 hueRot(vec3 c, float ang) {
|
||||
const vec3 k = vec3(0.57735);
|
||||
float ca = cos(ang);
|
||||
return max(c * ca + cross(k, c) * sin(ang) + k * dot(k, c) * (1.0 - ca), 0.0);
|
||||
}
|
||||
|
||||
void main() {
|
||||
vec2 uv = vec2(vUv.x, 1.0 - vUv.y); // top-left origin
|
||||
uv = (uv - 0.5) / uZoom + 0.5;
|
||||
float aspect = uRes.x / uRes.y;
|
||||
float t = uTime;
|
||||
|
||||
// Gentle flow: two layers of low-frequency sine warp make the fields drift
|
||||
// and bend like liquid without any visible shapes.
|
||||
vec2 w = uv;
|
||||
w += 0.050 * vec2(sin(uv.y * 3.1 + t * 0.110), sin(uv.x * 2.3 - t * 0.090));
|
||||
w += 0.022 * vec2(sin(uv.y * 5.7 - t * 0.070 + 1.3), sin(uv.x * 4.9 + t * 0.130 + 0.7));
|
||||
vec2 a = vec2(aspect, 1.0);
|
||||
|
||||
vec3 hi = uPal[0];
|
||||
vec3 mid = uPal[1];
|
||||
vec3 deep = uPal[2];
|
||||
|
||||
// Near-black base; colour lives in a few soft fields with dark gaps between.
|
||||
vec3 col = deep * 0.35 + vec3(0.003, 0.003, 0.005);
|
||||
// Fields on slow Lissajous paths. Two are hue-shifted for depth, like
|
||||
// Apple's dark gradients (never a single flat hue).
|
||||
vec2 c0 = vec2(0.76 + 0.10 * sin(t * 0.050), 0.18 + 0.08 * cos(t * 0.043));
|
||||
vec2 c1 = vec2(0.20 + 0.12 * cos(t * 0.037 + 1.0), 0.26 + 0.10 * sin(t * 0.041));
|
||||
vec2 c2 = vec2(0.52 + 0.20 * sin(t * 0.029 + 2.0), 0.62 + 0.08 * cos(t * 0.033 + 0.5));
|
||||
vec2 c3 = vec2(0.96 + 0.05 * cos(t * 0.045), 0.88 + 0.06 * sin(t * 0.052));
|
||||
vec2 c4 = vec2(0.04 + 0.06 * sin(t * 0.031 + 4.0), 0.94 + 0.05 * cos(t * 0.027));
|
||||
col += hi * 0.34 * field((w - c0) * a, 0.40);
|
||||
col += mid * 0.62 * field((w - c1) * a, 0.48);
|
||||
col += hueRot(mix(mid, hi, 0.4), 0.55) * 0.34 * field((w - c2) * a, 0.38);
|
||||
col += hueRot(mid, -0.70) * 0.40 * field((w - c3) * a, 0.36);
|
||||
col += mid * 0.30 * field((w - c4) * a, 0.34);
|
||||
|
||||
// Soft shoulder so bright palettes stay "dark mode".
|
||||
col = col / (1.0 + col * 1.2);
|
||||
|
||||
// Calmer at the bottom where the icons sit; dimmer when asked (uBright).
|
||||
col *= mix(1.0, 0.62, smoothstep(0.45, 1.0, uv.y));
|
||||
col *= mix(0.42, 1.0, uBright);
|
||||
vec2 v = uv - 0.5;
|
||||
col *= 1.0 - 0.30 * dot(v, v);
|
||||
|
||||
fragColor = vec4(col, 1.0);
|
||||
}
|
||||
"#;
|
||||
|
||||
/// Upscales the backdrop to the window with dithering (no banding).
|
||||
pub const BLIT: &str = r#"
|
||||
in vec2 vUv;
|
||||
out vec4 fragColor;
|
||||
uniform sampler2D uScene;
|
||||
uniform float uTime;
|
||||
|
||||
float hash12(vec2 p) {
|
||||
vec3 p3 = fract(vec3(p.xyx) * 0.1031);
|
||||
p3 += dot(p3, p3.yzx + 33.33);
|
||||
return fract((p3.x + p3.y) * p3.z);
|
||||
}
|
||||
|
||||
void main() {
|
||||
vec3 col = textureLod(uScene, vUv, 0.0).rgb;
|
||||
col += (hash12(gl_FragCoord.xy + fract(uTime) * 61.0) - 0.5) / 255.0;
|
||||
fragColor = vec4(col, 1.0);
|
||||
}
|
||||
"#;
|
||||
|
||||
/// 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.
|
||||
///
|
||||
/// The model follows Apple's Liquid Glass: light is *bent*, not scattered.
|
||||
/// Each panel is a slab of glass (IOR ~1.5) whose edge is a convex squircle
|
||||
/// bevel. The backdrop seen through it is displaced by a real refraction ray
|
||||
/// (Snell), with per-channel IOR for dispersion. Bigger panels are thicker:
|
||||
/// wider bevel, stronger lensing, deeper shadow. On top: Fresnel reflection,
|
||||
/// a geometry-aware specular rim, light from within when focused, and
|
||||
/// "materialize" (alpha ramps the lensing, not just the opacity).
|
||||
///
|
||||
/// The result is written as `dst * a + rgb` (blend ONE, SRC_ALPHA), so the
|
||||
/// shader never needs to read the framebuffer: shadows multiply, glass
|
||||
/// replaces, and nested glass (on another pane) lights what is already there.
|
||||
pub const GLASS: &str = r#"
|
||||
out vec4 fragColor;
|
||||
|
||||
#define MAX_GROUP 4
|
||||
|
||||
uniform sampler2D uScene;
|
||||
uniform vec2 uRes; // physical px
|
||||
uniform float uScale; // physical px per design px
|
||||
uniform float uTime;
|
||||
uniform vec2 uLight; // direction towards the key light (screen space, y down)
|
||||
uniform int uCount; // members of this run (> 1 = merged group)
|
||||
uniform vec4 uRect[MAX_GROUP]; // x, y, w, h (px, top-left origin)
|
||||
uniform vec4 uParam[MAX_GROUP]; // radius, focus, alpha, frost (mip lod; < 0 = nested on other glass)
|
||||
uniform vec4 uGlow[MAX_GROUP]; // accent rgb, unused
|
||||
uniform vec4 uTint[MAX_GROUP]; // tint rgb, tint amount
|
||||
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;
|
||||
return min(max(q.x, q.y), 0.0) + length(max(q, 0.0)) - r;
|
||||
}
|
||||
|
||||
// Analytic outward gradient of sdRoundRect.
|
||||
vec2 gradRoundRect(vec2 p, vec2 b, float r) {
|
||||
vec2 w = abs(p) - b + r;
|
||||
vec2 q = max(w, 0.0);
|
||||
vec2 g = (max(w.x, w.y) > 0.0) ? q / max(length(q), 1e-5) : ((w.x > w.y) ? vec2(1.0, 0.0) : vec2(0.0, 1.0));
|
||||
return sign(p) * g;
|
||||
}
|
||||
|
||||
float sdPanel(int i, vec2 p) {
|
||||
vec4 R = uRect[i];
|
||||
vec2 hs = R.zw * 0.5;
|
||||
float r = min(uParam[i].x, min(hs.x, hs.y));
|
||||
return sdRoundRect(p - (R.xy + hs), hs, r);
|
||||
}
|
||||
|
||||
// Polynomial smooth minimum: the "liquid bridge" between merged panels.
|
||||
float smin(float a, float b, float k) {
|
||||
float h = max(k - abs(a - b), 0.0) / k;
|
||||
return min(a, b) - h * h * k * 0.25;
|
||||
}
|
||||
|
||||
float sdGroup(vec2 p, float k) {
|
||||
float d = 1e5;
|
||||
for (int i = 0; i < MAX_GROUP; i++) {
|
||||
if (i >= uCount) break;
|
||||
if (uParam[i].z <= 0.001) continue;
|
||||
d = smin(d, sdPanel(i, p), k);
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
// uv has a top-left origin; the scene texture is stored GL-style (bottom row first).
|
||||
vec3 sceneAt(vec2 uv, float lod) {
|
||||
uv = clamp(uv, vec2(0.001), vec2(0.999));
|
||||
return textureLod(uScene, vec2(uv.x, 1.0 - uv.y), lod).rgb;
|
||||
}
|
||||
|
||||
float luma(vec3 c) { return dot(c, vec3(0.2126, 0.7152, 0.0722)); }
|
||||
|
||||
// Convex squircle bevel: height (0 at the rim, 1 on the flat top) and slope.
|
||||
// u = distance from the rim / bevel width.
|
||||
vec2 squircle(float u) {
|
||||
u = clamp(u, 0.0, 1.0);
|
||||
float a = 1.0 - u;
|
||||
float a4 = a * a * a * a;
|
||||
float h = pow(max(1.0 - a4, 1e-4), 0.25);
|
||||
float dh = a * a * a * pow(max(1.0 - a4, 1e-3), -0.75);
|
||||
return vec2(h, dh);
|
||||
}
|
||||
|
||||
// Where a vertical ray through the glass lands on the backdrop (px offset).
|
||||
vec2 refractOffset(vec3 N, float height, float ior) {
|
||||
vec3 t = refract(vec3(0.0, 0.0, -1.0), N, 1.0 / ior);
|
||||
return t.xy / max(-t.z, 0.2) * height;
|
||||
}
|
||||
|
||||
void main() {
|
||||
vec2 p = vec2(gl_FragCoord.x, uRes.y - gl_FragCoord.y); // px, top-left
|
||||
float s = uScale;
|
||||
float mergeK = 30.0 * s;
|
||||
bool merged = uCount > 1;
|
||||
|
||||
// Combined distance, and parameters blended towards the nearest member.
|
||||
float d = 1e5;
|
||||
float wsum = 0.0;
|
||||
vec4 P = vec4(0.0);
|
||||
vec3 accent = vec3(0.0);
|
||||
vec4 tint = vec4(0.0);
|
||||
vec2 center = vec2(0.0);
|
||||
vec2 halfSize = vec2(0.0);
|
||||
for (int k = 0; k < MAX_GROUP; k++) {
|
||||
if (k >= uCount) break;
|
||||
float a = uParam[k].z;
|
||||
if (a <= 0.001) continue;
|
||||
float dk = sdPanel(k, p);
|
||||
d = merged ? smin(d, dk, mergeK) : dk;
|
||||
float w = exp(-max(dk, 0.0) / (12.0 * s)) + 1e-4;
|
||||
wsum += w;
|
||||
P += uParam[k] * w;
|
||||
accent += uGlow[k].rgb * w;
|
||||
tint += uTint[k] * w;
|
||||
vec4 R = uRect[k];
|
||||
center += (R.xy + R.zw * 0.5) * w;
|
||||
halfSize += R.zw * 0.5 * w;
|
||||
}
|
||||
if (wsum <= 0.0) discard;
|
||||
P /= wsum; accent /= wsum; tint /= wsum; center /= wsum; halfSize /= wsum;
|
||||
|
||||
float focus = P.y;
|
||||
float alpha = P.z;
|
||||
float minHalf = min(halfSize.x, halfSize.y);
|
||||
bool nested = P.w < 0.0;
|
||||
// Size-dependent thickness: small controls are full domes (a drop of
|
||||
// liquid), big panes are thick slabs with a wide rounded edge.
|
||||
float bezel = min(minHalf * 0.80, 9.0 * s + minHalf * 0.10);
|
||||
bezel = clamp(bezel, 5.0 * s, 40.0 * s);
|
||||
float sizeK = clamp(minHalf / (240.0 * s), 0.0, 1.0);
|
||||
float small = 1.0 - clamp(minHalf / (90.0 * s), 0.0, 1.0);
|
||||
|
||||
// Output is dst * mul + add.
|
||||
float mul = 1.0;
|
||||
vec3 add = vec3(0.0);
|
||||
|
||||
// ---- outside: grounding shadow and a little accent light spill ----
|
||||
if (d > 0.0) {
|
||||
vec2 off = vec2(0.0, (10.0 + 18.0 * focus + 14.0 * sizeK) * s);
|
||||
float ds = merged ? sdGroup(p - off, mergeK) : sdPanel(0, p - off);
|
||||
float spread = (34.0 + 34.0 * focus + 50.0 * sizeK) * s * (nested ? 0.5 : 1.0);
|
||||
float shadow = (1.0 - smoothstep(-spread * 0.5, spread, ds)) * (0.26 + 0.22 * focus + 0.18 * sizeK);
|
||||
shadow += (1.0 - smoothstep(0.0, 6.0 * s, d)) * 0.10;
|
||||
mul = 1.0 - shadow * alpha;
|
||||
add = accent * exp(-d / (22.0 * s)) * focus * 0.16 * alpha;
|
||||
if (d > 1.0) {
|
||||
if (mul > 0.998 && dot(add, vec3(1.0)) < 0.002) discard;
|
||||
fragColor = vec4(add, mul);
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
// ---- surface geometry ----
|
||||
vec2 n2;
|
||||
if (merged) {
|
||||
vec2 e = vec2(0.75, 0.0);
|
||||
vec2 g2 = vec2(sdGroup(p + e.xy, mergeK) - sdGroup(p - e.xy, mergeK),
|
||||
sdGroup(p + e.yx, mergeK) - sdGroup(p - e.yx, mergeK));
|
||||
n2 = g2 / max(length(g2), 1e-5);
|
||||
} else {
|
||||
vec4 R = uRect[0];
|
||||
vec2 hs = R.zw * 0.5;
|
||||
n2 = gradRoundRect(p - (R.xy + hs), hs, min(uParam[0].x, min(hs.x, hs.y)));
|
||||
}
|
||||
|
||||
float inside = max(-d, 0.0);
|
||||
float u = inside / bezel;
|
||||
vec2 hp = squircle(u);
|
||||
float thick = bezel * (1.1 + 0.3 * focus); // glass height in px
|
||||
float height = thick * hp.x;
|
||||
float slope = (u < 1.0) ? hp.y * thick / bezel : 0.0;
|
||||
slope = min(slope, 6.0);
|
||||
vec3 N = normalize(vec3(n2 * slope, 1.0));
|
||||
|
||||
// Materialize: lensing and frost ramp up with alpha instead of a plain fade.
|
||||
float mat = smoothstep(0.0, 1.0, alpha);
|
||||
float lens = (1.25 + 0.35 * focus) * mat;
|
||||
vec2 mag = -(p - center) * (0.025 + 0.035 * focus) * mat;
|
||||
float lod = abs(P.w) * mix(0.35, 1.0, mat);
|
||||
|
||||
// The glass colour is affine in what is underneath: g = dst * A + B.
|
||||
float A = 0.0;
|
||||
vec3 B;
|
||||
if (nested || 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;
|
||||
B.g = sceneAt((p + refractOffset(N, height, 1.50) * lens + mag) / uRes, lod).g;
|
||||
B.b = sceneAt((p + refractOffset(N, height, 1.56) * lens + mag) / uRes, lod).b;
|
||||
} else {
|
||||
B = sceneAt((p + mag) / uRes, lod);
|
||||
}
|
||||
|
||||
// ---- body ----
|
||||
// Adaptive tone: lift glass over dark content, hold it back over bright content.
|
||||
float bgL = luma(sceneAt(center / uRes, 6.0));
|
||||
float kb = 1.02 + 0.10 * focus;
|
||||
A *= kb;
|
||||
B = B * kb + mix(0.045, -0.01, clamp(bgL * 2.0, 0.0, 1.0)) + (nested ? 0.025 : 0.0);
|
||||
A *= 1.0 - tint.a;
|
||||
B = mix(B, tint.rgb, tint.a);
|
||||
|
||||
// Light from within when focused: starts at the center, spreads to the rim.
|
||||
vec2 qn = (p - center) / max(halfSize, vec2(1.0));
|
||||
float core = exp(-dot(qn, qn) * 1.3);
|
||||
vec3 inner = mix(vec3(1.0), accent, 0.45);
|
||||
B += inner * focus * (0.06 + 0.12 * core);
|
||||
|
||||
// Focus sheen: a soft diagonal band of light glides across the glass now and then.
|
||||
float sweep = fract(uTime * 0.16 + center.x * 0.0007);
|
||||
float band = (qn.x * 0.8 + qn.y * 0.45) * 0.5 + 0.5;
|
||||
float sheen = exp(-pow((band - (sweep * 1.8 - 0.4)) * 7.0, 2.0));
|
||||
B += vec3(1.0) * sheen * focus * 0.10 * mat;
|
||||
|
||||
// Soft vertical sheen, as if lit from above.
|
||||
float vy = clamp((p.y - (center.y - halfSize.y)) / (2.0 * halfSize.y), 0.0, 1.0);
|
||||
B += vec3(0.06 + 0.05 * focus) * pow(1.0 - vy, 2.5);
|
||||
|
||||
// ---- light ----
|
||||
float wob = focus * 0.35 * sin(uTime * 0.9);
|
||||
vec2 L2 = mat2(cos(wob), sin(wob), -sin(wob), cos(wob)) * uLight;
|
||||
vec3 L = normalize(vec3(L2, 0.55));
|
||||
vec3 V = vec3(0.0, 0.0, 1.0);
|
||||
|
||||
// Fresnel: steep bevel reflects the (blurred, brightened) surroundings.
|
||||
float cosT = clamp(N.z, 0.0, 1.0);
|
||||
float F = 0.04 + 0.96 * pow(1.0 - cosT, 5.0);
|
||||
float Fm = 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);
|
||||
|
||||
// Specular on the bevel: key light, plus a weaker bounce on the far side.
|
||||
vec3 H = normalize(L + V);
|
||||
vec3 H2 = normalize(vec3(-L2, 0.55) + V);
|
||||
float spec = pow(max(dot(N, H), 0.0), 26.0);
|
||||
float spec2 = pow(max(dot(N, H2), 0.0), 26.0);
|
||||
float bevelMask = 1.0 - smoothstep(0.0, 1.0, u);
|
||||
B += vec3(1.0) * (spec * 0.60 + spec2 * 0.38) * bevelMask * (0.8 + 0.6 * focus) * mat;
|
||||
|
||||
// Glossy highlight on small domes, like a water drop.
|
||||
vec2 hl = qn - uLight * 0.42;
|
||||
float gloss = exp(-dot(hl * vec2(1.4, 2.2), hl * vec2(1.4, 2.2)) * 3.0);
|
||||
B += vec3(1.0) * gloss * small * 0.14 * mat;
|
||||
|
||||
// Crisp rim: a bright hairline all around, strongest towards the light
|
||||
// and again on the far side where light exits the glass.
|
||||
float facing = max(dot(n2, uLight), 0.0);
|
||||
float away = max(dot(n2, -uLight), 0.0);
|
||||
float rimLine = exp(-inside / (1.0 * s));
|
||||
float rimGlow = exp(-inside / (6.0 * s));
|
||||
B += rimLine * (0.22 + 0.80 * pow(facing, 2.0) + 0.55 * pow(away, 2.0) + 0.22 * focus) * mat;
|
||||
B += rimGlow * (0.06 + 0.10 * facing + 0.06 * away + 0.08 * focus) * mat;
|
||||
B += accent * rimGlow * focus * 0.10 * mat;
|
||||
|
||||
// Subtle inner shade on the side away from the light gives the slab depth.
|
||||
float shade = 1.0 - 0.08 * bevelMask * away * mat;
|
||||
A *= shade;
|
||||
B *= shade;
|
||||
|
||||
float cov = clamp(0.5 - d, 0.0, 1.0) * clamp(alpha * 2.0, 0.0, 1.0);
|
||||
float keep = 1.0 - cov + cov * A;
|
||||
fragColor = vec4(add * keep + cov * B, mul * keep);
|
||||
}
|
||||
"#;
|
||||
39
sf-ui/src/text.rs
Normal file
39
sf-ui/src/text.rs
Normal file
@@ -0,0 +1,39 @@
|
||||
//! String helpers Slint lacks (wired into the `SfText` global by `glue!`).
|
||||
|
||||
/// Without its last character.
|
||||
pub fn drop_last(s: &str) -> String {
|
||||
let mut s = s.to_string();
|
||||
s.pop();
|
||||
s
|
||||
}
|
||||
|
||||
/// `n` bullets (a masked password).
|
||||
pub fn dots(n: usize) -> String {
|
||||
"•".repeat(n)
|
||||
}
|
||||
|
||||
/// The characters of a key event's text that can be typed: no controls, no
|
||||
/// Slint special keys (arrows etc. arrive as private-use code points).
|
||||
pub fn typable(s: &str) -> String {
|
||||
s.chars().filter(|c| !c.is_control() && !('\u{E000}'..='\u{F8FF}').contains(c)).collect()
|
||||
}
|
||||
|
||||
/// At most `n` characters.
|
||||
pub fn truncate(s: &str, n: usize) -> String {
|
||||
s.chars().take(n).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn edits() {
|
||||
assert_eq!(drop_last("abő"), "ab");
|
||||
assert_eq!(drop_last(""), "");
|
||||
assert_eq!(dots(3), "•••");
|
||||
assert_eq!(truncate("árvíz", 3), "árv");
|
||||
assert_eq!(typable("a\u{F700}\n"), "a");
|
||||
assert_eq!(typable("Ő"), "Ő");
|
||||
}
|
||||
}
|
||||
483
sf-ui/src/video.rs
Normal file
483
sf-ui/src/video.rs
Normal file
@@ -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);
|
||||
}
|
||||
}
|
||||
BIN
sf-ui/ui/fonts/Onest-Bold.ttf
Normal file
BIN
sf-ui/ui/fonts/Onest-Bold.ttf
Normal file
Binary file not shown.
BIN
sf-ui/ui/fonts/Onest-Medium.ttf
Normal file
BIN
sf-ui/ui/fonts/Onest-Medium.ttf
Normal file
Binary file not shown.
93
sf-ui/ui/fonts/Onest-OFL.txt
Normal file
93
sf-ui/ui/fonts/Onest-OFL.txt
Normal file
@@ -0,0 +1,93 @@
|
||||
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:
|
||||
https://scripts.sil.org/OFL
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
-----------------------------------------------------------
|
||||
|
||||
PREAMBLE
|
||||
The goals of the Open Font License (OFL) are to stimulate worldwide
|
||||
development of collaborative font projects, to support the font creation
|
||||
efforts of academic and linguistic communities, and to provide a free and
|
||||
open framework in which fonts may be shared and improved in partnership
|
||||
with others.
|
||||
|
||||
The OFL allows the licensed fonts to be used, studied, modified and
|
||||
redistributed freely as long as they are not sold by themselves. The
|
||||
fonts, including any derivative works, can be bundled, embedded,
|
||||
redistributed and/or sold with any software provided that any reserved
|
||||
names are not used by derivative works. The fonts and derivatives,
|
||||
however, cannot be released under any other type of license. The
|
||||
requirement for fonts to remain under this license does not apply
|
||||
to any document created using the fonts or their derivatives.
|
||||
|
||||
DEFINITIONS
|
||||
"Font Software" refers to the set of files released by the Copyright
|
||||
Holder(s) under this license and clearly marked as such. This may
|
||||
include source files, build scripts and documentation.
|
||||
|
||||
"Reserved Font Name" refers to any names specified as such after the
|
||||
copyright statement(s).
|
||||
|
||||
"Original Version" refers to the collection of Font Software components as
|
||||
distributed by the Copyright Holder(s).
|
||||
|
||||
"Modified Version" refers to any derivative made by adding to, deleting,
|
||||
or substituting -- in part or in whole -- any of the components of the
|
||||
Original Version, by changing formats or by porting the Font Software to a
|
||||
new environment.
|
||||
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
Software, subject to the following conditions:
|
||||
|
||||
1) Neither the Font Software nor any of its individual components,
|
||||
in Original or Modified Versions, may be sold by itself.
|
||||
|
||||
2) Original or Modified Versions of the Font Software may be bundled,
|
||||
redistributed and/or sold with any software, provided that each copy
|
||||
contains the above copyright notice and this license. These can be
|
||||
included either as stand-alone text files, human-readable headers or
|
||||
in the appropriate machine-readable metadata fields within text or
|
||||
binary files as long as those fields can be easily viewed by the user.
|
||||
|
||||
3) No Modified Version of the Font Software may use the Reserved Font
|
||||
Name(s) unless explicit written permission is granted by the corresponding
|
||||
Copyright Holder. This restriction only applies to the primary font name as
|
||||
presented to the users.
|
||||
|
||||
4) The name(s) of the Copyright Holder(s) or the Author(s) of the Font
|
||||
Software shall not be used to promote, endorse or advertise any
|
||||
Modified Version, except to acknowledge the contribution(s) of the
|
||||
Copyright Holder(s) and the Author(s) or with their explicit written
|
||||
permission.
|
||||
|
||||
5) The Font Software, modified or unmodified, in part or in whole,
|
||||
must be distributed entirely under this license, and must not be
|
||||
distributed under any other license. The requirement for fonts to
|
||||
remain under this license does not apply to any document created
|
||||
using the Font Software.
|
||||
|
||||
TERMINATION
|
||||
This license becomes null and void if any of the above conditions are
|
||||
not met.
|
||||
|
||||
DISCLAIMER
|
||||
THE FONT SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO ANY WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT
|
||||
OF COPYRIGHT, PATENT, TRADEMARK, OR OTHER RIGHT. IN NO EVENT SHALL THE
|
||||
COPYRIGHT HOLDER BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
||||
INCLUDING ANY GENERAL, SPECIAL, INDIRECT, INCIDENTAL, OR CONSEQUENTIAL
|
||||
DAMAGES, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
FROM, OUT OF THE USE OR INABILITY TO USE THE FONT SOFTWARE OR FROM
|
||||
OTHER DEALINGS IN THE FONT SOFTWARE.
|
||||
BIN
sf-ui/ui/fonts/Onest-Regular.ttf
Normal file
BIN
sf-ui/ui/fonts/Onest-Regular.ttf
Normal file
Binary file not shown.
BIN
sf-ui/ui/fonts/Onest-SemiBold.ttf
Normal file
BIN
sf-ui/ui/fonts/Onest-SemiBold.ttf
Normal file
Binary file not shown.
960
sf-ui/ui/sf-ui.slint
Normal file
960
sf-ui/ui/sf-ui.slint
Normal file
@@ -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),
|
||||
];
|
||||
}
|
||||
40
templates/rust-app/.gitea/workflows/release.yml
Normal file
40
templates/rust-app/.gitea/workflows/release.yml
Normal file
@@ -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
|
||||
36
templates/rust-app/.github/workflows/release.yml
vendored
Normal file
36
templates/rust-app/.github/workflows/release.yml
vendored
Normal file
@@ -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"
|
||||
4
templates/rust-app/.gitignore
vendored
Normal file
4
templates/rust-app/.gitignore
vendored
Normal file
@@ -0,0 +1,4 @@
|
||||
/target
|
||||
/pkg
|
||||
/dist
|
||||
key.pem
|
||||
30
templates/rust-app/.gitlab-ci.yml
Normal file
30
templates/rust-app/.gitlab-ci.yml
Normal file
@@ -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
|
||||
5768
templates/rust-app/Cargo.lock
generated
Normal file
5768
templates/rust-app/Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
18
templates/rust-app/Cargo.toml
Normal file
18
templates/rust-app/Cargo.toml
Normal file
@@ -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]
|
||||
29
templates/rust-app/app.toml
Normal file
29
templates/rust-app/app.toml
Normal file
@@ -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"]
|
||||
18
templates/rust-app/package.sh
Normal file
18
templates/rust-app/package.sh
Normal file
@@ -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
|
||||
60
templates/rust-app/src/main.rs
Normal file
60
templates/rust-app/src/main.rs
Normal file
@@ -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()
|
||||
}
|
||||
Reference in New Issue
Block a user