SmartFox: launcher, Siri Remote driver, Debian image and installer

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Tamas Csikel
2026-10-24 09:06:06 +02:00
commit 79b03cac95
91 changed files with 15874 additions and 0 deletions

13
crates/sf-ipc/Cargo.toml Normal file
View File

@@ -0,0 +1,13 @@
[package]
name = "sf-ipc"
description = "Shared types for SmartFox: app manifests, settings and IPC messages"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
serde.workspace = true
serde_json.workspace = true
toml.workspace = true
anyhow.workspace = true
log.workspace = true

9
crates/sf-ipc/src/lib.rs Normal file
View File

@@ -0,0 +1,9 @@
//! Shared types for SmartFox components (launcher, core daemon, remote daemon).
pub mod manifest;
pub mod message;
pub mod settings;
pub use manifest::{AppKind, AppManifest, load_apps};
pub use message::{CoreEvent, LauncherRequest};
pub use settings::Settings;

View File

@@ -0,0 +1,137 @@
//! App manifests: one `app.toml` per folder under the apps directory.
use std::path::{Path, PathBuf};
use anyhow::{Context, Result};
use serde::{Deserialize, Serialize};
use crate::settings::Settings;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum AppKind {
/// Runs in the shared Chromium web runtime.
Web,
/// Any executable: AppImage, Rust binary, script.
Exec,
/// Built into the launcher (e.g. settings screen).
Builtin,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AppManifest {
pub id: String,
pub name: String,
pub kind: AppKind,
/// Short label above the title in the hero ("Saját app", "Castolás"...).
#[serde(default)]
pub category: String,
#[serde(default)]
pub description: String,
/// Web apps: start URL. May contain `${settings.<key>}` placeholders.
#[serde(default)]
pub url: Option<String>,
/// Exec apps: command line.
#[serde(default)]
pub exec: Option<Vec<String>>,
/// Built-in icon name used by the launcher.
#[serde(default)]
pub icon: String,
/// Accent color (hex), used for focus glow and buttons.
#[serde(default = "default_accent")]
pub accent: String,
/// Three colors for the animated hero backdrop: highlight, mid, deep.
#[serde(default)]
pub palette: Vec<String>,
/// Sort order on the home row.
#[serde(default)]
pub order: i32,
#[serde(default)]
pub web: WebOptions,
#[serde(default)]
pub dial: Option<DialOptions>,
/// Folder the manifest was loaded from (not serialized).
#[serde(skip)]
pub dir: PathBuf,
}
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct WebOptions {
/// Full user agent override.
#[serde(default)]
pub user_agent: Option<String>,
/// Appended to the default user agent.
#[serde(default)]
pub user_agent_suffix: Option<String>,
/// Unpacked extensions to load (paths relative to the app folder).
#[serde(default)]
pub extensions: Vec<String>,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct DialOptions {
/// DIAL application name, e.g. "YouTube".
pub name: String,
}
fn default_accent() -> String {
"#ffffff".into()
}
impl AppManifest {
/// Start URL with `${settings.key}` placeholders filled in.
pub fn resolved_url(&self, settings: &Settings) -> Option<String> {
self.url.as_ref().map(|u| settings.expand(u))
}
}
/// Loads every `*/app.toml` under `dir`, sorted by `order` then name.
pub fn load_apps(dir: &Path) -> Result<Vec<AppManifest>> {
let mut apps = Vec::new();
let entries = std::fs::read_dir(dir).with_context(|| format!("reading {}", dir.display()))?;
for entry in entries.flatten() {
let path = entry.path().join("app.toml");
if !path.is_file() {
continue;
}
match load_one(&path) {
Ok(app) => apps.push(app),
Err(e) => log::warn!("skipping {}: {e:#}", path.display()),
}
}
apps.sort_by(|a, b| a.order.cmp(&b.order).then_with(|| a.name.cmp(&b.name)));
Ok(apps)
}
fn load_one(path: &Path) -> Result<AppManifest> {
let text = std::fs::read_to_string(path)?;
let mut app: AppManifest = toml::from_str(&text)?;
app.dir = path.parent().unwrap_or(Path::new(".")).to_path_buf();
Ok(app)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_web_manifest() {
let app: AppManifest = toml::from_str(
r##"
id = "netflex"
name = "Netflex"
kind = "web"
url = "${settings.netflex_server}/"
accent = "#E50914"
palette = ["#ff3b3b", "#7a0a10", "#0c0203"]
[web]
user_agent_suffix = "SMART-TV SmartFox/0.1"
"##,
)
.unwrap();
assert_eq!(app.kind, AppKind::Web);
let mut s = Settings::default();
s.values.insert("netflex_server".into(), "http://10.0.0.5:7880".into());
assert_eq!(app.resolved_url(&s).unwrap(), "http://10.0.0.5:7880/");
}
}

View File

@@ -0,0 +1,23 @@
//! Messages between the launcher and the core daemon (newline-delimited JSON
//! over a unix socket). The core daemon itself comes in phase 3.
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum LauncherRequest {
Launch { app_id: String },
/// Bring the launcher back to the front (freezes the foreground app).
GoHome,
SetSetting { key: String, value: String },
}
#[derive(Debug, Clone, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "snake_case")]
pub enum CoreEvent {
AppStarted { app_id: String },
AppStopped { app_id: String },
/// Something connected over DIAL/AirPlay/Miracast.
CastConnected { app_id: String, device: String },
Toast { text: String },
}

View File

@@ -0,0 +1,57 @@
//! Flat key/value settings stored in `settings.toml`.
use std::collections::BTreeMap;
use std::path::Path;
use anyhow::Result;
use serde::{Deserialize, Serialize};
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
pub struct Settings {
#[serde(flatten)]
pub values: BTreeMap<String, String>,
}
impl Settings {
/// Missing file means default settings.
pub fn load(path: &Path) -> Result<Self> {
if !path.exists() {
return Ok(Self::default());
}
Ok(toml::from_str(&std::fs::read_to_string(path)?)?)
}
pub fn save(&self, path: &Path) -> Result<()> {
if let Some(dir) = path.parent() {
std::fs::create_dir_all(dir)?;
}
std::fs::write(path, toml::to_string_pretty(self)?)?;
Ok(())
}
pub fn get(&self, key: &str) -> Option<&str> {
self.values.get(key).map(String::as_str)
}
/// Replaces `${settings.key}` with the value (or an empty string).
pub fn expand(&self, input: &str) -> String {
let mut out = String::with_capacity(input.len());
let mut rest = input;
while let Some(start) = rest.find("${settings.") {
out.push_str(&rest[..start]);
let after = &rest[start + "${settings.".len()..];
match after.find('}') {
Some(end) => {
out.push_str(self.get(&after[..end]).unwrap_or(""));
rest = &after[end + 1..];
}
None => {
out.push_str(&rest[start..]);
rest = "";
}
}
}
out.push_str(rest);
out
}
}

View File

@@ -0,0 +1,24 @@
[package]
name = "sf-launcher"
description = "SmartFox TV launcher: Slint UI on top of a Liquid Glass OpenGL layer"
version.workspace = true
edition.workspace = true
# Slint is used under GPL-3.0 (or its royalty-free license on desktop).
license = "GPL-3.0-only"
[dependencies]
sf-ipc.workspace = true
anyhow.workspace = true
log.workspace = true
env_logger.workspace = true
serde_json.workspace = true
slint = { version = "1.18", default-features = false, features = ["std", "backend-default", "renderer-femtovg", "compat-1-2"] }
glow = "0.16"
png = "0.18"
chrono = { version = "0.4", default-features = false, features = ["clock", "std"] }
[build-dependencies]
slint-build = "1.18"
[target.'cfg(windows)'.dependencies]
windows-sys = { version = "0.61", features = ["Win32_Foundation", "Win32_UI_WindowsAndMessaging"] }

View File

@@ -0,0 +1,3 @@
fn main() {
slint_build::compile("ui/app.slint").expect("compiling ui/app.slint");
}

View File

@@ -0,0 +1,116 @@
//! Dev helper: scripted key presses and a PNG snapshot of the window, so UI
//! changes can be checked without a person at the screen.
//!
//! - `SMARTFOX_KEYS="up right enter"`: keys sent one by one (left, right, up,
//! down, enter, esc, `hold` = enter held for 0.8 s, or `wait`), starting
//! after 1.2 s, every 0.7 s (a hold takes two slots).
//! - `SMARTFOX_SNAPSHOT=out.png`: saves the frame and quits, 1.5 s after the
//! last key (or at `SMARTFOX_SNAPSHOT_MS`).
//! - `SMARTFOX_SIZE=1920x1080`: physical window size.
use std::cell::Cell;
use std::path::PathBuf;
use std::rc::Rc;
use std::time::Duration;
use slint::ComponentHandle;
use slint::platform::{Key, WindowEvent};
use crate::App;
use crate::glass::GlassRenderer;
pub struct Snapshot {
path: Option<PathBuf>,
due: Rc<Cell<bool>>,
}
pub fn setup(ui: &App) -> Snapshot {
if let Some((w, h)) = std::env::var("SMARTFOX_SIZE").ok().and_then(|s| {
let (w, h) = s.split_once('x')?;
Some((w.parse().ok()?, h.parse().ok()?))
}) {
ui.window().set_size(slint::PhysicalSize::new(w, h));
}
let keys: Vec<String> = std::env::var("SMARTFOX_KEYS")
.map(|s| s.split_whitespace().map(str::to_lowercase).collect())
.unwrap_or_default();
let mut at = 1200u64;
for k in &keys {
let hold = k == "hold";
let key: Option<Key> = match k.as_str() {
"hold" => Some(Key::Return),
"left" => Some(Key::LeftArrow),
"right" => Some(Key::RightArrow),
"up" => Some(Key::UpArrow),
"down" => Some(Key::DownArrow),
"enter" => Some(Key::Return),
"esc" => Some(Key::Escape),
_ => None,
};
let start = at;
at += if hold { 1400 } else { 700 };
let Some(key) = key else { continue };
let text: slint::SharedString = key.into();
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 });
}
});
}
}
let path = std::env::var_os("SMARTFOX_SNAPSHOT").map(PathBuf::from);
let due = Rc::new(Cell::new(false));
if path.is_some() {
let at = std::env::var("SMARTFOX_SNAPSHOT_MS")
.ok()
.and_then(|s| s.parse().ok())
.unwrap_or(at + 1500);
let due = due.clone();
slint::Timer::single_shot(Duration::from_millis(at), move || due.set(true));
}
Snapshot { path, due }
}
impl Snapshot {
pub fn capture_if_due(&self, ui: &App, r: &GlassRenderer) {
if !self.due.get() {
return;
}
self.due.set(false);
let Some(path) = &self.path else { return };
let size = ui.window().size();
// SAFETY: called from AfterRendering with the GL context current.
let mut pixels = unsafe { r.read_pixels(size.width, size.height) };
// Opaque output: the framebuffer alpha is meaningless here.
pixels.iter_mut().skip(3).step_by(4).for_each(|a| *a = 255);
match write_png(path, size.width, size.height, &pixels) {
Ok(()) => log::info!("snapshot saved to {}", path.display()),
Err(e) => log::error!("snapshot: {e:#}"),
}
let _ = slint::quit_event_loop();
}
}
fn write_png(path: &PathBuf, 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);
let mut writer = enc.write_header()?;
writer.write_image_data(rgba)?;
Ok(())
}

View File

@@ -0,0 +1,49 @@
//! "Liquid Glass" layer: an OpenGL pass under the Slint UI that draws the
//! animated backdrop and the frosted, refracting glass panels.
mod renderer;
mod shaders;
pub use renderer::GlassRenderer;
/// Panels drawn per frame at most (each one is its own small draw call).
pub const MAX_RECTS: usize = 48;
/// Members of one merged (liquid) group at most.
pub const MAX_GROUP: usize = 4;
/// One glass panel in physical pixels (top-left origin).
#[derive(Debug, Clone, Copy)]
pub struct Panel {
pub x: f32,
pub y: f32,
pub w: f32,
pub h: f32,
pub radius: f32,
/// 0..1, brightens the rim and adds the accent glow.
pub focus: f32,
pub alpha: f32,
/// Mip level used for the frost (higher = blurrier). Negative = nested glass.
pub blur: f32,
pub glow: [f32; 3],
/// Consecutive panels with the same group (> 0) melt into one shape.
pub group: f32,
/// rgb + amount.
pub tint: [f32; 4],
}
/// Everything the renderer needs for one frame.
#[derive(Debug, Clone)]
pub struct Frame {
pub width: u32,
pub height: u32,
pub scale: f32,
pub time: f32,
/// Backdrop palette (highlight, mid, deep), already crossfaded.
pub palette: [f32; 9],
/// 1 = top shelf visible (bright backdrop), 0 = scrolled down into the grid.
pub shelf: f32,
pub light: [f32; 2],
/// Backdrop zoom (1 = none), used for the launch fly-in.
pub zoom: f32,
pub rects: Vec<Panel>,
}

View File

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

View File

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

View File

@@ -0,0 +1,106 @@
#![cfg_attr(not(unix), allow(dead_code))]
//! Tiny command socket so other SmartFox components (the remote daemon) can
//! reach the launcher even while an app has focus.
//! Protocol: one command per line:
//! `home` bring the launcher to the front
//! `remote <state>` Siri Remote status (no-adapter|searching|pairing|paired|connected)
//! `power` the remote's power button: into or out of standby
//! `wake` leave standby (any button, or the remote reconnected)
//! Every command is answered with the standby state (see `power::reply`).
use crate::power;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Command {
Home,
Remote(String),
Power,
Wake,
/// A standby change already made on the socket thread; effects pending.
Standby(power::Change),
}
pub fn parse(line: &str) -> Option<Command> {
let line = line.trim();
match line.split_once(' ') {
_ if line == "home" => Some(Command::Home),
_ if line == "power" => Some(Command::Power),
_ if line == "wake" => Some(Command::Wake),
Some(("remote", state)) => Some(Command::Remote(state.trim().to_string())),
_ => None,
}
}
/// Standby changes happen right here, so the reply already carries the new
/// state. In standby, `home` (F12 on a keyboard) wakes instead.
fn resolve(cmd: Command) -> Command {
match cmd {
Command::Power => Command::Standby(power::press()),
Command::Wake => Command::Standby(power::wake()),
Command::Home if power::state() != power::State::Awake => Command::Standby(power::wake()),
other => other,
}
}
#[cfg(unix)]
pub fn socket_path() -> std::path::PathBuf {
if let Ok(p) = std::env::var("SMARTFOX_SOCKET") {
return p.into();
}
let dir = std::env::var("XDG_RUNTIME_DIR").unwrap_or_else(|_| "/tmp".into());
std::path::Path::new(&dir).join("smartfox.sock")
}
/// Calls `on_command` on the Slint event loop for every command received.
#[cfg(unix)]
pub fn listen(on_command: impl Fn(Command) + Send + Sync + Clone + 'static) {
use std::io::{BufRead, BufReader, Write};
use std::os::unix::net::UnixListener;
let path = socket_path();
let _ = std::fs::remove_file(&path);
let listener = match UnixListener::bind(&path) {
Ok(l) => l,
Err(e) => {
log::warn!("command socket {}: {e}", path.display());
return;
}
};
log::info!("command socket {}", path.display());
std::thread::spawn(move || {
for stream in listener.incoming().flatten() {
let mut reply_to = stream.try_clone().ok();
for line in BufReader::new(stream).lines().map_while(Result::ok) {
match parse(&line) {
Some(cmd) => {
let cmd = resolve(cmd);
let f = on_command.clone();
let _ = slint::invoke_from_event_loop(move || f(cmd));
}
None => log::warn!("unknown command {line:?}"),
}
// Older senders don't read the reply; that's fine.
if let Some(w) = reply_to.as_mut() {
let _ = writeln!(w, "{}", power::reply());
}
}
}
});
}
#[cfg(not(unix))]
pub fn listen(_on_command: impl Fn(Command) + Send + Sync + Clone + 'static) {}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_commands() {
assert_eq!(parse("home\n"), Some(Command::Home));
assert_eq!(parse("remote searching"), Some(Command::Remote("searching".into())));
assert_eq!(parse("power"), Some(Command::Power));
assert_eq!(parse("wake\n"), Some(Command::Wake));
assert_eq!(parse("bogus"), None);
}
}

View File

@@ -0,0 +1,217 @@
//! On-screen keyboard (tvOS style, one horizontal row of keys).
//!
//! ui/keyboard.slint draws it and moves the focus; this module owns the text,
//! checks its length and hands it to whoever opened the keyboard.
use std::cell::RefCell;
use slint::ComponentHandle;
use crate::App;
use crate::glass::Panel;
pub struct Request {
pub title: String,
pub subtitle: String,
pub placeholder: String,
/// Shows dots instead of the text (with a "Megjelenítés" chip).
pub secret: bool,
pub submit_label: String,
/// Characters needed before submitting (0 = anything, even empty).
pub min_len: usize,
pub max_len: usize,
/// Shown in red under the field until the text is edited (e.g. "wrong password").
pub error: Option<String>,
pub on_submit: Box<dyn FnOnce(String)>,
}
struct Open {
req: Request,
text: String,
error: Option<String>,
}
thread_local! {
static KB: RefCell<Option<Open>> = const { RefCell::new(None) };
}
/// A character that can be typed: no controls, no Slint special keys
/// (arrows etc. arrive as private-use code points).
fn typable(c: char) -> bool {
!c.is_control() && !('\u{E000}'..='\u{F8FF}').contains(&c)
}
pub fn install(ui: &App) {
let w = ui.as_weak();
ui.on_kb_type(move |s| {
edit(&w, |t, max| {
for c in s.chars().filter(|c| typable(*c)) {
if t.chars().count() < max {
t.push(c);
}
}
})
});
let w = ui.as_weak();
ui.on_kb_delete(move || {
edit(&w, |t, _| {
t.pop();
})
});
let w = ui.as_weak();
ui.on_kb_clear(move || edit(&w, |t, _| t.clear()));
let w = ui.as_weak();
ui.on_kb_submit(move || submit(&w));
// Every way out (Back, submit, settings closed) lands here: forget the text.
let w = ui.as_weak();
ui.on_kb_closed(move || {
KB.with(|k| k.borrow_mut().take());
if let Some(ui) = w.upgrade() {
ui.set_kb_text("".into());
ui.set_kb_masked("".into());
}
});
}
pub fn open(ui: &App, req: Request) {
ui.set_kb_title(req.title.clone().into());
ui.set_kb_subtitle(req.subtitle.clone().into());
ui.set_kb_placeholder(req.placeholder.clone().into());
ui.set_kb_secret(req.secret);
ui.set_kb_submit_label(req.submit_label.clone().into());
ui.set_kb_reveal(false);
ui.set_kb_mode(0);
ui.set_kb_index(1);
ui.set_kb_area(0);
ui.set_kb_chip(0);
let error = req.error.clone();
KB.with(|k| *k.borrow_mut() = Some(Open { req, text: String::new(), error }));
update(ui);
ui.set_kb_open(true);
}
fn edit(w: &slint::Weak<App>, f: impl FnOnce(&mut String, usize)) {
let Some(ui) = w.upgrade() else { return };
let changed = KB.with(|k| {
let mut k = k.borrow_mut();
let Some(open) = k.as_mut() else { return false };
let before = open.text.clone();
f(&mut open.text, open.req.max_len.max(1));
if open.text != before {
open.error = None;
true
} else {
false
}
});
if changed {
update(&ui);
}
}
fn update(ui: &App) {
KB.with(|k| {
let k = k.borrow();
let Some(open) = k.as_ref() else { return };
let len = open.text.chars().count();
let ok = len >= open.req.min_len;
let (hint, error) = match &open.error {
Some(e) => (e.clone(), true),
None if !ok && len == 0 => (format!("Legalább {} karakter", open.req.min_len), false),
None if !ok => (format!("Még {} karakter kell", open.req.min_len - len), false),
None if len >= open.req.max_len => (format!("Legfeljebb {} karakter", open.req.max_len), false),
None if open.req.secret => (format!("{len} karakter"), false),
None => (String::new(), false),
};
ui.set_kb_text(open.text.clone().into());
ui.set_kb_masked("•".repeat(len).into());
ui.set_kb_hint(hint.into());
ui.set_kb_hint_error(error);
ui.set_kb_can_submit(ok);
});
}
fn submit(w: &slint::Weak<App>) {
let Some(ui) = w.upgrade() else { return };
let taken = KB.with(|k| {
let mut k = k.borrow_mut();
let ok = k.as_ref().is_some_and(|o| o.text.chars().count() >= o.req.min_len);
if ok { k.take() } else { None }
});
let Some(open) = taken else { return };
ui.set_kb_open(false);
(open.req.on_submit)(open.text);
}
/// Glass for the keyboard, drawn on the settings pane. Mirrors the kb-*
/// geometry in ui/app.slint and the layout in ui/keyboard.slint.
pub fn glass(ui: &App, scale: f32) -> Vec<Panel> {
let t = ui.get_kb_t() * ui.get_set_t();
if t <= 0.001 {
return Vec::new();
}
let u = ui.get_u();
let px = |v: f32| v * scale;
let panel = |x: f32, y: f32, w: f32, h: f32, r: f32, focus: f32, alpha: f32, glow: [f32; 3], tint: [f32; 4]| Panel {
x: px(x),
y: px(y),
w: px(w),
h: px(h),
radius: px(r),
focus,
alpha,
blur: -1.0,
glow,
group: 0.0,
tint,
};
let white = [1.0, 1.0, 1.0];
let orange = [1.0, 0.48, 0.21];
let mut out = Vec::with_capacity(9);
// Text field.
let (fx, fy, fw, fh) = (ui.get_kb_field_x(), ui.get_kb_field_y(), ui.get_kb_field_w(), ui.get_kb_field_h());
out.push(panel(fx, fy, fw, fh, 30.0 * u, 0.25, t, orange, [1.0, 1.0, 1.0, 0.07]));
// Key track and the focus lens that glides along it.
let (rx, ry, rh, kw) = (ui.get_kb_row_x(), ui.get_kb_row_y(), ui.get_kb_row_h(), ui.get_kb_key_w());
let n = ui.get_kb_n() as f32;
let track_h = rh - 28.0 * u;
out.push(panel(rx - 26.0 * u, ry + 14.0 * u, n * kw + 52.0 * u, track_h, track_h / 2.0, 0.0, t, white, [1.0, 1.0, 1.0, 0.035]));
let active = ui.get_kb_keys_active();
let (lw, lh) = (86.0 * u, 112.0 * u);
let cx = rx + (ui.get_kb_pos() + 0.5) * kw;
out.push(panel(cx - lw / 2.0, ry + (rh - lh) / 2.0, lw, lh, 30.0 * u, active, t * active, white, [1.0, 1.0, 1.0, 0.88 * active]));
// Chips: modes, show/clear, submit.
let (chx, chy, chw, chh, step) =
(ui.get_kb_chip_x(), ui.get_kb_chip_y(), ui.get_kb_chip_w(), ui.get_kb_chip_h(), ui.get_kb_chip_step());
let (cpos, cactive, mode, can) = (ui.get_kb_cpos(), ui.get_kb_chips_active(), ui.get_kb_mode(), ui.get_kb_can_submit());
for i in 0..6 {
let f = (1.0 - (cpos - i as f32).abs()).max(0.0) * cactive;
let s = 1.0 + 0.05 * f;
let (w, h) = (chw * s, chh * s);
let x = chx + i as f32 * step - (w - chw) / 2.0;
let y = chy - (h - chh) / 2.0;
let (glow, tint) = if i == 5 {
(orange, [1.0, 0.48, 0.21, if can { 0.34 + 0.56 * f } else { 0.08 + 0.2 * f }])
} else {
let sel = if i < 4 && i == mode { 0.16 } else { 0.0 };
(white, [1.0, 1.0, 1.0, 0.04 + sel + 0.80 * f])
};
out.push(panel(x, y, w, h, h / 2.0, f, t, glow, tint));
}
out
}
#[cfg(test)]
mod tests {
use super::typable;
#[test]
fn filters_special_keys() {
assert!(typable('a') && typable('Ő') && typable(' ') && typable('"'));
// Slint's arrow keys, Return, Escape, Backspace.
assert!(!typable('\u{F700}') && !typable('\n') && !typable('\u{1b}') && !typable('\u{8}'));
}
}

