SmartFox: launcher, Siri Remote driver, Debian image and installer
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
24
crates/sf-launcher/Cargo.toml
Normal file
24
crates/sf-launcher/Cargo.toml
Normal 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"] }
|
||||
3
crates/sf-launcher/build.rs
Normal file
3
crates/sf-launcher/build.rs
Normal file
@@ -0,0 +1,3 @@
|
||||
fn main() {
|
||||
slint_build::compile("ui/app.slint").expect("compiling ui/app.slint");
|
||||
}
|
||||
116
crates/sf-launcher/src/devshot.rs
Normal file
116
crates/sf-launcher/src/devshot.rs
Normal 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(())
|
||||
}
|
||||
49
crates/sf-launcher/src/glass/mod.rs
Normal file
49
crates/sf-launcher/src/glass/mod.rs
Normal 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>,
|
||||
}
|
||||
425
crates/sf-launcher/src/glass/renderer.rs
Normal file
425
crates/sf-launcher/src/glass/renderer.rs
Normal 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(), ¶m[..n * 4]);
|
||||
gl.uniform_4_f32_slice(l.glow.as_ref(), &glow_c[..n * 4]);
|
||||
gl.uniform_4_f32_slice(l.tint.as_ref(), &tint[..n * 4]);
|
||||
gl.draw_arrays(glow::TRIANGLE_STRIP, 0, 4);
|
||||
}
|
||||
|
||||
self.restore(saved);
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads the current window framebuffer as top-down RGBA8 (dev snapshots).
|
||||
///
|
||||
/// # Safety
|
||||
/// Must be called with the context current, after Slint has rendered.
|
||||
pub unsafe fn read_pixels(&self, w: u32, h: u32) -> Vec<u8> {
|
||||
let mut buf = vec![0u8; (w * h * 4) as usize];
|
||||
unsafe {
|
||||
self.gl.pixel_store_i32(glow::PACK_ALIGNMENT, 1);
|
||||
self.gl.read_pixels(
|
||||
0,
|
||||
0,
|
||||
w as i32,
|
||||
h as i32,
|
||||
glow::RGBA,
|
||||
glow::UNSIGNED_BYTE,
|
||||
glow::PixelPackData::Slice(Some(&mut buf)),
|
||||
);
|
||||
}
|
||||
let row = (w * 4) as usize;
|
||||
let mut flipped = Vec::with_capacity(buf.len());
|
||||
for y in (0..h as usize).rev() {
|
||||
flipped.extend_from_slice(&buf[y * row..(y + 1) * row]);
|
||||
}
|
||||
flipped
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// Must be called with the context current.
|
||||
pub unsafe fn destroy(&mut self) {
|
||||
unsafe {
|
||||
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)
|
||||
}
|
||||
}
|
||||
384
crates/sf-launcher/src/glass/shaders.rs
Normal file
384
crates/sf-launcher/src/glass/shaders.rs
Normal 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);
|
||||
}
|
||||
"#;
|
||||
106
crates/sf-launcher/src/ipc.rs
Normal file
106
crates/sf-launcher/src/ipc.rs
Normal 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);
|
||||
}
|
||||
}
|
||||
217
crates/sf-launcher/src/keyboard.rs
Normal file
217
crates/sf-launcher/src/keyboard.rs
Normal 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}'));
|
||||
}
|
||||
}
|
||||
560
crates/sf-launcher/src/main.rs
Normal file
560
crates/sf-launcher/src/main.rs
Normal 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(())
|
||||
}
|
||||
298
crates/sf-launcher/src/power.rs
Normal file
298
crates/sf-launcher/src/power.rs
Normal 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);
|
||||
}
|
||||
}
|
||||
187
crates/sf-launcher/src/runtime.rs
Normal file
187
crates/sf-launcher/src/runtime.rs
Normal 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();
|
||||
}
|
||||
1091
crates/sf-launcher/src/settings_screen.rs
Normal file
1091
crates/sf-launcher/src/settings_screen.rs
Normal file
File diff suppressed because it is too large
Load Diff
927
crates/sf-launcher/src/system.rs
Normal file
927
crates/sf-launcher/src/system.rs
Normal 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);
|
||||
}
|
||||
}
|
||||
109
crates/sf-launcher/src/winfade.rs
Normal file
109
crates/sf-launcher/src/winfade.rs
Normal 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) };
|
||||
}
|
||||
}
|
||||
1030
crates/sf-launcher/ui/app.slint
Normal file
1030
crates/sf-launcher/ui/app.slint
Normal file
File diff suppressed because it is too large
Load Diff
BIN
crates/sf-launcher/ui/fonts/Inter-Medium.ttf
Normal file
BIN
crates/sf-launcher/ui/fonts/Inter-Medium.ttf
Normal file
Binary file not shown.
BIN
crates/sf-launcher/ui/fonts/Inter-Regular.ttf
Normal file
BIN
crates/sf-launcher/ui/fonts/Inter-Regular.ttf
Normal file
Binary file not shown.
BIN
crates/sf-launcher/ui/fonts/Inter-SemiBold.ttf
Normal file
BIN
crates/sf-launcher/ui/fonts/Inter-SemiBold.ttf
Normal file
Binary file not shown.
BIN
crates/sf-launcher/ui/fonts/InterDisplay-Bold.ttf
Normal file
BIN
crates/sf-launcher/ui/fonts/InterDisplay-Bold.ttf
Normal file
Binary file not shown.
BIN
crates/sf-launcher/ui/fonts/InterDisplay-ExtraBold.ttf
Normal file
BIN
crates/sf-launcher/ui/fonts/InterDisplay-ExtraBold.ttf
Normal file
Binary file not shown.
92
crates/sf-launcher/ui/fonts/OFL-LICENSE.txt
Normal file
92
crates/sf-launcher/ui/fonts/OFL-LICENSE.txt
Normal 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.
|
||||
295
crates/sf-launcher/ui/icons.slint
Normal file
295
crates/sf-launcher/ui/icons.slint
Normal 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;
|
||||
}
|
||||
}
|
||||
190
crates/sf-launcher/ui/keyboard.slint
Normal file
190
crates/sf-launcher/ui/keyboard.slint
Normal 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;
|
||||
}
|
||||
}
|
||||
318
crates/sf-launcher/ui/pairing.slint
Normal file
318
crates/sf-launcher/ui/pairing.slint
Normal 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
210
crates/sf-launcher/ui/settings.slint
Normal file
210
crates/sf-launcher/ui/settings.slint
Normal 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;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user