Add Store support and unsigned app releases

This commit is contained in:
Tamas Csikel
2026-10-25 14:11:49 +01:00
parent 4975784491
commit d7e9fe4568
157 changed files with 22985 additions and 944 deletions

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

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

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

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

View File

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

View File

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

View File

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

View File

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

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

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

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

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

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

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

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

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

View File

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

View File

@@ -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(), &param[..n * 4]);
gl.uniform_4_f32_slice(l.glow.as_ref(), &glow_c[..n * 4]);
gl.uniform_4_f32_slice(l.tint.as_ref(), &tint[..n * 4]);
gl.draw_arrays(glow::TRIANGLE_STRIP, 0, 4);
}
self.restore(saved);
}
}
/// Reads the current window framebuffer as top-down RGBA8 (dev snapshots).
///
/// # Safety
/// Must be called with the context current, after Slint has rendered.
pub unsafe fn read_pixels(&self, w: u32, h: u32) -> Vec<u8> {
let mut buf = vec![0u8; (w * h * 4) as usize];
unsafe {
self.gl.pixel_store_i32(glow::PACK_ALIGNMENT, 1);
self.gl.read_pixels(
0,
0,
w as i32,
h as i32,
glow::RGBA,
glow::UNSIGNED_BYTE,
glow::PixelPackData::Slice(Some(&mut buf)),
);
}
let row = (w * 4) as usize;
let mut flipped = Vec::with_capacity(buf.len());
for y in (0..h as usize).rev() {
flipped.extend_from_slice(&buf[y * row..(y + 1) * row]);
}
flipped
}
/// # Safety
/// Must be called with the context current.
pub unsafe fn destroy(&mut self) {
unsafe {
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]);
}
}

View 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
crates/sf-ui/src/text.rs Normal file
View File

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

483
crates/sf-ui/src/video.rs Normal file
View 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);
}
}

Binary file not shown.

Binary file not shown.

View 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.

Binary file not shown.

Binary file not shown.

960
crates/sf-ui/ui/sf-ui.slint Normal file
View 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),
];
}