View File

@@ -0,0 +1,560 @@
//! SmartFox launcher.
//!
//! Slint draws text and icons; the `glass` module draws the animated backdrop
//! and frosted glass panels underneath via a rendering notifier.
mod glass;
mod ipc;
mod devshot;
mod keyboard;
mod power;
mod runtime;
mod settings_screen;
mod system;
#[cfg(windows)]
mod winfade;
use std::cell::RefCell;
use std::path::{Path, PathBuf};
use std::rc::Rc;
use std::time::{Duration, Instant};
use anyhow::{Context, Result};
use chrono::{Datelike, Local, Timelike};
use glass::{Frame, GlassRenderer, Panel};
use sf_ipc::{AppKind, AppManifest, Settings};
use slint::{ComponentHandle, Model, ModelRc, SharedString, VecModel};
slint::include_modules!();
/// Time constant of the backdrop colour change when focus moves (seconds).
const CROSSFADE: f32 = 0.35;
struct Options {
apps_dir: PathBuf,
settings_path: PathBuf,
fullscreen: bool,
}
fn parse_args() -> Options {
let mut apps_dir = None;
let mut settings_path = None;
let mut fullscreen = false;
let mut args = std::env::args().skip(1);
while let Some(a) = args.next() {
match a.as_str() {
"--apps" => apps_dir = args.next().map(PathBuf::from),
"--settings" => settings_path = args.next().map(PathBuf::from),
"--fullscreen" | "-f" => fullscreen = true,
other => log::warn!("unknown argument {other}"),
}
}
Options {
apps_dir: apps_dir.or_else(find_apps_dir).unwrap_or_else(|| PathBuf::from("/usr/share/smartfox/apps")),
settings_path: settings_path.unwrap_or_else(default_settings_path),
fullscreen,
}
}
/// Looks for an `apps` folder next to the binary or in a parent of the cwd (dev checkout).
fn find_apps_dir() -> Option<PathBuf> {
let mut starts = vec![];
if let Ok(cwd) = std::env::current_dir() {
starts.push(cwd);
}
if let Ok(exe) = std::env::current_exe() {
starts.extend(exe.parent().map(Path::to_path_buf));
}
for start in starts {
for dir in start.ancestors() {
let candidate = dir.join("apps");
if candidate.join("netflex").is_dir() {
return Some(candidate);
}
}
}
None
}
fn default_settings_path() -> PathBuf {
if let Ok(p) = std::env::var("SMARTFOX_SETTINGS") {
return p.into();
}
let base = std::env::var_os("XDG_CONFIG_HOME")
.map(PathBuf::from)
.or_else(|| std::env::var_os("APPDATA").map(PathBuf::from))
.or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")))
.unwrap_or_else(|| PathBuf::from("."));
base.join("smartfox").join("settings.toml")
}
fn parse_hex(hex: &str) -> [f32; 3] {
let h = hex.trim_start_matches('#');
let v = u32::from_str_radix(h.get(..6).unwrap_or("ffffff"), 16).unwrap_or(0xffffff);
[((v >> 16) & 0xff) as f32 / 255.0, ((v >> 8) & 0xff) as f32 / 255.0, (v & 0xff) as f32 / 255.0]
}
fn to_color(rgb: [f32; 3]) -> slint::Color {
slint::Color::from_rgb_u8((rgb[0] * 255.0) as u8, (rgb[1] * 255.0) as u8, (rgb[2] * 255.0) as u8)
}
/// Backdrop palette (highlight, mid, deep) as linear floats.
fn palette_of(app: &AppManifest) -> [f32; 9] {
let fallback = ["#9aa4b5", "#2a3140", "#06070a"];
let mut out = [0.0; 9];
for i in 0..3 {
let hex = app.palette.get(i).map(String::as_str).unwrap_or(fallback[i]);
out[i * 3..i * 3 + 3].copy_from_slice(&parse_hex(hex));
}
out
}
fn entry_of(app: &AppManifest, settings: &Settings) -> AppEntry {
let (kind, kind_label, target) = match app.kind {
AppKind::Web => ("web", "Webes alkalmazás (Chromium)", app.resolved_url(settings).unwrap_or_default()),
AppKind::Exec => ("exec", "Natív alkalmazás", app.exec.clone().unwrap_or_default().join(" ")),
AppKind::Builtin => ("builtin", "Beépített", String::new()),
};
AppEntry {
id: app.id.clone().into(),
name: app.name.clone().into(),
category: app.category.clone().into(),
description: app.description.clone().into(),
icon: app.icon.clone().into(),
accent: to_color(parse_hex(&app.accent)),
kind: kind.into(),
kind_label: kind_label.into(),
target: target.into(),
}
}
/// Backdrop colours, eased towards the focused app's palette every frame.
struct Backdrop {
palette: [f32; 9],
last: f32,
}
fn color_rgb(c: slint::Color) -> [f32; 3] {
[c.red() as f32 / 255.0, c.green() as f32 / 255.0, c.blue() as f32 / 255.0]
}
fn rect_from_slint(g: &GlassRect, scale: f32) -> Panel {
Panel {
x: g.x * scale,
y: g.y * scale,
w: g.w * scale,
h: g.h * scale,
radius: g.r * scale,
focus: g.focus,
alpha: g.alpha,
blur: g.blur,
glow: color_rgb(g.glow),
group: g.group as f32,
tint: {
let [r, gr, b] = color_rgb(g.tint);
[r, gr, b, g.tint.alpha() as f32 / 255.0]
},
}
}
/// Mirrors the card formulas in ui/app.slint (`for app[i] in root.apps`).
///
/// Draw order: the other cards, then the focused one, then the context menu.
/// While the menu is out, the focused card and the menu share a merge group,
/// so the menu buds out of the icon like a droplet.
fn card_rects(ui: &App, scale: f32, accents: &[[f32; 3]]) -> Vec<Panel> {
let u = ui.get_u();
let cols = ui.get_cols().max(1) as usize;
let (row_x, row_y, step) = (ui.get_row_x(), ui.get_row_y(), ui.get_row_step());
let (cw, ch, gap, radius) = (ui.get_card_w(), ui.get_card_h(), ui.get_card_gap(), ui.get_card_r());
let (fx, fy, active, intro) = (ui.get_focus_x(), ui.get_focus_y(), ui.get_row_active(), ui.get_intro());
let (lift, press_in, press) = (ui.get_lift(), ui.get_press_in(), ui.get_press());
let scroll = ui.get_grid_scroll();
let menu_t = ui.get_menu_t().clamp(0.0, 1.0);
let focus_index = ui.get_focus_index().max(0) as usize;
let hidden = (1.0 - ui.get_launch_t()) * (1.0 - ui.get_sheet_t()) * ui.get_dim();
let card = |i: usize, accent: &[f32; 3]| {
let (col, row) = ((i % cols) as f32, (i / cols) as f32);
let f = (1.0 - (fx - col).abs()).max(0.0) * (1.0 - (fy - row).abs()).max(0.0) * active;
let s = 1.0 + (lift - press_in * press) * f;
let appear = (intro * 2.2 - col * 0.12 - row * 0.2 - 0.4).clamp(0.0, 1.0);
let others = if i == focus_index { 1.0 } else { 1.0 - 0.55 * menu_t };
let (w, h) = (cw * s, ch * s);
let x = row_x + col * (cw + gap) + (cw - w) / 2.0;
let y = row_y + row * step - scroll + (ch - h) / 2.0 + (1.0 - appear) * 60.0 * u;
// Coloured glass in the app's accent; focus makes it brighter and lighter.
let tint = accent.map(|c| {
let c = c * 0.72;
c + (1.0 - c) * 0.22 * f
});
Panel {
x: x * scale,
y: y * scale,
w: w * scale,
h: h * scale,
radius: radius * s * scale,
focus: f,
alpha: appear * others * hidden,
blur: 1.2 - 0.3 * f,
glow: *accent,
group: 0.0,
tint: [tint[0], tint[1], tint[2], 0.38 + 0.12 * f],
}
};
let mut out: Vec<Panel> =
accents.iter().enumerate().filter(|(i, _)| *i != focus_index).map(|(i, a)| card(i, a)).collect();
if let Some(accent) = accents.get(focus_index) {
let mut focused = card(focus_index, accent);
if menu_t > 0.001 {
focused.group = 2.0;
}
out.push(focused);
}
if menu_t > 0.001 {
out.extend(ui.get_glass_menu().iter().map(|g| rect_from_slint(&g, scale)));
}
out
}
const DAYS: [&str; 7] = ["hétfő", "kedd", "szerda", "csütörtök", "péntek", "szombat", "vasárnap"];
const MONTHS: [&str; 12] = ["jan.", "febr.", "márc.", "ápr.", "máj.", "jún.", "júl.", "aug.", "szept.", "okt.", "nov.", "dec."];
fn update_clock(ui: &App) {
let now = Local::now();
ui.set_clock(format!("{:02}:{:02}", now.hour(), now.minute()).into());
ui.set_date(
format!(
"{}, {} {}.",
DAYS[now.weekday().num_days_from_monday() as usize],
MONTHS[now.month0() as usize],
now.day()
)
.into(),
);
}
/// Remote status from sf-remote: drives the pairing guide and the settings row.
fn on_remote_state(ui: &App, state: &str) {
if ui.get_remote_state() != state {
log::info!("remote: {state}");
}
ui.set_remote_state(state.into());
ui.set_remote_status(
match state {
"no-adapter" => "Nincs Bluetooth adapter",
"searching" => "Nincs párosítva · keresés",
"pairing" => "Párosítás…",
"paired" => "Párosítva · alszik",
"connected" => "Csatlakozva",
other => other,
}
.into(),
);
match state {
// No remote yet: show the guide (unless skipped this session).
"searching" | "pairing" | "no-adapter" => {
if !ui.get_pairing_skipped() {
ui.set_settings_open(false);
ui.set_pairing_open(true);
}
log::debug!(
"pairing guide: open={} skipped={} t={}",
ui.get_pairing_open(),
ui.get_pairing_skipped(),
ui.get_pair_t()
);
}
// Paired: let the success state show for a moment, then close.
"paired" | "connected" if ui.get_pairing_open() => {
let weak = ui.as_weak();
slint::Timer::single_shot(Duration::from_millis(2200), move || {
if let Some(ui) = weak.upgrade() {
ui.set_pairing_open(false);
}
});
}
_ => {}
}
if let Some(screen) = settings_screen::current() {
screen.set_remote_status(&ui.get_remote_status());
}
}
fn show_toast(ui: &App, text: impl Into<SharedString>, timer: &slint::Timer) {
ui.set_toast_text(text.into());
ui.set_toast_shown(true);
let weak = ui.as_weak();
timer.start(slint::TimerMode::SingleShot, Duration::from_millis(2800), move || {
if let Some(ui) = weak.upgrade() {
ui.set_toast_shown(false);
}
});
}
fn main() -> Result<()> {
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
let opts = parse_args();
// The glass layer needs an OpenGL context, which the FemtoVG renderer provides
// on both winit (desktop) and linuxkms (TV).
slint::BackendSelector::new()
.renderer_name("femtovg".into())
.select()
.context("selecting the femtovg (OpenGL) renderer")?;
let mut settings = Settings::load(&opts.settings_path).unwrap_or_else(|e| {
log::warn!("settings: {e:#}");
Settings::default()
});
if settings.get("netflex_server").is_none() {
settings.values.insert("netflex_server".into(), "http://localhost:7880".into());
}
let data_dir = opts.settings_path.parent().map(Path::to_path_buf).unwrap_or_else(|| PathBuf::from("."));
let apps = sf_ipc::load_apps(&opts.apps_dir).with_context(|| format!("loading apps from {}", opts.apps_dir.display()))?;
log::info!("{} apps from {}", apps.len(), opts.apps_dir.display());
let ui = App::new()?;
let entries: Vec<AppEntry> = apps.iter().map(|a| entry_of(a, &settings)).collect();
ui.set_apps(ModelRc::new(VecModel::from(entries)));
let _screen = settings_screen::Screen::install(&ui, opts.settings_path.clone());
keyboard::install(&ui);
power::configure_from(&settings);
power::install(&ui, opts.settings_path.clone());
// The TV mode chosen in settings (wlr-randr; only inside the compositor).
if let Some(mode) = settings.get("display_mode").map(str::to_string) {
if !system::demo() && std::env::var_os("WAYLAND_DISPLAY").is_some() {
std::thread::spawn(move || {
if let Err(e) = system::apply_saved_mode(&mode) {
log::warn!("display: {e:#}");
}
});
}
}
update_clock(&ui);
let clock_timer = slint::Timer::default();
{
let weak = ui.as_weak();
clock_timer.start(slint::TimerMode::Repeated, Duration::from_secs(1), move || {
if let Some(ui) = weak.upgrade() {
update_clock(&ui);
}
});
}
// Launching. Locally the launcher starts apps itself; on the TV this moves to sf-core.
let toast_timer = Rc::new(slint::Timer::default());
let running: Rc<RefCell<Option<(String, std::process::Child)>>> = Rc::default();
{
let weak = ui.as_weak();
let apps = apps.clone();
let settings = settings.clone();
let toast_timer = toast_timer.clone();
let running = running.clone();
let data_dir = data_dir.clone();
let fullscreen = opts.fullscreen;
ui.on_launch(move |index| {
let Some(ui) = weak.upgrade() else { return };
let Some(app) = apps.get(index as usize) else { return };
if let Some((_, mut old)) = running.borrow_mut().take() {
runtime::stop(&mut old);
}
ui.set_launch_detail("indítása…".into());
ui.set_app_ready(false);
let pos = ui.window().position();
let size = ui.window().size();
let opts = runtime::LaunchOptions {
data_dir: &data_dir,
fullscreen,
bounds: Some((pos.x, pos.y, size.width, size.height)),
};
match runtime::launch(app, &settings, &opts) {
Ok(child) => {
log::info!("started {} (pid {})", app.id, child.id());
#[cfg(windows)]
{
// Keep the window hidden until the morph finishes and the page loads.
let weak = ui.as_weak();
let not_before = std::time::Instant::now() + Duration::from_millis(950);
winfade::reveal_when_ready(child.id(), not_before, move || {
let _ = weak.upgrade_in_event_loop(|ui| ui.set_app_ready(true));
});
}
*running.borrow_mut() = Some((app.name.clone(), child));
}
Err(e) => {
log::error!("launch {}: {e:#}", app.id);
ui.set_launching(false);
show_toast(&ui, format!("{}: {e:#}", app.name), &toast_timer);
}
}
});
}
{
let running = running.clone();
ui.on_cancel_launch(move || {
if let Some((name, mut child)) = running.borrow_mut().take() {
log::info!("closing {name}");
runtime::stop(&mut child);
}
});
}
// Global "home" (remote's TV button): close the foreground app and play the reverse morph.
{
let weak = ui.as_weak();
ipc::listen(move |cmd| {
let Some(ui) = weak.upgrade() else { return };
match cmd {
ipc::Command::Home => {
log::info!("home");
ui.invoke_cancel_launch();
ui.set_launching(false);
ui.set_app_ready(false);
ui.set_sheet_open(false);
ui.set_settings_open(false);
}
ipc::Command::Remote(state) => on_remote_state(&ui, &state),
ipc::Command::Standby(change) => power::apply(change),
// Resolved into Standby on the socket thread.
ipc::Command::Power | ipc::Command::Wake => {}
}
});
}
// Windows/dev: walk through the pairing guide without a remote.
if std::env::var_os("SMARTFOX_DEMO_PAIRING").is_some() {
for (ms, state) in [(1500, "searching"), (7000, "pairing"), (10000, "connected")] {
let weak = ui.as_weak();
slint::Timer::single_shot(Duration::from_millis(ms), move || {
if let Some(ui) = weak.upgrade() {
on_remote_state(&ui, state);
}
});
}
}
// Back to the home screen when the app exits on its own.
let app_watch = slint::Timer::default();
{
let weak = ui.as_weak();
let running = running.clone();
let toast_timer = toast_timer.clone();
app_watch.start(slint::TimerMode::Repeated, Duration::from_millis(400), move || {
let mut slot = running.borrow_mut();
let Some((name, child)) = slot.as_mut() else { return };
if let Ok(Some(status)) = child.try_wait() {
log::info!("{name} exited ({status})");
let name = name.clone();
*slot = None;
if let Some(ui) = weak.upgrade() {
#[cfg(windows)]
winfade::focus_self();
// Reverse morph: the full-screen glass shrinks back into the card.
ui.set_launching(false);
ui.set_app_ready(false);
show_toast(&ui, format!("{name} bezárva"), &toast_timer);
}
}
});
}
if opts.fullscreen {
ui.window().set_fullscreen(true);
}
let snapshot = devshot::setup(&ui);
// Glass layer.
let palettes: Vec<[f32; 9]> = apps.iter().map(palette_of).collect();
let accents: Vec<[f32; 3]> = apps.iter().map(|a| parse_hex(&a.accent)).collect();
let start = Instant::now();
let backdrop = Rc::new(RefCell::new(Backdrop { palette: palettes.first().copied().unwrap_or([0.0; 9]), last: 0.0 }));
let renderer: Rc<RefCell<Option<GlassRenderer>>> = Rc::default();
let frames = Rc::new(RefCell::new((Instant::now(), 0u32)));
let weak = ui.as_weak();
ui.window()
.set_rendering_notifier(move |state, api| match state {
slint::RenderingState::RenderingSetup => {
let slint::GraphicsAPI::NativeOpenGL { get_proc_address } = api else {
log::error!("glass layer needs OpenGL; running without it");
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!("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 bd = backdrop.borrow_mut();
let focus = ui.get_focus_index().max(0) as usize;
if let Some(target) = palettes.get(focus) {
let k = 1.0 - (-(time - bd.last).max(0.0) / CROSSFADE).exp();
for (c, t) in bd.palette.iter_mut().zip(target) {
*c += (t - *c) * k;
}
}
bd.last = time;
let mut rects: Vec<Panel> =
ui.get_glass_under().iter().map(|g| rect_from_slint(&g, scale)).collect();
rects.extend(card_rects(&ui, scale, &accents));
rects.extend(ui.get_glass_over().iter().map(|g| rect_from_slint(&g, scale)));
rects.extend(settings_screen::glass(&ui, scale));
rects.extend(keyboard::glass(&ui, scale));
// Each visible panel is one small draw; hidden ones are skipped.
rects.retain(|p| p.alpha > 0.002);
// Light sweeps gently and follows the focused card.
let angle = -2.25 + 0.10 * (time * 0.35).sin() + (ui.get_focus_x() - 2.0) * 0.06;
let frame = Frame {
width: size.width,
height: size.height,
scale,
time,
palette: bd.palette,
shelf: ui.get_shelf_t(),
light: [angle.cos(), angle.sin()],
zoom: 1.0 + 0.35 * ui.get_launch_t() * ui.get_launch_t(),
rects,
};
drop(bd);
// SAFETY: called on the UI thread with the Slint GL context current.
unsafe { r.render(&frame) };
let mut fps = frames.borrow_mut();
fps.1 += 1;
if fps.0.elapsed() >= Duration::from_secs(5) {
log::debug!("{:.1} fps", fps.1 as f32 / fps.0.elapsed().as_secs_f32());
*fps = (Instant::now(), 0);
}
}
slint::RenderingState::AfterRendering => {
// The backdrop is animated, so keep frames coming (vsync-limited).
if let Some(ui) = weak.upgrade() {
if let Some(r) = renderer.borrow().as_ref() {
snapshot.capture_if_due(&ui, r);
}
ui.window().request_redraw();
}
}
slint::RenderingState::RenderingTeardown => {
if let Some(mut r) = renderer.borrow_mut().take() {
unsafe { r.destroy() };
}
}
_ => {}
})
.map_err(|e| anyhow::anyhow!("rendering notifier: {e:?}"))?;
ui.run()?;
Ok(())
}

View File

@@ -0,0 +1,298 @@
//! Standby: what the remote's power button does (Settings > Energia).
//!
//! The launcher owns the standby state; sf-remote asks for changes over the
//! command socket (`power`, `wake`) and gets the state back after every
//! command (`standby off|screen|suspend <n>`). The launcher runs as `tv` and
//! can't suspend the machine, so sf-remote (root) does that when it sees a new
//! `suspend <n>`; it also wakes us when the remote reconnects after a resume.
//!
//! - Képernyő (Screen): the TV output is switched off, everything keeps running.
//! - Alvó mód (Suspend): screen off, then the machine suspends.
//! - Auto: screen off, and after `suspend_after` minutes the machine suspends.
use std::cell::{Cell, RefCell};
use std::path::PathBuf;
use std::rc::Rc;
use std::sync::Mutex;
use std::time::{Duration, Instant, SystemTime};
use slint::ComponentHandle;
use crate::App;
use crate::system;
/// Settings keys.
pub const MODE_KEY: &str = "power_button";
pub const AFTER_KEY: &str = "suspend_after_min";
pub const AFTER_CHOICES: [u32; 5] = [5, 15, 30, 60, 120];
const DEFAULT_AFTER: u32 = 15;
/// After a resume nobody asked for (no remote reconnected), sleep again.
const RESUSPEND_AFTER: Duration = Duration::from_secs(45);
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Mode {
Screen,
Suspend,
Auto,
}
impl Mode {
pub const ALL: [Mode; 3] = [Mode::Screen, Mode::Suspend, Mode::Auto];
pub fn key(self) -> &'static str {
match self {
Mode::Screen => "screen",
Mode::Suspend => "suspend",
Mode::Auto => "auto",
}
}
pub fn from_key(key: &str) -> Option<Mode> {
Mode::ALL.into_iter().find(|m| m.key() == key)
}
pub fn label(self) -> &'static str {
match self {
Mode::Screen => "Képernyő kikapcsolása",
Mode::Suspend => "Alvó mód",
Mode::Auto => "Képernyő ki, később alvás",
}
}
pub fn detail(self) -> &'static str {
match self {
Mode::Screen => "A gép bekapcsolva marad, azonnal ébred",
Mode::Suspend => "A legkevesebb áram, Bluetooth-ébresztéssel",
Mode::Auto => "Előbb csak a képernyő alszik, aztán a gép is",
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum State {
Awake,
/// Screen off, machine running.
Screen,
/// Machine asked to suspend (sf-remote does it).
Suspend,
}
struct Shared {
mode: Mode,
after_min: u32,
state: State,
/// Bumped on every suspend request, so sf-remote sees each one.
generation: u64,
}
static SHARED: Mutex<Shared> =
Mutex::new(Shared { mode: Mode::Screen, after_min: DEFAULT_AFTER, state: State::Awake, generation: 0 });
pub type Change = (State, State);
fn set(s: &mut Shared, next: State) -> Change {
let prev = s.state;
if next == State::Suspend && prev != State::Suspend {
s.generation += 1;
}
s.state = next;
(prev, next)
}
pub fn configure(mode: Mode, after_min: u32) {
let mut s = SHARED.lock().unwrap();
s.mode = mode;
s.after_min = after_min.max(1);
}
/// Reads the mode and delay from settings.toml values.
pub fn configure_from(settings: &sf_ipc::Settings) {
let mode = settings.get(MODE_KEY).and_then(Mode::from_key).unwrap_or(Mode::Screen);
let after = settings.get(AFTER_KEY).and_then(|v| v.parse().ok()).unwrap_or(DEFAULT_AFTER);
configure(mode, after);
}
pub fn mode() -> Mode {
SHARED.lock().unwrap().mode
}
pub fn after_min() -> u32 {
SHARED.lock().unwrap().after_min
}
pub fn state() -> State {
SHARED.lock().unwrap().state
}
/// Line sent back to sf-remote after every command.
#[cfg_attr(not(unix), allow(dead_code))]
pub fn reply() -> String {
let s = SHARED.lock().unwrap();
match s.state {
State::Awake => "standby off".into(),
State::Screen => "standby screen".into(),
State::Suspend => format!("standby suspend {}", s.generation),
}
}
/// Power button: into standby (per the mode) or back out of it.
pub fn press() -> Change {
let mut s = SHARED.lock().unwrap();
let next = match (s.state, s.mode) {
(State::Awake, Mode::Suspend) => State::Suspend,
(State::Awake, _) => State::Screen,
_ => State::Awake,
};
set(&mut s, next)
}
/// Any button (or the remote reconnecting) while in standby.
pub fn wake() -> Change {
set(&mut SHARED.lock().unwrap(), State::Awake)
}
/// Auto mode: the screen has been off long enough.
fn auto_suspend() -> Change {
let mut s = SHARED.lock().unwrap();
let next = if s.state == State::Screen { State::Suspend } else { s.state };
set(&mut s, next)
}
/// Woke up without anyone asking: ask sf-remote to suspend again.
fn resuspend() -> bool {
let mut s = SHARED.lock().unwrap();
if s.state != State::Suspend {
return false;
}
s.generation += 1;
true
}
// ---- effects on the UI thread ------------------------------------------------
struct Effects {
ui: slint::Weak<App>,
settings_path: PathBuf,
auto_timer: slint::Timer,
resuspend_timer: slint::Timer,
resume_watch: slint::Timer,
}
thread_local! {
static EFFECTS: RefCell<Option<Rc<Effects>>> = const { RefCell::new(None) };
}
pub fn install(ui: &App, settings_path: PathBuf) {
let fx = Rc::new(Effects {
ui: ui.as_weak(),
settings_path,
auto_timer: slint::Timer::default(),
resuspend_timer: slint::Timer::default(),
resume_watch: slint::Timer::default(),
});
EFFECTS.with(|e| *e.borrow_mut() = Some(fx.clone()));
ui.on_wake_requested(|| apply(wake()));
// Instant stands still while suspended, the wall clock doesn't: a jump
// between them means the machine just resumed.
let last = Cell::new((Instant::now(), SystemTime::now()));
fx.resume_watch.start(slint::TimerMode::Repeated, Duration::from_secs(2), move || {
let (mono, wall) = (Instant::now(), SystemTime::now());
let (last_mono, last_wall) = last.replace((mono, wall));
let slept = wall.duration_since(last_wall).unwrap_or_default().saturating_sub(mono - last_mono);
if slept > Duration::from_secs(5) {
on_resume(slept);
}
});
}
fn on_resume(slept: Duration) {
log::info!("power: resumed after ~{} s, state {:?}", slept.as_secs(), state());
if state() != State::Suspend {
return;
}
// A real wake comes with the remote reconnecting (sf-remote sends `wake`).
// Otherwise something else woke us (a stray Bluetooth advert, the RTC):
// stay dark and go back to sleep.
EFFECTS.with(|e| {
let Some(fx) = e.borrow().clone() else { return };
fx.resuspend_timer.start(slint::TimerMode::SingleShot, RESUSPEND_AFTER, || {
if resuspend() {
log::info!("power: nobody woke us, suspending again");
}
});
});
}
/// Runs the side effects of a state change. Call on the UI thread.
pub fn apply((prev, next): Change) {
if prev == next {
return;
}
log::info!("power: {prev:?} -> {next:?} (mode {:?})", mode());
let Some(fx) = EFFECTS.with(|e| e.borrow().clone()) else { return };
let Some(ui) = fx.ui.upgrade() else { return };
if prev == State::Awake {
ui.set_standby(true);
std::thread::spawn(|| {
if let Err(e) = system::display_power(false, None) {
log::warn!("power: screen off: {e:#}");
}
});
}
match next {
State::Screen if mode() == Mode::Auto => {
let after = Duration::from_secs(60 * after_min() as u64);
fx.auto_timer.start(slint::TimerMode::SingleShot, after, || apply(auto_suspend()));
}
State::Suspend => log::info!("power: suspend requested, sf-remote puts the machine to sleep"),
State::Awake => {
fx.auto_timer.stop();
fx.resuspend_timer.stop();
ui.set_standby(false);
let saved = sf_ipc::Settings::load(&fx.settings_path)
.ok()
.and_then(|s| s.get("display_mode").map(str::to_string));
std::thread::spawn(move || {
if let Err(e) = system::display_power(true, saved.as_deref()) {
log::warn!("power: screen on: {e:#}");
}
});
}
State::Screen => {}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn power_button_cycle() {
// One test touches the shared state, so the steps don't race.
configure(Mode::Screen, 15);
assert_eq!(press(), (State::Awake, State::Screen));
assert_eq!(reply(), "standby screen");
assert_eq!(press(), (State::Screen, State::Awake));
assert_eq!(reply(), "standby off");
configure(Mode::Suspend, 15);
let g = SHARED.lock().unwrap().generation;
assert_eq!(press(), (State::Awake, State::Suspend));
assert_eq!(reply(), format!("standby suspend {}", g + 1));
assert!(resuspend());
assert_eq!(reply(), format!("standby suspend {}", g + 2));
assert_eq!(wake(), (State::Suspend, State::Awake));
assert!(!resuspend());
configure(Mode::Auto, 5);
assert_eq!(press(), (State::Awake, State::Screen));
assert_eq!(auto_suspend(), (State::Screen, State::Suspend));
assert_eq!(wake().1, State::Awake);
assert_eq!(Mode::from_key("auto"), Some(Mode::Auto));
configure(Mode::Screen, 15);
}
}

View File

@@ -0,0 +1,187 @@
//! Starts apps. Web apps run in a Chromium-family browser in app/kiosk mode
//! with a per-app profile; exec apps are spawned directly.
//!
//! This lives in the launcher for local testing; on the TV it moves into the
//! sf-core daemon (systemd scopes, freeze/thaw).
use std::path::{Path, PathBuf};
use std::process::{Child, Command};
use anyhow::{Context, Result, bail};
use sf_ipc::{AppKind, AppManifest, Settings};
pub struct Browser {
pub exe: PathBuf,
/// Full version, used to build a realistic user agent.
pub version: String,
}
pub fn find_browser() -> Option<Browser> {
let mut candidates: Vec<PathBuf> = Vec::new();
if let Ok(p) = std::env::var("SMARTFOX_BROWSER") {
candidates.push(p.into());
}
#[cfg(windows)]
{
for base in ["ProgramFiles", "ProgramFiles(x86)", "LOCALAPPDATA"] {
if let Some(b) = std::env::var_os(base) {
let b = PathBuf::from(b);
candidates.push(b.join(r"Google\Chrome\Application\chrome.exe"));
candidates.push(b.join(r"Chromium\Application\chrome.exe"));
candidates.push(b.join(r"Microsoft\Edge\Application\msedge.exe"));
}
}
}
#[cfg(not(windows))]
{
for name in ["chromium", "chromium-browser", "google-chrome-stable", "google-chrome"] {
for dir in ["/usr/bin", "/usr/local/bin", "/snap/bin"] {
candidates.push(Path::new(dir).join(name));
}
}
}
let exe = candidates.into_iter().find(|p| p.is_file())?;
let version = browser_version(&exe).unwrap_or_else(|| "141.0.0.0".into());
Some(Browser { exe, version })
}
fn browser_version(exe: &Path) -> Option<String> {
// Windows installs keep a folder named after the version next to the exe.
if cfg!(windows) {
let dir = exe.parent()?;
let mut versions: Vec<String> = std::fs::read_dir(dir)
.ok()?
.flatten()
.filter_map(|e| e.file_name().into_string().ok())
.filter(|n| n.split('.').count() == 4 && n.split('.').all(|p| p.parse::<u32>().is_ok()))
.collect();
versions.sort_by_key(|v| v.split('.').map(|p| p.parse::<u32>().unwrap_or(0)).collect::<Vec<_>>());
return versions.pop();
}
let out = Command::new(exe).arg("--version").output().ok()?;
String::from_utf8_lossy(&out.stdout)
.split_whitespace()
.find(|w| w.chars().next().is_some_and(|c| c.is_ascii_digit()) && w.contains('.'))
.map(str::to_string)
}
fn default_user_agent(version: &str) -> String {
let platform = if cfg!(windows) { "Windows NT 10.0; Win64; x64" } else { "X11; Linux x86_64" };
let major = version.split('.').next().unwrap_or("141");
format!("Mozilla/5.0 ({platform}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{major}.0.0.0 Safari/537.36")
}
pub struct LaunchOptions<'a> {
pub data_dir: &'a Path,
pub fullscreen: bool,
/// Windowed mode: open the app exactly over the launcher (x, y, w, h).
pub bounds: Option<(i32, i32, u32, u32)>,
}
pub fn launch(app: &AppManifest, settings: &Settings, opts: &LaunchOptions) -> Result<Child> {
match app.kind {
AppKind::Web => launch_web(app, settings, opts),
AppKind::Exec => {
let cmd = app.exec.as_deref().unwrap_or_default();
let (prog, args) = cmd.split_first().context("empty exec command")?;
Command::new(prog).args(args).spawn().with_context(|| format!("starting {prog}"))
}
AppKind::Builtin => bail!("built-in app has no process"),
}
}
/// First-run preferences for an app profile: no translate prompt, Hungarian
/// content language. Existing profiles are left alone.
fn seed_profile(profile: &Path) -> Result<()> {
let prefs = profile.join("Default").join("Preferences");
if prefs.exists() {
return Ok(());
}
std::fs::create_dir_all(prefs.parent().unwrap())?;
std::fs::write(
&prefs,
r#"{"translate":{"enabled":false},"intl":{"accept_languages":"hu-HU,hu,en"},"browser":{"has_seen_welcome_page":true}}"#,
)?;
Ok(())
}
fn launch_web(app: &AppManifest, settings: &Settings, opts: &LaunchOptions) -> Result<Child> {
let browser = find_browser().context("no Chromium/Chrome/Edge found (set SMARTFOX_BROWSER)")?;
let url = app.resolved_url(settings).filter(|u| !u.is_empty()).context("app has no URL")?;
if url.starts_with('/') {
bail!("URL is not set (check settings: {url})");
}
let profile = opts.data_dir.join("profiles").join(&app.id);
seed_profile(&profile)?;
let ua = match (&app.web.user_agent, &app.web.user_agent_suffix) {
(Some(ua), _) => ua.clone(),
(None, Some(suffix)) => format!("{} {suffix}", default_user_agent(&browser.version)),
(None, None) => default_user_agent(&browser.version),
};
let mut cmd = Command::new(&browser.exe);
cmd.arg(format!("--user-data-dir={}", profile.display()))
.arg(format!("--user-agent={ua}"))
.arg("--no-first-run")
.arg("--no-default-browser-check")
.arg("--disable-session-crashed-bubble")
.arg("--hide-crash-restore-bubble")
.arg("--disable-features=Translate,TranslateUI,MediaRouter")
.arg("--lang=hu")
.arg("--accept-lang=hu-HU,hu,en")
// Dark first paint instead of a white flash before the page draws.
.arg("--force-dark-mode")
.arg("--autoplay-policy=no-user-gesture-required")
.arg("--overscroll-history-navigation=0");
if opts.fullscreen {
cmd.arg("--kiosk").arg(&url);
} else {
cmd.arg(format!("--app={url}"));
match opts.bounds {
Some((x, y, w, h)) => {
cmd.arg(format!("--window-position={x},{y}")).arg(format!("--window-size={w},{h}"));
}
None => {
cmd.arg("--window-size=1600,900");
}
}
}
if cfg!(target_os = "linux") {
// Chromium on Linux picks its UI language from the environment, not --lang.
cmd.env("LANGUAGE", "hu");
cmd.arg("--enable-features=VaapiVideoDecoder,VaapiIgnoreDriverChecks,PlatformHEVCDecoderSupport");
if std::env::var_os("WAYLAND_DISPLAY").is_some() {
cmd.arg("--ozone-platform=wayland");
}
}
for ext in &app.web.extensions {
cmd.arg(format!("--load-extension={}", app.dir.join(ext).display()));
}
// Own process group, so closing the app also ends Chromium's helper processes.
#[cfg(unix)]
{
use std::os::unix::process::CommandExt;
cmd.process_group(0);
}
log::info!("{} {:?}", browser.exe.display(), cmd.get_args().collect::<Vec<_>>());
cmd.spawn().with_context(|| format!("starting {}", browser.exe.display()))
}
/// Stops an app and everything it started.
pub fn stop(child: &mut Child) {
#[cfg(unix)]
{
// The app runs in its own process group (see launch_web).
let _ = Command::new("kill").arg("-TERM").arg("--").arg(format!("-{}", child.id())).status();
for _ in 0..20 {
if matches!(child.try_wait(), Ok(Some(_))) {
return;
}
std::thread::sleep(std::time::Duration::from_millis(50));
}
let _ = Command::new("kill").arg("-KILL").arg("--").arg(format!("-{}", child.id())).status();
}
let _ = child.kill();
let _ = child.wait();
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,927 @@
//! System backends for the settings screen: display modes (wlr-randr),
//! Bluetooth devices (bluetoothctl), Wi-Fi (iwd), network and device info.
//!
//! Off Linux (Windows dev builds), or with `SMARTFOX_DEMO_SYSTEM=1`, a demo
//! backend with in-memory state keeps the settings screen usable.
//! All calls can block for a moment, so run them off the UI thread.
use std::process::{Command, Stdio};
use std::sync::Mutex;
use std::time::{Duration, Instant};
use anyhow::{Context, Result, bail};
pub fn demo() -> bool {
!cfg!(target_os = "linux") || std::env::var_os("SMARTFOX_DEMO_SYSTEM").is_some()
}
/// Runs a command and returns its stdout; kills it after `timeout`.
fn run(prog: &str, args: &[&str], timeout: Duration) -> Result<String> {
let mut child = Command::new(prog)
.args(args)
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.with_context(|| format!("starting {prog}"))?;
let deadline = Instant::now() + timeout;
loop {
if child.try_wait()?.is_some() {
break;
}
if Instant::now() >= deadline {
let _ = child.kill();
let _ = child.wait();
bail!("{prog} {} timed out", args.join(" "));
}
std::thread::sleep(Duration::from_millis(20));
}
let out = child.wait_with_output()?;
let stdout = strip_ansi(&String::from_utf8_lossy(&out.stdout));
if !out.status.success() {
let err = strip_ansi(&String::from_utf8_lossy(&out.stderr));
bail!("{prog} {}: {}", args.join(" "), err.trim());
}
Ok(stdout)
}
/// bluetoothctl colours its output even when it isn't a terminal.
fn strip_ansi(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut chars = s.chars();
while let Some(c) = chars.next() {
if c == '\x1b' {
for c in chars.by_ref() {
if c.is_ascii_alphabetic() {
break;
}
}
} else if c != '\x01' && c != '\x02' {
out.push(c);
}
}
out
}
// ---- display ---------------------------------------------------------------
#[derive(Debug, Clone, PartialEq)]
pub struct Mode {
pub w: u32,
pub h: u32,
pub hz: f32,
pub preferred: bool,
}
impl Mode {
pub fn label(&self) -> String {
format!("{} × {} · {} Hz", self.w, self.h, fmt_hz(self.hz))
}
/// Short name of the format, e.g. "4K UHD".
pub fn name(&self) -> &'static str {
match (self.w, self.h) {
(3840, 2160) | (4096, 2160) => "4K UHD",
(2560, 1440) => "QHD",
(1920, 1080) => "Full HD",
(1280, 720) => "HD",
_ => "",
}
}
/// Key stored in settings.toml (`display_mode`).
pub fn key(&self) -> String {
format!("{}x{}@{:.3}", self.w, self.h, self.hz)
}
fn same(&self, other: &Mode) -> bool {
self.w == other.w && self.h == other.h && (self.hz - other.hz).abs() < 0.05
}
pub fn matches_key(&self, key: &str) -> bool {
parse_mode_key(key).is_some_and(|m| self.same(&m))
}
}
fn fmt_hz(hz: f32) -> String {
let r = (hz * 100.0).round() / 100.0;
if (r - r.round()).abs() < 0.005 { format!("{}", r.round() as u32) } else { format!("{r:.2}") }
}
fn parse_mode_key(key: &str) -> Option<Mode> {
let (size, hz) = key.split_once('@')?;
let (w, h) = size.split_once('x')?;
Some(Mode { w: w.parse().ok()?, h: h.parse().ok()?, hz: hz.trim_end_matches("Hz").parse().ok()?, preferred: false })
}
#[derive(Debug, Clone)]
pub struct Display {
pub output: String,
pub description: String,
pub modes: Vec<Mode>,
pub current: Option<usize>,
}
impl Display {
pub fn current_mode(&self) -> Option<&Mode> {
self.current.and_then(|i| self.modes.get(i))
}
}
/// Parses `wlr-randr` text output; the first output is the TV.
fn parse_wlr_randr(text: &str) -> Option<Display> {
let mut lines = text.lines();
let head = lines.find(|l| !l.trim().is_empty() && !l.starts_with(' '))?;
let (output, description) = match head.split_once(' ') {
Some((o, d)) => (o.to_string(), d.trim().trim_matches('"').to_string()),
None => (head.trim().to_string(), String::new()),
};
let mut modes: Vec<Mode> = Vec::new();
let mut current = None;
let mut in_modes = false;
for line in lines {
if !line.starts_with(' ') {
break; // next output
}
let t = line.trim();
if t == "Modes:" {
in_modes = true;
continue;
}
if !in_modes {
continue;
}
if !t.chars().next().is_some_and(|c| c.is_ascii_digit()) {
in_modes = false;
continue;
}
// "1920x1080 px, 60.000000 Hz (preferred, current)"
let Some((size, rest)) = t.split_once(" px,") else { continue };
let Some((w, h)) = size.split_once('x') else { continue };
let hz: f32 = rest.trim().split_whitespace().next().and_then(|v| v.parse().ok()).unwrap_or(60.0);
let flags = rest.split_once('(').map(|(_, f)| f).unwrap_or("");
let mode = Mode {
w: w.trim().parse().unwrap_or(0),
h: h.trim().parse().unwrap_or(0),
hz,
preferred: flags.contains("preferred"),
};
let is_current = flags.contains("current");
match modes.iter().position(|m| m.same(&mode)) {
Some(i) => {
modes[i].preferred |= mode.preferred;
if is_current {
current = Some(i);
}
}
None => {
modes.push(mode);
if is_current {
current = Some(modes.len() - 1);
}
}
}
}
// Biggest first; tiny legacy modes are not useful on a TV.
let cur = current.map(|i| modes[i].clone());
modes.retain(|m| (m.w >= 1024 && m.h >= 576) || cur.as_ref().is_some_and(|c| c.same(m)));
modes.sort_by(|a, b| (b.w * b.h).cmp(&(a.w * a.h)).then(b.hz.total_cmp(&a.hz)));
let current = cur.and_then(|c| modes.iter().position(|m| m.same(&c)));
Some(Display { output, description, modes, current })
}
static DEMO_DISPLAY: Mutex<Option<Display>> = Mutex::new(None);
fn demo_display() -> Display {
let mut guard = DEMO_DISPLAY.lock().unwrap();
guard
.get_or_insert_with(|| {
let m = |w, h, hz, preferred| Mode { w, h, hz, preferred };
Display {
output: "HDMI-A-1".into(),
description: "Fejlesztői mód (demó kijelző)".into(),
modes: vec![
m(3840, 2160, 60.0, true),
m(3840, 2160, 30.0, false),
m(2560, 1440, 60.0, false),
m(1920, 1080, 60.0, false),
m(1920, 1080, 50.0, false),
m(1280, 720, 60.0, false),
],
current: Some(3),
}
})
.clone()
}
pub fn display() -> Result<Display> {
if demo() {
return Ok(demo_display());
}
let out = run("wlr-randr", &[], Duration::from_secs(3))?;
parse_wlr_randr(&out).context("wlr-randr: no output found")
}
pub fn set_mode(output: &str, mode: &Mode) -> Result<()> {
if demo() {
let mut guard = DEMO_DISPLAY.lock().unwrap();
if let Some(d) = guard.as_mut() {
d.current = d.modes.iter().position(|m| m.same(mode));
}
return Ok(());
}
let arg = format!("{}x{}@{}Hz", mode.w, mode.h, mode.hz);
run("wlr-randr", &["--output", output, "--mode", &arg], Duration::from_secs(5))?;
Ok(())
}
/// Applies the saved `display_mode` at startup, if the TV offers it.
pub fn apply_saved_mode(key: &str) -> Result<()> {
let d = display()?;
let Some(mode) = d.modes.iter().find(|m| m.matches_key(key)) else {
bail!("saved mode {key} is not offered by {}", d.output);
};
if d.current_mode().is_some_and(|c| c.same(mode)) {
return Ok(());
}
log::info!("display: applying saved mode {}", mode.label());
set_mode(&d.output, mode)
}
/// Standby: switches the TV signal off or back on. `saved` is the
/// `display_mode` to restore after the output comes back.
pub fn display_power(on: bool, saved: Option<&str>) -> Result<()> {
if demo() || std::env::var_os("WAYLAND_DISPLAY").is_none() {
return Ok(());
}
let t = Duration::from_secs(4);
// DPMS keeps the mode; only if the compositor offers it (wlopm installed).
let state = if on { "--on" } else { "--off" };
if run("wlopm", &[state, "*"], t).is_ok() {
return Ok(());
}
// Otherwise disable the output (cage supports wlr-output-management).
let head = run("wlr-randr", &[], t)?;
let output = parse_wlr_randr(&head).context("wlr-randr: no output found")?.output;
run("wlr-randr", &["--output", &output, state], t)?;
if on {
if let Some(key) = saved {
apply_saved_mode(key)?;
}
}
Ok(())
}
/// Whether the Bluetooth controller may wake the machine (USB `power/wakeup`).
/// sf-remote (root) turns this on before suspending.
#[derive(Debug, Clone, PartialEq)]
pub enum BtWake {
NoController,
Enabled,
/// Off now; sf-remote enables it before each suspend.
Disabled,
Unknown,
}
pub fn bt_wake() -> BtWake {
if demo() {
return BtWake::Enabled;
}
let Ok(entries) = std::fs::read_dir("/sys/class/bluetooth") else { return BtWake::NoController };
let mut found = false;
for e in entries.flatten() {
let name = e.file_name().to_string_lossy().to_string();
if !name.starts_with("hci") || name.contains(':') {
continue;
}
found = true;
let Ok(dev) = std::fs::canonicalize(e.path().join("device")) else { continue };
if let Some(v) = dev.ancestors().find_map(|a| std::fs::read_to_string(a.join("power/wakeup")).ok()) {
return if v.trim() == "enabled" { BtWake::Enabled } else { BtWake::Disabled };
}
}
if found { BtWake::Unknown } else { BtWake::NoController }
}
// ---- bluetooth -----------------------------------------------------------
#[derive(Debug, Clone)]
pub struct BtDevice {
pub address: String,
pub name: String,
pub connected: bool,
pub battery: Option<u8>,
/// An Apple Siri Remote (the one sf-remote drives).
pub remote: bool,
pub icon: String,
}
impl BtDevice {
pub fn status(&self) -> String {
match (self.connected, self.battery) {
(true, Some(b)) => format!("Csatlakozva · {b}%"),
(true, None) => "Csatlakozva".into(),
(false, _) if self.remote => "Alszik · nyomj meg egy gombot".into(),
(false, _) => "Nincs csatlakozva".into(),
}
}
pub fn kind_label(&self) -> &'static str {
if self.remote {
return "Siri Remote";
}
match self.icon.as_str() {
"audio-headphones" | "audio-headset" => "Fejhallgató",
"audio-card" | "audio-speakers" => "Hangszóró",
"input-gaming" => "Játékvezérlő",
"input-keyboard" => "Billentyűzet",
"input-mouse" => "Egér",
"phone" => "Telefon",
_ => "Bluetooth eszköz",
}
}
}
fn is_mac(s: &str) -> bool {
s.len() == 17 && s.split(':').count() == 6 && s.split(':').all(|p| p.len() == 2 && p.chars().all(|c| c.is_ascii_hexdigit()))
}
/// "Device AA:BB:CC:DD:EE:FF Name" lines.
fn parse_device_list(text: &str) -> Vec<(String, String)> {
text.lines()
.filter_map(|l| {
let rest = &l[l.find("Device ")? + "Device ".len()..];
let (addr, name) = rest.split_once(' ').unwrap_or((rest, ""));
is_mac(addr).then(|| (addr.to_string(), name.trim().to_string()))
})
.collect()
}
fn parse_info(addr: &str, fallback_name: &str, text: &str) -> BtDevice {
let field = |key: &str| {
text.lines()
.map(str::trim)
.find_map(|l| l.strip_prefix(key).map(|v| v.trim().to_string()))
};
let name = field("Alias:").or_else(|| field("Name:")).unwrap_or_else(|| fallback_name.to_string());
let connected = field("Connected:").is_some_and(|v| v == "yes");
// "Battery Percentage: 0x5a (90)"
let battery = field("Battery Percentage:")
.and_then(|v| v.split_once('(').and_then(|(_, p)| p.trim_end_matches(')').parse().ok()));
// "Modalias: bluetooth:v004Cp0315d0001" (vendor 004C = Apple)
let modalias = field("Modalias:").unwrap_or_default().to_ascii_lowercase();
let remote = ["p0314", "p0315", "p0266"].iter().any(|p| modalias.contains(&format!("v004c{p}")));
let icon = field("Icon:").unwrap_or_default();
BtDevice { address: addr.to_string(), name, connected, battery, remote, icon }
}
static DEMO_DEVICES: Mutex<Option<Vec<BtDevice>>> = Mutex::new(None);
fn demo_devices() -> Vec<BtDevice> {
DEMO_DEVICES
.lock()
.unwrap()
.get_or_insert_with(|| {
vec![
BtDevice {
address: "F0:B3:EC:12:7A:41".into(),
name: "Siri Remote".into(),
connected: true,
battery: Some(82),
remote: true,
icon: "input-gaming".into(),
},
BtDevice {
address: "4C:87:5D:0E:22:9B".into(),
name: "AirPods Pro".into(),
connected: false,
battery: None,
remote: false,
icon: "audio-headphones".into(),
},
]
})
.clone()
}
pub fn bt_devices() -> Result<Vec<BtDevice>> {
if demo() {
return Ok(demo_devices());
}
let t = Duration::from_secs(4);
let list = match run("bluetoothctl", &["devices", "Paired"], t) {
Ok(out) if !parse_device_list(&out).is_empty() => out,
// Older BlueZ.
_ => run("bluetoothctl", &["paired-devices"], t).unwrap_or_default(),
};
let mut devices = Vec::new();
for (addr, name) in parse_device_list(&list) {
let info = run("bluetoothctl", &["info", &addr], t).unwrap_or_default();
devices.push(parse_info(&addr, &name, &info));
}
// Remotes first, then connected devices.
devices.sort_by_key(|d| (!d.remote, !d.connected, d.name.to_lowercase()));
Ok(devices)
}
pub fn bt_remove(addr: &str) -> Result<()> {
if demo() {
if let Some(list) = DEMO_DEVICES.lock().unwrap().as_mut() {
list.retain(|d| d.address != addr);
}
return Ok(());
}
let out = run("bluetoothctl", &["remove", addr], Duration::from_secs(6))?;
if out.contains("not available") || out.contains("Failed") {
bail!("{}", out.trim());
}
Ok(())
}
// ---- network & device info -------------------------------------------------
#[derive(Debug, Clone, Default)]
pub struct NetInfo {
pub iface: Option<String>,
pub wireless: bool,
pub ip: Option<String>,
pub gateway: Option<String>,
pub wifi_adapter: bool,
}
pub fn network() -> NetInfo {
if demo() {
return NetInfo {
iface: Some("enp1s0".into()),
wireless: false,
ip: Some("192.168.1.42".into()),
gateway: Some("192.168.1.1".into()),
wifi_adapter: true,
};
}
let t = Duration::from_secs(2);
let mut info = NetInfo::default();
// "2: enp1s0 inet 192.168.1.42/24 brd ... "
if let Ok(out) = run("ip", &["-o", "-4", "addr", "show", "scope", "global"], t) {
if let Some(line) = out.lines().next() {
let f: Vec<&str> = line.split_whitespace().collect();
info.iface = f.get(1).map(|s| s.to_string());
info.ip = f.get(3).map(|s| s.split('/').next().unwrap_or(s).to_string());
}
}
// "default via 192.168.1.1 dev enp1s0 ..."
if let Ok(out) = run("ip", &["route", "show", "default"], t) {
let f: Vec<&str> = out.split_whitespace().collect();
info.gateway = f.iter().position(|w| *w == "via").and_then(|i| f.get(i + 1)).map(|s| s.to_string());
}
let wireless = |iface: &str| std::path::Path::new("/sys/class/net").join(iface).join("wireless").exists();
info.wireless = info.iface.as_deref().is_some_and(wireless);
info.wifi_adapter = std::fs::read_dir("/sys/class/net")
.map(|d| d.flatten().any(|e| wireless(&e.file_name().to_string_lossy())))
.unwrap_or(false);
info
}
// ---- wi-fi (iwd over D-Bus) -------------------------------------------------
//
// Reads go through `busctl --json` (the whole iwd object tree in one call).
// A new password needs an agent, which `iwctl --passphrase` provides; known
// and open networks connect with a plain D-Bus call. The tv user reaches iwd
// through the netdev group (iwd's D-Bus policy).
const IWD: &str = "net.connman.iwd";
#[derive(Debug, Clone, Copy, PartialEq)]
pub enum Security {
Open,
Psk,
Wep,
Enterprise,
}
#[derive(Debug, Clone, PartialEq)]
pub struct WifiNetwork {
/// D-Bus object path, stable while the network is in range.
pub path: String,
pub name: String,
pub security: Security,
/// dBm.
pub signal: i32,
pub connected: bool,
/// KnownNetwork object path when a password is saved.
pub known: Option<String>,
}
impl WifiNetwork {
pub fn bars(&self) -> i32 {
match self.signal {
s if s >= -60 => 4,
s if s >= -67 => 3,
s if s >= -75 => 2,
_ => 1,
}
}
pub fn strength_label(&self) -> &'static str {
["", "Gyenge", "Közepes", "Jó", "Kiváló"][self.bars() as usize]
}
pub fn security_label(&self) -> &'static str {
match self.security {
Security::Open => "Nyílt hálózat",
Security::Psk => "Jelszóval védett",
Security::Wep => "WEP (elavult)",
Security::Enterprise => "Vállalati (802.1X)",
}
}
}
#[derive(Debug, Clone, Default, PartialEq)]
pub struct Wifi {
/// iwd Device object path.
pub device: String,
/// Interface name, e.g. "wlan0".
pub iface: String,
pub powered: bool,
pub scanning: bool,
/// Strongest first, the connected one on top.
pub networks: Vec<WifiNetwork>,
}
fn busctl(args: &[&str], timeout: Duration) -> Result<serde_json::Value> {
let mut all = vec!["--json=short"];
all.extend_from_slice(args);
let out = run("busctl", &all, timeout).map_err(|e| {
let text = format!("{e:#}");
if text.contains("not provided by any") || text.contains("ServiceUnknown") || text.contains("was not provided") {
anyhow::anyhow!("a Wi-Fi szolgáltatás (iwd) nem fut")
} else {
e
}
})?;
if out.trim().is_empty() {
return Ok(serde_json::Value::Null);
}
serde_json::from_str(&out).context("busctl: unexpected output")
}
/// One D-Bus property from a GetManagedObjects entry.
fn prop<'a>(obj: &'a serde_json::Value, iface: &str, name: &str) -> Option<&'a serde_json::Value> {
obj.get(iface)?.get(name)?.get("data")
}
/// Builds the state from `GetManagedObjects` data and the ordered
/// (network path, signal in 100 * dBm) list of the station.
fn parse_wifi(objects: &serde_json::Value, ordered: &[(String, i64)]) -> Option<Wifi> {
let objs = objects.as_object()?;
let (device, dev) = objs
.iter()
.filter(|(_, o)| o.get("net.connman.iwd.Device").is_some())
.min_by_key(|(p, _)| p.len())?;
let text = |o: &serde_json::Value, i: &str, n: &str| prop(o, i, n).and_then(|v| v.as_str()).unwrap_or("").to_string();
let flag = |o: &serde_json::Value, i: &str, n: &str| prop(o, i, n).and_then(|v| v.as_bool()).unwrap_or(false);
let mut wifi = Wifi {
device: device.clone(),
iface: text(dev, "net.connman.iwd.Device", "Name"),
powered: flag(dev, "net.connman.iwd.Device", "Powered"),
scanning: flag(dev, "net.connman.iwd.Station", "Scanning"),
networks: Vec::new(),
};
for (path, signal) in ordered {
let Some(net) = objs.get(path) else { continue };
let name = text(net, "net.connman.iwd.Network", "Name");
if name.is_empty() {
continue;
}
let security = match text(net, "net.connman.iwd.Network", "Type").as_str() {
"open" | "owe" => Security::Open,
"wep" => Security::Wep,
"8021x" => Security::Enterprise,
_ => Security::Psk,
};
wifi.networks.push(WifiNetwork {
path: path.clone(),
name,
security,
signal: (*signal / 100) as i32,
connected: flag(net, "net.connman.iwd.Network", "Connected"),
known: prop(net, "net.connman.iwd.Network", "KnownNetwork").and_then(|v| v.as_str()).map(str::to_string),
});
}
// Stable sort keeps iwd's signal order inside each group.
wifi.networks.sort_by_key(|n| !n.connected);
Some(wifi)
}
static DEMO_WIFI: Mutex<Option<Wifi>> = Mutex::new(None);
fn with_demo_wifi<T>(f: impl FnOnce(&mut Wifi) -> T) -> T {
let mut guard = DEMO_WIFI.lock().unwrap();
let wifi = guard.get_or_insert_with(|| {
let n = |i: usize, name: &str, security, signal, known: bool| WifiNetwork {
path: format!("/net/connman/iwd/0/4/demo{i}"),
name: name.into(),
security,
signal,
connected: false,
known: known.then(|| format!("/net/connman/iwd/known/demo{i}")),
};
Wifi {
device: "/net/connman/iwd/0/4".into(),
iface: "wlan0".into(),
powered: true,
scanning: false,
networks: vec![
n(1, "Otthon-5G", Security::Psk, -48, false),
n(2, "Otthon", Security::Psk, -58, true),
n(3, "Kávézó vendég", Security::Open, -69, false),
n(4, "Szomszéd_WiFi", Security::Psk, -77, false),
n(5, "Iroda", Security::Enterprise, -81, false),
],
}
});
f(wifi)
}
/// Ok(None) when there is no Wi-Fi adapter.
pub fn wifi() -> Result<Option<Wifi>> {
if demo() {
return Ok(Some(with_demo_wifi(|w| {
let mut w = w.clone();
if !w.powered {
w.networks.clear();
}
w
})));
}
let t = Duration::from_secs(3);
let objects = busctl(&["call", IWD, "/", "org.freedesktop.DBus.ObjectManager", "GetManagedObjects"], t)?;
let objects = &objects["data"][0];
let station = objects.as_object().and_then(|o| {
o.iter()
.filter(|(_, v)| v.get("net.connman.iwd.Station").is_some())
.map(|(p, _)| p.clone())
.min_by_key(|p| p.len())
});
let mut ordered = Vec::new();
if let Some(station) = station {
// {"type":"a(on)","data":[[["/net/connman/iwd/0/4/..._psk",-5400], ...]]}
let v = busctl(&["call", IWD, &station, "net.connman.iwd.Station", "GetOrderedNetworks"], t)?;
if let Some(list) = v["data"][0].as_array() {
for item in list {
if let (Some(p), Some(s)) = (item[0].as_str(), item[1].as_i64()) {
ordered.push((p.to_string(), s));
}
}
}
}
Ok(parse_wifi(objects, &ordered))
}
/// Starts a scan; results show up in `wifi()` a few seconds later.
pub fn wifi_scan(device: &str) -> Result<()> {
if demo() {
return Ok(());
}
match busctl(&["call", IWD, device, "net.connman.iwd.Station", "Scan"], Duration::from_secs(5)) {
Err(e) if format!("{e:#}").contains("InProgress") => Ok(()),
r => r.map(|_| ()),
}
}
pub fn wifi_set_powered(device: &str, on: bool) -> Result<()> {
if demo() {
with_demo_wifi(|w| w.powered = on);
return Ok(());
}
let t = Duration::from_secs(5);
let value = if on { "true" } else { "false" };
if on {
// The adapter (radio) has to be on before the device can be.
let adapter = busctl(&["get-property", IWD, device, "net.connman.iwd.Device", "Adapter"], t)?;
if let Some(adapter) = adapter["data"].as_str() {
busctl(&["set-property", IWD, adapter, "net.connman.iwd.Adapter", "Powered", "b", "true"], t)?;
}
}
busctl(&["set-property", IWD, device, "net.connman.iwd.Device", "Powered", "b", value], t)?;
Ok(())
}
/// Connects and waits until iwd reports the network connected.
/// `passphrase` is needed only for a protected network that isn't saved yet.
pub fn wifi_connect(iface: &str, net: &WifiNetwork, passphrase: Option<&str>) -> Result<()> {
if demo() {
std::thread::sleep(Duration::from_millis(1500));
if passphrase.is_some_and(|p| p == "rosszjelszo") {
bail!("hibás jelszó");
}
with_demo_wifi(|w| {
for n in &mut w.networks {
n.connected = n.path == net.path;
if n.connected && n.known.is_none() && n.security != Security::Open {
n.known = Some(format!("/net/connman/iwd/known/{}", n.name));
}
}
w.networks.sort_by_key(|n| !n.connected);
});
return Ok(());
}
let t = Duration::from_secs(40);
let attempt = match passphrase {
Some(p) => run("iwctl", &["--passphrase", p, "station", iface, "connect", &net.name], t),
None => busctl(&["call", IWD, &net.path, "net.connman.iwd.Network", "Connect"], t).map(|_| String::new()),
};
// iwctl doesn't always exit non-zero on failure: trust iwd's state instead.
let connected = wifi().ok().flatten().is_some_and(|w| w.networks.iter().any(|n| n.connected && n.name == net.name));
if connected {
return Ok(());
}
let detail = match attempt {
Ok(out) => out.trim().to_string(),
Err(e) => format!("{e:#}"),
};
log::warn!("wifi: connecting to {} failed: {detail}", net.name);
if passphrase.is_some() || detail.contains("Failed") || detail.contains("Operation failed") {
bail!("hibás jelszó, vagy a hálózat nem érhető el");
}
bail!("{}", if detail.is_empty() { "a kapcsolat nem jött létre".to_string() } else { detail })
}
pub fn wifi_disconnect(device: &str) -> Result<()> {
if demo() {
with_demo_wifi(|w| w.networks.iter_mut().for_each(|n| n.connected = false));
return Ok(());
}
busctl(&["call", IWD, device, "net.connman.iwd.Station", "Disconnect"], Duration::from_secs(10))?;
Ok(())
}
/// Deletes the saved password (and disconnects if it is the current network).
pub fn wifi_forget(known: &str) -> Result<()> {
if demo() {
with_demo_wifi(|w| {
for n in &mut w.networks {
if n.known.as_deref() == Some(known) {
n.known = None;
n.connected = false;
}
}
});
return Ok(());
}
busctl(&["call", IWD, known, "net.connman.iwd.KnownNetwork", "Forget"], Duration::from_secs(10))?;
Ok(())
}
#[derive(Debug, Clone, Default)]
pub struct DeviceInfo {
pub hostname: String,
pub os: String,
pub kernel: String,
}
pub fn device_info() -> DeviceInfo {
if !cfg!(target_os = "linux") {
return DeviceInfo {
hostname: std::env::var("COMPUTERNAME").unwrap_or_else(|_| "smartfox".into()).to_lowercase(),
os: "Windows (fejlesztői mód)".into(),
kernel: "-".into(),
};
}
let read = |p: &str| std::fs::read_to_string(p).unwrap_or_default().trim().to_string();
let os = read("/etc/os-release")
.lines()
.find_map(|l| l.strip_prefix("PRETTY_NAME=").map(|v| v.trim_matches('"').to_string()))
.unwrap_or_else(|| "Linux".into());
DeviceInfo { hostname: read("/etc/hostname"), os, kernel: read("/proc/sys/kernel/osrelease") }
}
// ---- remote debugging (ssh) ----------------------------------------------
/// The launcher runs as `tv`, so it can't start sshd itself: it writes this
/// flag and sf-remote-debug.path (root) starts or stops ssh.service.
const DEBUG_FLAG: &str = "/var/lib/smartfox/remote-debug";
static DEMO_DEBUG: Mutex<bool> = Mutex::new(false);
#[derive(Debug, Clone, Default, PartialEq)]
pub struct RemoteDebug {
/// sshd is running.
pub on: bool,
/// When it turns off by itself ("21:45"); None without a time limit (VM).
pub until: Option<String>,
}
pub fn remote_debug() -> RemoteDebug {
if demo() {
let on = *DEMO_DEBUG.lock().unwrap();
return RemoteDebug { on, until: on.then(|| "21:45".into()) };
}
let t = Duration::from_secs(2);
// `is-active` exits non-zero unless the unit is active.
let on = run("systemctl", &["is-active", "ssh.service"], t).is_ok();
let until = if on {
run("systemctl", &["show", "sf-remote-debug-off.timer", "--property=NextElapseUSecRealtime", "--value"], t)
.ok()
.and_then(|v| clock(&v))
} else {
None
};
RemoteDebug { on, until }
}
/// "Fri 2026-10-23 21:45:00 CEST" -> "21:45".
fn clock(timestamp: &str) -> Option<String> {
timestamp
.split_whitespace()
.find(|w| w.len() == 8 && w.as_bytes()[2] == b':' && w.as_bytes()[5] == b':')
.map(|w| w[..5].to_string())
}
/// Turns sshd on or off and waits until it has happened.
pub fn set_remote_debug(on: bool) -> Result<()> {
if demo() {
*DEMO_DEBUG.lock().unwrap() = on;
return Ok(());
}
std::fs::write(DEBUG_FLAG, if on { "on\n" } else { "off\n" }).with_context(|| format!("writing {DEBUG_FLAG}"))?;
let deadline = Instant::now() + Duration::from_secs(8);
while Instant::now() < deadline {
if remote_debug().on == on {
return Ok(());
}
std::thread::sleep(Duration::from_millis(250));
}
bail!("ssh.service is still {}", if on { "stopped" } else { "running" })
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_wlr_randr() {
let text = "HDMI-A-1 \"Samsung Electric Company SAMSUNG (HDMI-A-1)\"\n Enabled: yes\n Modes:\n 3840x2160 px, 30.000000 Hz\n 1920x1080 px, 60.000000 Hz (preferred, current)\n 1920x1080 px, 59.940002 Hz\n 3840x2160 px, 60.000000 Hz\n 720x400 px, 70.082001 Hz\n Position: 0,0\n Transform: normal\n Scale: 1.000000\n";
let d = parse_wlr_randr(text).unwrap();
assert_eq!(d.output, "HDMI-A-1");
assert!(d.description.starts_with("Samsung"));
assert_eq!(d.modes.len(), 4);
assert_eq!((d.modes[0].w, d.modes[0].hz), (3840, 60.0));
let cur = d.current_mode().unwrap();
assert_eq!((cur.w, cur.h, cur.preferred), (1920, 1080, true));
assert_eq!(cur.label(), "1920 × 1080 · 60 Hz");
assert_eq!(d.modes[3].label(), "1920 × 1080 · 59.94 Hz");
assert!(cur.matches_key(&cur.key()));
}
#[test]
fn parses_bluetoothctl() {
let list = "\x1b[0;94m[bluetooth]\x1b[0m# Device F0:B3:EC:12:7A:41 Siri Remote\nDevice 4C:87:5D:0E:22:9B AirPods Pro\nnoise";
let devs = parse_device_list(&strip_ansi(list));
assert_eq!(devs.len(), 2);
assert_eq!(devs[0], ("F0:B3:EC:12:7A:41".into(), "Siri Remote".into()));
let info = "Device F0:B3:EC:12:7A:41 (public)\n\tName: Siri Remote\n\tAlias: Nappali távirányító\n\tIcon: input-gaming\n\tConnected: yes\n\tModalias: bluetooth:v004Cp0315d0001\n\tBattery Percentage: 0x52 (82)\n";
let d = parse_info("F0:B3:EC:12:7A:41", "x", info);
assert!(d.remote && d.connected);
assert_eq!(d.battery, Some(82));
assert_eq!(d.name, "Nappali távirányító");
}
#[test]
fn parses_iwd_objects() {
let objects: serde_json::Value = serde_json::from_str(
r#"{
"/net/connman/iwd/0": {"net.connman.iwd.Adapter": {"Powered": {"type":"b","data":true}}},
"/net/connman/iwd/0/4": {
"net.connman.iwd.Device": {"Name": {"type":"s","data":"wlan0"}, "Powered": {"type":"b","data":true}, "Mode": {"type":"s","data":"station"}},
"net.connman.iwd.Station": {"State": {"type":"s","data":"connected"}, "Scanning": {"type":"b","data":false}}
},
"/net/connman/iwd/0/4/4f74686f6e_psk": {"net.connman.iwd.Network": {
"Name": {"type":"s","data":"Otthon"}, "Type": {"type":"s","data":"psk"}, "Connected": {"type":"b","data":true},
"KnownNetwork": {"type":"o","data":"/net/connman/iwd/4f74686f6e_psk"}}},
"/net/connman/iwd/0/4/4b617665_open": {"net.connman.iwd.Network": {
"Name": {"type":"s","data":"Kávé"}, "Type": {"type":"s","data":"open"}, "Connected": {"type":"b","data":false}}}
}"#,
)
.unwrap();
let ordered = vec![
("/net/connman/iwd/0/4/4b617665_open".to_string(), -4500),
("/net/connman/iwd/0/4/4f74686f6e_psk".to_string(), -7000),
];
let w = parse_wifi(&objects, &ordered).unwrap();
assert_eq!((w.iface.as_str(), w.powered, w.device.as_str()), ("wlan0", true, "/net/connman/iwd/0/4"));
assert_eq!(w.networks.len(), 2);
// Connected first, then by signal.
assert_eq!(w.networks[0].name, "Otthon");
assert!(w.networks[0].connected && w.networks[0].known.is_some());
assert_eq!((w.networks[0].signal, w.networks[0].bars()), (-70, 2));
assert_eq!((w.networks[1].security, w.networks[1].bars()), (Security::Open, 4));
assert!(parse_wifi(&serde_json::json!({}), &[]).is_none());
}
#[test]
fn parses_timer_clock() {
assert_eq!(clock("Fri 2026-10-23 21:45:07 CEST\n").as_deref(), Some("21:45"));
assert_eq!(clock(""), None);
}
}

View File

@@ -0,0 +1,109 @@
//! Windows-only helpers for local testing: keep a freshly started app window
//! invisible while the launcher plays its transition, then fade it in.
//! (On the TV the compositor does this.)
use std::time::{Duration, Instant};
use windows_sys::Win32::Foundation::{HWND, LPARAM};
use windows_sys::Win32::UI::WindowsAndMessaging::{
EnumWindows, GW_OWNER, GWL_EXSTYLE, GetWindow, GetWindowLongPtrW, GetWindowTextW, GetWindowThreadProcessId,
IsWindowVisible, LWA_ALPHA, SetForegroundWindow, SetLayeredWindowAttributes, SetWindowLongPtrW, WS_EX_LAYERED,
};
struct Search {
pid: u32,
found: HWND,
}
unsafe extern "system" fn enum_cb(hwnd: HWND, lparam: LPARAM) -> i32 {
let search = unsafe { &mut *(lparam as *mut Search) };
let mut pid = 0u32;
unsafe { GetWindowThreadProcessId(hwnd, &mut pid) };
let top_level = unsafe { GetWindow(hwnd, GW_OWNER) }.is_null();
if pid == search.pid && top_level && unsafe { IsWindowVisible(hwnd) } != 0 {
search.found = hwnd;
return 0; // stop
}
1
}
fn find_window(pid: u32) -> Option<HWND> {
let mut s = Search { pid, found: std::ptr::null_mut() };
unsafe { EnumWindows(Some(enum_cb), &mut s as *mut Search as LPARAM) };
(!s.found.is_null()).then_some(s.found)
}
fn title(hwnd: HWND) -> String {
let mut buf = [0u16; 256];
let n = unsafe { GetWindowTextW(hwnd, buf.as_mut_ptr(), buf.len() as i32) };
String::from_utf16_lossy(&buf[..n.max(0) as usize])
}
fn set_alpha(hwnd: HWND, alpha: u8) {
unsafe {
let ex = GetWindowLongPtrW(hwnd, GWL_EXSTYLE);
if ex & WS_EX_LAYERED as isize == 0 {
SetWindowLongPtrW(hwnd, GWL_EXSTYLE, ex | WS_EX_LAYERED as isize);
}
SetLayeredWindowAttributes(hwnd, 0, alpha, LWA_ALPHA);
}
}
fn clear_layered(hwnd: HWND) {
unsafe {
let ex = GetWindowLongPtrW(hwnd, GWL_EXSTYLE);
SetWindowLongPtrW(hwnd, GWL_EXSTYLE, ex & !(WS_EX_LAYERED as isize));
}
}
/// Hides the app's window as soon as it appears, waits until `not_before`
/// and until the page has a title (or a timeout), then fades it in.
/// Runs on its own thread; `on_shown` is called after the fade.
pub fn reveal_when_ready(pid: u32, not_before: Instant, on_shown: impl FnOnce() + Send + 'static) {
std::thread::spawn(move || {
let start = Instant::now();
let hwnd = loop {
if let Some(h) = find_window(pid) {
set_alpha(h, 0);
break h as usize;
}
if start.elapsed() > Duration::from_secs(20) {
log::warn!("app window for pid {pid} not found");
on_shown();
return;
}
std::thread::sleep(Duration::from_millis(5));
};
let hwnd = hwnd as HWND;
let found_at = Instant::now();
// Wait for the page to load: Chrome app windows take the page title.
loop {
let t = title(hwnd);
let loaded = !t.is_empty() && !t.starts_with("http") && !t.contains("about:blank");
let waited = found_at.elapsed() > Duration::from_millis(3500);
if Instant::now() >= not_before && (loaded || waited) {
break;
}
std::thread::sleep(Duration::from_millis(30));
}
let fade = Duration::from_millis(340);
let t0 = Instant::now();
while t0.elapsed() < fade {
let x = t0.elapsed().as_secs_f32() / fade.as_secs_f32();
let eased = 1.0 - (1.0 - x).powi(3);
set_alpha(hwnd, (eased * 255.0) as u8);
std::thread::sleep(Duration::from_millis(8));
}
set_alpha(hwnd, 255);
clear_layered(hwnd);
unsafe { SetForegroundWindow(hwnd) };
on_shown();
});
}
/// Brings this process's own window back to the front.
pub fn focus_self() {
if let Some(h) = find_window(std::process::id()) {
unsafe { SetForegroundWindow(h) };
}
}

File diff suppressed because it is too large Load Diff

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

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

View File

@@ -0,0 +1,295 @@
// Vector icons (32x32 viewbox). Brand marks are simplified, original drawings.
export component AppIcon inherits Rectangle {
in property <string> icon;
in property <color> ink: #ffffff;
if root.icon == "netflex": Rectangle {
// Netflex mark: mirrored "N" in three ribbons (from netflex/apps/web/public/favicon.svg).
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M7 3h6v26H7z";
fill: @linear-gradient(180deg, #b20710 0%, #831010 100%);
}
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M19 3h6v26h-6z";
fill: @linear-gradient(0deg, #b20710 0%, #831010 100%);
}
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M18.4 3h6.6L13.6 29H7z";
fill: #00000059;
}
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M19 3h6L13 29H7z";
fill: @linear-gradient(35deg, #e50914 0%, #f6303a 100%);
}
}
if root.icon == "youtube": Rectangle {
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M3 11.2C3 8.4 5 6.6 7.8 6.4 11.4 6.1 20.6 6.1 24.2 6.4 27 6.6 29 8.4 29 11.2v9.6c0 2.8-2 4.6-4.8 4.8-3.6.3-12.8.3-16.4 0C5 25.4 3 23.6 3 20.8z";
fill: @linear-gradient(160deg, #ff3b30 0%, #d90d1d 100%);
}
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M13.2 11.6v8.8l7.6-4.4z";
fill: #ffffff;
}
}
if root.icon == "airplay": Rectangle {
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M9.5 22.5H6.5a3 3 0 0 1-3-3V7.5a3 3 0 0 1 3-3h19a3 3 0 0 1 3 3v12a3 3 0 0 1-3 3h-3";
stroke: root.ink;
stroke-width: 2.4px;
stroke-line-cap: round;
}
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M16 18.5l7 9.5H9z";
fill: @linear-gradient(180deg, #8fd0ff 0%, #3d8bff 100%);
}
}
if root.icon == "miracast": Rectangle {
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M6.5 5h19a3 3 0 0 1 3 3v12a3 3 0 0 1-3 3h-19a3 3 0 0 1-3-3V8a3 3 0 0 1 3-3zM11 28h10";
stroke: root.ink;
stroke-width: 2.4px;
stroke-line-cap: round;
}
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M10.5 13.2a8 8 0 0 1 11 0M13.3 16.3a4 4 0 0 1 5.4 0";
stroke: #5ff0d4;
stroke-width: 2.4px;
stroke-line-cap: round;
}
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M14.4 19.4a1.6 1.6 0 1 0 3.2 0a1.6 1.6 0 1 0-3.2 0z";
fill: #5ff0d4;
}
}
if root.icon == "settings": Rectangle {
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M5 10h22M5 22h22";
stroke: root.ink;
stroke-width: 2.4px;
stroke-line-cap: round;
}
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M8.2 10a3.8 3.8 0 1 0 7.6 0a3.8 3.8 0 1 0-7.6 0zM16.2 22a3.8 3.8 0 1 0 7.6 0a3.8 3.8 0 1 0-7.6 0z";
fill: @linear-gradient(180deg, #ffffff 0%, #b9c4d4 100%);
}
}
}
// SmartFox brand mark: a geometric fox head.
export component FoxMark inherits Rectangle {
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M3 5l8 6h10l8-6-2.2 13.5L16 28 5.2 18.5z";
fill: @linear-gradient(150deg, #ffb14a 0%, #ff6a2b 55%, #ff3d6e 100%);
}
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M5.2 18.5L16 15l10.8 3.5L16 28z";
fill: #ffffff2e;
}
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M14 21.5h4L16 24z";
fill: #1b0d08;
}
}
export component WifiIcon inherits Rectangle {
in property <color> ink: #ffffff;
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M4.5 12.5a16.5 16.5 0 0 1 23 0M8.8 16.8a10.4 10.4 0 0 1 14.4 0M13 21a4.3 4.3 0 0 1 6 0";
stroke: root.ink;
stroke-width: 2.2px;
stroke-line-cap: round;
}
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M14.4 25.4a1.6 1.6 0 1 0 3.2 0a1.6 1.6 0 1 0-3.2 0z";
fill: root.ink;
}
}
export component BluetoothIcon inherits Rectangle {
in property <color> ink: #ffffff;
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M9.5 10.5l13 11-6.5 5.5V5l6.5 5.5-13 11";
stroke: root.ink;
stroke-width: 2.2px;
stroke-line-cap: round;
stroke-line-join: round;
}
}
export component PlayIcon inherits Rectangle {
in property <color> ink: #ffffff;
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M9 5.5v21c0 1.2 1.3 1.9 2.3 1.3l16.5-10.5a1.5 1.5 0 0 0 0-2.6L11.3 4.2C10.3 3.6 9 4.3 9 5.5z";
fill: root.ink;
}
}
export component InfoIcon inherits Rectangle {
in property <color> ink: #ffffff;
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M4 16a12 12 0 1 0 24 0a12 12 0 1 0-24 0zM16 14.5v8";
stroke: root.ink;
stroke-width: 2.4px;
stroke-line-cap: round;
}
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M14.4 10a1.6 1.6 0 1 0 3.2 0a1.6 1.6 0 1 0-3.2 0z";
fill: root.ink;
}
}
export component DisplayIcon inherits Rectangle {
in property <color> ink: #ffffff;
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M6.5 6h19a2.5 2.5 0 0 1 2.5 2.5v11a2.5 2.5 0 0 1-2.5 2.5h-19A2.5 2.5 0 0 1 4 19.5v-11A2.5 2.5 0 0 1 6.5 6zM11 27h10";
stroke: root.ink;
stroke-width: 2.2px;
stroke-line-cap: round;
stroke-line-join: round;
}
}
// Wi-Fi strength: `level` arcs (1-4) lit, the rest dimmed.
export component SignalIcon inherits Rectangle {
in property <color> ink: #ffffff;
in property <int> level: 4;
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M4.5 12.5a16.5 16.5 0 0 1 23 0";
stroke: root.level >= 4 ? root.ink : root.ink.transparentize(0.75);
stroke-width: 2.4px;
stroke-line-cap: round;
}
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M8.8 16.8a10.4 10.4 0 0 1 14.4 0";
stroke: root.level >= 3 ? root.ink : root.ink.transparentize(0.75);
stroke-width: 2.4px;
stroke-line-cap: round;
}
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M13 21a4.3 4.3 0 0 1 6 0";
stroke: root.level >= 2 ? root.ink : root.ink.transparentize(0.75);
stroke-width: 2.4px;
stroke-line-cap: round;
}
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M14.4 25.4a1.6 1.6 0 1 0 3.2 0a1.6 1.6 0 1 0-3.2 0z";
fill: root.ink;
}
}
export component LockIcon inherits Rectangle {
in property <color> ink: #ffffff;
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M10.5 14.5v-3.5a5.5 5.5 0 0 1 11 0v3.5";
stroke: root.ink;
stroke-width: 2.4px;
stroke-line-cap: round;
}
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M9 14.5h14a2 2 0 0 1 2 2v8.5a2 2 0 0 1-2 2H9a2 2 0 0 1-2-2v-8.5a2 2 0 0 1 2-2z";
fill: root.ink;
}
}
// Keyboard keys.
export component SpaceIcon inherits Rectangle {
in property <color> ink: #ffffff;
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M5 13.5v5h22v-5";
stroke: root.ink;
stroke-width: 2.4px;
stroke-line-cap: round;
stroke-line-join: round;
}
}
export component DeleteIcon inherits Rectangle {
in property <color> ink: #ffffff;
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M12.5 7.5h13a2.5 2.5 0 0 1 2.5 2.5v12a2.5 2.5 0 0 1-2.5 2.5h-13L4 16zM15.5 12.5l7 7M22.5 12.5l-7 7";
stroke: root.ink;
stroke-width: 2.2px;
stroke-line-cap: round;
stroke-line-join: round;
}
}
export component PowerIcon inherits Rectangle {
in property <color> ink: #ffffff;
Path {
width: 100%; height: 100%;
viewbox-width: 32; viewbox-height: 32;
commands: "M10.3 8.6a10.5 10.5 0 1 0 11.4 0M16 4.5v11";
stroke: root.ink;
stroke-width: 2.4px;
stroke-line-cap: round;
}
}

View File

@@ -0,0 +1,190 @@
// On-screen keyboard in the tvOS style: one horizontal row of characters,
// the text field above it and the mode chips below.
//
// Drawn inside the settings pane, which stays; the settings content fades out.
// Only text and icons are drawn here. The glass (field, key track, focus lens,
// chips) comes from `keyboard::glass` in Rust, which mirrors the geometry the
// App exports (kb-* properties): keep the two in sync.
//
// Key row: index 0 = space, 1..n-2 = characters, n-1 = delete.
import { SpaceIcon, DeleteIcon } from "icons.slint";
export component KeyboardView inherits Rectangle {
in property <length> u;
in property <length> pane-x;
in property <length> pane-y;
in property <length> pane-w;
in property <length> pane-h;
in property <length> back-x;
in property <length> field-x;
in property <length> field-y;
in property <length> field-w;
in property <length> field-h;
in property <length> row-x;
in property <length> row-y;
in property <length> row-h;
in property <length> key-w;
in property <length> chip-x;
in property <length> chip-y;
in property <length> chip-w;
in property <length> chip-h;
in property <length> chip-step;
in property <[string]> keys;
in property <[string]> chips;
in property <int> mode;
in property <float> pos;
in property <float> cpos;
in property <float> keys-active;
in property <float> chips-active;
in property <string> title;
in property <string> subtitle;
in property <string> shown-text;
in property <string> placeholder;
in property <string> hint;
in property <bool> hint-error;
in property <bool> can-submit;
property <int> n: self.keys.length + 2;
// ---- heading ----------------------------------------------------------
Text {
x: root.pane-x;
y: root.pane-y + 58 * root.u;
width: root.pane-w;
horizontal-alignment: center;
text: root.title;
font-family: "Inter Display";
font-weight: 800;
font-size: 46 * root.u;
letter-spacing: -1.2 * root.u;
color: #ffffff;
overflow: elide;
}
Text {
x: root.pane-x + 80 * root.u;
y: root.pane-y + 128 * root.u;
width: root.pane-w - 160 * root.u;
horizontal-alignment: center;
text: root.subtitle;
font-size: 23 * root.u;
color: #ffffffa8;
overflow: elide;
}
// ---- text field ---------------------------------------------------------
Rectangle {
x: root.field-x;
y: root.field-y;
width: root.field-w;
height: root.field-h;
clip: true;
HorizontalLayout {
padding-left: 36 * root.u;
padding-right: 36 * root.u;
alignment: start;
spacing: 4 * root.u;
if root.shown-text == "": Text {
vertical-alignment: center;
text: root.placeholder;
font-size: 32 * root.u;
color: #ffffff59;
}
if root.shown-text != "": Text {
vertical-alignment: center;
text: root.shown-text;
font-size: 34 * root.u;
font-weight: 500;
letter-spacing: 1 * root.u;
color: #ffffff;
}
// Blinking caret.
Rectangle {
width: 3 * root.u;
Rectangle {
y: (parent.height - self.height) / 2;
width: 100%;
height: 44 * root.u;
border-radius: self.width / 2;
background: #ff9a5c;
opacity: mod(animation-tick() / 1000ms, 1) < 0.55 ? 1 : 0;
}
}
}
}
Text {
x: root.field-x;
y: root.field-y + root.field-h + 18 * root.u;
width: root.field-w;
horizontal-alignment: center;
text: root.hint;
font-size: 21 * root.u;
color: root.hint-error ? #ff8278 : #ffffff8c;
}
// ---- key row ---------------------------------------------------------------
// Keys grow as the focus lens passes them (fish-eye), like on tvOS.
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 * root.u;
y: root.row-y;
width: root.key-w + 40 * root.u;
height: root.row-h;
horizontal-alignment: center;
vertical-alignment: center;
text: key;
font-size: (31 + 17 * self.f) * root.u;
font-weight: self.f > 0.5 ? 700 : 500;
color: self.f > 0.5 ? #121317 : #ffffffd8;
}
SpaceIcon {
property <float> f: max(0, 1 - abs(root.pos)) * root.keys-active;
property <length> size: (30 + 10 * self.f) * root.u;
x: root.row-x + (root.key-w - self.size) / 2;
y: root.row-y + (root.row-h - self.size) / 2;
width: self.size;
height: self.size;
ink: self.f > 0.5 ? #121317 : #ffffffd8;
}
DeleteIcon {
property <float> f: max(0, 1 - abs(root.pos - (root.n - 1))) * root.keys-active;
property <length> size: (32 + 10 * self.f) * root.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;
width: self.size;
height: self.size;
ink: self.f > 0.5 ? #121317 : #ffffffd8;
}
// ---- mode and action 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 * root.u;
font-weight: self.submit || self.selected ? 700 : 500;
color: self.submit
? (root.can-submit ? #ffffff : #ffffff66)
: self.f > 0.5 ? #121317 : self.selected ? #ff9a5c : #ffffffc8;
}
Text {
x: root.back-x;
y: root.pane-y + root.pane-h - 92 * root.u;
width: 300 * root.u;
height: 56 * root.u;
horizontal-alignment: center;
vertical-alignment: center;
text: "‹ Mégse · Vissza";
font-size: 21 * root.u;
font-weight: 500;
color: #ffffffc0;
}
}

View File

@@ -0,0 +1,318 @@
// First-run pairing guide for the Apple Siri Remote. The frosted pane behind
// it is drawn by the glass layer (see `glass-over` in app.slint).
// Pulsing ring that draws the eye to a button.
component Pulse inherits Rectangle {
in property <length> size;
in property <color> tint;
in property <duration> delay;
property <float> phase: mod((animation-tick() + root.delay) / 1400ms, 1);
width: self.size * (1 + 0.9 * self.phase);
height: self.width;
border-radius: self.width / 2;
border-width: 3px;
border-color: root.tint.with-alpha(0.9 * (1 - self.phase));
background: root.tint.with-alpha(0.18 * (1 - self.phase));
}
component RemoteButton inherits Rectangle {
in property <length> u;
in property <string> glyph;
in property <bool> hot;
in property <color> accent;
width: 52 * self.u;
height: self.width;
border-radius: self.width / 2;
background: self.hot ? #2a2a2e : #1b1b1d;
drop-shadow-blur: 3 * self.u;
drop-shadow-color: #00000080;
drop-shadow-offset-y: 1 * self.u;
if root.hot: Pulse {
size: root.width;
tint: root.accent;
x: (parent.width - self.width) / 2;
y: (parent.height - self.height) / 2;
}
if root.hot: Pulse {
size: root.width;
tint: root.accent;
delay: 700ms;
x: (parent.width - self.width) / 2;
y: (parent.height - self.height) / 2;
}
Text {
text: root.glyph;
color: root.hot ? root.accent.brighter(0.5) : #e8e8ea;
font-size: 24 * root.u;
font-weight: 600;
horizontal-alignment: center;
vertical-alignment: center;
}
}
// Apple Siri Remote (2nd gen, aluminium), drawn front-on.
export component SiriRemote inherits Rectangle {
in property <length> u;
in property <color> accent;
width: 150 * self.u;
height: 560 * self.u;
border-radius: 44 * self.u;
background: @linear-gradient(90deg, #8d929a 0%, #d9dde2 22%, #f1f3f5 45%, #c6cad0 75%, #959aa2 100%);
drop-shadow-blur: 30 * self.u;
drop-shadow-color: #000000a0;
drop-shadow-offset-y: 16 * self.u;
// Siri button on the right edge.
Rectangle {
x: parent.width - 2 * root.u;
y: 200 * root.u;
width: 5 * root.u;
height: 46 * root.u;
border-radius: 2 * root.u;
background: #8b9097;
}
// Power button.
Rectangle {
x: parent.width - 34 * root.u;
y: 16 * root.u;
width: 18 * root.u;
height: 18 * root.u;
border-radius: self.width / 2;
background: #1b1b1d;
Text {
text: "⏻";
color: #d0d0d4;
font-size: 11 * root.u;
horizontal-alignment: center;
vertical-alignment: center;
}
}
// Clickpad: outer touch ring and center.
Rectangle {
x: (parent.width - self.width) / 2;
y: 44 * root.u;
width: 128 * root.u;
height: self.width;
border-radius: self.width / 2;
background: @radial-gradient(circle, #2b2c30 0%, #1a1b1d 100%);
Rectangle {
x: (parent.width - self.width) / 2;
y: (parent.height - self.height) / 2;
width: 64 * root.u;
height: self.width;
border-radius: self.width / 2;
background: #232427;
border-width: 1px;
border-color: #ffffff14;
}
for d in [{ x: 0.5, y: 0.1 }, { x: 0.5, y: 0.9 }, { x: 0.1, y: 0.5 }, { x: 0.9, y: 0.5 }]: Rectangle {
x: parent.width * d.x - 2.5 * root.u;
y: parent.height * d.y - 2.5 * root.u;
width: 5 * root.u;
height: self.width;
border-radius: self.width / 2;
background: #ffffff60;
}
}
// Button grid below the clickpad.
property <length> col1: 18 * root.u;
property <length> col2: root.width - 18 * root.u - 52 * root.u;
RemoteButton { u: root.u; accent: root.accent; x: root.col1; y: 200 * root.u; glyph: "‹"; hot: true; }
RemoteButton { u: root.u; accent: root.accent; x: root.col2; y: 200 * root.u; glyph: "▭"; }
RemoteButton { u: root.u; accent: root.accent; x: root.col1; y: 268 * root.u; glyph: "⏯"; }
RemoteButton { u: root.u; accent: root.accent; x: root.col1; y: 336 * root.u; glyph: "🔇"; }
// Volume rocker: + is the one to hold.
Rectangle {
x: root.col2;
y: 268 * root.u;
width: 52 * root.u;
height: 120 * root.u;
border-radius: self.width / 2;
background: #1b1b1d;
RemoteButton {
u: root.u;
accent: root.accent;
x: 0;
y: 0;
glyph: "+";
hot: true;
background: transparent;
}
Text {
y: parent.height - 52 * root.u;
width: parent.width;
height: 52 * root.u;
text: "−";
color: #e8e8ea;
font-size: 24 * root.u;
horizontal-alignment: center;
vertical-alignment: center;
}
}
}
component Step inherits Rectangle {
in property <length> u;
in property <int> n;
in property <string> label;
in property <color> accent;
height: 70 * self.u;
Rectangle {
x: 0;
y: 4 * root.u;
width: 40 * root.u;
height: self.width;
// The glass bead behind the number is drawn by the glass layer (app.slint).
Text {
text: root.n;
color: root.accent.brighter(0.6);
font-size: 20 * root.u;
font-weight: 700;
horizontal-alignment: center;
vertical-alignment: center;
}
}
Text {
x: 60 * root.u;
y: 10 * root.u;
width: parent.width - 60 * root.u;
text: root.label;
wrap: word-wrap;
font-size: 24 * root.u;
color: #ffffffd8;
}
}
// Pane content; `state` is the remote status from sf-remote.
export component PairingGuide inherits Rectangle {
in property <length> u;
in property <string> state;
in property <color> accent: #ff7a35;
property <bool> ok: self.state == "paired" || self.state == "connected";
property <bool> broken: self.state == "no-adapter";
SiriRemote {
u: root.u;
accent: root.accent;
x: 120 * root.u;
y: (parent.height - self.height) / 2;
}
Rectangle {
x: 420 * root.u;
y: 70 * root.u;
width: parent.width - 420 * root.u - 80 * root.u;
height: parent.height - 140 * root.u;
Text {
x: 0;
y: 0;
text: "ELSŐ LÉPÉS";
font-size: 20 * root.u;
font-weight: 600;
letter-spacing: 3 * root.u;
color: root.accent.brighter(0.3);
}
Text {
x: 0;
y: 34 * root.u;
width: parent.width;
text: "Párosítsd a Siri Remote-ot";
wrap: word-wrap;
font-family: "Inter Display";
font-weight: 800;
font-size: 58 * root.u;
letter-spacing: -1.6 * root.u;
color: #ffffff;
}
Step {
u: root.u;
accent: root.accent;
x: 0;
y: 150 * root.u;
width: parent.width;
n: 1;
label: "Vidd a távirányítót a TV közelébe.";
}
Step {
u: root.u;
accent: root.accent;
x: 0;
y: 226 * root.u;
width: parent.width;
n: 2;
label: "Tartsd nyomva egyszerre a Vissza (‹) és a Hangerő + gombot kb. 5 másodpercig.";
}
Step {
u: root.u;
accent: root.accent;
x: 0;
y: 330 * root.u;
width: parent.width;
n: 3;
label: "Engedd el. A TV magától megtalálja és párosítja.";
}
// Live status.
Rectangle {
x: 0;
y: parent.height - 70 * root.u;
width: 520 * root.u;
height: 64 * root.u;
// Glass pill (tinted by state) is drawn by the glass layer (app.slint).
// Searching: three breathing dots. Done: check mark. Error: "!".
if !root.ok && !root.broken: HorizontalLayout {
x: 26 * root.u;
width: 60 * root.u;
spacing: 8 * root.u;
alignment: start;
for i in 3: Rectangle {
property <float> p: mod((animation-tick() + i * 180ms) / 900ms, 1);
y: (parent.height - self.height) / 2;
width: 10 * root.u;
height: self.width;
border-radius: self.width / 2;
background: root.accent.brighter(0.4);
opacity: 0.25 + 0.75 * abs(sin(self.p * 180deg));
}
}
if root.ok || root.broken: Text {
x: 26 * root.u;
width: 40 * root.u;
height: parent.height;
text: root.ok ? "✓" : "!";
color: root.ok ? #34c759 : #ff9f0a;
font-size: 30 * root.u;
font-weight: 800;
vertical-alignment: center;
}
Text {
x: 92 * root.u;
width: parent.width - 110 * root.u;
height: parent.height;
vertical-alignment: center;
font-size: 24 * root.u;
font-weight: 500;
color: #ffffff;
text: root.ok ? "Sikeres párosítás!"
: root.broken ? "Nem található Bluetooth adapter"
: root.state == "pairing" ? "Párosítás…"
: "Távirányító keresése…";
}
}
Text {
x: 556 * root.u;
y: parent.height - 68 * root.u;
width: 204 * root.u;
height: 60 * root.u;
horizontal-alignment: center;
vertical-alignment: center;
text: "Kihagyás · Esc";
font-size: 21 * root.u;
font-weight: 500;
color: #ffffffc0;
}
}
}

View File

@@ -0,0 +1,210 @@
// Settings screen: categories on the left, rows on the right.
//
// Only text and icons are drawn here. The glass (pane, rows, chips) comes from
// `settings_screen::glass` in Rust, which mirrors the geometry below: keep the
// row/nav formulas (position, focus `f`, visibility `vis`) in sync with it.
import { WifiIcon, BluetoothIcon, InfoIcon, DisplayIcon, PowerIcon, SignalIcon, LockIcon } from "icons.slint";
export struct SettingRow {
title: string,
value: string,
detail: string,
// info | choice | device | action | danger | option | network
kind: string,
// network rows: signal bars (1-4) and a lock for protected networks
level: int,
lock: bool,
}
component NavIcon inherits Rectangle {
in property <int> index;
in property <color> ink;
if root.index == 0: DisplayIcon { width: 100%; height: 100%; ink: root.ink; }
if root.index == 1: BluetoothIcon { width: 100%; height: 100%; ink: root.ink; }
if root.index == 2: WifiIcon { width: 100%; height: 100%; ink: root.ink; }
if root.index == 3: PowerIcon { width: 100%; height: 100%; ink: root.ink; }
if root.index == 4: InfoIcon { width: 100%; height: 100%; ink: root.ink; }
}
export component SettingsView inherits Rectangle {
in property <length> u;
in property <length> pane-x;
in property <length> pane-y;
in property <length> pane-h;
in property <length> nav-x;
in property <length> nav-y;
in property <length> nav-w;
in property <length> nav-h;
in property <length> nav-step;
in property <length> rows-x;
in property <length> rows-y;
in property <length> rows-w;
in property <length> row-h;
in property <length> row-step;
in property <length> rows-view-h;
in property <length> rows-scroll;
in property <float> nav-pos;
in property <float> nav-active;
in property <float> row-pos;
in property <float> content-active;
in property <string> title;
in property <string> subtitle;
in property <[SettingRow]> rows;
in property <[string]> categories;
// ---- left column ----------------------------------------------------
Text {
x: root.nav-x + 8 * root.u;
y: root.pane-y + 50 * root.u;
text: "Beállítások";
font-family: "Inter Display";
font-weight: 800;
font-size: 50 * root.u;
letter-spacing: -1.5 * root.u;
color: #ffffff;
}
for name[i] in root.categories: Rectangle {
property <float> f: max(0, 1 - abs(root.nav-pos - i)) * root.nav-active;
property <float> sel: max(0, 1 - abs(root.nav-pos - i));
property <color> ink: self.f > 0.5 ? #121317 : #ffffff.with-alpha(0.72 + 0.28 * self.sel);
x: root.nav-x;
y: root.nav-y + i * root.nav-step;
width: root.nav-w;
height: root.nav-h;
NavIcon {
x: 28 * root.u;
y: (parent.height - self.height) / 2;
width: 34 * root.u;
height: 34 * root.u;
index: i;
ink: parent.ink;
}
Text {
x: 82 * root.u;
width: parent.width - 100 * root.u;
height: parent.height;
vertical-alignment: center;
text: name;
font-size: 26 * root.u;
font-weight: 600;
color: parent.ink;
overflow: elide;
}
}
Text {
x: root.nav-x;
y: root.pane-y + root.pane-h - 92 * root.u;
width: 300 * root.u;
height: 56 * root.u;
horizontal-alignment: center;
vertical-alignment: center;
text: "‹ Vissza · Esc";
font-size: 21 * root.u;
font-weight: 500;
color: #ffffffc0;
}
// ---- right column ---------------------------------------------------
Text {
x: root.rows-x + 8 * root.u;
y: root.pane-y + 44 * root.u;
width: root.rows-w - 16 * root.u;
text: root.title;
font-family: "Inter Display";
font-weight: 800;
font-size: 40 * root.u;
letter-spacing: -1 * root.u;
color: #ffffff;
overflow: elide;
}
Text {
x: root.rows-x + 8 * root.u;
y: root.pane-y + 102 * root.u;
width: root.rows-w - 16 * root.u;
height: 64 * root.u;
text: root.subtitle;
wrap: word-wrap;
overflow: elide;
font-size: 21 * root.u;
color: #ffffffa8;
}
for row[j] in root.rows: r := Rectangle {
property <float> f: max(0, 1 - abs(root.row-pos - j)) * root.content-active;
property <length> top: root.rows-y + j * root.row-step - root.rows-scroll;
property <float> over: max(root.rows-y - self.top, self.top + root.row-h - (root.rows-y + root.rows-view-h)) / root.row-h;
property <float> vis: clamp(1 - self.over, 0, 1);
property <bool> hot: self.f > 0.5;
property <bool> danger: row.kind == "danger";
property <color> ink: self.hot ? (self.danger ? #ffffff : #121317) : (self.danger ? #ff8278 : #ffffff);
property <color> ink-dim: self.hot ? (self.danger ? #ffffffd0 : #121317b0) : #ffffff99;
property <bool> chevron: row.kind == "choice" || row.kind == "device";
property <bool> network: row.kind == "network";
x: root.rows-x;
y: self.top;
width: root.rows-w;
height: root.row-h;
opacity: self.vis;
visible: self.vis > 0.01;
Text {
x: 30 * root.u;
y: row.detail == "" ? (parent.height - self.height) / 2 : 15 * root.u;
width: parent.width * 0.55;
text: row.title;
font-size: 26 * root.u;
font-weight: 600;
color: r.ink;
overflow: elide;
}
if row.detail != "": Text {
x: 30 * root.u;
y: 51 * root.u;
width: parent.width * 0.55;
text: row.detail;
font-size: 19 * root.u;
color: r.ink-dim;
overflow: elide;
}
Text {
x: parent.width * 0.4;
width: parent.width * 0.6 - (r.network ? 124 : r.chevron ? 64 : 32) * root.u;
height: parent.height;
horizontal-alignment: right;
vertical-alignment: center;
text: row.value;
font-size: row.kind == "option" ? 30 * root.u : 23 * root.u;
font-weight: row.kind == "option" ? 700 : 400;
color: row.kind == "option" ? (r.hot ? #121317 : #ff9a5c) : r.ink-dim;
overflow: elide;
}
if r.chevron: Text {
x: parent.width - 50 * root.u;
width: 24 * root.u;
height: parent.height;
vertical-alignment: center;
text: "›";
font-size: 36 * root.u;
color: r.ink-dim;
}
// Wi-Fi network: lock (protected) and signal strength on the right.
if r.network && row.lock: LockIcon {
x: parent.width - 104 * root.u;
y: (parent.height - self.height) / 2;
width: 24 * root.u;
height: 24 * root.u;
ink: r.ink-dim;
}
if r.network: SignalIcon {
x: parent.width - 66 * root.u;
y: (parent.height - self.height) / 2;
width: 34 * root.u;
height: 34 * root.u;
level: row.level;
ink: r.ink;
}
}
}

View File

@@ -0,0 +1,18 @@
[package]
name = "sf-remote"
description = "SmartFox Apple Siri Remote driver: BLE GATT -> uinput keys + touch gestures"
version.workspace = true
edition.workspace = true
license.workspace = true
[dependencies]
anyhow.workspace = true
log.workspace = true
env_logger.workspace = true
[target.'cfg(target_os = "linux")'.dependencies]
bluer = { version = "0.17", features = ["bluetoothd"] }
tokio = { version = "1", features = ["rt", "macros", "time", "signal", "sync"] }
futures = "0.3"
evdev = { version = "0.13", features = ["tokio"] }
libc = "0.2"

View File

@@ -0,0 +1,85 @@
//! Global hotkeys from physical keyboards. Apps (Chromium) own keyboard focus,
//! so the launcher can't see these; we read evdev directly (without grabbing).
//! F12 -> home
//! Esc held 0.8 s -> home (a short press still means "back" in the app)
use std::collections::HashSet;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use evdev::{EventType, KeyCode};
use crate::link::Link;
const ESC_HOLD: Duration = Duration::from_millis(800);
const OWN_DEVICE: &str = "SmartFox Siri Remote";
pub fn spawn(link: Link) {
std::thread::spawn(move || {
let rt = match tokio::runtime::Builder::new_current_thread().enable_all().build() {
Ok(rt) => rt,
Err(e) => return log::error!("keyboard watcher: {e}"),
};
rt.block_on(watch(link));
});
}
async fn watch(link: Link) {
let watched: Arc<Mutex<HashSet<PathBuf>>> = Arc::default();
let mut rescan = tokio::time::interval(Duration::from_secs(3));
loop {
rescan.tick().await;
link.resend();
for (path, dev) in evdev::enumerate() {
if watched.lock().unwrap().contains(&path) || dev.name() == Some(OWN_DEVICE) {
continue;
}
let is_keyboard = dev
.supported_keys()
.is_some_and(|k| k.contains(KeyCode::KEY_ESC) && k.contains(KeyCode::KEY_F12));
if !is_keyboard {
continue;
}
let Ok(mut stream) = dev.into_event_stream() else { continue };
log::info!("watching keyboard {}", path.display());
watched.lock().unwrap().insert(path.clone());
let (link, watched) = (link.clone(), watched.clone());
tokio::spawn(async move {
// Deadline at which a still-held Esc turns into "home".
let mut esc_deadline: Option<tokio::time::Instant> = None;
loop {
let ev = match esc_deadline {
Some(deadline) => tokio::select! {
ev = stream.next_event() => ev,
_ = tokio::time::sleep_until(deadline) => {
log::info!("Esc held -> home");
esc_deadline = None;
link.home();
continue;
}
},
None => stream.next_event().await,
};
let Ok(ev) = ev else { break };
if ev.event_type() != EventType::KEY {
continue;
}
let (code, value) = (KeyCode::new(ev.code()), ev.value());
if code == KeyCode::KEY_F12 && value == 1 {
log::info!("F12 -> home");
link.home();
} else if code == KeyCode::KEY_ESC {
match value {
1 => esc_deadline = Some(tokio::time::Instant::now() + ESC_HOLD),
0 => esc_deadline = None,
_ => {}
}
}
}
log::info!("keyboard {} gone", path.display());
watched.lock().unwrap().remove(&path);
});
}
}
}

View File

@@ -0,0 +1,160 @@
//! Connection to the launcher's command socket: global `home`, remote status
//! and standby. The launcher answers every command with its standby state
//! (`standby off|screen|suspend <n>`), which we cache here.
use std::io::{BufRead, BufReader, Write};
use std::os::unix::net::UnixStream;
use std::path::PathBuf;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use tokio::sync::watch;
/// Remote states the launcher understands.
pub mod state {
/// No Bluetooth controller present.
pub const NO_ADAPTER: &str = "no-adapter";
/// No paired remote: scanning for one in pairing mode.
pub const SEARCHING: &str = "searching";
/// A remote in pairing mode was found; pairing in progress.
pub const PAIRING: &str = "pairing";
/// Paired but not connected (asleep).
pub const PAIRED: &str = "paired";
pub const CONNECTED: &str = "connected";
}
/// The launcher's standby state.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Standby {
#[default]
Off,
/// Screen off, machine running.
Screen,
/// The launcher wants the machine suspended; the number changes with
/// every request (also when it asks again after a stray wake-up).
Suspend(u64),
}
impl Standby {
pub fn parse(line: &str) -> Option<Standby> {
let mut w = line.split_whitespace();
if w.next()? != "standby" {
return None;
}
match w.next()? {
"off" => Some(Standby::Off),
"screen" => Some(Standby::Screen),
"suspend" => Some(Standby::Suspend(w.next().and_then(|n| n.parse().ok()).unwrap_or(0))),
_ => None,
}
}
pub fn active(self) -> bool {
self != Standby::Off
}
}
#[derive(Clone)]
pub struct Link {
socket: Option<PathBuf>,
status: Arc<Mutex<String>>,
standby: Arc<watch::Sender<Standby>>,
}
impl Link {
pub fn new(socket: Option<PathBuf>) -> Self {
Self { socket, status: Arc::default(), standby: Arc::new(watch::Sender::new(Standby::Off)) }
}
/// Sends one command and reads the launcher's standby reply.
fn send(&self, line: &str) -> bool {
let Some(path) = &self.socket else { return false };
let result = UnixStream::connect(path).and_then(|mut s| {
s.set_read_timeout(Some(Duration::from_millis(500)))?;
s.write_all(format!("{line}\n").as_bytes())?;
let mut reply = String::new();
// An older launcher doesn't answer; the timeout covers that.
let _ = BufReader::new(&s).read_line(&mut reply);
Ok(reply)
});
match result {
Ok(reply) => {
if let Some(state) = Standby::parse(&reply) {
self.standby.send_if_modified(|cur| {
let changed = *cur != state;
if changed {
log::info!("standby: {state:?}");
*cur = state;
}
changed
});
}
true
}
Err(e) => {
log::trace!("launcher socket {}: {e}", path.display());
false
}
}
}
/// Asks the launcher to come to the front. False if it isn't listening.
pub fn home(&self) -> bool {
self.send("home")
}
/// Power button: the launcher toggles standby.
pub fn power(&self) -> Standby {
self.send("power");
self.standby()
}
/// Leave standby.
pub fn wake(&self) {
self.send("wake");
}
/// Last known standby state (refreshed with every command, at least every 3 s).
pub fn standby(&self) -> Standby {
*self.standby.borrow()
}
pub fn watch_standby(&self) -> watch::Receiver<Standby> {
self.standby.subscribe()
}
pub fn status(&self, s: &str) {
let changed = {
let mut cur = self.status.lock().unwrap();
let changed = *cur != s;
*cur = s.to_string();
changed
};
if changed {
log::info!("remote status: {s}");
}
self.send(&format!("remote {s}"));
}
/// Re-sends the last status (the launcher may have restarted).
pub fn resend(&self) {
let s = self.status.lock().unwrap().clone();
if !s.is_empty() {
self.send(&format!("remote {s}"));
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn parses_standby_reply() {
assert_eq!(Standby::parse("standby off\n"), Some(Standby::Off));
assert_eq!(Standby::parse("standby screen"), Some(Standby::Screen));
assert_eq!(Standby::parse("standby suspend 7"), Some(Standby::Suspend(7)));
assert_eq!(Standby::parse(""), None);
assert!(Standby::Screen.active() && !Standby::Off.active());
}
}

View File

@@ -0,0 +1,542 @@
use std::pin::Pin;
use std::sync::{Arc, Mutex};
use std::time::{Duration, Instant};
use anyhow::{Context, Result};
use bluer::{Adapter, AddressType, Device, Uuid};
use evdev::uinput::VirtualDevice;
use evdev::{AttributeSet, EventType, InputEvent, KeyCode};
use futures::{Stream, StreamExt};
use crate::link::{Link, Standby, state};
use crate::protocol::{self, Gestures, Report, Swipe, button};
use crate::wake;
const APPLE: u32 = 0x004C;
/// Known Siri Remote product ids (0x0314/0x0315: 2nd/3rd gen aluminium).
const PRODUCTS: [u32; 3] = [0x0314, 0x0315, 0x0266];
const HID_SERVICE: u16 = 0x1812;
const HID_REPORT: u16 = 0x2A4D;
const REPEAT_DELAY: Duration = Duration::from_millis(450);
const REPEAT_EVERY: Duration = Duration::from_millis(110);
struct Options {
dry_run: bool,
step: i32,
/// Launcher command socket; the TV button sends `home` there instead of a key.
home_socket: Option<std::path::PathBuf>,
}
fn parse_args() -> Options {
let mut o = Options {
dry_run: false,
step: 300,
home_socket: std::env::var_os("SMARTFOX_SOCKET").map(Into::into),
};
let mut args = std::env::args().skip(1);
while let Some(a) = args.next() {
match a.as_str() {
"--dry-run" | "-n" => o.dry_run = true,
"--step" => o.step = args.next().and_then(|v| v.parse().ok()).unwrap_or(o.step),
"--home-socket" => o.home_socket = args.next().map(Into::into),
other => log::warn!("unknown argument {other}"),
}
}
o
}
fn key_for(bit: u16) -> Option<KeyCode> {
Some(match bit {
button::UP => KeyCode::KEY_UP,
button::DOWN => KeyCode::KEY_DOWN,
button::LEFT => KeyCode::KEY_LEFT,
button::RIGHT => KeyCode::KEY_RIGHT,
button::SELECT => KeyCode::KEY_ENTER,
button::BACK => KeyCode::KEY_ESC,
button::HOME => KeyCode::KEY_HOMEPAGE,
button::PLAY_PAUSE => KeyCode::KEY_PLAYPAUSE,
button::VOL_UP => KeyCode::KEY_VOLUMEUP,
button::VOL_DOWN => KeyCode::KEY_VOLUMEDOWN,
button::MUTE => KeyCode::KEY_MUTE,
button::SIRI => KeyCode::KEY_VOICECOMMAND,
// Not KEY_POWER: logind would shut the machine down. The launcher
// handles standby (`power` on its socket), see serve().
button::POWER => return None,
_ => return None,
})
}
fn repeats(bit: u16) -> bool {
matches!(
bit,
button::UP
| button::DOWN
| button::LEFT
| button::RIGHT
| button::VOL_UP
| button::VOL_DOWN
)
}
/// Virtual keyboard (or a logger in --dry-run mode).
struct Keys {
dev: Option<VirtualDevice>,
}
impl Keys {
fn new(dry_run: bool) -> Result<Self> {
if dry_run {
return Ok(Self { dev: None });
}
let mut keys = AttributeSet::<KeyCode>::new();
for (bit, _) in button::ALL {
if let Some(k) = key_for(bit) {
keys.insert(k);
}
}
// Sent when going into standby: pauses playback in the app.
keys.insert(KeyCode::KEY_PAUSECD);
let dev = VirtualDevice::builder()
.context("opening /dev/uinput (is the user in the smartfox group?)")?
.name("SmartFox Siri Remote")
.with_keys(&keys)?
.build()?;
Ok(Self { dev: Some(dev) })
}
fn send(&mut self, key: KeyCode, value: i32) {
log::debug!("key {key:?} {}", ["up", "down", "repeat"][value as usize]);
if let Some(dev) = self.dev.as_mut() {
let ev = InputEvent::new(EventType::KEY.0, key.code(), value);
if let Err(e) = dev.emit(&[ev]) {
log::warn!("uinput: {e}");
}
}
}
fn tap(&mut self, key: KeyCode) {
self.send(key, 1);
self.send(key, 0);
}
}
fn short_uuid(u: Uuid) -> Option<u16> {
let s = u.to_string();
s.ends_with("-0000-1000-8000-00805f9b34fb")
.then(|| u16::from_str_radix(&s[4..8], 16).ok())
.flatten()
}
async fn find_remote(adapter: &Adapter) -> Result<Option<Device>> {
for addr in adapter.device_addresses().await? {
let dev = adapter.device(addr)?;
let Ok(Some(m)) = dev.modalias().await else {
continue;
};
if m.vendor == APPLE
&& PRODUCTS.contains(&m.product)
&& dev.is_paired().await.unwrap_or(false)
{
return Ok(Some(dev));
}
}
Ok(None)
}
type Notify = Pin<Box<dyn Stream<Item = Vec<u8>> + Send>>;
async fn subscribe(dev: &Device) -> Result<Vec<Notify>> {
let mut streams: Vec<Notify> = Vec::new();
for svc in dev.services().await? {
if short_uuid(svc.uuid().await?) != Some(HID_SERVICE) {
continue;
}
for ch in svc.characteristics().await? {
if short_uuid(ch.uuid().await?) != Some(HID_REPORT) || !ch.flags().await?.notify {
continue;
}
log::info!("subscribing to report characteristic {:#06x}", ch.id());
streams.push(Box::pin(ch.notify().await?));
}
}
if streams.is_empty() {
anyhow::bail!("no HID report characteristics visible - is BlueZ's input plugin disabled?");
}
Ok(streams)
}
/// Power toggles standby; in standby any other button just wakes the TV.
fn standby_button(bit: u16, link: &Link, keys: &mut Keys) {
let before = link.standby();
if bit != button::POWER {
log::info!("button in standby -> wake");
link.wake();
return;
}
let after = link.power();
log::info!("power: {before:?} -> {after:?}");
if !before.active() && after.active() {
keys.tap(KeyCode::KEY_PAUSECD);
}
}
/// Puts the machine to sleep whenever the launcher asks for it (a new
/// `standby suspend <n>`). The launcher runs as `tv` and can't do this.
async fn suspend_on_request(link: Link, target: Arc<Mutex<Option<wake::Target>>>) {
let mut rx = link.watch_standby();
let mut done = None;
loop {
let Standby::Suspend(n) = *rx.borrow_and_update() else {
if rx.changed().await.is_err() {
return;
}
continue;
};
if done == Some(n) {
if rx.changed().await.is_err() {
return;
}
continue;
}
done = Some(n);
// Give the screen time to go dark and the app to pause.
tokio::time::sleep(Duration::from_millis(1500)).await;
if link.standby() != Standby::Suspend(n) {
log::info!("suspend {n} cancelled");
continue;
}
let target = *target.lock().unwrap();
let result = tokio::task::spawn_blocking(move || suspend(target)).await;
if let Ok(Err(e)) | Err(e) = result.map_err(anyhow::Error::from) {
log::warn!("suspend: {e:#}");
}
}
}
fn suspend(target: Option<wake::Target>) -> Result<()> {
let n = wake::enable_controller_wakeup();
log::info!("wake: controller wakeup ready ({n} switched on)");
match target {
Some(t) => match wake::allow_remote_wakeup(&t) {
Ok(()) => log::info!("wake: remote may wake the machine"),
Err(e) => log::warn!("wake: {e:#} (only the PC's own button will wake it)"),
},
None => log::warn!("wake: no paired remote known"),
}
log::info!("suspending");
let status = std::process::Command::new("systemctl").arg("suspend").status().context("systemctl suspend")?;
if !status.success() {
anyhow::bail!("systemctl suspend: {status}");
}
Ok(())
}
async fn wake_target(adapter: &Adapter, dev: &Device) -> Option<wake::Target> {
let index = adapter.name().strip_prefix("hci")?.parse().ok()?;
let public = match dev.address_type().await.ok()? {
AddressType::LePublic => true,
AddressType::LeRandom => false,
AddressType::BrEdr => return None,
};
Some(wake::Target { index, addr: dev.address().0, public })
}
/// Handles one connection until the remote disconnects.
async fn serve(dev: &Device, keys: &mut Keys, step: i32, link: &Link) -> Result<()> {
let mut reports = futures::stream::select_all(subscribe(dev).await?);
let mut gestures = Gestures::new(step);
let mut held: u16 = 0;
// Buttons whose press woke (or put to sleep) the TV: their release and
// auto-repeat must not reach the app.
let mut swallowed: u16 = 0;
let mut held_since = Instant::now();
let mut last_repeat = Instant::now();
let mut tick = tokio::time::interval(Duration::from_millis(20));
loop {
tokio::select! {
item = reports.next() => {
let Some(data) = item else { return Ok(()) };
match protocol::parse(&data) {
Report::Buttons(state) => {
let changed = state ^ held;
for (bit, name) in button::ALL {
if changed & bit == 0 { continue; }
let down = state & bit != 0;
log::info!("{name} {}", if down { "pressed" } else { "released" });
if !down && swallowed & bit != 0 {
swallowed &= !bit;
continue;
}
if down && (bit == button::POWER || link.standby().active()) {
swallowed |= bit;
standby_button(bit, link, keys);
continue;
}
if bit == button::HOME && down && link.home() {
continue;
}
if let Some(k) = key_for(bit) { keys.send(k, down as i32); }
}
if state & !held != 0 {
gestures.on_button();
held_since = Instant::now();
}
held = state;
}
Report::Touch(f) => {
log::trace!("touch {:5} {:5} size {:?}{}", f.x, f.y, f.size, if f.released { " released" } else { "" });
if let Some(s) = gestures.on_touch(&f) {
log::info!("swipe {s:?}");
if link.standby().active() {
continue; // a swipe doesn't wake the TV
}
keys.tap(match s {
Swipe::Up => KeyCode::KEY_UP,
Swipe::Down => KeyCode::KEY_DOWN,
Swipe::Left => KeyCode::KEY_LEFT,
Swipe::Right => KeyCode::KEY_RIGHT,
});
}
}
Report::Audio => log::trace!("siri audio packet"),
Report::Unknown(n) => log::debug!("unknown report ({n} bytes): {data:02x?}"),
}
}
_ = tick.tick() => {
// Auto-repeat for held d-pad and volume keys.
if held != 0 && held_since.elapsed() >= REPEAT_DELAY && last_repeat.elapsed() >= REPEAT_EVERY {
last_repeat = Instant::now();
for (bit, _) in button::ALL {
if held & !swallowed & bit != 0 && repeats(bit) {
if let Some(k) = key_for(bit) { keys.send(k, 2); }
}
}
}
}
}
}
}
/// The remote advertises with a rotating private address. The controller's
/// accept list only knows its identity address, so BlueZ's passive
/// auto-connect never sees it. An active scan lets the kernel resolve the
/// address with the bonded IRK; we connect as soon as an advert arrives.
async fn wait_for_advert(adapter: &Adapter, dev: &Device) -> Result<()> {
use bluer::{DeviceEvent, DeviceProperty, DiscoveryFilter, DiscoveryTransport};
adapter
.set_discovery_filter(DiscoveryFilter {
transport: DiscoveryTransport::Le,
duplicate_data: true,
..Default::default()
})
.await?;
let mut discovery = adapter.discover_devices_with_changes().await?;
let mut events = dev.events().await?;
let mut recheck = tokio::time::interval(Duration::from_secs(2));
loop {
tokio::select! {
// A connection may come up between our checks (e.g. a pending Connect()).
_ = recheck.tick() => {
if dev.is_connected().await.unwrap_or(false) {
return Ok(());
}
// Removed in the launcher's settings: go back to pairing.
if !dev.is_paired().await.unwrap_or(false) {
anyhow::bail!("remote {} was unpaired", dev.address());
}
}
ev = events.next() => match ev {
Some(DeviceEvent::PropertyChanged(DeviceProperty::Rssi(rssi))) => {
log::info!("remote advertising (rssi {rssi}), connecting");
return Ok(());
}
Some(DeviceEvent::PropertyChanged(DeviceProperty::Connected(true))) => return Ok(()),
Some(_) => {}
None => anyhow::bail!("device event stream ended"),
},
// Keep the discovery session alive and drained.
_ = discovery.next() => {}
}
}
}
fn is_remote_advert(md: Option<&std::collections::HashMap<u16, Vec<u8>>>, uuids: Option<&std::collections::HashSet<Uuid>>, appearance: Option<u16>) -> bool {
let apple = md.is_some_and(|m| m.contains_key(&(APPLE as u16)));
let hid = uuids.is_some_and(|u| u.iter().any(|u| short_uuid(*u) == Some(HID_SERVICE)));
apple && (hid || appearance == Some(0x03C0))
}
/// Pairing mode: scan until a Siri Remote in pairing mode (Back + Volume Up)
/// shows up and pair it at once. It only advertises for ~0.2 s at a time with a
/// fresh private address, so we react to the first advert.
async fn pair_new(adapter: &Adapter, link: &Link) -> Result<Device> {
use bluer::{AdapterEvent, DiscoveryFilter, DiscoveryTransport};
adapter.set_pairable(true).await?;
adapter
.set_discovery_filter(DiscoveryFilter {
transport: DiscoveryTransport::Le,
duplicate_data: true,
..Default::default()
})
.await?;
let mut events = adapter.discover_devices_with_changes().await?;
link.status(state::SEARCHING);
let mut resend = tokio::time::interval(Duration::from_secs(5));
loop {
let addr = tokio::select! {
ev = events.next() => match ev {
Some(AdapterEvent::DeviceAdded(addr)) => addr,
Some(_) => continue,
None => anyhow::bail!("discovery ended"),
},
_ = resend.tick() => {
// Another paired remote may have appeared meanwhile.
if let Some(dev) = find_remote(adapter).await? {
return Ok(dev);
}
continue;
}
};
let dev = adapter.device(addr)?;
if dev.is_paired().await.unwrap_or(false) {
continue;
}
let md = dev.manufacturer_data().await.ok().flatten();
let uuids = dev.uuids().await.ok().flatten();
let appearance = dev.appearance().await.ok().flatten();
if !is_remote_advert(md.as_ref(), uuids.as_ref(), appearance) {
continue;
}
log::info!("remote in pairing mode: {addr}, pairing");
link.status(state::PAIRING);
match tokio::time::timeout(Duration::from_secs(30), dev.pair()).await {
Ok(Ok(())) => {
dev.set_trusted(true).await?;
log::info!("paired {}", dev.address());
return Ok(dev);
}
Ok(Err(e)) => log::info!("pair attempt failed: {e} (will retry on next advert)"),
Err(_) => log::info!("pair attempt timed out"),
}
link.status(state::SEARCHING);
}
}
async fn connect(adapter: &Adapter, dev: &Device) -> Result<bool> {
if dev.is_connected().await.unwrap_or(false) {
return Ok(true);
}
wait_for_advert(adapter, dev).await?;
if dev.is_connected().await.unwrap_or(false) {
return Ok(true);
}
match tokio::time::timeout(Duration::from_secs(10), dev.connect()).await {
Ok(Ok(())) => Ok(true),
Ok(Err(e)) if e.kind == bluer::ErrorKind::InProgress => {
tokio::time::sleep(Duration::from_secs(2)).await;
Ok(false)
}
Ok(Err(e)) => {
log::debug!("connect: {e}");
Ok(false)
}
Err(_) => {
log::debug!("connect timed out");
Ok(false)
}
}
}
pub fn run() -> Result<()> {
let opts = parse_args();
let link = Link::new(opts.home_socket.clone());
crate::keyboard::spawn(link.clone());
let rt = tokio::runtime::Builder::new_current_thread().enable_all().build()?;
rt.block_on(async move {
let mut keys = Keys::new(opts.dry_run)?;
let target: Arc<Mutex<Option<wake::Target>>> = Arc::default();
tokio::spawn(suspend_on_request(link.clone(), target.clone()));
let session = bluer::Session::new().await?;
// NoInputNoOutput agent that accepts "just works" pairing (registered once bluetoothd is up).
let mut agent = None;
loop {
// Without a controller bluetoothd isn't even running and D-Bus calls just hang.
let has_controller = std::fs::read_dir("/sys/class/bluetooth").is_ok_and(|mut d| d.next().is_some());
let adapter = if has_controller {
tokio::time::timeout(Duration::from_secs(5), session.default_adapter()).await.ok()
} else {
None
};
let adapter = match adapter {
Some(Ok(a)) if a.set_powered(true).await.is_ok() => a,
_ => {
link.status(state::NO_ADAPTER);
tokio::time::sleep(Duration::from_secs(3)).await;
continue;
}
};
if agent.is_none() {
agent = session
.register_agent(bluer::agent::Agent { request_default: true, ..Default::default() })
.await
.ok();
}
let dev = match find_remote(&adapter).await {
Ok(Some(dev)) => dev,
Ok(None) => match pair_new(&adapter, &link).await {
Ok(dev) => dev,
Err(e) => {
log::warn!("pairing: {e:#}");
tokio::time::sleep(Duration::from_secs(2)).await;
continue;
}
},
Err(e) => {
log::warn!("{e:#}");
tokio::time::sleep(Duration::from_secs(2)).await;
continue;
}
};
if !dev.is_connected().await.unwrap_or(false) {
link.status(state::PAIRED);
log::info!("waiting for {} (press any button)", dev.address());
match connect(&adapter, &dev).await {
Ok(true) => {}
Ok(false) => continue,
Err(e) => {
log::warn!("scan: {e:#}");
tokio::time::sleep(Duration::from_secs(2)).await;
continue;
}
}
}
let battery = dev.battery_percentage().await.ok().flatten();
log::info!("connected to {} (battery {:?}%)", dev.address(), battery);
link.status(state::CONNECTED);
// The remote only reconnects when a button is pressed, and that
// press is lost while connecting: after a suspend (or the remote's
// own sleep) the reconnect itself means "wake up".
if link.standby().active() {
log::info!("remote reconnected in standby -> wake");
link.wake();
}
if let Some(t) = wake_target(&adapter, &dev).await {
*target.lock().unwrap() = Some(t);
}
match serve(&dev, &mut keys, opts.step, &link).await {
Ok(()) => log::info!("remote disconnected"),
Err(e) => {
log::warn!("{e:#}");
tokio::time::sleep(Duration::from_secs(2)).await;
}
}
link.status(state::PAIRED);
}
})
}

View File

@@ -0,0 +1,30 @@
#![cfg_attr(not(target_os = "linux"), allow(dead_code))]
//! sf-remote: Apple Siri Remote driver for SmartFox.
//!
//! Subscribes to the remote's HID report characteristics over BlueZ D-Bus
//! (BlueZ's own HID plugin must be disabled, it drops these reports) and
//! turns buttons and touchpad swipes into key presses on a uinput device.
mod protocol;
#[cfg(target_os = "linux")]
mod keyboard;
#[cfg(target_os = "linux")]
mod link;
#[cfg(target_os = "linux")]
mod linux;
#[cfg(target_os = "linux")]
mod wake;
fn main() -> anyhow::Result<()> {
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
#[cfg(target_os = "linux")]
{
linux::run()
}
#[cfg(not(target_os = "linux"))]
{
anyhow::bail!("sf-remote needs Linux (BlueZ + uinput)")
}
}

View File

@@ -0,0 +1,200 @@
//! Siri Remote (2nd gen, Apple 0x004C:0x0315) wire format, reverse engineered
//! from btmon captures (see docs/siri-remote.md).
//!
//! All data arrives as HID Report (0x2A4D) GATT notifications, told apart by length:
//! - 2 bytes: button bitmask (u16 little-endian)
//! - 11 bytes: touchpad frame (~66 Hz while touched)
//! - 99 bytes: Siri microphone audio (not decoded)
/// Button bits (u16 little-endian of the 2-byte report).
pub mod button {
pub const HOME: u16 = 0x0001; // TV / Home
pub const VOL_UP: u16 = 0x0002;
pub const VOL_DOWN: u16 = 0x0004;
pub const SELECT: u16 = 0x0008; // center click
pub const POWER: u16 = 0x0010;
pub const SIRI: u16 = 0x0020;
pub const BACK: u16 = 0x0040;
pub const MUTE: u16 = 0x0080;
pub const PLAY_PAUSE: u16 = 0x0100;
pub const UP: u16 = 0x0200;
pub const RIGHT: u16 = 0x0400;
pub const DOWN: u16 = 0x0800;
pub const LEFT: u16 = 0x1000;
pub const ALL: [(u16, &str); 13] = [
(HOME, "home"),
(VOL_UP, "vol_up"),
(VOL_DOWN, "vol_down"),
(SELECT, "select"),
(POWER, "power"),
(SIRI, "siri"),
(BACK, "back"),
(MUTE, "mute"),
(PLAY_PAUSE, "play_pause"),
(UP, "up"),
(RIGHT, "right"),
(DOWN, "down"),
(LEFT, "left"),
];
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Report {
Buttons(u16),
Touch(TouchFrame),
Audio,
Unknown(usize),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TouchFrame {
/// Device timestamp (wraps), roughly 0.47 ms per unit.
pub stamp: u16,
/// Signed coordinates: +x right, +y up. Roughly -1100..+400 / -1100..+250.
pub x: i16,
pub y: i16,
/// Contact size / pressure-like values.
pub size: [u8; 3],
/// Last frame of a touch (finger lifted).
pub released: bool,
}
fn s12(v: u16) -> i16 {
if v >= 2048 { v as i16 - 4096 } else { v as i16 }
}
pub fn parse(data: &[u8]) -> Report {
match data.len() {
2 => Report::Buttons(u16::from_le_bytes([data[0], data[1]])),
11 => {
let x = s12(data[4] as u16 | ((data[5] as u16 & 0x0f) << 8));
let y = s12((data[5] as u16 >> 4) | ((data[6] as u16) << 4));
let size = [data[7], data[8], data[9]];
Report::Touch(TouchFrame {
stamp: u16::from_le_bytes([data[1], data[2]]),
x,
y,
size,
released: size == [0, 0, 0],
})
}
99 => Report::Audio,
n => Report::Unknown(n),
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Swipe {
Up,
Down,
Left,
Right,
}
/// Turns touch movement into discrete steps, like tvOS: every `step` units of
/// travel along the dominant axis emits one swipe. Touches that end in a
/// button click (ring/center press) are ignored.
pub struct Gestures {
pub step: i32,
origin: Option<(i32, i32)>,
suppressed: bool,
}
impl Default for Gestures {
fn default() -> Self {
Self { step: 300, origin: None, suppressed: false }
}
}
impl Gestures {
pub fn new(step: i32) -> Self {
Self { step, ..Default::default() }
}
/// A button press during a touch means the user is clicking, not swiping.
pub fn on_button(&mut self) {
if self.origin.is_some() {
self.suppressed = true;
}
}
pub fn on_touch(&mut self, f: &TouchFrame) -> Option<Swipe> {
if f.released {
self.origin = None;
self.suppressed = false;
return None;
}
let p = (f.x as i32, f.y as i32);
let Some(o) = self.origin else {
self.origin = Some(p);
return None;
};
if self.suppressed {
return None;
}
let (dx, dy) = (p.0 - o.0, p.1 - o.1);
let swipe = if dx.abs() >= self.step && dx.abs() * 2 > dy.abs() * 3 {
Some(if dx > 0 { Swipe::Right } else { Swipe::Left })
} else if dy.abs() >= self.step && dy.abs() * 2 > dx.abs() * 3 {
Some(if dy > 0 { Swipe::Up } else { Swipe::Down })
} else {
None
};
if swipe.is_some() {
self.origin = Some(p);
}
swipe
}
}
#[cfg(test)]
mod tests {
use super::*;
fn hex(s: &str) -> Vec<u8> {
s.split_whitespace().map(|b| u8::from_str_radix(b, 16).unwrap()).collect()
}
#[test]
fn buttons_from_capture() {
assert_eq!(parse(&hex("00 02")), Report::Buttons(button::UP));
assert_eq!(parse(&hex("08 00")), Report::Buttons(button::SELECT));
assert_eq!(parse(&hex("00 01")), Report::Buttons(button::PLAY_PAUSE));
assert_eq!(parse(&hex("40 00")), Report::Buttons(button::BACK));
assert_eq!(parse(&hex("00 00")), Report::Buttons(0));
}
#[test]
fn touch_from_capture() {
// Swipe left -> right crossing x = 0 (captured 448.406 / 448.452).
let Report::Touch(a) = parse(&hex("32 0c e9 00 ea 9f e8 83 6f 14 84")) else { panic!() };
let Report::Touch(b) = parse(&hex("32 68 e9 00 0b 50 e9 84 6c 13 84")) else { panic!() };
assert_eq!((a.x, b.x), (-22, 11));
assert!(b.y > a.y);
let Report::Touch(end) = parse(&hex("32 00 00 00 28 61 f4 00 00 00 67")) else { panic!() };
assert!(end.released);
}
#[test]
fn swipe_steps() {
let mut g = Gestures::default();
let frame = |x, y| TouchFrame { stamp: 0, x, y, size: [100, 100, 10], released: false };
assert_eq!(g.on_touch(&frame(-900, -500)), None);
assert_eq!(g.on_touch(&frame(-700, -480)), None);
assert_eq!(g.on_touch(&frame(-590, -470)), Some(Swipe::Right));
assert_eq!(g.on_touch(&frame(-300, -460)), None);
assert_eq!(g.on_touch(&frame(-280, -460)), Some(Swipe::Right));
// a button press without a finger on the pad must not swallow the next swipe
g.on_touch(&TouchFrame { released: true, ..frame(0, 0) });
g.on_button();
g.on_touch(&frame(0, 0));
assert_eq!(g.on_touch(&frame(400, 0)), Some(Swipe::Right));
// click during a touch suppresses
g.on_touch(&TouchFrame { released: true, ..frame(0, 0) });
g.on_touch(&frame(0, 0));
g.on_button();
assert_eq!(g.on_touch(&frame(0, 600)), None);
}
}

View File

@@ -0,0 +1,202 @@
//! Waking the machine from suspend with the remote.
//!
//! Two things have to be in place:
//! 1. The Bluetooth controller may wake the system: `power/wakeup = enabled`
//! on its USB device and the ports above it.
//! 2. The kernel keeps scanning for the remote while suspended. It does that
//! for devices on its connect list that carry the "remote wakeup" flag.
//! BlueZ sets both only through its HID plugins, which SmartFox disables
//! (they drop the Siri Remote's reports), so we send the two management
//! commands ourselves: Add Device (auto-connect) and Set Device Flags.
//!
//! The remote advertises with a rotating private address. Without controller
//! side address resolution (kernel "LL privacy") the kernel can't filter for
//! it while suspended and accepts every advert, so other Bluetooth devices
//! nearby may wake the machine too; the launcher puts it back to sleep then.
use std::os::fd::{AsRawFd, FromRawFd, OwnedFd};
use std::path::Path;
use std::time::{Duration, Instant};
use anyhow::{Context, Result, bail};
/// The remote as the kernel knows it.
#[derive(Debug, Clone, Copy)]
pub struct Target {
/// Controller index (hci0 -> 0).
pub index: u16,
/// Address as printed ("10:B9:..." -> [0x10, 0xB9, ...]).
pub addr: [u8; 6],
/// true: LE public identity address, false: LE random (static).
pub public: bool,
}
/// Enables wakeup on every Bluetooth controller's device and its parents
/// (USB device, hub, xHCI). Returns how many files were switched on.
pub fn enable_controller_wakeup() -> usize {
let mut changed = 0;
let Ok(entries) = std::fs::read_dir("/sys/class/bluetooth") else { return 0 };
for e in entries.flatten() {
let name = e.file_name().to_string_lossy().to_string();
if !name.starts_with("hci") || name.contains(':') {
continue;
}
let Ok(dev) = std::fs::canonicalize(e.path().join("device")) else { continue };
for dir in dev.ancestors().take_while(|d| d.starts_with("/sys/devices")) {
changed += enable(&dir.join("power/wakeup")) as usize;
}
}
changed
}
fn enable(file: &Path) -> bool {
match std::fs::read_to_string(file) {
Ok(v) if v.trim() == "disabled" => match std::fs::write(file, "enabled") {
Ok(()) => {
log::info!("wake: enabled {}", file.display());
true
}
Err(e) => {
log::warn!("wake: {}: {e}", file.display());
false
}
},
_ => false,
}
}
// ---- kernel Bluetooth management interface ---------------------------------------
const AF_BLUETOOTH: libc::c_int = 31;
const BTPROTO_HCI: libc::c_int = 1;
const HCI_CHANNEL_CONTROL: u16 = 3;
const HCI_DEV_NONE: u16 = 0xffff;
const MGMT_OP_ADD_DEVICE: u16 = 0x0033;
const MGMT_OP_SET_DEVICE_FLAGS: u16 = 0x0050;
const MGMT_EV_CMD_COMPLETE: u16 = 0x0001;
const MGMT_EV_CMD_STATUS: u16 = 0x0002;
const ADDR_LE_PUBLIC: u8 = 1;
const ADDR_LE_RANDOM: u8 = 2;
/// Add Device action: connect automatically whenever it advertises.
const ACTION_AUTO_CONNECT: u8 = 2;
const DEVICE_FLAG_REMOTE_WAKEUP: u32 = 1;
#[repr(C)]
struct SockaddrHci {
family: libc::sa_family_t,
dev: u16,
channel: u16,
}
struct Mgmt(OwnedFd);
impl Mgmt {
fn open() -> Result<Self> {
// SAFETY: plain socket/bind calls; the fd is owned right away.
unsafe {
let fd = libc::socket(AF_BLUETOOTH, libc::SOCK_RAW | libc::SOCK_CLOEXEC, BTPROTO_HCI);
if fd < 0 {
bail!("mgmt socket: {}", std::io::Error::last_os_error());
}
let fd = OwnedFd::from_raw_fd(fd);
let addr = SockaddrHci { family: AF_BLUETOOTH as _, dev: HCI_DEV_NONE, channel: HCI_CHANNEL_CONTROL };
let len = std::mem::size_of::<SockaddrHci>() as libc::socklen_t;
if libc::bind(fd.as_raw_fd(), &addr as *const _ as *const libc::sockaddr, len) < 0 {
bail!("mgmt bind: {}", std::io::Error::last_os_error());
}
Ok(Mgmt(fd))
}
}
/// Sends a command and waits for its completion; Err on a non-zero status.
fn call(&self, op: u16, index: u16, params: &[u8]) -> Result<()> {
let mut msg = Vec::with_capacity(6 + params.len());
msg.extend_from_slice(&op.to_le_bytes());
msg.extend_from_slice(&index.to_le_bytes());
msg.extend_from_slice(&(params.len() as u16).to_le_bytes());
msg.extend_from_slice(params);
// SAFETY: writing an initialised buffer to our own socket.
let n = unsafe { libc::write(self.0.as_raw_fd(), msg.as_ptr().cast(), msg.len()) };
if n != msg.len() as isize {
bail!("mgmt write: {}", std::io::Error::last_os_error());
}
let deadline = Instant::now() + Duration::from_secs(2);
let mut buf = [0u8; 512];
loop {
let left = deadline.saturating_duration_since(Instant::now());
if left.is_zero() {
bail!("mgmt {op:#06x}: no reply");
}
let mut pfd = libc::pollfd { fd: self.0.as_raw_fd(), events: libc::POLLIN, revents: 0 };
// SAFETY: one valid pollfd.
if unsafe { libc::poll(&mut pfd, 1, left.as_millis() as libc::c_int) } <= 0 {
continue;
}
// SAFETY: reading into our own buffer.
let n = unsafe { libc::read(self.0.as_raw_fd(), buf.as_mut_ptr().cast(), buf.len()) };
if n < 9 {
continue;
}
let ev = u16::from_le_bytes([buf[0], buf[1]]);
let ev_index = u16::from_le_bytes([buf[2], buf[3]]);
let opcode = u16::from_le_bytes([buf[6], buf[7]]);
let status = buf[8];
if (ev == MGMT_EV_CMD_COMPLETE || ev == MGMT_EV_CMD_STATUS) && opcode == op && ev_index == index {
if status != 0 {
bail!("mgmt {op:#06x}: status {status:#04x}{}", status_name(status));
}
return Ok(());
}
}
}
}
fn status_name(status: u8) -> &'static str {
match status {
0x01 => " (unknown command: kernel too old)",
0x0b => " (rejected)",
0x0c => " (not supported)",
0x0d => " (invalid parameters)",
0x11 => " (invalid index)",
_ => "",
}
}
/// mgmt_addr_info: address in little-endian byte order plus its type.
fn addr_info(t: &Target) -> [u8; 7] {
let mut out = [0u8; 7];
for (i, b) in t.addr.iter().rev().enumerate() {
out[i] = *b;
}
out[6] = if t.public { ADDR_LE_PUBLIC } else { ADDR_LE_RANDOM };
out
}
/// Lets the remote wake the machine: on the kernel's connect list, flagged
/// for remote wakeup. Safe to repeat.
pub fn allow_remote_wakeup(t: &Target) -> Result<()> {
let mgmt = Mgmt::open().context("Bluetooth management socket (needs root)")?;
let addr = addr_info(t);
let mut add = addr.to_vec();
add.push(ACTION_AUTO_CONNECT);
mgmt.call(MGMT_OP_ADD_DEVICE, t.index, &add).context("Add Device")?;
let mut flags = addr.to_vec();
flags.extend_from_slice(&DEVICE_FLAG_REMOTE_WAKEUP.to_le_bytes());
mgmt.call(MGMT_OP_SET_DEVICE_FLAGS, t.index, &flags).context("Set Device Flags (remote wakeup)")?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn address_is_little_endian() {
let t = Target { index: 0, addr: [0x10, 0xB9, 0xC4, 0x17, 0xC0, 0x0F], public: true };
assert_eq!(addr_info(&t), [0x0F, 0xC0, 0x17, 0xC4, 0xB9, 0x10, ADDR_LE_PUBLIC]);
}
}