Add Store support and unsigned app releases
This commit is contained in:
26
crates/sf-compositor/Cargo.toml
Normal file
26
crates/sf-compositor/Cargo.toml
Normal file
@@ -0,0 +1,26 @@
|
||||
[package]
|
||||
name = "sf-compositor"
|
||||
description = "Fennec OS kiosk Wayland compositor (Smithay): launcher + one full-screen app, animated switching, volume OSD"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
sf-ipc.workspace = true
|
||||
anyhow.workspace = true
|
||||
tracing = "0.1"
|
||||
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
smithay = { version = "0.7", default-features = false, features = [
|
||||
"backend_drm",
|
||||
"backend_gbm",
|
||||
"backend_egl",
|
||||
"backend_libinput",
|
||||
"backend_udev",
|
||||
"backend_session_libseat",
|
||||
"backend_winit",
|
||||
"renderer_gl",
|
||||
"wayland_frontend",
|
||||
"desktop",
|
||||
] }
|
||||
72
crates/sf-compositor/src/control.rs
Normal file
72
crates/sf-compositor/src/control.rs
Normal file
@@ -0,0 +1,72 @@
|
||||
//! Control socket for sf-core. One command per line, one reply line:
|
||||
//! focus launcher | focus <app-id> -> ok
|
||||
//! register <pgid> <app-id> -> ok (windows of that process group belong to the app)
|
||||
//! status -> ok visible=<app|launcher|none> target=<...>
|
||||
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::os::unix::net::UnixListener;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Result;
|
||||
use smithay::reexports::calloop::generic::Generic;
|
||||
use smithay::reexports::calloop::{Interest, LoopHandle, Mode, PostAction};
|
||||
|
||||
use crate::state::{App, Target};
|
||||
|
||||
pub fn listen(handle: &LoopHandle<'static, App>) -> Result<()> {
|
||||
let path = sf_ipc::paths::wm_socket();
|
||||
let _ = std::fs::remove_file(&path);
|
||||
let listener = UnixListener::bind(&path)?;
|
||||
listener.set_nonblocking(true)?;
|
||||
tracing::info!("control socket {}", path.display());
|
||||
handle
|
||||
.insert_source(Generic::new(listener, Interest::READ, Mode::Level), |_, listener, app: &mut App| {
|
||||
while let Ok((stream, _)) = listener.accept() {
|
||||
let _ = stream.set_nonblocking(false);
|
||||
let _ = stream.set_read_timeout(Some(Duration::from_millis(300)));
|
||||
let Ok(mut writer) = stream.try_clone() else { continue };
|
||||
let mut line = String::new();
|
||||
if BufReader::new(stream).read_line(&mut line).is_err() {
|
||||
continue;
|
||||
}
|
||||
let reply = handle_command(app, line.trim());
|
||||
let _ = writeln!(writer, "{reply}");
|
||||
}
|
||||
Ok(PostAction::Continue)
|
||||
})
|
||||
.map_err(|e| anyhow::anyhow!("control source: {e}"))?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn handle_command(app: &mut App, cmd: &str) -> String {
|
||||
let st = &mut app.state;
|
||||
match cmd.split_once(' ') {
|
||||
Some(("focus", "launcher")) => {
|
||||
st.set_target(Target::Launcher);
|
||||
"ok".into()
|
||||
}
|
||||
Some(("focus", id)) if !id.trim().is_empty() => {
|
||||
st.set_target(Target::App(id.trim().to_string()));
|
||||
"ok".into()
|
||||
}
|
||||
Some(("register", rest)) => match rest.trim().split_once(' ') {
|
||||
Some((pgid, id)) if pgid.parse::<i32>().is_ok() && !id.trim().is_empty() => {
|
||||
st.register(pgid.parse().unwrap(), id.trim().to_string());
|
||||
"ok".into()
|
||||
}
|
||||
_ => "err usage: register <pgid> <app-id>".into(),
|
||||
},
|
||||
_ if cmd == "status" => {
|
||||
let visible = match &st.visible {
|
||||
Some(w) => st.app_of_window(w).unwrap_or_else(|| "launcher".into()),
|
||||
None => "none".into(),
|
||||
};
|
||||
let target = match &st.target {
|
||||
Target::Launcher => "launcher".to_string(),
|
||||
Target::App(id) => id.clone(),
|
||||
};
|
||||
format!("ok visible={visible} target={target} windows={} screen={}", st.wins.len(), if st.screen_on { "on" } else { "off" })
|
||||
}
|
||||
_ => format!("err unknown command {cmd:?}"),
|
||||
}
|
||||
}
|
||||
112
crates/sf-compositor/src/main.rs
Normal file
112
crates/sf-compositor/src/main.rs
Normal file
@@ -0,0 +1,112 @@
|
||||
//! sf-compositor: the Fennec OS kiosk Wayland compositor (Smithay).
|
||||
//!
|
||||
//! - Every window is full screen. One is visible: the launcher or the app
|
||||
//! sf-core put in front (`focus <app-id>` on the control socket). Other
|
||||
//! app windows stay mapped but hidden, so a frozen app comes back at once.
|
||||
//! - Switching animates: an app zooms and fades in over the launcher, and
|
||||
//! back out on Home.
|
||||
//! - Volume keys change the PipeWire volume and show an OSD bar; the Home key
|
||||
//! (if it reaches us as a key) is sent to the launcher.
|
||||
//! - wlr-output-management, so `wlr-randr` can list and set display modes
|
||||
//! and turn the screen off (the launcher's display settings and standby).
|
||||
//!
|
||||
//! Usage: `sf-compositor [--winit] -- <startup command>`; exits when the
|
||||
//! startup command exits (like cage).
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
mod control;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod output_mgmt;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod state;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod udev;
|
||||
#[cfg(target_os = "linux")]
|
||||
mod winit;
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
let filter = tracing_subscriber::EnvFilter::try_from_default_env()
|
||||
.unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info,smithay=warn"));
|
||||
tracing_subscriber::fmt().with_env_filter(filter).init();
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
linux_main()
|
||||
}
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
anyhow::bail!("sf-compositor needs Linux (DRM/KMS or a Wayland/X11 session for --winit)")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
fn linux_main() -> anyhow::Result<()> {
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::Context;
|
||||
use smithay::reexports::calloop::EventLoop;
|
||||
use smithay::reexports::calloop::timer::{TimeoutAction, Timer};
|
||||
use smithay::reexports::wayland_server::Display;
|
||||
|
||||
let mut winit = std::env::var_os("WAYLAND_DISPLAY").is_some() || std::env::var_os("DISPLAY").is_some();
|
||||
let mut command: Vec<String> = vec![];
|
||||
let mut args = std::env::args().skip(1);
|
||||
while let Some(a) = args.next() {
|
||||
match a.as_str() {
|
||||
"--winit" => winit = true,
|
||||
"--drm" => winit = false,
|
||||
"--" => {
|
||||
command = args.by_ref().collect();
|
||||
break;
|
||||
}
|
||||
other => command.push(other.to_string()),
|
||||
}
|
||||
}
|
||||
|
||||
let mut event_loop: EventLoop<state::App> = EventLoop::try_new()?;
|
||||
let display: Display<state::State> = Display::new()?;
|
||||
let mut st = state::State::new(&mut event_loop, display)?;
|
||||
let backend = if winit {
|
||||
tracing::info!("backend: winit (nested window)");
|
||||
winit::init(&mut event_loop, &mut st)?
|
||||
} else {
|
||||
tracing::info!("backend: DRM/KMS");
|
||||
udev::init(&mut event_loop, &mut st)?
|
||||
};
|
||||
control::listen(&event_loop.handle()).context("control socket")?;
|
||||
|
||||
// SAFETY-free env setup: done before any thread is spawned by us.
|
||||
unsafe {
|
||||
std::env::set_var("WAYLAND_DISPLAY", &st.socket_name);
|
||||
std::env::set_var("SMARTFOX_WM_SOCKET", sf_ipc::paths::wm_socket());
|
||||
}
|
||||
tracing::info!("WAYLAND_DISPLAY={}", st.socket_name.to_string_lossy());
|
||||
|
||||
let mut app = state::App { state: st, backend };
|
||||
|
||||
if let Some((prog, rest)) = command.split_first() {
|
||||
let mut child = std::process::Command::new(prog)
|
||||
.args(rest)
|
||||
.spawn()
|
||||
.with_context(|| format!("starting {prog}"))?;
|
||||
tracing::info!("started {prog} (pid {})", child.id());
|
||||
event_loop
|
||||
.handle()
|
||||
.insert_source(Timer::from_duration(Duration::from_millis(500)), move |_, _, app: &mut state::App| {
|
||||
match child.try_wait() {
|
||||
Ok(Some(status)) => {
|
||||
tracing::info!("startup command exited ({status}), quitting");
|
||||
app.state.loop_signal.stop();
|
||||
TimeoutAction::Drop
|
||||
}
|
||||
_ => TimeoutAction::ToDuration(Duration::from_millis(500)),
|
||||
}
|
||||
})
|
||||
.map_err(|e| anyhow::anyhow!("timer: {e}"))?;
|
||||
}
|
||||
|
||||
event_loop.run(Some(Duration::from_millis(16)), &mut app, |app| {
|
||||
app.after_dispatch();
|
||||
})?;
|
||||
let _ = std::fs::remove_file(sf_ipc::paths::wm_socket());
|
||||
Ok(())
|
||||
}
|
||||
355
crates/sf-compositor/src/output_mgmt.rs
Normal file
355
crates/sf-compositor/src/output_mgmt.rs
Normal file
@@ -0,0 +1,355 @@
|
||||
//! wlr-output-management (v2), so `wlr-randr` works: it lists the TV's
|
||||
//! modes, sets one, and turns the output off/on (standby).
|
||||
//!
|
||||
//! Changes are not applied here: `apply` queues a `PendingConfig`, and the
|
||||
//! backend applies it after the dispatch (`App::after_dispatch`).
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use smithay::reexports::wayland_protocols_wlr::output_management::v1::server::{
|
||||
zwlr_output_configuration_head_v1::{self, ZwlrOutputConfigurationHeadV1},
|
||||
zwlr_output_configuration_v1::{self, ZwlrOutputConfigurationV1},
|
||||
zwlr_output_head_v1::{self, ZwlrOutputHeadV1},
|
||||
zwlr_output_manager_v1::{self, ZwlrOutputManagerV1},
|
||||
zwlr_output_mode_v1::{self, ZwlrOutputModeV1},
|
||||
};
|
||||
use smithay::reexports::wayland_server::backend::GlobalId;
|
||||
use smithay::reexports::wayland_server::protocol::wl_output;
|
||||
use smithay::reexports::wayland_server::{
|
||||
Client, DataInit, Dispatch, DisplayHandle, GlobalDispatch, New, Resource, WEnum,
|
||||
};
|
||||
|
||||
use crate::state::State;
|
||||
|
||||
const VERSION: u32 = 2;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct ModeInfo {
|
||||
pub width: i32,
|
||||
pub height: i32,
|
||||
/// mHz
|
||||
pub refresh: i32,
|
||||
pub preferred: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Default)]
|
||||
pub struct HeadInfo {
|
||||
pub name: String,
|
||||
pub description: String,
|
||||
pub make: String,
|
||||
pub model: String,
|
||||
pub physical: (i32, i32),
|
||||
pub modes: Vec<ModeInfo>,
|
||||
pub current: Option<usize>,
|
||||
pub enabled: bool,
|
||||
}
|
||||
|
||||
impl HeadInfo {
|
||||
/// From the current output; the backend keeps the mode list in the
|
||||
/// output's user data (`OutputModes`).
|
||||
pub fn from_state(state: &State) -> Option<HeadInfo> {
|
||||
let output = state.output.as_ref()?;
|
||||
let props = output.physical_properties();
|
||||
let modes: Vec<ModeInfo> = output
|
||||
.user_data()
|
||||
.get::<OutputModes>()
|
||||
.map(|m| m.0.lock().unwrap().clone())
|
||||
.unwrap_or_default();
|
||||
let cur = output.current_mode();
|
||||
let current = cur.and_then(|c| {
|
||||
modes.iter().position(|m| m.width == c.size.w && m.height == c.size.h && (m.refresh - c.refresh).abs() < 500)
|
||||
});
|
||||
Some(HeadInfo {
|
||||
name: output.name(),
|
||||
description: format!("{} {} ({})", props.make, props.model, output.name()),
|
||||
make: props.make.clone(),
|
||||
model: props.model.clone(),
|
||||
physical: (props.size.w, props.size.h),
|
||||
modes,
|
||||
current,
|
||||
enabled: state.screen_on,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// Mode list of an output, stored in `Output::user_data()` by the backend.
|
||||
#[derive(Default)]
|
||||
pub struct OutputModes(pub Mutex<Vec<ModeInfo>>);
|
||||
|
||||
/// What a client asked for in one configuration.
|
||||
#[derive(Debug, Default, Clone)]
|
||||
struct Requested {
|
||||
enabled: Option<bool>,
|
||||
mode: Option<ModeInfo>,
|
||||
/// Refresh 0 in a custom mode: any rate.
|
||||
any_refresh: bool,
|
||||
}
|
||||
|
||||
struct ConfigData {
|
||||
serial: u32,
|
||||
req: Requested,
|
||||
used: bool,
|
||||
}
|
||||
|
||||
pub struct PendingConfig {
|
||||
config: ZwlrOutputConfigurationV1,
|
||||
pub enabled: bool,
|
||||
/// Wanted mode; None keeps the current one.
|
||||
pub mode: Option<ModeInfo>,
|
||||
pub any_refresh: bool,
|
||||
pub test_only: bool,
|
||||
}
|
||||
|
||||
impl PendingConfig {
|
||||
pub fn succeeded(&self) {
|
||||
self.config.succeeded();
|
||||
}
|
||||
pub fn failed(&self) {
|
||||
self.config.failed();
|
||||
}
|
||||
}
|
||||
|
||||
struct ManagerEntry {
|
||||
manager: ZwlrOutputManagerV1,
|
||||
head: Option<ZwlrOutputHeadV1>,
|
||||
modes: Vec<ZwlrOutputModeV1>,
|
||||
}
|
||||
|
||||
pub struct OutputMgmtState {
|
||||
_global: GlobalId,
|
||||
managers: Vec<ManagerEntry>,
|
||||
info: Option<HeadInfo>,
|
||||
serial: u32,
|
||||
}
|
||||
|
||||
impl OutputMgmtState {
|
||||
pub fn new(dh: &DisplayHandle) -> Self {
|
||||
let global = dh.create_global::<State, ZwlrOutputManagerV1, _>(VERSION, ());
|
||||
OutputMgmtState { _global: global, managers: vec![], info: None, serial: 1 }
|
||||
}
|
||||
|
||||
/// New output state: resend it to every client if it changed.
|
||||
pub fn update(&mut self, dh: &DisplayHandle, info: Option<HeadInfo>) {
|
||||
if info == self.info {
|
||||
return;
|
||||
}
|
||||
self.info = info;
|
||||
self.serial += 1;
|
||||
for i in 0..self.managers.len() {
|
||||
self.send_heads(dh, i);
|
||||
}
|
||||
}
|
||||
|
||||
fn send_heads(&mut self, dh: &DisplayHandle, i: usize) {
|
||||
let serial = self.serial;
|
||||
let info = self.info.clone();
|
||||
let entry = &mut self.managers[i];
|
||||
// Simplest correct way to change heads and modes: retire the old
|
||||
// objects and announce new ones.
|
||||
for m in entry.modes.drain(..) {
|
||||
m.finished();
|
||||
}
|
||||
if let Some(h) = entry.head.take() {
|
||||
h.finished();
|
||||
}
|
||||
let Ok(client) = dh.get_client(entry.manager.id()) else { return };
|
||||
if let Some(info) = info {
|
||||
let version = entry.manager.version();
|
||||
let Ok(head) = client.create_resource::<ZwlrOutputHeadV1, _, State>(dh, version, ()) else { return };
|
||||
entry.manager.head(&head);
|
||||
head.name(info.name.clone());
|
||||
head.description(info.description.clone());
|
||||
if info.physical.0 > 0 {
|
||||
head.physical_size(info.physical.0, info.physical.1);
|
||||
}
|
||||
for m in &info.modes {
|
||||
let Ok(mode) = client.create_resource::<ZwlrOutputModeV1, _, State>(dh, version, m.clone()) else {
|
||||
continue;
|
||||
};
|
||||
head.mode(&mode);
|
||||
mode.size(m.width, m.height);
|
||||
mode.refresh(m.refresh);
|
||||
if m.preferred {
|
||||
mode.preferred();
|
||||
}
|
||||
entry.modes.push(mode);
|
||||
}
|
||||
head.enabled(i32::from(info.enabled));
|
||||
if info.enabled {
|
||||
if let Some(cur) = info.current.and_then(|c| entry.modes.get(c)) {
|
||||
head.current_mode(cur);
|
||||
}
|
||||
head.position(0, 0);
|
||||
head.transform(wl_output::Transform::Normal);
|
||||
head.scale(1.0);
|
||||
}
|
||||
if version >= 2 {
|
||||
head.make(info.make.clone());
|
||||
head.model(info.model.clone());
|
||||
}
|
||||
entry.head = Some(head);
|
||||
}
|
||||
entry.manager.done(serial);
|
||||
}
|
||||
}
|
||||
|
||||
impl GlobalDispatch<ZwlrOutputManagerV1, ()> for State {
|
||||
fn bind(
|
||||
state: &mut State,
|
||||
dh: &DisplayHandle,
|
||||
_client: &Client,
|
||||
resource: New<ZwlrOutputManagerV1>,
|
||||
_global_data: &(),
|
||||
data_init: &mut DataInit<'_, State>,
|
||||
) {
|
||||
let manager = data_init.init(resource, ());
|
||||
state.output_mgmt.managers.push(ManagerEntry { manager, head: None, modes: vec![] });
|
||||
let i = state.output_mgmt.managers.len() - 1;
|
||||
state.output_mgmt.send_heads(dh, i);
|
||||
}
|
||||
}
|
||||
|
||||
impl Dispatch<ZwlrOutputManagerV1, ()> for State {
|
||||
fn request(
|
||||
state: &mut State,
|
||||
_client: &Client,
|
||||
resource: &ZwlrOutputManagerV1,
|
||||
request: zwlr_output_manager_v1::Request,
|
||||
_data: &(),
|
||||
_dh: &DisplayHandle,
|
||||
data_init: &mut DataInit<'_, State>,
|
||||
) {
|
||||
match request {
|
||||
zwlr_output_manager_v1::Request::CreateConfiguration { id, serial } => {
|
||||
data_init.init(id, Arc::new(Mutex::new(ConfigData { serial, req: Requested::default(), used: false })));
|
||||
}
|
||||
zwlr_output_manager_v1::Request::Stop => {
|
||||
resource.finished();
|
||||
state.output_mgmt.managers.retain(|m| &m.manager != resource);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn destroyed(state: &mut State, _client: smithay::reexports::wayland_server::backend::ClientId, resource: &ZwlrOutputManagerV1, _data: &()) {
|
||||
state.output_mgmt.managers.retain(|m| &m.manager != resource);
|
||||
}
|
||||
}
|
||||
|
||||
impl Dispatch<ZwlrOutputHeadV1, ()> for State {
|
||||
fn request(
|
||||
_state: &mut State,
|
||||
_client: &Client,
|
||||
_resource: &ZwlrOutputHeadV1,
|
||||
_request: zwlr_output_head_v1::Request,
|
||||
_data: &(),
|
||||
_dh: &DisplayHandle,
|
||||
_data_init: &mut DataInit<'_, State>,
|
||||
) {
|
||||
}
|
||||
}
|
||||
|
||||
impl Dispatch<ZwlrOutputModeV1, ModeInfo> for State {
|
||||
fn request(
|
||||
_state: &mut State,
|
||||
_client: &Client,
|
||||
_resource: &ZwlrOutputModeV1,
|
||||
_request: zwlr_output_mode_v1::Request,
|
||||
_data: &ModeInfo,
|
||||
_dh: &DisplayHandle,
|
||||
_data_init: &mut DataInit<'_, State>,
|
||||
) {
|
||||
}
|
||||
}
|
||||
|
||||
type ConfigRef = Arc<Mutex<ConfigData>>;
|
||||
|
||||
impl Dispatch<ZwlrOutputConfigurationV1, ConfigRef> for State {
|
||||
fn request(
|
||||
state: &mut State,
|
||||
_client: &Client,
|
||||
resource: &ZwlrOutputConfigurationV1,
|
||||
request: zwlr_output_configuration_v1::Request,
|
||||
data: &ConfigRef,
|
||||
_dh: &DisplayHandle,
|
||||
data_init: &mut DataInit<'_, State>,
|
||||
) {
|
||||
use zwlr_output_configuration_v1::Request;
|
||||
match request {
|
||||
Request::EnableHead { id, head: _ } => {
|
||||
data.lock().unwrap().req.enabled = Some(true);
|
||||
data_init.init(id, data.clone());
|
||||
}
|
||||
Request::DisableHead { head: _ } => {
|
||||
data.lock().unwrap().req.enabled = Some(false);
|
||||
}
|
||||
Request::Apply | Request::Test => {
|
||||
let test_only = matches!(request, Request::Test);
|
||||
let mut d = data.lock().unwrap();
|
||||
if d.used {
|
||||
resource.post_error(zwlr_output_configuration_v1::Error::AlreadyUsed, "already used");
|
||||
return;
|
||||
}
|
||||
d.used = true;
|
||||
if d.serial != state.output_mgmt.serial {
|
||||
resource.cancelled();
|
||||
return;
|
||||
}
|
||||
state.pending_configs.push(PendingConfig {
|
||||
config: resource.clone(),
|
||||
enabled: d.req.enabled.unwrap_or(true),
|
||||
mode: d.req.mode.clone(),
|
||||
any_refresh: d.req.any_refresh,
|
||||
test_only,
|
||||
});
|
||||
}
|
||||
Request::Destroy => {}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Dispatch<ZwlrOutputConfigurationHeadV1, ConfigRef> for State {
|
||||
fn request(
|
||||
_state: &mut State,
|
||||
_client: &Client,
|
||||
_resource: &ZwlrOutputConfigurationHeadV1,
|
||||
request: zwlr_output_configuration_head_v1::Request,
|
||||
data: &ConfigRef,
|
||||
_dh: &DisplayHandle,
|
||||
_data_init: &mut DataInit<'_, State>,
|
||||
) {
|
||||
use zwlr_output_configuration_head_v1::Request;
|
||||
let mut d = data.lock().unwrap();
|
||||
match request {
|
||||
Request::SetMode { mode } => {
|
||||
if let Some(m) = mode.data::<ModeInfo>() {
|
||||
d.req.mode = Some(m.clone());
|
||||
d.req.any_refresh = false;
|
||||
}
|
||||
}
|
||||
Request::SetCustomMode { width, height, refresh } => {
|
||||
d.req.mode = Some(ModeInfo { width, height, refresh, preferred: false });
|
||||
d.req.any_refresh = refresh == 0;
|
||||
}
|
||||
// One output at 0,0, normal, scale 1: accept and ignore.
|
||||
Request::SetPosition { .. } | Request::SetScale { .. } => {}
|
||||
Request::SetTransform { transform } => {
|
||||
if !matches!(transform, WEnum::Value(wl_output::Transform::Normal)) {
|
||||
tracing::info!("output transform not supported, ignored");
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Picks the mode a client asked for from the available ones.
|
||||
pub fn match_mode<'a>(modes: &'a [ModeInfo], want: &ModeInfo, any_refresh: bool) -> Option<(usize, &'a ModeInfo)> {
|
||||
let same_size = modes.iter().enumerate().filter(|(_, m)| m.width == want.width && m.height == want.height);
|
||||
if any_refresh {
|
||||
same_size.max_by_key(|(_, m)| m.refresh)
|
||||
} else {
|
||||
same_size.min_by_key(|(_, m)| (m.refresh - want.refresh).abs()).filter(|(_, m)| (m.refresh - want.refresh).abs() < 1000)
|
||||
}
|
||||
}
|
||||
962
crates/sf-compositor/src/state.rs
Normal file
962
crates/sf-compositor/src/state.rs
Normal file
@@ -0,0 +1,962 @@
|
||||
//! Compositor state: Wayland protocol handlers, which window is visible,
|
||||
//! the switch animation, the volume OSD and the render element list.
|
||||
|
||||
use std::ffi::OsString;
|
||||
use std::io::Write;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use smithay::backend::input::{Event, InputBackend, InputEvent, KeyState, KeyboardKeyEvent};
|
||||
use smithay::backend::renderer::element::Kind;
|
||||
use smithay::backend::renderer::element::solid::{SolidColorBuffer, SolidColorRenderElement};
|
||||
use smithay::backend::renderer::element::surface::WaylandSurfaceRenderElement;
|
||||
use smithay::backend::renderer::element::utils::RescaleRenderElement;
|
||||
use smithay::backend::renderer::element::AsRenderElements;
|
||||
use smithay::backend::renderer::gles::GlesRenderer;
|
||||
use smithay::backend::renderer::utils::on_commit_buffer_handler;
|
||||
use smithay::backend::session::Session;
|
||||
use smithay::backend::session::libseat::LibSeatSession;
|
||||
use smithay::desktop::{PopupKind, PopupManager, Space, Window, find_popup_root_surface, get_popup_toplevel_coords};
|
||||
use smithay::input::keyboard::{FilterResult, XkbConfig, keysyms};
|
||||
use smithay::input::{Seat, SeatHandler, SeatState};
|
||||
use smithay::output::Output;
|
||||
use smithay::reexports::calloop::generic::Generic;
|
||||
use smithay::reexports::calloop::timer::{TimeoutAction, Timer};
|
||||
use smithay::reexports::calloop::{EventLoop, Interest, LoopHandle, LoopSignal, Mode, PostAction};
|
||||
use smithay::reexports::wayland_protocols::xdg::decoration::zv1::server::zxdg_toplevel_decoration_v1;
|
||||
use smithay::reexports::wayland_protocols::xdg::shell::server::xdg_toplevel;
|
||||
use smithay::reexports::wayland_server::backend::{ClientData, ClientId, DisconnectReason};
|
||||
use smithay::reexports::wayland_server::protocol::{wl_buffer, wl_output, wl_seat, wl_surface::WlSurface};
|
||||
use smithay::reexports::wayland_server::{Client, Display, DisplayHandle, Resource};
|
||||
use smithay::utils::{IsAlive, Logical, Physical, Point, Rectangle, SERIAL_COUNTER, Scale, Serial, Size};
|
||||
use smithay::wayland::buffer::BufferHandler;
|
||||
use smithay::wayland::compositor::{
|
||||
CompositorClientState, CompositorHandler, CompositorState, get_parent, is_sync_subsurface, with_states,
|
||||
};
|
||||
use smithay::wayland::dmabuf::{DmabufGlobal, DmabufHandler, DmabufState, ImportNotifier};
|
||||
use smithay::wayland::output::{OutputHandler, OutputManagerState};
|
||||
use smithay::wayland::selection::SelectionHandler;
|
||||
use smithay::wayland::selection::data_device::{
|
||||
ClientDndGrabHandler, DataDeviceHandler, DataDeviceState, ServerDndGrabHandler, set_data_device_focus,
|
||||
};
|
||||
use smithay::wayland::shell::xdg::decoration::{XdgDecorationHandler, XdgDecorationState};
|
||||
use smithay::wayland::shell::xdg::{
|
||||
PopupSurface, PositionerState, ToplevelSurface, XdgShellHandler, XdgShellState, XdgToplevelSurfaceData,
|
||||
};
|
||||
use smithay::wayland::shm::{ShmHandler, ShmState};
|
||||
use smithay::wayland::socket::ListeningSocketSource;
|
||||
use smithay::wayland::viewporter::ViewporterState;
|
||||
use smithay::{
|
||||
delegate_compositor, delegate_data_device, delegate_dmabuf, delegate_output, delegate_seat, delegate_shm,
|
||||
delegate_viewporter, delegate_xdg_decoration, delegate_xdg_shell,
|
||||
};
|
||||
|
||||
use crate::output_mgmt::{OutputMgmtState, PendingConfig};
|
||||
|
||||
/// App <-> launcher switch: the app fades in (growing a little) over the
|
||||
/// launcher's splash, or fades out (shrinking) over the home screen.
|
||||
const ENTER: Duration = Duration::from_millis(560);
|
||||
const LEAVE: Duration = Duration::from_millis(420);
|
||||
/// The launcher's launch morph (app.slint `launch-t`). An app coming up over
|
||||
/// the launcher waits until the morph has nearly settled.
|
||||
const MORPH: Duration = Duration::from_millis(720);
|
||||
/// A new window's first frames are often blank; give it a moment.
|
||||
const SETTLE: Duration = Duration::from_millis(250);
|
||||
/// Longest wait for a browser window to finish loading its page.
|
||||
const LOAD_TIMEOUT: Duration = Duration::from_secs(4);
|
||||
/// How often a held-back app window is checked again.
|
||||
const HOLD_POLL: Duration = Duration::from_millis(30);
|
||||
const OSD_TIME: Duration = Duration::from_millis(1600);
|
||||
|
||||
/// evdev key codes + 8 (xkb keycodes).
|
||||
const KEY_MUTE: u32 = 113 + 8;
|
||||
const KEY_VOLUMEDOWN: u32 = 114 + 8;
|
||||
const KEY_VOLUMEUP: u32 = 115 + 8;
|
||||
const KEY_HOMEPAGE: u32 = 172 + 8;
|
||||
|
||||
smithay::backend::renderer::element::render_elements! {
|
||||
pub SfElement<=GlesRenderer>;
|
||||
Surface=WaylandSurfaceRenderElement<GlesRenderer>,
|
||||
Scaled=RescaleRenderElement<WaylandSurfaceRenderElement<GlesRenderer>>,
|
||||
Solid=SolidColorRenderElement,
|
||||
}
|
||||
|
||||
/// The event loop data: protocol state plus the display backend.
|
||||
pub struct App {
|
||||
pub state: State,
|
||||
pub backend: Backend,
|
||||
}
|
||||
|
||||
pub enum Backend {
|
||||
Winit(crate::winit::WinitData),
|
||||
Udev(crate::udev::UdevData),
|
||||
}
|
||||
|
||||
impl App {
|
||||
/// Runs after every event loop dispatch.
|
||||
pub fn after_dispatch(&mut self) {
|
||||
// Output configuration requests (wlr-randr) need the backend.
|
||||
for cfg in std::mem::take(&mut self.state.pending_configs) {
|
||||
let result = match &mut self.backend {
|
||||
Backend::Winit(w) => w.apply_config(&mut self.state, &cfg),
|
||||
Backend::Udev(u) => u.apply_config(&mut self.state, &cfg),
|
||||
};
|
||||
match result {
|
||||
Ok(()) => {
|
||||
cfg.succeeded();
|
||||
self.state.output_mgmt_refresh();
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("output configuration failed: {e:#}");
|
||||
cfg.failed();
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Backend::Udev(u) = &mut self.backend {
|
||||
u.kick(&mut self.state);
|
||||
}
|
||||
self.state.space.refresh();
|
||||
self.state.popups.cleanup();
|
||||
let _ = self.state.dh.flush_clients();
|
||||
}
|
||||
}
|
||||
|
||||
/// What sf-core wants on screen.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Target {
|
||||
Launcher,
|
||||
App(String),
|
||||
}
|
||||
|
||||
pub struct Win {
|
||||
pub window: Window,
|
||||
/// The app the client belongs to; None for the launcher (system UI).
|
||||
pub app: Option<String>,
|
||||
pub pid: Option<i32>,
|
||||
/// Has a buffer, can be shown.
|
||||
pub mapped: bool,
|
||||
pub mapped_at: Option<Instant>,
|
||||
pub serial: u64,
|
||||
}
|
||||
|
||||
/// `over` zooms/fades in on top of `under` (entering) or out of it (leaving).
|
||||
pub struct Transition {
|
||||
pub over: Window,
|
||||
pub under: Option<Window>,
|
||||
pub start: Instant,
|
||||
pub duration: Duration,
|
||||
pub entering: bool,
|
||||
}
|
||||
|
||||
pub struct Osd {
|
||||
pub level: f32,
|
||||
pub muted: bool,
|
||||
pub until: Instant,
|
||||
}
|
||||
|
||||
pub struct State {
|
||||
pub dh: DisplayHandle,
|
||||
pub handle: LoopHandle<'static, App>,
|
||||
pub loop_signal: LoopSignal,
|
||||
pub socket_name: OsString,
|
||||
pub start: Instant,
|
||||
|
||||
pub compositor_state: CompositorState,
|
||||
pub xdg_shell_state: XdgShellState,
|
||||
pub shm_state: ShmState,
|
||||
// Kept for their globals.
|
||||
#[allow(dead_code)]
|
||||
pub output_manager_state: OutputManagerState,
|
||||
pub seat_state: SeatState<State>,
|
||||
pub data_device_state: DataDeviceState,
|
||||
pub dmabuf_state: DmabufState,
|
||||
pub dmabuf_global: Option<DmabufGlobal>,
|
||||
#[allow(dead_code)]
|
||||
pub viewporter_state: ViewporterState,
|
||||
#[allow(dead_code)]
|
||||
pub decoration_state: XdgDecorationState,
|
||||
pub output_mgmt: OutputMgmtState,
|
||||
pub pending_configs: Vec<PendingConfig>,
|
||||
pub popups: PopupManager,
|
||||
pub seat: Seat<State>,
|
||||
pub space: Space<Window>,
|
||||
pub session: Option<LibSeatSession>,
|
||||
|
||||
pub output: Option<Output>,
|
||||
pub wins: Vec<Win>,
|
||||
/// Process groups of apps, from sf-core (`register`).
|
||||
pub registered: std::collections::HashMap<i32, String>,
|
||||
serial: u64,
|
||||
pub target: Target,
|
||||
/// When `target` last changed (the launcher starts its morph then).
|
||||
target_at: Instant,
|
||||
/// An app window that could be shown but waits for the launcher's
|
||||
/// morph and for its own first real frame.
|
||||
held: Option<Window>,
|
||||
hold_poll: bool,
|
||||
pub visible: Option<Window>,
|
||||
pub transition: Option<Transition>,
|
||||
pub osd: Option<Osd>,
|
||||
osd_bg: SolidColorBuffer,
|
||||
osd_track: SolidColorBuffer,
|
||||
osd_fill: SolidColorBuffer,
|
||||
/// False while the screen is turned off (wlr-randr --off / standby).
|
||||
pub screen_on: bool,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub struct ClientState {
|
||||
pub compositor_state: CompositorClientState,
|
||||
}
|
||||
|
||||
impl ClientData for ClientState {
|
||||
fn initialized(&self, _client_id: ClientId) {}
|
||||
fn disconnected(&self, _client_id: ClientId, _reason: DisconnectReason) {}
|
||||
}
|
||||
|
||||
/// Process group of a pid (field 5 of /proc/<pid>/stat).
|
||||
fn pgid_of(pid: i32) -> Option<i32> {
|
||||
let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
|
||||
// The command name may contain spaces; fields start after the last ')'.
|
||||
let rest = &stat[stat.rfind(')')? + 1..];
|
||||
rest.split_whitespace().nth(2)?.parse().ok()
|
||||
}
|
||||
|
||||
/// The app a client process belongs to:
|
||||
/// 1. its process group, as registered by sf-core (`register <pgid> <app>`);
|
||||
/// 2. its systemd scope (`sf-app-<id>-<n>.scope`);
|
||||
/// 3. `SMARTFOX_APP` in its environment (Chromium overwrites that area, so
|
||||
/// this only works for simple programs like UxPlay).
|
||||
fn app_of_pid(pid: i32, registered: &std::collections::HashMap<i32, String>) -> Option<String> {
|
||||
if let Some(app) = pgid_of(pid).and_then(|g| registered.get(&g)) {
|
||||
return Some(app.clone());
|
||||
}
|
||||
if let Ok(cg) = std::fs::read_to_string(format!("/proc/{pid}/cgroup")) {
|
||||
for unit in cg.split(['/', '\n']) {
|
||||
if let Some(rest) = unit.strip_prefix("sf-app-").and_then(|u| u.strip_suffix(".scope")) {
|
||||
if let Some((id, _serial)) = rest.rsplit_once('-') {
|
||||
return Some(id.to_string());
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let env = std::fs::read(format!("/proc/{pid}/environ")).ok()?;
|
||||
let key = format!("{}=", sf_ipc::launch::APP_ENV);
|
||||
env.split(|b| *b == 0)
|
||||
.find_map(|kv| kv.strip_prefix(key.as_bytes()))
|
||||
.map(|v| String::from_utf8_lossy(v).into_owned())
|
||||
.filter(|v| !v.is_empty())
|
||||
}
|
||||
|
||||
fn ease_out(t: f32) -> f32 {
|
||||
1.0 - (1.0 - t.clamp(0.0, 1.0)).powi(3)
|
||||
}
|
||||
|
||||
/// Slow start and end: a crossfade you can see, not a cut.
|
||||
fn ease_in_out(t: f32) -> f32 {
|
||||
let t = t.clamp(0.0, 1.0);
|
||||
if t < 0.5 { 4.0 * t * t * t } else { 1.0 - (-2.0 * t + 2.0).powi(3) / 2.0 }
|
||||
}
|
||||
|
||||
/// Whether a window has something worth showing. Browsers show the URL as
|
||||
/// their title until the page has loaded and set its own.
|
||||
fn page_loaded(window: &Window) -> bool {
|
||||
let Some(toplevel) = window.toplevel() else { return true };
|
||||
let (title, app_id) = with_states(toplevel.wl_surface(), |states| {
|
||||
states
|
||||
.data_map
|
||||
.get::<XdgToplevelSurfaceData>()
|
||||
.map(|d| {
|
||||
let d = d.lock().unwrap();
|
||||
(d.title.clone().unwrap_or_default(), d.app_id.clone().unwrap_or_default().to_lowercase())
|
||||
})
|
||||
.unwrap_or_default()
|
||||
});
|
||||
let browser = app_id.contains("chrom") || app_id.contains("edge");
|
||||
let url_like = !title.contains(' ') && (title.contains('/') || title.contains('.') || title.contains(':'));
|
||||
!browser || !(title.is_empty() || title.contains("about:blank") || url_like)
|
||||
}
|
||||
|
||||
impl State {
|
||||
pub fn new(event_loop: &mut EventLoop<'static, App>, display: Display<State>) -> anyhow::Result<Self> {
|
||||
let dh = display.handle();
|
||||
let compositor_state = CompositorState::new::<Self>(&dh);
|
||||
let xdg_shell_state = XdgShellState::new::<Self>(&dh);
|
||||
let shm_state = ShmState::new::<Self>(&dh, vec![]);
|
||||
let output_manager_state = OutputManagerState::new_with_xdg_output::<Self>(&dh);
|
||||
let mut seat_state = SeatState::new();
|
||||
let data_device_state = DataDeviceState::new::<Self>(&dh);
|
||||
let viewporter_state = ViewporterState::new::<Self>(&dh);
|
||||
let decoration_state = XdgDecorationState::new::<Self>(&dh);
|
||||
let output_mgmt = OutputMgmtState::new(&dh);
|
||||
|
||||
let mut seat: Seat<Self> = seat_state.new_wl_seat(&dh, "seat0");
|
||||
// Same repeat as cage/wlroots: 600 ms delay, 25 per second.
|
||||
seat.add_keyboard(XkbConfig::default(), 600, 25)
|
||||
.map_err(|e| anyhow::anyhow!("keyboard: {e:?}"))?;
|
||||
|
||||
let socket = ListeningSocketSource::new_auto()?;
|
||||
let socket_name = socket.socket_name().to_os_string();
|
||||
let handle = event_loop.handle();
|
||||
handle
|
||||
.insert_source(socket, |stream, _, app: &mut App| {
|
||||
if let Err(e) = app.state.dh.insert_client(stream, Arc::new(ClientState::default())) {
|
||||
tracing::warn!("client: {e}");
|
||||
}
|
||||
})
|
||||
.map_err(|e| anyhow::anyhow!("socket source: {e}"))?;
|
||||
handle
|
||||
.insert_source(Generic::new(display, Interest::READ, Mode::Level), |_, display, app: &mut App| {
|
||||
// SAFETY: the display is not dropped while the source lives.
|
||||
unsafe {
|
||||
display.get_mut().dispatch_clients(&mut app.state).ok();
|
||||
}
|
||||
Ok(PostAction::Continue)
|
||||
})
|
||||
.map_err(|e| anyhow::anyhow!("display source: {e}"))?;
|
||||
|
||||
Ok(State {
|
||||
dh,
|
||||
handle,
|
||||
loop_signal: event_loop.get_signal(),
|
||||
socket_name,
|
||||
start: Instant::now(),
|
||||
compositor_state,
|
||||
xdg_shell_state,
|
||||
shm_state,
|
||||
output_manager_state,
|
||||
seat_state,
|
||||
data_device_state,
|
||||
dmabuf_state: DmabufState::new(),
|
||||
dmabuf_global: None,
|
||||
viewporter_state,
|
||||
decoration_state,
|
||||
output_mgmt,
|
||||
pending_configs: vec![],
|
||||
popups: PopupManager::default(),
|
||||
seat,
|
||||
space: Space::default(),
|
||||
session: None,
|
||||
output: None,
|
||||
wins: vec![],
|
||||
registered: Default::default(),
|
||||
serial: 0,
|
||||
target: Target::Launcher,
|
||||
target_at: Instant::now(),
|
||||
held: None,
|
||||
hold_poll: false,
|
||||
visible: None,
|
||||
transition: None,
|
||||
osd: None,
|
||||
osd_bg: SolidColorBuffer::default(),
|
||||
osd_track: SolidColorBuffer::default(),
|
||||
osd_fill: SolidColorBuffer::default(),
|
||||
screen_on: true,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn output_size(&self) -> Size<i32, Physical> {
|
||||
self.output
|
||||
.as_ref()
|
||||
.and_then(|o| o.current_mode())
|
||||
.map(|m| m.size)
|
||||
.unwrap_or_else(|| (1920, 1080).into())
|
||||
}
|
||||
|
||||
/// A new or changed output: everyone gets its size.
|
||||
pub fn set_output(&mut self, output: Option<Output>) {
|
||||
if let Some(old) = self.output.take() {
|
||||
self.space.unmap_output(&old);
|
||||
}
|
||||
if let Some(o) = &output {
|
||||
self.space.map_output(o, (0, 0));
|
||||
}
|
||||
self.output = output;
|
||||
self.reconfigure_all();
|
||||
self.output_mgmt_refresh();
|
||||
}
|
||||
|
||||
pub fn reconfigure_all(&mut self) {
|
||||
let wins: Vec<Window> = self.wins.iter().map(|w| w.window.clone()).collect();
|
||||
for w in wins {
|
||||
self.configure(&w);
|
||||
}
|
||||
}
|
||||
|
||||
/// Full screen at the output size; activated if visible.
|
||||
fn configure(&self, window: &Window) {
|
||||
let Some(toplevel) = window.toplevel() else { return };
|
||||
let size = self.output_size();
|
||||
let active = self.visible.as_ref() == Some(window);
|
||||
toplevel.with_pending_state(|s| {
|
||||
s.size = Some((size.w, size.h).into());
|
||||
s.states.set(xdg_toplevel::State::Fullscreen);
|
||||
if active {
|
||||
s.states.set(xdg_toplevel::State::Activated);
|
||||
} else {
|
||||
s.states.unset(xdg_toplevel::State::Activated);
|
||||
}
|
||||
s.decoration_mode = Some(zxdg_toplevel_decoration_v1::Mode::ServerSide);
|
||||
});
|
||||
if toplevel.is_initial_configure_sent() {
|
||||
toplevel.send_pending_configure();
|
||||
}
|
||||
}
|
||||
|
||||
fn win_of(&self, window: &Window) -> Option<&Win> {
|
||||
self.wins.iter().find(|w| &w.window == window)
|
||||
}
|
||||
|
||||
pub fn app_of_window(&self, window: &Window) -> Option<String> {
|
||||
self.win_of(window).and_then(|w| w.app.clone())
|
||||
}
|
||||
|
||||
fn find_visible(&self) -> Option<Window> {
|
||||
let pick = |pred: &dyn Fn(&Win) -> bool| {
|
||||
self.wins.iter().filter(|w| w.mapped && pred(w)).max_by_key(|w| w.serial).map(|w| w.window.clone())
|
||||
};
|
||||
let launcher = || pick(&|w| w.app.is_none());
|
||||
match &self.target {
|
||||
Target::App(id) => pick(&|w| w.app.as_deref() == Some(id.as_str())).or_else(launcher),
|
||||
Target::Launcher => launcher(),
|
||||
}
|
||||
.or_else(|| pick(&|_| true))
|
||||
}
|
||||
|
||||
/// sf-core started an app in process group `pgid`. Windows that showed
|
||||
/// up before this arrived are reassigned.
|
||||
pub fn register(&mut self, pgid: i32, app: String) {
|
||||
self.registered.retain(|g, _| std::path::Path::new(&format!("/proc/{g}")).exists());
|
||||
self.registered.insert(pgid, app.clone());
|
||||
let mut changed = false;
|
||||
for w in self.wins.iter_mut() {
|
||||
if w.app.is_none() && w.pid.and_then(pgid_of) == Some(pgid) {
|
||||
tracing::info!("window of pid {:?} belongs to {app}", w.pid);
|
||||
w.app = Some(app.clone());
|
||||
changed = true;
|
||||
}
|
||||
}
|
||||
if changed {
|
||||
self.update_visible();
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_target(&mut self, target: Target) {
|
||||
tracing::info!("focus {target:?}");
|
||||
if target != self.target {
|
||||
self.target_at = Instant::now();
|
||||
}
|
||||
self.target = target;
|
||||
self.update_visible();
|
||||
}
|
||||
|
||||
/// Recomputes the visible window; animates the change.
|
||||
pub fn update_visible(&mut self) {
|
||||
let new = self.find_visible();
|
||||
if self.held.is_some() && self.held != new {
|
||||
self.held = None;
|
||||
}
|
||||
if new == self.visible {
|
||||
return;
|
||||
}
|
||||
if let Some(wait) = new.as_ref().and_then(|n| self.reveal_wait(n)) {
|
||||
// Not yet: the launcher's splash stays up (and keeps the focus,
|
||||
// so Back still cancels). The app gets frame callbacks meanwhile.
|
||||
self.held = new;
|
||||
self.poll_held(wait.min(HOLD_POLL));
|
||||
return;
|
||||
}
|
||||
self.held = None;
|
||||
let old = self.visible.take();
|
||||
let to_launcher = new.as_ref().is_some_and(|w| self.app_of_window(w).is_none());
|
||||
let from_app = old.as_ref().is_some_and(|w| self.app_of_window(w).is_some());
|
||||
self.transition = match (&old, &new) {
|
||||
// Home: the app shrinks away, revealing the launcher.
|
||||
(Some(o), Some(n)) if to_launcher && from_app && o.alive() => Some(Transition {
|
||||
over: o.clone(),
|
||||
under: Some(n.clone()),
|
||||
start: Instant::now(),
|
||||
duration: LEAVE,
|
||||
entering: false,
|
||||
}),
|
||||
(o, Some(n)) => Some(Transition {
|
||||
over: n.clone(),
|
||||
under: o.clone().filter(|w| w.alive()),
|
||||
start: Instant::now(),
|
||||
duration: ENTER,
|
||||
entering: true,
|
||||
}),
|
||||
_ => None,
|
||||
};
|
||||
self.visible = new.clone();
|
||||
tracing::info!(
|
||||
"visible: {}",
|
||||
match &new {
|
||||
Some(w) => self.app_of_window(w).unwrap_or_else(|| "launcher".into()),
|
||||
None => "nothing".into(),
|
||||
}
|
||||
);
|
||||
let serial = SERIAL_COUNTER.next_serial();
|
||||
let focus = new.as_ref().and_then(|w| w.toplevel()).map(|t| t.wl_surface().clone());
|
||||
if let Some(kb) = self.seat.get_keyboard() {
|
||||
kb.set_focus(self, focus, serial);
|
||||
}
|
||||
for w in [old, new].into_iter().flatten() {
|
||||
w.set_activated(self.visible.as_ref() == Some(&w));
|
||||
self.configure(&w);
|
||||
}
|
||||
}
|
||||
|
||||
/// How long an app window should stay hidden: until the launcher's morph
|
||||
/// is done (when it comes up over the launcher), it has drawn for a
|
||||
/// moment, and its page has loaded (or that timed out).
|
||||
fn reveal_wait(&self, window: &Window) -> Option<Duration> {
|
||||
let win = self.win_of(window)?;
|
||||
win.app.as_ref()?;
|
||||
let mapped_at = win.mapped_at?;
|
||||
let over_launcher = self.visible.as_ref().is_some_and(|v| self.app_of_window(v).is_none());
|
||||
let mut ready_at = mapped_at + SETTLE;
|
||||
if over_launcher {
|
||||
ready_at = ready_at.max(self.target_at + MORPH);
|
||||
}
|
||||
if !page_loaded(window) {
|
||||
ready_at = ready_at.max(mapped_at + LOAD_TIMEOUT);
|
||||
}
|
||||
let now = Instant::now();
|
||||
(ready_at > now).then(|| ready_at - now)
|
||||
}
|
||||
|
||||
fn poll_held(&mut self, after: Duration) {
|
||||
if self.hold_poll {
|
||||
return;
|
||||
}
|
||||
self.hold_poll = true;
|
||||
let _ = self.handle.insert_source(Timer::from_duration(after), |_, _, app: &mut App| {
|
||||
app.state.hold_poll = false;
|
||||
if app.state.held.is_some() {
|
||||
app.state.update_visible();
|
||||
}
|
||||
TimeoutAction::Drop
|
||||
});
|
||||
}
|
||||
|
||||
fn surface_window(&self, surface: &WlSurface) -> Option<Window> {
|
||||
self.wins.iter().find(|w| w.window.toplevel().is_some_and(|t| t.wl_surface() == surface)).map(|w| w.window.clone())
|
||||
}
|
||||
|
||||
// ---- input ----------------------------------------------------------
|
||||
|
||||
pub fn handle_input<B: InputBackend>(&mut self, event: InputEvent<B>) {
|
||||
let InputEvent::Keyboard { event } = event else { return };
|
||||
let serial = SERIAL_COUNTER.next_serial();
|
||||
let time = Event::time_msec(&event);
|
||||
let pressed = event.state() == KeyState::Pressed;
|
||||
let Some(kb) = self.seat.get_keyboard() else { return };
|
||||
enum Action {
|
||||
Home,
|
||||
Volume(i32),
|
||||
Mute,
|
||||
Vt(i32),
|
||||
Quit,
|
||||
/// Release or repeat of a key we handle: keep it from the app.
|
||||
Swallow,
|
||||
}
|
||||
let action = kb.input::<Action, _>(self, event.key_code(), event.state(), serial, time, |_, mods, key| {
|
||||
let code = key.raw_code().raw();
|
||||
let sym = key.modified_sym().raw();
|
||||
let hit = match code {
|
||||
KEY_HOMEPAGE => Some(Action::Home),
|
||||
KEY_VOLUMEUP => Some(Action::Volume(5)),
|
||||
KEY_VOLUMEDOWN => Some(Action::Volume(-5)),
|
||||
KEY_MUTE => Some(Action::Mute),
|
||||
_ if (keysyms::KEY_XF86Switch_VT_1..=keysyms::KEY_XF86Switch_VT_12).contains(&sym) => {
|
||||
Some(Action::Vt((sym - keysyms::KEY_XF86Switch_VT_1 + 1) as i32))
|
||||
}
|
||||
_ if mods.ctrl && mods.alt && sym == keysyms::KEY_BackSpace => Some(Action::Quit),
|
||||
_ => None,
|
||||
};
|
||||
match hit {
|
||||
Some(a) if pressed => FilterResult::Intercept(a),
|
||||
// Swallow the release (and repeats) of keys we handle.
|
||||
Some(_) => FilterResult::Intercept(Action::Swallow),
|
||||
None => FilterResult::Forward,
|
||||
}
|
||||
});
|
||||
match action {
|
||||
Some(Action::Home) => send_home(),
|
||||
Some(Action::Volume(d)) => self.change_volume(Some(d)),
|
||||
Some(Action::Mute) => self.change_volume(None),
|
||||
Some(Action::Vt(n)) => {
|
||||
if let Some(s) = self.session.as_mut() {
|
||||
if let Err(e) = s.change_vt(n) {
|
||||
tracing::warn!("change vt {n}: {e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
Some(Action::Quit) => {
|
||||
tracing::info!("ctrl+alt+backspace: quitting");
|
||||
self.loop_signal.stop();
|
||||
}
|
||||
Some(Action::Swallow) | None => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// Volume up/down by `delta` percent, or toggle mute (`None`), then show the OSD.
|
||||
fn change_volume(&mut self, delta: Option<i32>) {
|
||||
let (tx, rx) = smithay::reexports::calloop::channel::channel::<(f32, bool)>();
|
||||
std::thread::spawn(move || {
|
||||
let sink = "@DEFAULT_AUDIO_SINK@";
|
||||
let _ = match delta {
|
||||
Some(d) => {
|
||||
let arg = format!("{}%{}", d.abs(), if d > 0 { "+" } else { "-" });
|
||||
std::process::Command::new("wpctl").args(["set-mute", sink, "0"]).status().ok();
|
||||
std::process::Command::new("wpctl").args(["set-volume", "-l", "1.0", sink, &arg]).status()
|
||||
}
|
||||
None => std::process::Command::new("wpctl").args(["set-mute", sink, "toggle"]).status(),
|
||||
};
|
||||
let out = std::process::Command::new("wpctl").args(["get-volume", sink]).output();
|
||||
let text = out.map(|o| String::from_utf8_lossy(&o.stdout).into_owned()).unwrap_or_default();
|
||||
// "Volume: 0.45" or "Volume: 0.45 [MUTED]"
|
||||
let level = text.split_whitespace().nth(1).and_then(|v| v.parse::<f32>().ok()).unwrap_or(0.0);
|
||||
let _ = tx.send((level, text.contains("MUTED")));
|
||||
});
|
||||
let _ = self.handle.insert_source(rx, |ev, _, app: &mut App| {
|
||||
if let smithay::reexports::calloop::channel::Event::Msg((level, muted)) = ev {
|
||||
app.state.osd = Some(Osd { level, muted, until: Instant::now() + OSD_TIME });
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ---- rendering ------------------------------------------------------
|
||||
|
||||
fn window_elements(&self, renderer: &mut GlesRenderer, window: &Window, alpha: f32) -> Vec<WaylandSurfaceRenderElement<GlesRenderer>> {
|
||||
let origin: Point<i32, Logical> = (0, 0).into();
|
||||
let loc: Point<i32, Physical> = (origin - window.geometry().loc).to_physical_precise_round(1.0);
|
||||
window.render_elements(renderer, loc, Scale::from(1.0), alpha)
|
||||
}
|
||||
|
||||
/// Render elements, front to back.
|
||||
pub fn elements(&mut self, renderer: &mut GlesRenderer) -> Vec<SfElement> {
|
||||
let mut out: Vec<SfElement> = vec![];
|
||||
if !self.screen_on {
|
||||
return out;
|
||||
}
|
||||
let size = self.output_size();
|
||||
let now = Instant::now();
|
||||
|
||||
// Volume OSD: a pill near the bottom with a level bar.
|
||||
if let Some(osd) = &self.osd {
|
||||
if now < osd.until {
|
||||
let fade = ((osd.until - now).as_secs_f32() / 0.3).min(1.0);
|
||||
let (w, h) = (size.w as f32, size.h as f32);
|
||||
let bar_w = (w * 0.26) as i32;
|
||||
let bar_h = (h * 0.010).max(8.0) as i32;
|
||||
let pad = (h * 0.022) as i32;
|
||||
let x = (size.w - bar_w) / 2;
|
||||
let y = (h * 0.86) as i32;
|
||||
let fill_w = ((bar_w as f32) * osd.level.clamp(0.0, 1.0)) as i32;
|
||||
let fill = if osd.muted { [1.0, 0.42, 0.42, 0.95] } else { [1.0, 1.0, 1.0, 0.95] };
|
||||
self.osd_fill.update((fill_w.max(1), bar_h), fill);
|
||||
self.osd_track.update((bar_w, bar_h), [1.0, 1.0, 1.0, 0.22]);
|
||||
self.osd_bg.update((bar_w + 2 * pad, bar_h + 2 * pad), [0.04, 0.05, 0.08, 0.72]);
|
||||
out.push(SolidColorRenderElement::from_buffer(&self.osd_fill, (x, y), 1.0, fade, Kind::Unspecified).into());
|
||||
out.push(SolidColorRenderElement::from_buffer(&self.osd_track, (x, y), 1.0, fade, Kind::Unspecified).into());
|
||||
out.push(SolidColorRenderElement::from_buffer(&self.osd_bg, (x - pad, y - pad), 1.0, fade, Kind::Unspecified).into());
|
||||
} else {
|
||||
self.osd = None;
|
||||
}
|
||||
}
|
||||
|
||||
let done = self.transition.as_ref().is_some_and(|t| now - t.start >= t.duration || !t.over.alive());
|
||||
if done {
|
||||
self.transition = None;
|
||||
}
|
||||
let center: Point<i32, Physical> = (size.w / 2, size.h / 2).into();
|
||||
match &self.transition {
|
||||
Some(t) => {
|
||||
let x = (now - t.start).as_secs_f32() / t.duration.as_secs_f32();
|
||||
let (fade, grow) = (ease_in_out(x), ease_out(x));
|
||||
let (alpha, scale) = if t.entering { (fade, 0.965 + 0.035 * grow) } else { (1.0 - fade, 1.0 - 0.05 * grow) };
|
||||
let over = t.over.clone();
|
||||
let under = t.under.clone();
|
||||
for el in self.window_elements(renderer, &over, alpha) {
|
||||
out.push(RescaleRenderElement::from_element(el, center, scale as f64).into());
|
||||
}
|
||||
if let Some(u) = under.filter(|u| u.alive()) {
|
||||
out.extend(self.window_elements(renderer, &u, 1.0).into_iter().map(SfElement::from));
|
||||
}
|
||||
}
|
||||
None => {
|
||||
if let Some(v) = self.visible.clone() {
|
||||
out.extend(self.window_elements(renderer, &v, 1.0).into_iter().map(SfElement::from));
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Frame callbacks for what is on screen (hidden apps get none, so they idle).
|
||||
pub fn send_frames(&self) {
|
||||
let Some(output) = self.output.as_ref() else { return };
|
||||
let time = self.start.elapsed();
|
||||
// The held-back app draws too, so its page is ready when it shows.
|
||||
let mut shown: Vec<&Window> = self.visible.iter().chain(self.held.iter()).collect();
|
||||
if let Some(t) = &self.transition {
|
||||
shown.push(&t.over);
|
||||
shown.extend(t.under.iter());
|
||||
}
|
||||
for w in shown {
|
||||
w.send_frame(output, time, Some(Duration::ZERO), |_, _| Some(output.clone()));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn output_mgmt_refresh(&mut self) {
|
||||
let info = crate::output_mgmt::HeadInfo::from_state(self);
|
||||
self.output_mgmt.update(&self.dh, info);
|
||||
}
|
||||
|
||||
fn unconstrain_popup(&self, popup: &PopupSurface) {
|
||||
let Ok(root) = find_popup_root_surface(&PopupKind::Xdg(popup.clone())) else { return };
|
||||
let Some(window) = self.surface_window(&root) else { return };
|
||||
let size = self.output_size();
|
||||
let mut target = Rectangle::new((0, 0).into(), (size.w, size.h).into());
|
||||
target.loc -= get_popup_toplevel_coords(&PopupKind::Xdg(popup.clone()));
|
||||
target.loc += window.geometry().loc;
|
||||
popup.with_pending_state(|state| {
|
||||
state.geometry = state.positioner.get_unconstrained_geometry(target);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// The launcher decides what Home means (it tells sf-core).
|
||||
pub fn send_home() {
|
||||
std::thread::spawn(|| {
|
||||
let path = sf_ipc::paths::launcher_socket();
|
||||
match std::os::unix::net::UnixStream::connect(&path) {
|
||||
Ok(mut s) => {
|
||||
let _ = s.write_all(b"home\n");
|
||||
}
|
||||
Err(e) => tracing::warn!("home: {}: {e}", path.display()),
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// ---- protocol handlers ------------------------------------------------------
|
||||
|
||||
impl CompositorHandler for State {
|
||||
fn compositor_state(&mut self) -> &mut CompositorState {
|
||||
&mut self.compositor_state
|
||||
}
|
||||
|
||||
fn client_compositor_state<'a>(&self, client: &'a Client) -> &'a CompositorClientState {
|
||||
&client.get_data::<ClientState>().unwrap().compositor_state
|
||||
}
|
||||
|
||||
fn commit(&mut self, surface: &WlSurface) {
|
||||
on_commit_buffer_handler::<Self>(surface);
|
||||
if !is_sync_subsurface(surface) {
|
||||
let mut root = surface.clone();
|
||||
while let Some(parent) = get_parent(&root) {
|
||||
root = parent;
|
||||
}
|
||||
if let Some(window) = self.surface_window(&root) {
|
||||
window.on_commit();
|
||||
}
|
||||
}
|
||||
|
||||
// Toplevels: initial configure, then "mapped" once a buffer arrives.
|
||||
if let Some(window) = self.surface_window(surface) {
|
||||
let toplevel = window.toplevel().unwrap();
|
||||
let initial_sent = with_states(surface, |states| {
|
||||
states
|
||||
.data_map
|
||||
.get::<XdgToplevelSurfaceData>()
|
||||
.map(|d| d.lock().unwrap().initial_configure_sent)
|
||||
.unwrap_or(true)
|
||||
});
|
||||
if !initial_sent {
|
||||
self.configure(&window);
|
||||
toplevel.send_configure();
|
||||
}
|
||||
let has_buffer = window.bbox().size.w > 0;
|
||||
let newly_mapped = match self.wins.iter_mut().find(|w| w.window == window) {
|
||||
Some(w) if !w.mapped && has_buffer => {
|
||||
w.mapped = true;
|
||||
w.mapped_at = Some(Instant::now());
|
||||
Some(w.app.clone())
|
||||
}
|
||||
_ => None,
|
||||
};
|
||||
if let Some(app) = newly_mapped {
|
||||
tracing::info!("mapped: {}", app.as_deref().unwrap_or("launcher"));
|
||||
match app {
|
||||
// A new app window comes to the front (like cage).
|
||||
Some(id) => self.set_target(Target::App(id)),
|
||||
None => self.update_visible(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
self.popups.commit(surface);
|
||||
if let Some(PopupKind::Xdg(xdg)) = self.popups.find_popup(surface) {
|
||||
if !xdg.is_initial_configure_sent() {
|
||||
let _ = xdg.send_configure();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl BufferHandler for State {
|
||||
fn buffer_destroyed(&mut self, _buffer: &wl_buffer::WlBuffer) {}
|
||||
}
|
||||
|
||||
impl ShmHandler for State {
|
||||
fn shm_state(&self) -> &ShmState {
|
||||
&self.shm_state
|
||||
}
|
||||
}
|
||||
|
||||
impl XdgShellHandler for State {
|
||||
fn xdg_shell_state(&mut self) -> &mut XdgShellState {
|
||||
&mut self.xdg_shell_state
|
||||
}
|
||||
|
||||
fn new_toplevel(&mut self, surface: ToplevelSurface) {
|
||||
let pid = surface.wl_surface().client().and_then(|c| c.get_credentials(&self.dh).ok()).map(|c| c.pid);
|
||||
let app = pid.and_then(|p| app_of_pid(p, &self.registered));
|
||||
tracing::info!("new window: pid {pid:?}, app {}", app.as_deref().unwrap_or("launcher"));
|
||||
let window = Window::new_wayland_window(surface);
|
||||
self.space.map_element(window.clone(), (0, 0), false);
|
||||
self.serial += 1;
|
||||
self.wins.push(Win { window: window.clone(), app, pid, mapped: false, mapped_at: None, serial: self.serial });
|
||||
self.configure(&window);
|
||||
}
|
||||
|
||||
fn toplevel_destroyed(&mut self, surface: ToplevelSurface) {
|
||||
let Some(window) = self.surface_window(surface.wl_surface()) else { return };
|
||||
tracing::info!("window closed: {}", self.app_of_window(&window).unwrap_or_else(|| "launcher".into()));
|
||||
self.space.unmap_elem(&window);
|
||||
self.wins.retain(|w| w.window != window);
|
||||
if self.transition.as_ref().is_some_and(|t| t.over == window || t.under.as_ref() == Some(&window)) {
|
||||
self.transition = None;
|
||||
}
|
||||
if self.held.as_ref() == Some(&window) {
|
||||
self.held = None;
|
||||
}
|
||||
if self.visible.as_ref() == Some(&window) {
|
||||
self.visible = None;
|
||||
// The app is gone: back to the launcher unless sf-core says otherwise.
|
||||
if let Target::App(id) = &self.target {
|
||||
if !self.wins.iter().any(|w| w.mapped && w.app.as_deref() == Some(id.as_str())) {
|
||||
self.target = Target::Launcher;
|
||||
}
|
||||
}
|
||||
self.update_visible();
|
||||
}
|
||||
}
|
||||
|
||||
fn new_popup(&mut self, surface: PopupSurface, _positioner: PositionerState) {
|
||||
self.unconstrain_popup(&surface);
|
||||
let _ = self.popups.track_popup(PopupKind::Xdg(surface));
|
||||
}
|
||||
|
||||
fn reposition_request(&mut self, surface: PopupSurface, positioner: PositionerState, token: u32) {
|
||||
surface.with_pending_state(|state| {
|
||||
state.geometry = positioner.get_geometry();
|
||||
state.positioner = positioner;
|
||||
});
|
||||
self.unconstrain_popup(&surface);
|
||||
surface.send_repositioned(token);
|
||||
}
|
||||
|
||||
fn grab(&mut self, _surface: PopupSurface, _seat: wl_seat::WlSeat, _serial: Serial) {}
|
||||
|
||||
fn fullscreen_request(&mut self, surface: ToplevelSurface, _output: Option<wl_output::WlOutput>) {
|
||||
if let Some(w) = self.surface_window(surface.wl_surface()) {
|
||||
self.configure(&w);
|
||||
}
|
||||
}
|
||||
|
||||
fn unfullscreen_request(&mut self, surface: ToplevelSurface) {
|
||||
if let Some(w) = self.surface_window(surface.wl_surface()) {
|
||||
self.configure(&w);
|
||||
}
|
||||
}
|
||||
|
||||
fn maximize_request(&mut self, surface: ToplevelSurface) {
|
||||
if let Some(w) = self.surface_window(surface.wl_surface()) {
|
||||
self.configure(&w);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl XdgDecorationHandler for State {
|
||||
fn new_decoration(&mut self, toplevel: ToplevelSurface) {
|
||||
toplevel.with_pending_state(|s| s.decoration_mode = Some(zxdg_toplevel_decoration_v1::Mode::ServerSide));
|
||||
}
|
||||
fn request_mode(&mut self, toplevel: ToplevelSurface, _mode: zxdg_toplevel_decoration_v1::Mode) {
|
||||
toplevel.with_pending_state(|s| s.decoration_mode = Some(zxdg_toplevel_decoration_v1::Mode::ServerSide));
|
||||
if toplevel.is_initial_configure_sent() {
|
||||
toplevel.send_pending_configure();
|
||||
}
|
||||
}
|
||||
fn unset_mode(&mut self, toplevel: ToplevelSurface) {
|
||||
self.request_mode(toplevel, zxdg_toplevel_decoration_v1::Mode::ServerSide);
|
||||
}
|
||||
}
|
||||
|
||||
impl SeatHandler for State {
|
||||
type KeyboardFocus = WlSurface;
|
||||
type PointerFocus = WlSurface;
|
||||
type TouchFocus = WlSurface;
|
||||
|
||||
fn seat_state(&mut self) -> &mut SeatState<State> {
|
||||
&mut self.seat_state
|
||||
}
|
||||
|
||||
fn focus_changed(&mut self, seat: &Seat<Self>, focused: Option<&WlSurface>) {
|
||||
let client = focused.and_then(|s| self.dh.get_client(s.id()).ok());
|
||||
set_data_device_focus(&self.dh, seat, client);
|
||||
}
|
||||
}
|
||||
|
||||
impl SelectionHandler for State {
|
||||
type SelectionUserData = ();
|
||||
}
|
||||
|
||||
impl DataDeviceHandler for State {
|
||||
fn data_device_state(&self) -> &DataDeviceState {
|
||||
&self.data_device_state
|
||||
}
|
||||
}
|
||||
|
||||
impl ClientDndGrabHandler for State {}
|
||||
impl ServerDndGrabHandler for State {}
|
||||
|
||||
impl OutputHandler for State {}
|
||||
|
||||
impl DmabufHandler for State {
|
||||
fn dmabuf_state(&mut self) -> &mut DmabufState {
|
||||
&mut self.dmabuf_state
|
||||
}
|
||||
|
||||
fn dmabuf_imported(
|
||||
&mut self,
|
||||
_global: &DmabufGlobal,
|
||||
_dmabuf: smithay::backend::allocator::dmabuf::Dmabuf,
|
||||
notifier: ImportNotifier,
|
||||
) {
|
||||
// Formats come from the renderer; a bad buffer shows up when drawn.
|
||||
let _ = notifier.successful::<State>();
|
||||
}
|
||||
}
|
||||
|
||||
delegate_compositor!(State);
|
||||
delegate_shm!(State);
|
||||
delegate_xdg_shell!(State);
|
||||
delegate_xdg_decoration!(State);
|
||||
delegate_seat!(State);
|
||||
delegate_data_device!(State);
|
||||
delegate_output!(State);
|
||||
delegate_dmabuf!(State);
|
||||
delegate_viewporter!(State);
|
||||
391
crates/sf-compositor/src/udev.rs
Normal file
391
crates/sf-compositor/src/udev.rs
Normal file
@@ -0,0 +1,391 @@
|
||||
//! DRM/KMS backend for the TV: libseat session, one GPU, the first
|
||||
//! connected output (HDMI), libinput keyboards. Handles HDMI hotplug, VT
|
||||
//! switching, mode changes and turning the screen off (wlr-randr).
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use smithay::backend::allocator::Fourcc;
|
||||
use smithay::backend::allocator::gbm::{GbmAllocator, GbmBufferFlags, GbmDevice};
|
||||
use smithay::backend::drm::compositor::FrameFlags;
|
||||
use smithay::backend::drm::exporter::gbm::GbmFramebufferExporter;
|
||||
use smithay::backend::drm::output::{DrmOutput, DrmOutputManager, DrmOutputRenderElements};
|
||||
use smithay::backend::drm::{DrmDevice, DrmDeviceFd, DrmEvent, DrmNode};
|
||||
use smithay::backend::egl::{EGLContext, EGLDevice, EGLDisplay};
|
||||
use smithay::backend::libinput::{LibinputInputBackend, LibinputSessionInterface};
|
||||
use smithay::backend::renderer::gles::GlesRenderer;
|
||||
use smithay::backend::renderer::{ImportDma, ImportMemWl};
|
||||
use smithay::backend::session::libseat::LibSeatSession;
|
||||
use smithay::backend::session::{Event as SessionEvent, Session};
|
||||
use smithay::backend::udev::{UdevBackend, UdevEvent, all_gpus, primary_gpu};
|
||||
use smithay::output::{Mode as WlMode, Output, PhysicalProperties, Subpixel};
|
||||
use smithay::reexports::calloop::timer::{TimeoutAction, Timer};
|
||||
use smithay::reexports::calloop::EventLoop;
|
||||
use smithay::reexports::drm::control::{Device as ControlDevice, ModeTypeFlags, connector, crtc};
|
||||
use smithay::reexports::input::Libinput;
|
||||
use smithay::reexports::rustix::fs::OFlags;
|
||||
use smithay::reexports::wayland_server::backend::GlobalId;
|
||||
use smithay::utils::DeviceFd;
|
||||
use smithay::wayland::dmabuf::DmabufFeedbackBuilder;
|
||||
|
||||
use crate::output_mgmt::{ModeInfo, OutputModes, PendingConfig, match_mode};
|
||||
use crate::state::{App, Backend, SfElement, State};
|
||||
|
||||
type Allocator = GbmAllocator<DrmDeviceFd>;
|
||||
type Exporter = GbmFramebufferExporter<DrmDeviceFd>;
|
||||
|
||||
const FORMATS: &[Fourcc] = &[Fourcc::Argb8888, Fourcc::Abgr8888, Fourcc::Xrgb8888];
|
||||
|
||||
struct Out {
|
||||
drm_output: DrmOutput<Allocator, Exporter, (), DrmDeviceFd>,
|
||||
connector: connector::Handle,
|
||||
crtc: crtc::Handle,
|
||||
modes: Vec<smithay::reexports::drm::control::Mode>,
|
||||
output: Output,
|
||||
global: Option<GlobalId>,
|
||||
frame_pending: bool,
|
||||
/// The CRTC is off (DPMS) after wlr-randr --off.
|
||||
cleared: bool,
|
||||
}
|
||||
|
||||
pub struct UdevData {
|
||||
/// Keeps the seat session (and device access) alive.
|
||||
_session: LibSeatSession,
|
||||
libinput: Libinput,
|
||||
manager: DrmOutputManager<Allocator, Exporter, (), DrmDeviceFd>,
|
||||
renderer: GlesRenderer,
|
||||
out: Option<Out>,
|
||||
active: bool,
|
||||
/// A render is queued on a timer (no damage last time).
|
||||
retry_scheduled: bool,
|
||||
}
|
||||
|
||||
pub fn init(event_loop: &mut EventLoop<'static, App>, state: &mut State) -> Result<Backend> {
|
||||
let (session, notifier) = LibSeatSession::new().map_err(|e| anyhow!("libseat session: {e}"))?;
|
||||
state.session = Some(session.clone());
|
||||
let seat = session.seat();
|
||||
|
||||
let path = primary_gpu(&seat)?
|
||||
.or_else(|| all_gpus(&seat).ok()?.into_iter().next())
|
||||
.context("no GPU found")?;
|
||||
tracing::info!("GPU {}", path.display());
|
||||
let mut session_for_open = session.clone();
|
||||
let fd = session_for_open
|
||||
.open(&path, OFlags::RDWR | OFlags::CLOEXEC | OFlags::NOCTTY | OFlags::NONBLOCK)
|
||||
.map_err(|e| anyhow!("opening {}: {e}", path.display()))?;
|
||||
let fd = DrmDeviceFd::new(DeviceFd::from(fd));
|
||||
let (drm, drm_notifier) = DrmDevice::new(fd.clone(), true).map_err(|e| anyhow!("drm: {e}"))?;
|
||||
let gbm = GbmDevice::new(fd).context("gbm")?;
|
||||
let node = DrmNode::from_path(&path).map_err(|e| anyhow!("drm node: {e}"))?;
|
||||
|
||||
let egl = unsafe { EGLDisplay::new(gbm.clone()) }.map_err(|e| anyhow!("egl display: {e}"))?;
|
||||
let render_node = EGLDevice::device_for_display(&egl)
|
||||
.ok()
|
||||
.and_then(|d| d.try_get_render_node().ok().flatten())
|
||||
.unwrap_or(node);
|
||||
let ctx = EGLContext::new(&egl).map_err(|e| anyhow!("egl context: {e}"))?;
|
||||
let renderer = unsafe { GlesRenderer::new(ctx) }.map_err(|e| anyhow!("gles: {e}"))?;
|
||||
|
||||
state.shm_state.update_formats(renderer.shm_formats());
|
||||
let dmabuf_formats = renderer.dmabuf_formats();
|
||||
let feedback = DmabufFeedbackBuilder::new(render_node.dev_id(), dmabuf_formats.clone())
|
||||
.build()
|
||||
.map_err(|e| anyhow!("dmabuf feedback: {e}"))?;
|
||||
state.dmabuf_global = Some(state.dmabuf_state.create_global_with_default_feedback::<State>(&state.dh, &feedback));
|
||||
|
||||
let render_formats = renderer.egl_context().dmabuf_render_formats().clone();
|
||||
let allocator = GbmAllocator::new(gbm.clone(), GbmBufferFlags::RENDERING | GbmBufferFlags::SCANOUT);
|
||||
let exporter = GbmFramebufferExporter::new(gbm.clone(), Some(render_node));
|
||||
let manager = DrmOutputManager::new(drm, allocator, exporter, Some(gbm), FORMATS.iter().copied(), render_formats);
|
||||
|
||||
// Input.
|
||||
let mut libinput = Libinput::new_with_udev::<LibinputSessionInterface<LibSeatSession>>(session.clone().into());
|
||||
libinput.udev_assign_seat(&seat).map_err(|_| anyhow!("libinput: assigning seat {seat}"))?;
|
||||
let handle = event_loop.handle();
|
||||
handle
|
||||
.insert_source(LibinputInputBackend::new(libinput.clone()), |event, _, app: &mut App| {
|
||||
app.state.handle_input(event);
|
||||
})
|
||||
.map_err(|e| anyhow!("libinput source: {e}"))?;
|
||||
|
||||
// Vblanks.
|
||||
handle
|
||||
.insert_source(drm_notifier, |event, _, app: &mut App| match event {
|
||||
DrmEvent::VBlank(_crtc) => {
|
||||
if let Backend::Udev(u) = &mut app.backend {
|
||||
u.frame_done(&mut app.state);
|
||||
}
|
||||
}
|
||||
DrmEvent::Error(e) => tracing::error!("drm: {e:?}"),
|
||||
})
|
||||
.map_err(|e| anyhow!("drm source: {e}"))?;
|
||||
|
||||
// VT switches.
|
||||
handle
|
||||
.insert_source(notifier, |event, _, app: &mut App| {
|
||||
let Backend::Udev(u) = &mut app.backend else { return };
|
||||
match event {
|
||||
SessionEvent::PauseSession => {
|
||||
tracing::info!("session paused");
|
||||
u.libinput.suspend();
|
||||
u.manager.pause();
|
||||
u.active = false;
|
||||
}
|
||||
SessionEvent::ActivateSession => {
|
||||
tracing::info!("session active");
|
||||
if u.libinput.resume().is_err() {
|
||||
tracing::error!("libinput resume failed");
|
||||
}
|
||||
if let Err(e) = u.manager.activate(false) {
|
||||
tracing::error!("drm activate: {e}");
|
||||
}
|
||||
u.active = true;
|
||||
if let Some(out) = u.out.as_mut() {
|
||||
out.frame_pending = false;
|
||||
out.drm_output.reset_buffers();
|
||||
}
|
||||
u.render(&mut app.state);
|
||||
}
|
||||
}
|
||||
})
|
||||
.map_err(|e| anyhow!("session source: {e}"))?;
|
||||
|
||||
// HDMI hotplug: rescan connectors when the GPU reports a change.
|
||||
let udev = UdevBackend::new(&seat)?;
|
||||
handle
|
||||
.insert_source(udev, |event, _, app: &mut App| {
|
||||
if let UdevEvent::Changed { .. } = event {
|
||||
if let Backend::Udev(u) = &mut app.backend {
|
||||
u.scan(&mut app.state);
|
||||
}
|
||||
}
|
||||
})
|
||||
.map_err(|e| anyhow!("udev source: {e}"))?;
|
||||
|
||||
let mut data = UdevData { _session: session, libinput, manager, renderer, out: None, active: true, retry_scheduled: false };
|
||||
data.scan(state);
|
||||
if data.out.is_none() {
|
||||
tracing::warn!("no connected display yet; waiting for hotplug");
|
||||
}
|
||||
Ok(Backend::Udev(data))
|
||||
}
|
||||
|
||||
fn mode_info(m: &smithay::reexports::drm::control::Mode) -> ModeInfo {
|
||||
let wl = WlMode::from(*m);
|
||||
ModeInfo {
|
||||
width: wl.size.w,
|
||||
height: wl.size.h,
|
||||
refresh: wl.refresh,
|
||||
preferred: m.mode_type().contains(ModeTypeFlags::PREFERRED),
|
||||
}
|
||||
}
|
||||
|
||||
impl UdevData {
|
||||
/// First connected connector and a CRTC for it.
|
||||
fn find_connector(&self) -> Option<(connector::Info, crtc::Handle)> {
|
||||
let dev = self.manager.device();
|
||||
let res = dev.resource_handles().ok()?;
|
||||
for handle in res.connectors() {
|
||||
let Ok(info) = dev.get_connector(*handle, false) else { continue };
|
||||
if info.state() != connector::State::Connected || info.modes().is_empty() {
|
||||
continue;
|
||||
}
|
||||
// Keep the CRTC we already drive for this connector.
|
||||
if let Some(out) = &self.out {
|
||||
if out.connector == *handle {
|
||||
return Some((info, out.crtc));
|
||||
}
|
||||
}
|
||||
for enc in info.encoders() {
|
||||
let Ok(enc) = dev.get_encoder(*enc) else { continue };
|
||||
if let Some(crtc) = res.filter_crtcs(enc.possible_crtcs()).into_iter().next() {
|
||||
return Some((info, crtc));
|
||||
}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
fn scan(&mut self, state: &mut State) {
|
||||
let found = self.find_connector();
|
||||
let same = match (&found, &self.out) {
|
||||
(Some((info, _)), Some(out)) => info.handle() == out.connector,
|
||||
(None, None) => true,
|
||||
_ => false,
|
||||
};
|
||||
if same {
|
||||
return;
|
||||
}
|
||||
if let Some(out) = self.out.take() {
|
||||
tracing::info!("display disconnected: {}", out.output.name());
|
||||
if let Some(g) = out.global {
|
||||
state.dh.remove_global::<State>(g);
|
||||
}
|
||||
state.set_output(None);
|
||||
}
|
||||
let Some((info, crtc)) = found else { return };
|
||||
if let Err(e) = self.setup_output(state, &info, crtc) {
|
||||
tracing::error!("display setup: {e:#}");
|
||||
}
|
||||
}
|
||||
|
||||
fn setup_output(&mut self, state: &mut State, info: &connector::Info, crtc: crtc::Handle) -> Result<()> {
|
||||
let name = format!("{}-{}", info.interface().as_str(), info.interface_id());
|
||||
let modes = info.modes().to_vec();
|
||||
let mode = *modes.iter().find(|m| m.mode_type().contains(ModeTypeFlags::PREFERRED)).unwrap_or(&modes[0]);
|
||||
let wl_mode = WlMode::from(mode);
|
||||
let (pw, ph) = info.size().unwrap_or((0, 0));
|
||||
let output = Output::new(
|
||||
name.clone(),
|
||||
PhysicalProperties {
|
||||
size: (pw as i32, ph as i32).into(),
|
||||
subpixel: Subpixel::Unknown,
|
||||
make: "TV".into(),
|
||||
model: name.clone(),
|
||||
},
|
||||
);
|
||||
let global = output.create_global::<State>(&state.dh);
|
||||
output.set_preferred(wl_mode);
|
||||
output.change_current_state(Some(wl_mode), None, None, Some((0, 0).into()));
|
||||
*output.user_data().get_or_insert(OutputModes::default).0.lock().unwrap() = modes.iter().map(mode_info).collect();
|
||||
|
||||
let drm_output = self
|
||||
.manager
|
||||
.initialize_output::<_, SfElement>(
|
||||
crtc,
|
||||
mode,
|
||||
&[info.handle()],
|
||||
&output,
|
||||
None,
|
||||
&mut self.renderer,
|
||||
&DrmOutputRenderElements::default(),
|
||||
)
|
||||
.map_err(|e| anyhow!("initializing {name}: {e:?}"))?;
|
||||
tracing::info!("display {name}: {}x{}@{:.2}", wl_mode.size.w, wl_mode.size.h, wl_mode.refresh as f32 / 1000.0);
|
||||
self.out = Some(Out {
|
||||
drm_output,
|
||||
connector: info.handle(),
|
||||
crtc,
|
||||
modes,
|
||||
output: output.clone(),
|
||||
global: Some(global),
|
||||
frame_pending: false,
|
||||
cleared: false,
|
||||
});
|
||||
state.set_output(Some(output));
|
||||
self.render(state);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Called after every dispatch: start rendering if nothing is in flight.
|
||||
pub fn kick(&mut self, state: &mut State) {
|
||||
let idle = self.out.as_ref().is_some_and(|o| !o.frame_pending);
|
||||
if idle && !self.retry_scheduled {
|
||||
self.render(state);
|
||||
}
|
||||
}
|
||||
|
||||
fn frame_done(&mut self, state: &mut State) {
|
||||
let Some(out) = self.out.as_mut() else { return };
|
||||
if let Err(e) = out.drm_output.frame_submitted() {
|
||||
tracing::warn!("frame_submitted: {e:?}");
|
||||
}
|
||||
out.frame_pending = false;
|
||||
state.send_frames();
|
||||
self.render(state);
|
||||
}
|
||||
|
||||
fn render(&mut self, state: &mut State) {
|
||||
if !self.active {
|
||||
return;
|
||||
}
|
||||
let Some(out) = self.out.as_mut() else { return };
|
||||
if out.frame_pending {
|
||||
return;
|
||||
}
|
||||
if !state.screen_on {
|
||||
if !out.cleared {
|
||||
if let Err(e) = out.drm_output.with_compositor(|c| c.clear()) {
|
||||
tracing::warn!("screen off: {e}");
|
||||
}
|
||||
out.cleared = true;
|
||||
tracing::info!("screen off");
|
||||
}
|
||||
// Apps still get (slow) frame callbacks so they don't hang.
|
||||
self.schedule_retry(state, Duration::from_millis(250));
|
||||
return;
|
||||
}
|
||||
if out.cleared {
|
||||
out.cleared = false;
|
||||
out.drm_output.reset_buffers();
|
||||
tracing::info!("screen on");
|
||||
}
|
||||
let elements = state.elements(&mut self.renderer);
|
||||
let rendered = match out.drm_output.render_frame(&mut self.renderer, &elements, [0.0, 0.0, 0.0, 1.0], FrameFlags::DEFAULT) {
|
||||
Ok(r) => !r.is_empty,
|
||||
Err(e) => {
|
||||
tracing::warn!("render: {e:?}");
|
||||
false
|
||||
}
|
||||
};
|
||||
if rendered {
|
||||
match out.drm_output.queue_frame(()) {
|
||||
Ok(()) => out.frame_pending = true,
|
||||
Err(e) => tracing::warn!("queue_frame: {e:?}"),
|
||||
}
|
||||
} else {
|
||||
// Nothing changed: send frame callbacks, look again in a frame.
|
||||
state.send_frames();
|
||||
let frame = out.output.current_mode().map(|m| 1_000_000 / m.refresh.max(1) as u64).unwrap_or(16);
|
||||
self.schedule_retry(state, Duration::from_millis(frame.max(4)));
|
||||
}
|
||||
}
|
||||
|
||||
fn schedule_retry(&mut self, state: &mut State, after: Duration) {
|
||||
if self.retry_scheduled {
|
||||
return;
|
||||
}
|
||||
self.retry_scheduled = true;
|
||||
let _ = state.handle.insert_source(Timer::from_duration(after), |_, _, app: &mut App| {
|
||||
if let Backend::Udev(u) = &mut app.backend {
|
||||
u.retry_scheduled = false;
|
||||
if !app.state.screen_on {
|
||||
app.state.send_frames();
|
||||
}
|
||||
u.render(&mut app.state);
|
||||
}
|
||||
TimeoutAction::Drop
|
||||
});
|
||||
}
|
||||
|
||||
pub fn apply_config(&mut self, state: &mut State, cfg: &PendingConfig) -> Result<()> {
|
||||
let Some(out) = self.out.as_mut() else { bail!("no display connected") };
|
||||
let infos: Vec<ModeInfo> = out.modes.iter().map(mode_info).collect();
|
||||
let target = match &cfg.mode {
|
||||
Some(want) => {
|
||||
let (idx, _) = match_mode(&infos, want, cfg.any_refresh)
|
||||
.with_context(|| format!("{}x{}@{} is not offered by the display", want.width, want.height, want.refresh))?;
|
||||
Some(out.modes[idx])
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
if cfg.test_only {
|
||||
return Ok(());
|
||||
}
|
||||
if let Some(mode) = target {
|
||||
let wl = WlMode::from(mode);
|
||||
if out.output.current_mode() != Some(wl) {
|
||||
out.drm_output
|
||||
.use_mode::<_, SfElement>(mode, &mut self.renderer, &DrmOutputRenderElements::default())
|
||||
.map_err(|e| anyhow!("mode change: {e:?}"))?;
|
||||
out.output.change_current_state(Some(wl), None, None, None);
|
||||
tracing::info!("mode {}x{}@{:.2}", wl.size.w, wl.size.h, wl.refresh as f32 / 1000.0);
|
||||
state.reconfigure_all();
|
||||
}
|
||||
}
|
||||
state.screen_on = cfg.enabled;
|
||||
out.frame_pending = false;
|
||||
self.render(state);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
110
crates/sf-compositor/src/winit.rs
Normal file
110
crates/sf-compositor/src/winit.rs
Normal file
@@ -0,0 +1,110 @@
|
||||
//! Nested backend: the compositor runs in a window of a desktop session
|
||||
//! (WSLg, a Linux desktop). For development only.
|
||||
|
||||
use anyhow::{Result, anyhow, bail};
|
||||
use smithay::backend::renderer::ImportDma;
|
||||
use smithay::backend::renderer::ImportMemWl;
|
||||
use smithay::backend::renderer::damage::OutputDamageTracker;
|
||||
use smithay::backend::renderer::gles::GlesRenderer;
|
||||
use smithay::backend::winit::{self, WinitEvent, WinitGraphicsBackend};
|
||||
use smithay::output::{Mode, Output, PhysicalProperties, Subpixel};
|
||||
use smithay::reexports::calloop::EventLoop;
|
||||
use smithay::utils::Transform;
|
||||
|
||||
use crate::output_mgmt::{ModeInfo, OutputModes, PendingConfig};
|
||||
use crate::state::{App, Backend, State};
|
||||
|
||||
pub struct WinitData {
|
||||
backend: WinitGraphicsBackend<GlesRenderer>,
|
||||
damage: OutputDamageTracker,
|
||||
output: Output,
|
||||
}
|
||||
|
||||
fn set_modes(output: &Output, mode: Mode) {
|
||||
let modes = output.user_data().get_or_insert(OutputModes::default);
|
||||
*modes.0.lock().unwrap() =
|
||||
vec![ModeInfo { width: mode.size.w, height: mode.size.h, refresh: mode.refresh, preferred: true }];
|
||||
}
|
||||
|
||||
pub fn init(event_loop: &mut EventLoop<'static, App>, state: &mut State) -> Result<Backend> {
|
||||
let (mut backend, winit_loop) = winit::init::<GlesRenderer>().map_err(|e| anyhow!("winit: {e:?}"))?;
|
||||
let mode = Mode { size: backend.window_size(), refresh: 60_000 };
|
||||
let output = Output::new(
|
||||
"WINIT-1".into(),
|
||||
PhysicalProperties { size: (0, 0).into(), subpixel: Subpixel::Unknown, make: "Fennec OS".into(), model: "Nested".into() },
|
||||
);
|
||||
let _global = output.create_global::<State>(&state.dh);
|
||||
output.change_current_state(Some(mode), Some(Transform::Flipped180), None, Some((0, 0).into()));
|
||||
output.set_preferred(mode);
|
||||
set_modes(&output, mode);
|
||||
|
||||
state.shm_state.update_formats(backend.renderer().shm_formats());
|
||||
let formats = backend.renderer().dmabuf_formats();
|
||||
state.dmabuf_global = Some(state.dmabuf_state.create_global::<State>(&state.dh, formats));
|
||||
state.set_output(Some(output.clone()));
|
||||
|
||||
let damage = OutputDamageTracker::from_output(&output);
|
||||
event_loop
|
||||
.handle()
|
||||
.insert_source(winit_loop, |event, _, app: &mut App| match event {
|
||||
WinitEvent::Resized { size, .. } => {
|
||||
let Backend::Winit(w) = &mut app.backend else { return };
|
||||
let mode = Mode { size, refresh: 60_000 };
|
||||
w.output.change_current_state(Some(mode), None, None, None);
|
||||
w.output.set_preferred(mode);
|
||||
set_modes(&w.output, mode);
|
||||
app.state.reconfigure_all();
|
||||
app.state.output_mgmt_refresh();
|
||||
}
|
||||
WinitEvent::Input(event) => app.state.handle_input(event),
|
||||
WinitEvent::Redraw => render(app),
|
||||
WinitEvent::CloseRequested => app.state.loop_signal.stop(),
|
||||
_ => {}
|
||||
})
|
||||
.map_err(|e| anyhow!("winit source: {e}"))?;
|
||||
|
||||
Ok(Backend::Winit(WinitData { backend, damage, output }))
|
||||
}
|
||||
|
||||
fn render(app: &mut App) {
|
||||
let Backend::Winit(w) = &mut app.backend else { return };
|
||||
let age = w.backend.buffer_age().unwrap_or(0);
|
||||
let damage = match w.backend.bind() {
|
||||
Ok((renderer, mut fb)) => {
|
||||
let elements = app.state.elements(renderer);
|
||||
match w.damage.render_output(renderer, &mut fb, age, &elements, [0.0, 0.0, 0.0, 1.0]) {
|
||||
Ok(r) => r.damage.cloned(),
|
||||
Err(e) => {
|
||||
tracing::warn!("render: {e:?}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) => {
|
||||
tracing::warn!("bind: {e:?}");
|
||||
None
|
||||
}
|
||||
};
|
||||
if let Some(damage) = damage {
|
||||
if let Err(e) = w.backend.submit(Some(&damage)) {
|
||||
tracing::warn!("submit: {e:?}");
|
||||
}
|
||||
}
|
||||
app.state.send_frames();
|
||||
w.backend.window().request_redraw();
|
||||
}
|
||||
|
||||
impl WinitData {
|
||||
pub fn apply_config(&mut self, state: &mut State, cfg: &PendingConfig) -> Result<()> {
|
||||
if let Some(m) = &cfg.mode {
|
||||
let cur = self.backend.window_size();
|
||||
if (m.width, m.height) != (cur.w, cur.h) {
|
||||
bail!("the nested window is {}x{}", cur.w, cur.h);
|
||||
}
|
||||
}
|
||||
if !cfg.test_only {
|
||||
state.screen_on = cfg.enabled;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
18
crates/sf-core/Cargo.toml
Normal file
18
crates/sf-core/Cargo.toml
Normal file
@@ -0,0 +1,18 @@
|
||||
[package]
|
||||
name = "sf-core"
|
||||
description = "Fennec OS core daemon: app lifecycle (systemd scopes, freeze/thaw), DIAL, AirPlay/Miracast receivers"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
sf-ipc.workspace = true
|
||||
sf-dial.workspace = true
|
||||
anyhow.workspace = true
|
||||
log.workspace = true
|
||||
env_logger.workspace = true
|
||||
serde_json.workspace = true
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
tokio = { version = "1", features = ["rt", "net", "time", "io-util", "sync", "macros", "process", "signal"] }
|
||||
libc = "0.2"
|
||||
493
crates/sf-core/src/apps.rs
Normal file
493
crates/sf-core/src/apps.rs
Normal file
@@ -0,0 +1,493 @@
|
||||
//! App lifecycle: start, bring to front, send to the background (freeze),
|
||||
//! close. One app is in the foreground; with sf-compositor the others wait
|
||||
//! frozen in the background, under cage they are closed.
|
||||
|
||||
use std::os::unix::process::CommandExt;
|
||||
use std::path::PathBuf;
|
||||
use std::process::Command as StdCommand;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use sf_ipc::launch::{LaunchOptions, command};
|
||||
use sf_ipc::{AppKind, AppManifest, CoreEvent, Settings};
|
||||
use tokio::sync::broadcast;
|
||||
|
||||
use crate::wm;
|
||||
|
||||
/// Frozen apps kept in the background; the oldest beyond this is closed.
|
||||
const MAX_BACKGROUND: usize = 2;
|
||||
/// Below this much available memory the oldest frozen app is closed.
|
||||
const LOW_MEMORY_KB: u64 = 400 * 1024;
|
||||
/// Freeze only after the compositor's switch animation has finished.
|
||||
const FREEZE_DELAY: Duration = Duration::from_millis(600);
|
||||
|
||||
struct Running {
|
||||
id: String,
|
||||
pid: u32,
|
||||
/// systemd scope (`sf-app-<id>-<n>.scope`), if scopes are used.
|
||||
unit: Option<String>,
|
||||
frozen: bool,
|
||||
last_used: Instant,
|
||||
serial: u64,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct State {
|
||||
apps: Vec<AppManifest>,
|
||||
running: Vec<Running>,
|
||||
foreground: Option<String>,
|
||||
serial: u64,
|
||||
/// While a cast window is up: what to show when it ends (None: launcher).
|
||||
cast_return: Option<Option<String>>,
|
||||
}
|
||||
|
||||
pub struct Core {
|
||||
apps_dirs: Vec<PathBuf>,
|
||||
/// Installed store apps (sandboxed, see sf_ipc::sandbox).
|
||||
store_dir: Option<PathBuf>,
|
||||
settings_path: PathBuf,
|
||||
scopes: bool,
|
||||
pub events: broadcast::Sender<CoreEvent>,
|
||||
state: Mutex<State>,
|
||||
}
|
||||
|
||||
/// True if a systemd user manager answers (`systemctl --user`).
|
||||
fn systemd_user_available() -> bool {
|
||||
if std::env::var_os("SMARTFOX_NO_SCOPES").is_some() {
|
||||
return false;
|
||||
}
|
||||
StdCommand::new("systemctl")
|
||||
.args(["--user", "is-system-running"])
|
||||
.output()
|
||||
.map(|o| {
|
||||
let s = String::from_utf8_lossy(&o.stdout);
|
||||
["running", "degraded", "starting"].iter().any(|w| s.trim() == *w)
|
||||
})
|
||||
.unwrap_or(false)
|
||||
}
|
||||
|
||||
fn kill_group(pid: u32, sig: libc::c_int) -> bool {
|
||||
// SAFETY: plain syscall; a negative pid addresses the process group.
|
||||
unsafe { libc::kill(-(pid as libc::pid_t), sig) == 0 }
|
||||
}
|
||||
|
||||
async fn systemctl(verb: &str, unit: &str) -> Result<()> {
|
||||
let st = tokio::process::Command::new("systemctl").args(["--user", verb, unit]).status().await?;
|
||||
if !st.success() {
|
||||
bail!("systemctl --user {verb} {unit}: {st}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn mem_available_kb() -> Option<u64> {
|
||||
let text = std::fs::read_to_string("/proc/meminfo").ok()?;
|
||||
let line = text.lines().find(|l| l.starts_with("MemAvailable:"))?;
|
||||
line.split_whitespace().nth(1)?.parse().ok()
|
||||
}
|
||||
|
||||
impl Core {
|
||||
pub fn new(apps_dirs: Vec<PathBuf>, store_dir: Option<PathBuf>, settings_path: PathBuf) -> Result<Self> {
|
||||
let apps = sf_ipc::manifest::load_all(&apps_dirs, store_dir.as_deref())?;
|
||||
let (events, _) = broadcast::channel(64);
|
||||
Ok(Core {
|
||||
apps_dirs,
|
||||
store_dir,
|
||||
settings_path,
|
||||
scopes: systemd_user_available(),
|
||||
events,
|
||||
state: Mutex::new(State { apps, ..Default::default() }),
|
||||
})
|
||||
}
|
||||
|
||||
pub fn app_count(&self) -> usize {
|
||||
self.state.lock().unwrap().apps.len()
|
||||
}
|
||||
|
||||
pub fn uses_scopes(&self) -> bool {
|
||||
self.scopes
|
||||
}
|
||||
|
||||
pub fn apps(&self) -> Vec<AppManifest> {
|
||||
self.state.lock().unwrap().apps.clone()
|
||||
}
|
||||
|
||||
pub fn foreground(&self) -> Option<String> {
|
||||
self.state.lock().unwrap().foreground.clone()
|
||||
}
|
||||
|
||||
pub fn is_running(&self, id: &str) -> bool {
|
||||
self.state.lock().unwrap().running.iter().any(|r| r.id == id)
|
||||
}
|
||||
|
||||
pub fn emit(&self, ev: CoreEvent) {
|
||||
log::debug!("event {ev:?}");
|
||||
let _ = self.events.send(ev);
|
||||
}
|
||||
|
||||
/// Re-reads the manifests (new packages may have been installed).
|
||||
fn reload_apps(&self) {
|
||||
match sf_ipc::manifest::load_all(&self.apps_dirs, self.store_dir.as_deref()) {
|
||||
Ok(apps) => self.state.lock().unwrap().apps = apps,
|
||||
Err(e) => log::warn!("reloading apps: {e:#}"),
|
||||
}
|
||||
}
|
||||
|
||||
fn data_dir(&self) -> PathBuf {
|
||||
self.settings_path.parent().map(PathBuf::from).unwrap_or_else(|| PathBuf::from("."))
|
||||
}
|
||||
|
||||
/// Starts the app or brings it back. `query` (DIAL) restarts a running
|
||||
/// app so it sees the new parameters.
|
||||
pub async fn launch(self: &Arc<Self>, id: &str, query: Option<String>, cast: bool) -> Result<()> {
|
||||
self.reload_apps();
|
||||
let app = self.state.lock().unwrap().apps.iter().find(|a| a.id == id).cloned();
|
||||
let app = app.with_context(|| format!("no app {id:?}"))?;
|
||||
if app.kind == AppKind::Builtin || app.service {
|
||||
return Ok(());
|
||||
}
|
||||
if query.is_some() && self.is_running(id) {
|
||||
self.stop_and_wait(id).await;
|
||||
}
|
||||
let switching = wm::available();
|
||||
|
||||
// Already running: thaw and show it.
|
||||
let existing = {
|
||||
let st = self.state.lock().unwrap();
|
||||
st.running.iter().find(|r| r.id == id).map(|r| (r.unit.clone(), r.pid, r.frozen))
|
||||
};
|
||||
if let Some((unit, pid, frozen)) = existing {
|
||||
if frozen {
|
||||
self.thaw(id, unit.as_deref(), pid).await;
|
||||
}
|
||||
let prev = self.set_foreground(Some(id));
|
||||
self.leave_foreground(prev, switching);
|
||||
wm::focus(Some(id));
|
||||
self.emit(CoreEvent::AppStarted { app_id: id.to_string(), cast });
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let prev = self.set_foreground(None);
|
||||
self.leave_foreground(prev, switching);
|
||||
if !switching {
|
||||
// Under cage only the newest window shows; don't leave others running.
|
||||
let others: Vec<String> = self.state.lock().unwrap().running.iter().map(|r| r.id.clone()).collect();
|
||||
for other in others {
|
||||
self.stop(&other);
|
||||
}
|
||||
}
|
||||
self.spawn(&app, query.as_deref())?;
|
||||
self.set_foreground(Some(id));
|
||||
wm::focus(Some(id));
|
||||
self.emit(CoreEvent::AppStarted { app_id: id.to_string(), cast });
|
||||
self.enforce_background_limit();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_foreground(&self, id: Option<&str>) -> Option<String> {
|
||||
let mut st = self.state.lock().unwrap();
|
||||
if let Some(id) = id {
|
||||
if let Some(r) = st.running.iter_mut().find(|r| r.id == id) {
|
||||
r.last_used = Instant::now();
|
||||
}
|
||||
}
|
||||
let prev = std::mem::replace(&mut st.foreground, id.map(str::to_string));
|
||||
prev.filter(|p| Some(p.as_str()) != id)
|
||||
}
|
||||
|
||||
/// The previous foreground app goes to the background (or is closed
|
||||
/// when the compositor can't keep it there).
|
||||
fn leave_foreground(self: &Arc<Self>, prev: Option<String>, switching: bool) {
|
||||
let Some(prev) = prev else { return };
|
||||
if switching {
|
||||
self.freeze_later(prev);
|
||||
} else {
|
||||
self.stop(&prev);
|
||||
}
|
||||
}
|
||||
|
||||
fn spawn(self: &Arc<Self>, app: &AppManifest, query: Option<&str>) -> Result<()> {
|
||||
let settings = Settings::load(&self.settings_path).unwrap_or_default();
|
||||
let data_dir = self.data_dir();
|
||||
let opts = LaunchOptions { data_dir: &data_dir, fullscreen: true, bounds: None, query };
|
||||
let inner = command(app, &settings, &opts)?;
|
||||
|
||||
let serial = {
|
||||
let mut st = self.state.lock().unwrap();
|
||||
st.serial += 1;
|
||||
st.serial
|
||||
};
|
||||
let (mut cmd, unit) = if self.scopes {
|
||||
let unit = format!("sf-app-{}-{serial}", app.id);
|
||||
let mut cmd = StdCommand::new("systemd-run");
|
||||
cmd.args(["--user", "--scope", "--quiet", "--collect"])
|
||||
.arg(format!("--unit={unit}"))
|
||||
.args(["-p", "TimeoutStopSec=3"])
|
||||
.arg("--")
|
||||
.arg(inner.get_program())
|
||||
.args(inner.get_args());
|
||||
(cmd, Some(format!("{unit}.scope")))
|
||||
} else {
|
||||
let mut cmd = StdCommand::new(inner.get_program());
|
||||
cmd.args(inner.get_args());
|
||||
(cmd, None)
|
||||
};
|
||||
for (k, v) in inner.get_envs() {
|
||||
match v {
|
||||
Some(v) => cmd.env(k, v),
|
||||
None => cmd.env_remove(k),
|
||||
};
|
||||
}
|
||||
cmd.process_group(0);
|
||||
let mut child = tokio::process::Command::from(cmd)
|
||||
.kill_on_drop(false)
|
||||
.spawn()
|
||||
.with_context(|| format!("starting {}", app.id))?;
|
||||
let pid = child.id().context("no pid")?;
|
||||
// The app runs in its own process group (pgid == pid).
|
||||
wm::register(pid, &app.id);
|
||||
log::info!("started {} (pid {pid}{})", app.id, unit.as_deref().map(|u| format!(", {u}")).unwrap_or_default());
|
||||
self.state.lock().unwrap().running.push(Running {
|
||||
id: app.id.clone(),
|
||||
pid,
|
||||
unit,
|
||||
frozen: false,
|
||||
last_used: Instant::now(),
|
||||
serial,
|
||||
});
|
||||
let core = self.clone();
|
||||
let id = app.id.clone();
|
||||
tokio::spawn(async move {
|
||||
let status = child.wait().await;
|
||||
log::info!("{id} exited ({status:?})");
|
||||
core.on_exit(&id, serial);
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn on_exit(&self, id: &str, serial: u64) {
|
||||
let was_foreground = {
|
||||
let mut st = self.state.lock().unwrap();
|
||||
st.running.retain(|r| !(r.id == id && r.serial == serial));
|
||||
if st.running.iter().any(|r| r.id == id) {
|
||||
return; // a newer instance is already up
|
||||
}
|
||||
let fg = st.foreground.as_deref() == Some(id);
|
||||
if fg {
|
||||
st.foreground = None;
|
||||
}
|
||||
if let Some(Some(ret)) = &st.cast_return {
|
||||
if ret == id {
|
||||
st.cast_return = Some(None);
|
||||
}
|
||||
}
|
||||
fg
|
||||
};
|
||||
if was_foreground {
|
||||
wm::focus(None);
|
||||
}
|
||||
self.emit(CoreEvent::AppStopped { app_id: id.to_string() });
|
||||
}
|
||||
|
||||
/// Home: show the launcher; the foreground app waits frozen (or closes).
|
||||
pub fn go_home(self: &Arc<Self>) {
|
||||
let prev = self.set_foreground(None);
|
||||
let switching = wm::available();
|
||||
wm::focus(None);
|
||||
self.leave_foreground(prev, switching);
|
||||
self.enforce_background_limit();
|
||||
}
|
||||
|
||||
fn freeze_later(self: &Arc<Self>, id: String) {
|
||||
let core = self.clone();
|
||||
tokio::spawn(async move {
|
||||
tokio::time::sleep(FREEZE_DELAY).await;
|
||||
let target = {
|
||||
let st = core.state.lock().unwrap();
|
||||
if st.foreground.as_deref() == Some(id.as_str()) {
|
||||
return; // came back in the meantime
|
||||
}
|
||||
st.running.iter().find(|r| r.id == id && !r.frozen).map(|r| (r.unit.clone(), r.pid))
|
||||
};
|
||||
let Some((unit, pid)) = target else { return };
|
||||
let ok = match &unit {
|
||||
Some(u) => systemctl("freeze", u).await.map_err(|e| log::warn!("{e:#}")).is_ok(),
|
||||
None => kill_group(pid, libc::SIGSTOP),
|
||||
};
|
||||
if ok {
|
||||
// It may have been brought back while we were freezing it.
|
||||
let back = {
|
||||
let mut st = core.state.lock().unwrap();
|
||||
if let Some(r) = st.running.iter_mut().find(|r| r.id == id) {
|
||||
r.frozen = true;
|
||||
}
|
||||
st.foreground.as_deref() == Some(id.as_str())
|
||||
};
|
||||
if back {
|
||||
core.thaw(&id, unit.as_deref(), pid).await;
|
||||
} else {
|
||||
log::info!("{id} frozen");
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
async fn thaw(&self, id: &str, unit: Option<&str>, pid: u32) {
|
||||
match unit {
|
||||
Some(u) => {
|
||||
if let Err(e) = systemctl("thaw", u).await {
|
||||
log::warn!("{e:#}");
|
||||
}
|
||||
}
|
||||
None => {
|
||||
kill_group(pid, libc::SIGCONT);
|
||||
}
|
||||
}
|
||||
if let Some(r) = self.state.lock().unwrap().running.iter_mut().find(|r| r.id == id) {
|
||||
r.frozen = false;
|
||||
}
|
||||
log::info!("{id} thawed");
|
||||
}
|
||||
|
||||
/// Closes the app (asynchronously); false if it wasn't running.
|
||||
pub fn stop(self: &Arc<Self>, id: &str) -> bool {
|
||||
let target = {
|
||||
let st = self.state.lock().unwrap();
|
||||
st.running.iter().find(|r| r.id == id).map(|r| (r.unit.clone(), r.pid))
|
||||
};
|
||||
let Some((unit, pid)) = target else { return false };
|
||||
log::info!("stopping {id}");
|
||||
tokio::spawn(async move {
|
||||
match unit {
|
||||
// Stops every process of the scope, thawing it first.
|
||||
Some(u) => {
|
||||
let _ = systemctl("thaw", &u).await;
|
||||
if let Err(e) = systemctl("stop", &u).await {
|
||||
log::warn!("{e:#}");
|
||||
kill_group(pid, libc::SIGKILL);
|
||||
}
|
||||
}
|
||||
None => {
|
||||
kill_group(pid, libc::SIGCONT);
|
||||
kill_group(pid, libc::SIGTERM);
|
||||
tokio::time::sleep(Duration::from_secs(3)).await;
|
||||
kill_group(pid, libc::SIGKILL);
|
||||
}
|
||||
}
|
||||
});
|
||||
true
|
||||
}
|
||||
|
||||
async fn stop_and_wait(self: &Arc<Self>, id: &str) {
|
||||
if !self.stop(id) {
|
||||
return;
|
||||
}
|
||||
for _ in 0..60 {
|
||||
if !self.is_running(id) {
|
||||
return;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
log::warn!("{id} did not stop in time");
|
||||
}
|
||||
|
||||
/// The oldest frozen app, if any.
|
||||
fn oldest_background(&self) -> Option<String> {
|
||||
let st = self.state.lock().unwrap();
|
||||
st.running
|
||||
.iter()
|
||||
.filter(|r| st.foreground.as_deref() != Some(r.id.as_str()))
|
||||
.min_by_key(|r| r.last_used)
|
||||
.map(|r| r.id.clone())
|
||||
}
|
||||
|
||||
fn background_count(&self) -> usize {
|
||||
let st = self.state.lock().unwrap();
|
||||
st.running.iter().filter(|r| st.foreground.as_deref() != Some(r.id.as_str())).count()
|
||||
}
|
||||
|
||||
fn enforce_background_limit(self: &Arc<Self>) {
|
||||
while self.background_count() > MAX_BACKGROUND {
|
||||
let Some(id) = self.oldest_background() else { break };
|
||||
log::info!("too many apps in the background, closing {id}");
|
||||
if !self.stop(&id) {
|
||||
break;
|
||||
}
|
||||
// Don't pick it again while it shuts down.
|
||||
self.state.lock().unwrap().running.retain(|r| r.id != id);
|
||||
self.emit(CoreEvent::AppStopped { app_id: id });
|
||||
}
|
||||
}
|
||||
|
||||
/// A receiver (AirPlay/Miracast) got a connection: its window goes on
|
||||
/// top, the foreground app pauses in the background.
|
||||
pub fn cast_connected(self: &Arc<Self>, app_id: &str, device: &str) {
|
||||
let switching = wm::available();
|
||||
let prev = {
|
||||
let mut st = self.state.lock().unwrap();
|
||||
if st.cast_return.is_none() {
|
||||
st.cast_return = Some(st.foreground.clone());
|
||||
}
|
||||
if switching { st.foreground.take() } else { None }
|
||||
};
|
||||
if let Some(prev) = prev {
|
||||
self.freeze_later(prev);
|
||||
}
|
||||
wm::focus(Some(app_id));
|
||||
self.emit(CoreEvent::CastConnected { app_id: app_id.to_string(), device: device.to_string() });
|
||||
}
|
||||
|
||||
/// The cast ended: back to what was on screen before.
|
||||
pub fn cast_ended(self: &Arc<Self>, app_id: &str) {
|
||||
let ret = self.state.lock().unwrap().cast_return.take();
|
||||
self.emit(CoreEvent::CastEnded { app_id: app_id.to_string() });
|
||||
let Some(ret) = ret else { return };
|
||||
if !wm::available() {
|
||||
return;
|
||||
}
|
||||
match ret.filter(|id| self.is_running(id)) {
|
||||
Some(id) => {
|
||||
let core = self.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = core.launch(&id, None, false).await {
|
||||
log::warn!("back to {id}: {e:#}");
|
||||
}
|
||||
});
|
||||
}
|
||||
None => wm::focus(None),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn shutdown(self: &Arc<Self>) {
|
||||
let ids: Vec<(Option<String>, u32)> =
|
||||
self.state.lock().unwrap().running.iter().map(|r| (r.unit.clone(), r.pid)).collect();
|
||||
for (unit, pid) in ids {
|
||||
if let Some(u) = unit {
|
||||
let _ = StdCommand::new("systemctl").args(["--user", "thaw", &u]).status();
|
||||
let _ = StdCommand::new("systemctl").args(["--user", "stop", "--no-block", &u]).status();
|
||||
}
|
||||
kill_group(pid, libc::SIGCONT);
|
||||
kill_group(pid, libc::SIGTERM);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Closes the oldest frozen app when memory runs low.
|
||||
pub async fn watch_memory(core: Arc<Core>) {
|
||||
let mut tick = tokio::time::interval(Duration::from_secs(5));
|
||||
loop {
|
||||
tick.tick().await;
|
||||
let Some(avail) = mem_available_kb() else { continue };
|
||||
if avail >= LOW_MEMORY_KB {
|
||||
continue;
|
||||
}
|
||||
let Some(id) = core.oldest_background() else { continue };
|
||||
let name = core.apps().into_iter().find(|a| a.id == id).map(|a| a.name).unwrap_or(id.clone());
|
||||
log::warn!("low memory ({} MB available), closing {id}", avail / 1024);
|
||||
if core.stop(&id) {
|
||||
core.state.lock().unwrap().running.retain(|r| r.id != id);
|
||||
core.emit(CoreEvent::AppStopped { app_id: id });
|
||||
core.emit(CoreEvent::Toast { text: format!("Kevés a memória: {name} bezárva") });
|
||||
}
|
||||
}
|
||||
}
|
||||
57
crates/sf-core/src/dial.rs
Normal file
57
crates/sf-core/src/dial.rs
Normal file
@@ -0,0 +1,57 @@
|
||||
//! DIAL glue: apps with a `[dial]` section in their manifest (YouTube) can be
|
||||
//! started from a phone.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use sf_dial::{AppState, Config, Handler, LaunchParams};
|
||||
|
||||
use crate::apps::Core;
|
||||
|
||||
struct Dial(Arc<Core>);
|
||||
|
||||
impl Dial {
|
||||
fn app_for(&self, dial_name: &str) -> Option<String> {
|
||||
self.0.apps().into_iter().find(|a| a.dial.as_ref().is_some_and(|d| d.name == dial_name)).map(|a| a.id)
|
||||
}
|
||||
}
|
||||
|
||||
impl Handler for Dial {
|
||||
fn state(&self, name: &str) -> Option<AppState> {
|
||||
let id = self.app_for(name)?;
|
||||
Some(if self.0.is_running(&id) { AppState::Running } else { AppState::Stopped })
|
||||
}
|
||||
|
||||
fn launch(&self, name: &str, params: LaunchParams) -> Result<()> {
|
||||
let id = self.app_for(name).context("unknown app")?;
|
||||
log::info!("dial: {name} -> {id} from {}", params.peer);
|
||||
let core = self.0.clone();
|
||||
let query = params.query();
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = core.launch(&id, Some(query), true).await {
|
||||
log::error!("dial launch {id}: {e:#}");
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn stop(&self, name: &str) -> bool {
|
||||
match self.app_for(name) {
|
||||
Some(id) => self.0.stop(&id),
|
||||
None => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn run(core: Arc<Core>, port: u16) -> Result<()> {
|
||||
let settings = sf_ipc::Settings::load(&sf_ipc::paths::settings_file()).unwrap_or_default();
|
||||
let mut config = Config { http_port: port, ..Default::default() };
|
||||
if let Some(name) = settings.get("device_name").filter(|n| !n.trim().is_empty()) {
|
||||
config.friendly_name = name.trim().to_string();
|
||||
}
|
||||
if let Ok(id) = std::fs::read_to_string("/etc/machine-id") {
|
||||
config.uuid = sf_dial::uuid_from_machine_id(&id);
|
||||
}
|
||||
log::info!("dial: \"{}\" uuid:{}", config.friendly_name, config.uuid);
|
||||
sf_dial::run(config, Dial(core)).await
|
||||
}
|
||||
128
crates/sf-core/src/main.rs
Normal file
128
crates/sf-core/src/main.rs
Normal file
@@ -0,0 +1,128 @@
|
||||
//! sf-core: the Fennec OS core daemon.
|
||||
//!
|
||||
//! - Starts apps for the launcher, each in its own systemd user scope.
|
||||
//! Home freezes the foreground app (`systemctl --user freeze`) so it comes
|
||||
//! back instantly; under memory pressure the oldest frozen app is closed.
|
||||
//! - Runs the DIAL server, so the YouTube app on a phone can cast to the TV.
|
||||
//! - Keeps the AirPlay (UxPlay) and Miracast receivers running and reports
|
||||
//! when a device connects.
|
||||
//!
|
||||
//! Talks JSON lines with the launcher (`sf_ipc::message`) and plain text
|
||||
//! lines with the compositor (`focus launcher`, `focus <app-id>`).
|
||||
|
||||
#[cfg(unix)]
|
||||
mod apps;
|
||||
#[cfg(unix)]
|
||||
mod dial;
|
||||
#[cfg(unix)]
|
||||
mod server;
|
||||
#[cfg(unix)]
|
||||
mod services;
|
||||
#[cfg(unix)]
|
||||
mod wm;
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
unix_main()
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
{
|
||||
anyhow::bail!("sf-core runs on the TV (Linux); on a desktop the launcher starts apps itself")
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
struct Options {
|
||||
apps_dirs: Vec<std::path::PathBuf>,
|
||||
store_dir: Option<std::path::PathBuf>,
|
||||
settings: std::path::PathBuf,
|
||||
dial_port: u16,
|
||||
no_dial: bool,
|
||||
no_services: bool,
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn parse_args() -> Options {
|
||||
let mut o = Options {
|
||||
apps_dirs: vec![],
|
||||
store_dir: None,
|
||||
settings: sf_ipc::paths::settings_file(),
|
||||
dial_port: 56789,
|
||||
no_dial: false,
|
||||
no_services: false,
|
||||
};
|
||||
let mut args = std::env::args().skip(1);
|
||||
while let Some(a) = args.next() {
|
||||
match a.as_str() {
|
||||
"--apps" => o.apps_dirs.extend(args.next().map(Into::into)),
|
||||
"--store-apps" => o.store_dir = args.next().map(Into::into),
|
||||
"--settings" => o.settings = args.next().map(Into::into).unwrap_or(o.settings),
|
||||
"--dial-port" => o.dial_port = args.next().and_then(|p| p.parse().ok()).unwrap_or(o.dial_port),
|
||||
"--no-dial" => o.no_dial = true,
|
||||
"--no-services" => o.no_services = true,
|
||||
other => log::warn!("unknown argument {other}"),
|
||||
}
|
||||
}
|
||||
if o.apps_dirs.is_empty() {
|
||||
o.apps_dirs.push(sf_ipc::paths::apps_dir());
|
||||
}
|
||||
o
|
||||
}
|
||||
|
||||
/// Resolves when the Wayland display we started in goes away, so a new
|
||||
/// session doesn't find an old sf-core still running.
|
||||
#[cfg(unix)]
|
||||
async fn session_gone() {
|
||||
let Some(display) = std::env::var_os("WAYLAND_DISPLAY") else {
|
||||
return std::future::pending().await;
|
||||
};
|
||||
let path = sf_ipc::paths::runtime_dir().join(display);
|
||||
loop {
|
||||
tokio::time::sleep(std::time::Duration::from_secs(5)).await;
|
||||
if !path.exists() {
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn unix_main() -> anyhow::Result<()> {
|
||||
use std::sync::Arc;
|
||||
|
||||
let opts = parse_args();
|
||||
let rt = tokio::runtime::Builder::new_current_thread().enable_all().build()?;
|
||||
rt.block_on(async move {
|
||||
let core = Arc::new(apps::Core::new(opts.apps_dirs.clone(), opts.store_dir.clone(), opts.settings.clone())?);
|
||||
log::info!(
|
||||
"{} apps; systemd scopes: {}; window switching: {}",
|
||||
core.app_count(),
|
||||
core.uses_scopes(),
|
||||
wm::available()
|
||||
);
|
||||
tokio::spawn(apps::watch_memory(core.clone()));
|
||||
if !opts.no_services {
|
||||
services::start_all(core.clone());
|
||||
}
|
||||
if !opts.no_dial {
|
||||
let core = core.clone();
|
||||
let port = opts.dial_port;
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = dial::run(core, port).await {
|
||||
log::error!("dial: {e:#}");
|
||||
}
|
||||
});
|
||||
}
|
||||
let serve = server::serve(core.clone());
|
||||
let mut term = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate())?;
|
||||
tokio::select! {
|
||||
r = serve => r?,
|
||||
_ = session_gone() => log::info!("the Wayland session ended"),
|
||||
_ = term.recv() => log::info!("terminating"),
|
||||
_ = tokio::signal::ctrl_c() => log::info!("interrupted"),
|
||||
}
|
||||
core.shutdown();
|
||||
Ok(())
|
||||
})
|
||||
}
|
||||
81
crates/sf-core/src/server.rs
Normal file
81
crates/sf-core/src/server.rs
Normal file
@@ -0,0 +1,81 @@
|
||||
//! The core socket: the launcher sends requests, every client gets events.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use sf_ipc::{CoreEvent, LauncherRequest};
|
||||
use tokio::io::{AsyncBufReadExt, AsyncWriteExt, BufReader};
|
||||
use tokio::net::{UnixListener, UnixStream};
|
||||
use tokio::sync::broadcast::error::RecvError;
|
||||
|
||||
use crate::apps::Core;
|
||||
use crate::wm;
|
||||
|
||||
pub async fn serve(core: Arc<Core>) -> Result<()> {
|
||||
let path = sf_ipc::paths::core_socket();
|
||||
let _ = std::fs::remove_file(&path);
|
||||
let listener = UnixListener::bind(&path).with_context(|| format!("binding {}", path.display()))?;
|
||||
log::info!("core socket {}", path.display());
|
||||
loop {
|
||||
let (stream, _) = listener.accept().await?;
|
||||
let core = core.clone();
|
||||
tokio::spawn(async move {
|
||||
if let Err(e) = client(core, stream).await {
|
||||
log::debug!("client: {e:#}");
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async fn client(core: Arc<Core>, stream: UnixStream) -> Result<()> {
|
||||
let (read, mut write) = stream.into_split();
|
||||
let mut events = core.events.subscribe();
|
||||
let hello = CoreEvent::Hello { switching: wm::available(), foreground: core.foreground() };
|
||||
write.write_all(hello.to_line().as_bytes()).await?;
|
||||
|
||||
let writer = tokio::spawn(async move {
|
||||
loop {
|
||||
match events.recv().await {
|
||||
Ok(ev) => {
|
||||
if write.write_all(ev.to_line().as_bytes()).await.is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
Err(RecvError::Lagged(n)) => log::warn!("client lagged, {n} events dropped"),
|
||||
Err(RecvError::Closed) => break,
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
let mut lines = BufReader::new(read).lines();
|
||||
while let Some(line) = lines.next_line().await? {
|
||||
let line = line.trim();
|
||||
if line.is_empty() {
|
||||
continue;
|
||||
}
|
||||
match serde_json::from_str::<LauncherRequest>(line) {
|
||||
Ok(req) => handle(&core, req).await,
|
||||
Err(e) => log::warn!("bad request {line:?}: {e}"),
|
||||
}
|
||||
}
|
||||
writer.abort();
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn handle(core: &Arc<Core>, req: LauncherRequest) {
|
||||
log::info!("request {req:?}");
|
||||
match req {
|
||||
LauncherRequest::Launch { app_id, query } => {
|
||||
if let Err(e) = core.launch(&app_id, query, false).await {
|
||||
log::error!("launch {app_id}: {e:#}");
|
||||
let name = core.apps().into_iter().find(|a| a.id == app_id).map(|a| a.name).unwrap_or(app_id.clone());
|
||||
core.emit(CoreEvent::Toast { text: format!("{name}: {e:#}") });
|
||||
core.emit(CoreEvent::AppStopped { app_id });
|
||||
}
|
||||
}
|
||||
LauncherRequest::GoHome => core.go_home(),
|
||||
LauncherRequest::Stop { app_id } => {
|
||||
core.stop(&app_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
179
crates/sf-core/src/services.rs
Normal file
179
crates/sf-core/src/services.rs
Normal file
@@ -0,0 +1,179 @@
|
||||
//! Background receivers (manifests with `service = true`): AirPlay (UxPlay)
|
||||
//! and Miracast (sf-miracast). They run all the time and are restarted if
|
||||
//! they exit; their output tells us when a device connects.
|
||||
|
||||
use std::process::Stdio;
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use sf_ipc::launch::{LaunchOptions, command};
|
||||
use sf_ipc::{AppManifest, Settings};
|
||||
use tokio::io::{AsyncBufReadExt, BufReader};
|
||||
use tokio::sync::mpsc;
|
||||
|
||||
use crate::apps::Core;
|
||||
|
||||
#[derive(Debug, PartialEq)]
|
||||
pub enum Signal {
|
||||
Connected(String),
|
||||
Ended,
|
||||
}
|
||||
|
||||
/// Recognizes connection events in a receiver's output.
|
||||
/// - UxPlay: `connection request from <name> (<model>) with deviceID = …`,
|
||||
/// `Open connections: <n>`;
|
||||
/// - our own receivers: `SF-EVENT connected <name>`, `SF-EVENT ended`.
|
||||
pub fn parse_line(line: &str, connected: bool) -> Option<Signal> {
|
||||
let line = line.trim();
|
||||
if let Some(rest) = line.strip_prefix("SF-EVENT ") {
|
||||
return match rest.split_once(' ') {
|
||||
Some(("connected", name)) => Some(Signal::Connected(name.trim().to_string())),
|
||||
_ if rest == "connected" => Some(Signal::Connected(String::new())),
|
||||
_ if rest.starts_with("ended") => Some(Signal::Ended),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
if let Some(i) = line.find("connection request from ") {
|
||||
let rest = &line[i + "connection request from ".len()..];
|
||||
let name = rest.split(" (").next().unwrap_or(rest).trim();
|
||||
return Some(Signal::Connected(name.to_string()));
|
||||
}
|
||||
if let Some(i) = line.find("Open connections: ") {
|
||||
let n: u32 = line[i + "Open connections: ".len()..].trim().parse().ok()?;
|
||||
return match (n, connected) {
|
||||
(0, true) => Some(Signal::Ended),
|
||||
(n, false) if n > 0 => Some(Signal::Connected(String::new())),
|
||||
_ => None,
|
||||
};
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn start_all(core: Arc<Core>) {
|
||||
for app in core.apps().into_iter().filter(|a| a.service) {
|
||||
tokio::spawn(supervise(core.clone(), app));
|
||||
}
|
||||
}
|
||||
|
||||
async fn supervise(core: Arc<Core>, app: AppManifest) {
|
||||
let mut failures = 0u32;
|
||||
loop {
|
||||
let settings = Settings::load(&sf_ipc::paths::settings_file()).unwrap_or_default();
|
||||
let data_dir = std::env::temp_dir();
|
||||
let opts = LaunchOptions { data_dir: &data_dir, fullscreen: true, bounds: None, query: None };
|
||||
let cmd = match command(&app, &settings, &opts) {
|
||||
Ok(c) => c,
|
||||
Err(e) => {
|
||||
log::error!("{}: {e:#}", app.id);
|
||||
return;
|
||||
}
|
||||
};
|
||||
let mut cmd = cmd;
|
||||
// The receiver must not outlive us: an orphaned UxPlay would keep its
|
||||
// ports and make the next session's copy fail.
|
||||
// SAFETY: prctl is async-signal-safe.
|
||||
unsafe {
|
||||
use std::os::unix::process::CommandExt;
|
||||
cmd.pre_exec(|| {
|
||||
libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM);
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
let mut cmd = tokio::process::Command::from(cmd);
|
||||
cmd.stdout(Stdio::piped()).stderr(Stdio::piped()).stdin(Stdio::null()).kill_on_drop(true);
|
||||
let mut child = match cmd.spawn() {
|
||||
Ok(c) => c,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => {
|
||||
log::warn!("{}: {:?} is not installed; retrying in 5 minutes", app.id, app.exec);
|
||||
tokio::time::sleep(Duration::from_secs(300)).await;
|
||||
continue;
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("{}: {e}", app.id);
|
||||
tokio::time::sleep(Duration::from_secs(30)).await;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
log::info!("{} receiver running (pid {:?})", app.id, child.id());
|
||||
if let Some(pid) = child.id() {
|
||||
crate::wm::register(pid, &app.id);
|
||||
}
|
||||
let started = std::time::Instant::now();
|
||||
|
||||
let (tx, mut rx) = mpsc::unbounded_channel::<String>();
|
||||
for out in [child.stdout.take().map(|s| Box::new(s) as Box<dyn tokio::io::AsyncRead + Unpin + Send>),
|
||||
child.stderr.take().map(|s| Box::new(s) as Box<dyn tokio::io::AsyncRead + Unpin + Send>)]
|
||||
.into_iter()
|
||||
.flatten()
|
||||
{
|
||||
let tx = tx.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut lines = BufReader::new(out).lines();
|
||||
while let Ok(Some(line)) = lines.next_line().await {
|
||||
if tx.send(line).is_err() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
drop(tx);
|
||||
|
||||
let mut connected = false;
|
||||
loop {
|
||||
tokio::select! {
|
||||
line = rx.recv() => {
|
||||
let Some(line) = line else {
|
||||
let status = child.wait().await;
|
||||
log::warn!("{} receiver exited: {status:?}", app.id);
|
||||
break;
|
||||
};
|
||||
log::debug!("[{}] {line}", app.id);
|
||||
match parse_line(&line, connected) {
|
||||
Some(Signal::Connected(name)) if !connected => {
|
||||
connected = true;
|
||||
let name = if name.is_empty() { "eszköz".to_string() } else { name };
|
||||
log::info!("{}: {name} connected", app.id);
|
||||
core.cast_connected(&app.id, &name);
|
||||
}
|
||||
Some(Signal::Ended) if connected => {
|
||||
connected = false;
|
||||
log::info!("{}: session ended", app.id);
|
||||
core.cast_ended(&app.id);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
status = child.wait() => {
|
||||
log::warn!("{} receiver exited: {status:?}", app.id);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
let _ = child.kill().await;
|
||||
if connected {
|
||||
core.cast_ended(&app.id);
|
||||
}
|
||||
failures = if started.elapsed() > Duration::from_secs(60) { 0 } else { failures + 1 };
|
||||
let wait = Duration::from_secs((2u64 << failures.min(5)).min(60));
|
||||
tokio::time::sleep(wait).await;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_receiver_output() {
|
||||
assert_eq!(
|
||||
parse_line("connection request from Peti iPhone-ja (iPhone15,2) with deviceID = AA:BB", false),
|
||||
Some(Signal::Connected("Peti iPhone-ja".into()))
|
||||
);
|
||||
assert_eq!(parse_line("Open connections: 0", true), Some(Signal::Ended));
|
||||
assert_eq!(parse_line("Open connections: 0", false), None);
|
||||
assert_eq!(parse_line("Open connections: 1", false), Some(Signal::Connected(String::new())));
|
||||
assert_eq!(parse_line("SF-EVENT connected Galaxy S24", false), Some(Signal::Connected("Galaxy S24".into())));
|
||||
assert_eq!(parse_line("SF-EVENT ended", true), Some(Signal::Ended));
|
||||
assert_eq!(parse_line("random", false), None);
|
||||
}
|
||||
}
|
||||
56
crates/sf-core/src/wm.rs
Normal file
56
crates/sf-core/src/wm.rs
Normal file
@@ -0,0 +1,56 @@
|
||||
//! Client for the sf-compositor control socket. One command per line, one
|
||||
//! reply line (`ok` or `err <reason>`):
|
||||
//! focus launcher show the launcher
|
||||
//! focus <app-id> show that app's window (as soon as it has one)
|
||||
//! register <pgid> <app-id> windows of that process group belong to the app
|
||||
//!
|
||||
//! Without sf-compositor (e.g. under cage) there is no socket: the newest
|
||||
//! window is always on top, so apps can't wait in the background.
|
||||
|
||||
use std::io::{BufRead, BufReader, Write};
|
||||
use std::os::unix::net::UnixStream;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
|
||||
pub fn available() -> bool {
|
||||
sf_ipc::paths::wm_socket().exists()
|
||||
}
|
||||
|
||||
pub fn send(cmd: &str) -> Result<()> {
|
||||
let path = sf_ipc::paths::wm_socket();
|
||||
let mut s = UnixStream::connect(&path).with_context(|| format!("connecting {}", path.display()))?;
|
||||
s.set_read_timeout(Some(Duration::from_secs(2)))?;
|
||||
s.set_write_timeout(Some(Duration::from_secs(2)))?;
|
||||
writeln!(s, "{cmd}")?;
|
||||
let mut reply = String::new();
|
||||
BufReader::new(s).read_line(&mut reply)?;
|
||||
let reply = reply.trim();
|
||||
if reply == "ok" {
|
||||
Ok(())
|
||||
} else {
|
||||
bail!("compositor: {reply}")
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows an app, or the launcher with `None`. Logs instead of failing.
|
||||
pub fn focus(app_id: Option<&str>) {
|
||||
if !available() {
|
||||
return;
|
||||
}
|
||||
let cmd = format!("focus {}", app_id.unwrap_or("launcher"));
|
||||
if let Err(e) = send(&cmd) {
|
||||
log::warn!("{cmd}: {e:#}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Tells the compositor which app a process group belongs to (Chromium hides
|
||||
/// its environment, so the compositor can't find out by itself).
|
||||
pub fn register(pgid: u32, app_id: &str) {
|
||||
if !available() {
|
||||
return;
|
||||
}
|
||||
if let Err(e) = send(&format!("register {pgid} {app_id}")) {
|
||||
log::warn!("register {app_id}: {e:#}");
|
||||
}
|
||||
}
|
||||
15
crates/sf-dial/Cargo.toml
Normal file
15
crates/sf-dial/Cargo.toml
Normal file
@@ -0,0 +1,15 @@
|
||||
[package]
|
||||
name = "sf-dial"
|
||||
description = "DIAL (DIscovery And Launch) server: SSDP discovery and the app REST API, so phones can cast YouTube"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
anyhow.workspace = true
|
||||
log.workspace = true
|
||||
tokio = { version = "1", features = ["rt", "net", "time", "io-util", "sync", "macros"] }
|
||||
socket2 = { version = "0.6", features = ["all"] }
|
||||
|
||||
[dev-dependencies]
|
||||
tokio = { version = "1", features = ["rt-multi-thread", "macros"] }
|
||||
243
crates/sf-dial/src/http.rs
Normal file
243
crates/sf-dial/src/http.rs
Normal file
@@ -0,0 +1,243 @@
|
||||
//! Just enough HTTP/1.1 for DIAL: small requests, `Content-Length` bodies,
|
||||
//! one request per connection (`Connection: close`).
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
|
||||
|
||||
/// DIAL limits launch payloads; anything bigger is refused (413).
|
||||
pub const MAX_BODY: usize = 4096;
|
||||
const MAX_HEAD: usize = 8192;
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Request {
|
||||
pub method: String,
|
||||
/// Path without the query string.
|
||||
pub path: String,
|
||||
pub query: String,
|
||||
pub headers: Vec<(String, String)>,
|
||||
pub body: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Request {
|
||||
pub fn header(&self, name: &str) -> Option<&str> {
|
||||
self.headers.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
pub enum ReadError {
|
||||
TooLarge,
|
||||
Bad(anyhow::Error),
|
||||
}
|
||||
|
||||
impl From<anyhow::Error> for ReadError {
|
||||
fn from(e: anyhow::Error) -> Self {
|
||||
ReadError::Bad(e)
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn read_request<S: AsyncRead + Unpin>(stream: &mut S) -> Result<Request, ReadError> {
|
||||
tokio::time::timeout(Duration::from_secs(10), read_inner(stream))
|
||||
.await
|
||||
.map_err(|_| ReadError::Bad(anyhow::anyhow!("timeout")))?
|
||||
}
|
||||
|
||||
async fn read_inner<S: AsyncRead + Unpin>(stream: &mut S) -> Result<Request, ReadError> {
|
||||
let mut buf = Vec::with_capacity(1024);
|
||||
let head_end = loop {
|
||||
if let Some(i) = find(&buf, b"\r\n\r\n") {
|
||||
break i;
|
||||
}
|
||||
if buf.len() > MAX_HEAD {
|
||||
return Err(ReadError::TooLarge);
|
||||
}
|
||||
let mut chunk = [0u8; 1024];
|
||||
let n = stream.read(&mut chunk).await.context("read")?;
|
||||
if n == 0 {
|
||||
return Err(ReadError::Bad(anyhow::anyhow!("connection closed")));
|
||||
}
|
||||
buf.extend_from_slice(&chunk[..n]);
|
||||
};
|
||||
let head = std::str::from_utf8(&buf[..head_end]).context("head is not UTF-8")?;
|
||||
let mut req = parse_head(head)?;
|
||||
let len: usize = match req.header("content-length") {
|
||||
Some(v) => v.trim().parse().context("bad content-length")?,
|
||||
None => 0,
|
||||
};
|
||||
if len > MAX_BODY {
|
||||
return Err(ReadError::TooLarge);
|
||||
}
|
||||
let mut body = buf[head_end + 4..].to_vec();
|
||||
while body.len() < len {
|
||||
let mut chunk = [0u8; 1024];
|
||||
let n = stream.read(&mut chunk).await.context("read body")?;
|
||||
if n == 0 {
|
||||
break;
|
||||
}
|
||||
body.extend_from_slice(&chunk[..n]);
|
||||
}
|
||||
body.truncate(len);
|
||||
req.body = body;
|
||||
Ok(req)
|
||||
}
|
||||
|
||||
fn find(hay: &[u8], needle: &[u8]) -> Option<usize> {
|
||||
hay.windows(needle.len()).position(|w| w == needle)
|
||||
}
|
||||
|
||||
fn parse_head(head: &str) -> Result<Request> {
|
||||
let mut lines = head.split("\r\n");
|
||||
let first = lines.next().context("empty request")?;
|
||||
let mut parts = first.split(' ');
|
||||
let (Some(method), Some(target), Some(version)) = (parts.next(), parts.next(), parts.next()) else {
|
||||
bail!("bad request line {first:?}");
|
||||
};
|
||||
if !version.starts_with("HTTP/1.") {
|
||||
bail!("unsupported {version}");
|
||||
}
|
||||
let (path, query) = match target.split_once('?') {
|
||||
Some((p, q)) => (p, q),
|
||||
None => (target, ""),
|
||||
};
|
||||
let headers = lines
|
||||
.filter_map(|l| l.split_once(':'))
|
||||
.map(|(k, v)| (k.trim().to_string(), v.trim().to_string()))
|
||||
.collect();
|
||||
Ok(Request { method: method.to_string(), path: path.to_string(), query: query.to_string(), headers, body: vec![] })
|
||||
}
|
||||
|
||||
pub struct Response {
|
||||
pub status: u16,
|
||||
pub headers: Vec<(String, String)>,
|
||||
pub body: Vec<u8>,
|
||||
}
|
||||
|
||||
impl Response {
|
||||
pub fn new(status: u16) -> Self {
|
||||
Response { status, headers: vec![], body: vec![] }
|
||||
}
|
||||
|
||||
pub fn header(mut self, k: &str, v: impl Into<String>) -> Self {
|
||||
self.headers.push((k.to_string(), v.into()));
|
||||
self
|
||||
}
|
||||
|
||||
pub fn xml(status: u16, body: String) -> Self {
|
||||
Response::new(status).header("Content-Type", "text/xml; charset=\"utf-8\"").with_body(body.into_bytes())
|
||||
}
|
||||
|
||||
pub fn with_body(mut self, body: Vec<u8>) -> Self {
|
||||
self.body = body;
|
||||
self
|
||||
}
|
||||
|
||||
pub async fn write<S: AsyncWrite + Unpin>(&self, stream: &mut S) -> std::io::Result<()> {
|
||||
let mut out = format!("HTTP/1.1 {} {}\r\n", self.status, reason(self.status));
|
||||
for (k, v) in &self.headers {
|
||||
out.push_str(&format!("{k}: {v}\r\n"));
|
||||
}
|
||||
out.push_str(&format!("Content-Length: {}\r\nConnection: close\r\n\r\n", self.body.len()));
|
||||
stream.write_all(out.as_bytes()).await?;
|
||||
stream.write_all(&self.body).await?;
|
||||
stream.flush().await
|
||||
}
|
||||
}
|
||||
|
||||
fn reason(status: u16) -> &'static str {
|
||||
match status {
|
||||
200 => "OK",
|
||||
201 => "Created",
|
||||
204 => "No Content",
|
||||
400 => "Bad Request",
|
||||
403 => "Forbidden",
|
||||
404 => "Not Found",
|
||||
405 => "Method Not Allowed",
|
||||
413 => "Request Entity Too Large",
|
||||
500 => "Internal Server Error",
|
||||
503 => "Service Unavailable",
|
||||
_ => "",
|
||||
}
|
||||
}
|
||||
|
||||
/// Decodes an `application/x-www-form-urlencoded` string into pairs.
|
||||
pub fn parse_form(s: &str) -> Vec<(String, String)> {
|
||||
s.split('&')
|
||||
.filter(|p| !p.is_empty())
|
||||
.map(|p| match p.split_once('=') {
|
||||
Some((k, v)) => (url_decode(k), url_decode(v)),
|
||||
None => (url_decode(p), String::new()),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn url_decode(s: &str) -> String {
|
||||
let bytes = s.as_bytes();
|
||||
let mut out = Vec::with_capacity(bytes.len());
|
||||
let mut i = 0;
|
||||
while i < bytes.len() {
|
||||
match bytes[i] {
|
||||
b'+' => out.push(b' '),
|
||||
b'%' if i + 2 < bytes.len() => {
|
||||
match u8::from_str_radix(std::str::from_utf8(&bytes[i + 1..i + 3]).unwrap_or("zz"), 16) {
|
||||
Ok(b) => {
|
||||
out.push(b);
|
||||
i += 2;
|
||||
}
|
||||
Err(_) => out.push(b'%'),
|
||||
}
|
||||
}
|
||||
b => out.push(b),
|
||||
}
|
||||
i += 1;
|
||||
}
|
||||
String::from_utf8_lossy(&out).into_owned()
|
||||
}
|
||||
|
||||
pub fn url_encode(s: &str) -> String {
|
||||
let mut out = String::with_capacity(s.len());
|
||||
for b in s.bytes() {
|
||||
match b {
|
||||
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => out.push(b as char),
|
||||
_ => out.push_str(&format!("%{b:02X}")),
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub fn xml_escape(s: &str) -> String {
|
||||
s.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """).replace('\'', "'")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn reads_post() {
|
||||
let raw = b"POST /apps/YouTube?x=1 HTTP/1.1\r\nHost: a\r\nContent-Length: 11\r\n\r\npairingCode";
|
||||
let req = read_request(&mut &raw[..]).await.unwrap();
|
||||
assert_eq!(req.method, "POST");
|
||||
assert_eq!(req.path, "/apps/YouTube");
|
||||
assert_eq!(req.query, "x=1");
|
||||
assert_eq!(req.header("content-length"), Some("11"));
|
||||
assert_eq!(req.body, b"pairingCode");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn refuses_big_body() {
|
||||
let raw = b"POST / HTTP/1.1\r\nContent-Length: 99999\r\n\r\n";
|
||||
assert!(matches!(read_request(&mut &raw[..]).await, Err(ReadError::TooLarge)));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_forms() {
|
||||
assert_eq!(
|
||||
parse_form("a=1&b=hello+world%21&c"),
|
||||
vec![("a".into(), "1".into()), ("b".into(), "hello world!".into()), ("c".into(), "".into())]
|
||||
);
|
||||
assert_eq!(url_decode("100%"), "100%");
|
||||
assert_eq!(url_encode("http://x/y z"), "http%3A%2F%2Fx%2Fy%20z");
|
||||
}
|
||||
}
|
||||
372
crates/sf-dial/src/lib.rs
Normal file
372
crates/sf-dial/src/lib.rs
Normal file
@@ -0,0 +1,372 @@
|
||||
//! DIAL server (DIAL 2.1): phones find the TV over SSDP and start apps on
|
||||
//! it with a REST call. This is how the YouTube app casts to a TV that has
|
||||
//! no Google Cast receiver: it POSTs a pairing code to `/apps/YouTube`, the
|
||||
//! TV opens `youtube.com/tv?<that body>`, and the page pairs with the phone.
|
||||
//!
|
||||
//! The server only speaks the protocol; what "launch" means is up to the
|
||||
//! [`Handler`] (sf-core starts the YouTube web app).
|
||||
|
||||
pub mod http;
|
||||
pub mod ssdp;
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::net::{IpAddr, SocketAddr};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use tokio::net::TcpListener;
|
||||
|
||||
use http::{Request, Response, parse_form, url_encode, xml_escape};
|
||||
|
||||
pub use ssdp::DIAL_ST;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum AppState {
|
||||
Running,
|
||||
Stopped,
|
||||
}
|
||||
|
||||
/// What a phone sent with a launch request.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct LaunchParams {
|
||||
/// The POST body (YouTube: `pairingCode=…&v=…&t=…`).
|
||||
pub body: String,
|
||||
/// Where the running app may store data for the phone (DIAL `additionalDataUrl`).
|
||||
pub additional_data_url: String,
|
||||
pub peer: IpAddr,
|
||||
}
|
||||
|
||||
impl LaunchParams {
|
||||
/// Query string for the app's start URL: the body plus `additionalDataUrl`.
|
||||
pub fn query(&self) -> String {
|
||||
let body = self.body.trim().trim_start_matches(['?', '&']);
|
||||
let extra = format!("additionalDataUrl={}", url_encode(&self.additional_data_url));
|
||||
if body.is_empty() { extra } else { format!("{body}&{extra}") }
|
||||
}
|
||||
}
|
||||
|
||||
pub trait Handler: Send + Sync + 'static {
|
||||
/// State of a DIAL app, `None` if we don't know the name (404).
|
||||
fn state(&self, name: &str) -> Option<AppState>;
|
||||
fn launch(&self, name: &str, params: LaunchParams) -> Result<()>;
|
||||
/// Stop the app; false if it wasn't running.
|
||||
fn stop(&self, name: &str) -> bool;
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Config {
|
||||
pub friendly_name: String,
|
||||
pub manufacturer: String,
|
||||
pub model_name: String,
|
||||
/// Stable device id (UPnP UDN without the `uuid:` prefix).
|
||||
pub uuid: String,
|
||||
pub http_port: u16,
|
||||
}
|
||||
|
||||
impl Default for Config {
|
||||
fn default() -> Self {
|
||||
Config {
|
||||
friendly_name: "Fennec OS".into(),
|
||||
manufacturer: "Fennec OS".into(),
|
||||
model_name: "Fennec OS TV".into(),
|
||||
uuid: "2f6e7d1c-5a8b-4c3d-9e0f-736d61727466".into(),
|
||||
http_port: 56789,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A UUID derived from a machine id (e.g. `/etc/machine-id`), so the TV keeps
|
||||
/// its identity across reboots and phones remember it.
|
||||
pub fn uuid_from_machine_id(id: &str) -> String {
|
||||
let hex: String = id.chars().filter(|c| c.is_ascii_hexdigit()).take(32).collect::<String>().to_lowercase();
|
||||
if hex.len() < 32 {
|
||||
return Config::default().uuid;
|
||||
}
|
||||
format!("{}-{}-{}-{}-{}", &hex[0..8], &hex[8..12], &hex[12..16], &hex[16..20], &hex[20..32])
|
||||
}
|
||||
|
||||
struct Server<H> {
|
||||
config: Config,
|
||||
handler: H,
|
||||
/// `additionalData` posted by running apps, per DIAL app name.
|
||||
data: Mutex<HashMap<String, Vec<(String, String)>>>,
|
||||
}
|
||||
|
||||
/// Runs SSDP and the HTTP server until an error stops one of them.
|
||||
pub async fn run<H: Handler>(config: Config, handler: H) -> Result<()> {
|
||||
let listener = TcpListener::bind(("0.0.0.0", config.http_port))
|
||||
.await
|
||||
.with_context(|| format!("binding DIAL http port {}", config.http_port))?;
|
||||
log::info!("dial: http on :{}", config.http_port);
|
||||
let announce = ssdp::Announce {
|
||||
uuid: config.uuid.clone(),
|
||||
http_port: config.http_port,
|
||||
server: "Linux/6 UPnP/1.1 FennecOS/0.1".into(),
|
||||
};
|
||||
let server = Arc::new(Server { config, handler, data: Mutex::default() });
|
||||
let http = async move {
|
||||
loop {
|
||||
let (mut stream, peer) = listener.accept().await?;
|
||||
let server = server.clone();
|
||||
tokio::spawn(async move {
|
||||
let local = stream.local_addr().ok();
|
||||
let resp = match http::read_request(&mut stream).await {
|
||||
Ok(req) => server.route(&req, peer, local),
|
||||
Err(http::ReadError::TooLarge) => Response::new(413),
|
||||
Err(http::ReadError::Bad(e)) => {
|
||||
log::debug!("dial: bad request from {peer}: {e:#}");
|
||||
Response::new(400)
|
||||
}
|
||||
};
|
||||
let _ = resp.write(&mut stream).await;
|
||||
});
|
||||
}
|
||||
#[allow(unreachable_code)]
|
||||
Ok::<(), anyhow::Error>(())
|
||||
};
|
||||
tokio::select! {
|
||||
r = http => r,
|
||||
r = ssdp::run(announce) => r,
|
||||
}
|
||||
}
|
||||
|
||||
/// DIAL 2.1 asks servers to refuse web pages from other sites (CSRF).
|
||||
/// Native apps send no Origin, or a non-web one like `package:…`.
|
||||
fn origin_allowed(origin: Option<&str>) -> bool {
|
||||
let Some(origin) = origin else { return true };
|
||||
let Some(rest) = origin.strip_prefix("https://").or_else(|| origin.strip_prefix("http://")) else {
|
||||
return true;
|
||||
};
|
||||
let host = rest.split(['/', ':']).next().unwrap_or("");
|
||||
host == "localhost" || host == "127.0.0.1" || host == "youtube.com" || host.ends_with(".youtube.com")
|
||||
}
|
||||
|
||||
impl<H: Handler> Server<H> {
|
||||
fn base_url(&self, local: Option<SocketAddr>) -> String {
|
||||
let ip = match local {
|
||||
Some(SocketAddr::V4(a)) => a.ip().to_string(),
|
||||
Some(SocketAddr::V6(a)) => match a.ip().to_ipv4_mapped() {
|
||||
Some(v4) => v4.to_string(),
|
||||
None => format!("[{}]", a.ip()),
|
||||
},
|
||||
None => "127.0.0.1".into(),
|
||||
};
|
||||
format!("http://{ip}:{}", self.config.http_port)
|
||||
}
|
||||
|
||||
fn route(&self, req: &Request, peer: SocketAddr, local: Option<SocketAddr>) -> Response {
|
||||
log::debug!("dial: {} {} from {peer}", req.method, req.path);
|
||||
let cors = |r: Response| {
|
||||
r.header("Access-Control-Allow-Origin", "*")
|
||||
.header("Access-Control-Allow-Methods", "GET, POST, DELETE, OPTIONS")
|
||||
.header("Access-Control-Allow-Headers", "Content-Type")
|
||||
.header("Access-Control-Allow-Private-Network", "true")
|
||||
};
|
||||
if req.method == "OPTIONS" {
|
||||
return cors(Response::new(204));
|
||||
}
|
||||
let segs: Vec<&str> = req.path.trim_matches('/').split('/').collect();
|
||||
match (req.method.as_str(), segs.as_slice()) {
|
||||
("GET", ["dd.xml"]) => self.device_description(local),
|
||||
(_, ["apps", name, ..]) if !origin_allowed(req.header("origin")) => {
|
||||
log::warn!("dial: {} {name} refused, origin {:?}", req.method, req.header("origin"));
|
||||
Response::new(403)
|
||||
}
|
||||
("GET", ["apps", name]) => self.app_status(name),
|
||||
("POST", ["apps", name]) => self.launch(name, req, peer, local),
|
||||
("DELETE", ["apps", name, "run"]) => {
|
||||
if self.handler.state(name).is_none() {
|
||||
return Response::new(404);
|
||||
}
|
||||
if self.handler.stop(name) {
|
||||
self.data.lock().unwrap().remove(*name);
|
||||
log::info!("dial: {name} stopped by {peer}");
|
||||
Response::new(200)
|
||||
} else {
|
||||
Response::new(404)
|
||||
}
|
||||
}
|
||||
("POST", ["apps", name, "dial_data"]) => {
|
||||
if self.handler.state(name).is_none() {
|
||||
return Response::new(404);
|
||||
}
|
||||
let mut pairs = parse_form(&req.query);
|
||||
pairs.extend(parse_form(&String::from_utf8_lossy(&req.body)));
|
||||
self.data.lock().unwrap().insert(name.to_string(), pairs);
|
||||
cors(Response::new(200))
|
||||
}
|
||||
(_, ["apps", ..]) => Response::new(405),
|
||||
_ => Response::new(404),
|
||||
}
|
||||
}
|
||||
|
||||
fn device_description(&self, local: Option<SocketAddr>) -> Response {
|
||||
let c = &self.config;
|
||||
let xml = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<root xmlns="urn:schemas-upnp-org:device-1-0">
|
||||
<specVersion><major>1</major><minor>0</minor></specVersion>
|
||||
<device>
|
||||
<deviceType>urn:dial-multiscreen-org:device:dial:1</deviceType>
|
||||
<friendlyName>{}</friendlyName>
|
||||
<manufacturer>{}</manufacturer>
|
||||
<modelName>{}</modelName>
|
||||
<UDN>uuid:{}</UDN>
|
||||
<serviceList>
|
||||
<service>
|
||||
<serviceType>urn:dial-multiscreen-org:service:dial:1</serviceType>
|
||||
<serviceId>urn:dial-multiscreen-org:serviceId:dial</serviceId>
|
||||
<controlURL>/ssdp/notfound</controlURL>
|
||||
<eventSubURL>/ssdp/notfound</eventSubURL>
|
||||
<SCPDURL>/ssdp/notfound</SCPDURL>
|
||||
</service>
|
||||
</serviceList>
|
||||
</device>
|
||||
</root>
|
||||
"#,
|
||||
xml_escape(&c.friendly_name),
|
||||
xml_escape(&c.manufacturer),
|
||||
xml_escape(&c.model_name),
|
||||
xml_escape(&c.uuid),
|
||||
);
|
||||
Response::xml(200, xml)
|
||||
.header("Application-URL", format!("{}/apps/", self.base_url(local)))
|
||||
.header("Access-Control-Expose-Headers", "Application-URL")
|
||||
}
|
||||
|
||||
fn app_status(&self, name: &str) -> Response {
|
||||
let Some(state) = self.handler.state(name) else { return Response::new(404) };
|
||||
let running = state == AppState::Running;
|
||||
let data: String = self
|
||||
.data
|
||||
.lock()
|
||||
.unwrap()
|
||||
.get(name)
|
||||
.filter(|_| running)
|
||||
.map(|pairs| {
|
||||
pairs
|
||||
.iter()
|
||||
.filter(|(k, _)| !k.is_empty() && k.chars().all(|c| c.is_ascii_alphanumeric() || c == '_'))
|
||||
.map(|(k, v)| format!("<{k}>{}</{k}>", xml_escape(v)))
|
||||
.collect()
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let xml = format!(
|
||||
r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<service xmlns="urn:dial-multiscreen-org:schemas:dial" dialVer="2.1">
|
||||
<name>{}</name>
|
||||
<options allowStop="true"/>
|
||||
<state>{}</state>{}
|
||||
<additionalData>{data}</additionalData>
|
||||
</service>
|
||||
"#,
|
||||
xml_escape(name),
|
||||
if running { "running" } else { "stopped" },
|
||||
if running { "\n <link rel=\"run\" href=\"run\"/>" } else { "" },
|
||||
);
|
||||
Response::xml(200, xml)
|
||||
}
|
||||
|
||||
fn launch(&self, name: &str, req: &Request, peer: SocketAddr, local: Option<SocketAddr>) -> Response {
|
||||
if self.handler.state(name).is_none() {
|
||||
return Response::new(404);
|
||||
}
|
||||
let params = LaunchParams {
|
||||
body: String::from_utf8_lossy(&req.body).into_owned(),
|
||||
// The app runs on this machine, so it reaches us on localhost
|
||||
// (an https page may call http://localhost, not a LAN address).
|
||||
additional_data_url: format!("http://localhost:{}/apps/{name}/dial_data", self.config.http_port),
|
||||
peer: peer.ip(),
|
||||
};
|
||||
log::info!("dial: launch {name} from {peer} ({} bytes)", params.body.len());
|
||||
match self.handler.launch(name, params) {
|
||||
Ok(()) => Response::new(201)
|
||||
.header("Location", format!("{}/apps/{name}/run", self.base_url(local)))
|
||||
.header("Content-Type", "text/plain"),
|
||||
Err(e) => {
|
||||
log::error!("dial: launching {name}: {e:#}");
|
||||
Response::new(503)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use std::sync::atomic::{AtomicBool, Ordering};
|
||||
|
||||
#[derive(Default)]
|
||||
struct Fake {
|
||||
running: AtomicBool,
|
||||
last: Mutex<Option<LaunchParams>>,
|
||||
}
|
||||
|
||||
impl Handler for Arc<Fake> {
|
||||
fn state(&self, name: &str) -> Option<AppState> {
|
||||
(name == "YouTube").then(|| if self.running.load(Ordering::SeqCst) { AppState::Running } else { AppState::Stopped })
|
||||
}
|
||||
fn launch(&self, _name: &str, params: LaunchParams) -> Result<()> {
|
||||
self.running.store(true, Ordering::SeqCst);
|
||||
*self.last.lock().unwrap() = Some(params);
|
||||
Ok(())
|
||||
}
|
||||
fn stop(&self, _name: &str) -> bool {
|
||||
self.running.swap(false, Ordering::SeqCst)
|
||||
}
|
||||
}
|
||||
|
||||
fn req(method: &str, path: &str, body: &str, origin: Option<&str>) -> Request {
|
||||
let mut headers = vec![];
|
||||
if let Some(o) = origin {
|
||||
headers.push(("Origin".to_string(), o.to_string()));
|
||||
}
|
||||
Request { method: method.into(), path: path.into(), query: String::new(), headers, body: body.as_bytes().to_vec() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn launch_status_stop() {
|
||||
let fake = Arc::new(Fake::default());
|
||||
let s = Server { config: Config::default(), handler: fake.clone(), data: Mutex::default() };
|
||||
let peer: SocketAddr = "10.0.0.20:5555".parse().unwrap();
|
||||
let local: Option<SocketAddr> = Some("10.0.0.7:56789".parse().unwrap());
|
||||
|
||||
let dd = s.route(&req("GET", "/dd.xml", "", None), peer, local);
|
||||
assert_eq!(dd.status, 200);
|
||||
assert!(dd.headers.iter().any(|(k, v)| k == "Application-URL" && v == "http://10.0.0.7:56789/apps/"));
|
||||
|
||||
let st = s.route(&req("GET", "/apps/YouTube", "", None), peer, local);
|
||||
assert!(String::from_utf8_lossy(&st.body).contains("<state>stopped</state>"));
|
||||
assert_eq!(s.route(&req("GET", "/apps/Netflix", "", None), peer, local).status, 404);
|
||||
|
||||
let r = s.route(&req("POST", "/apps/YouTube", "pairingCode=abc&v=xyz", None), peer, local);
|
||||
assert_eq!(r.status, 201);
|
||||
assert!(r.headers.iter().any(|(k, v)| k == "Location" && v == "http://10.0.0.7:56789/apps/YouTube/run"));
|
||||
let q = fake.last.lock().unwrap().as_ref().unwrap().query();
|
||||
assert_eq!(q, "pairingCode=abc&v=xyz&additionalDataUrl=http%3A%2F%2Flocalhost%3A56789%2Fapps%2FYouTube%2Fdial_data");
|
||||
|
||||
s.route(&req("POST", "/apps/YouTube/dial_data", "screenId=s1&x<y=1", None), peer, local);
|
||||
let st = s.route(&req("GET", "/apps/YouTube", "", None), peer, local);
|
||||
let body = String::from_utf8_lossy(&st.body).into_owned();
|
||||
assert!(body.contains("<state>running</state>"));
|
||||
assert!(body.contains("<additionalData><screenId>s1</screenId></additionalData>"));
|
||||
|
||||
assert_eq!(s.route(&req("DELETE", "/apps/YouTube/run", "", None), peer, local).status, 200);
|
||||
assert_eq!(s.route(&req("DELETE", "/apps/YouTube/run", "", None), peer, local).status, 404);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refuses_foreign_web_origins() {
|
||||
let s = Server { config: Config::default(), handler: Arc::new(Fake::default()), data: Mutex::default() };
|
||||
let peer: SocketAddr = "10.0.0.20:5555".parse().unwrap();
|
||||
assert_eq!(s.route(&req("POST", "/apps/YouTube", "", Some("https://evil.example")), peer, None).status, 403);
|
||||
assert_eq!(s.route(&req("POST", "/apps/YouTube", "", Some("https://www.youtube.com")), peer, None).status, 201);
|
||||
assert_eq!(s.route(&req("POST", "/apps/YouTube", "", Some("package:com.google.android.youtube")), peer, None).status, 201);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn uuid_from_machine_id_is_stable() {
|
||||
assert_eq!(uuid_from_machine_id("0123456789abcdef0123456789ABCDEF\n"), "01234567-89ab-cdef-0123-456789abcdef");
|
||||
assert_eq!(uuid_from_machine_id("short"), Config::default().uuid);
|
||||
}
|
||||
}
|
||||
197
crates/sf-dial/src/ssdp.rs
Normal file
197
crates/sf-dial/src/ssdp.rs
Normal file
@@ -0,0 +1,197 @@
|
||||
//! SSDP: answers M-SEARCH for the DIAL service and announces the TV with
|
||||
//! NOTIFY, so phones on the same network find it.
|
||||
|
||||
use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4, UdpSocket as StdUdp};
|
||||
use std::sync::Arc;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use socket2::{Domain, Protocol, Socket, Type};
|
||||
use tokio::net::UdpSocket;
|
||||
|
||||
pub const DIAL_ST: &str = "urn:dial-multiscreen-org:service:dial:1";
|
||||
const GROUP: Ipv4Addr = Ipv4Addr::new(239, 255, 255, 250);
|
||||
const PORT: u16 = 1900;
|
||||
const MAX_AGE: u32 = 1800;
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct Announce {
|
||||
pub uuid: String,
|
||||
pub http_port: u16,
|
||||
pub server: String,
|
||||
}
|
||||
|
||||
impl Announce {
|
||||
fn location(&self, ip: Ipv4Addr) -> String {
|
||||
format!("http://{ip}:{}/dd.xml", self.http_port)
|
||||
}
|
||||
|
||||
fn usn(&self, st: &str) -> String {
|
||||
if st == format!("uuid:{}", self.uuid) {
|
||||
st.to_string()
|
||||
} else {
|
||||
format!("uuid:{}::{st}", self.uuid)
|
||||
}
|
||||
}
|
||||
|
||||
/// Unicast answer to an M-SEARCH.
|
||||
pub fn search_response(&self, st: &str, ip: Ipv4Addr) -> String {
|
||||
format!(
|
||||
"HTTP/1.1 200 OK\r\nCACHE-CONTROL: max-age={MAX_AGE}\r\nEXT:\r\nLOCATION: {}\r\nSERVER: {}\r\nST: {st}\r\nUSN: {}\r\nBOOTID.UPNP.ORG: 1\r\nCONFIGID.UPNP.ORG: 1\r\n\r\n",
|
||||
self.location(ip),
|
||||
self.server,
|
||||
self.usn(st),
|
||||
)
|
||||
}
|
||||
|
||||
fn notify(&self, nt: &str, ip: Ipv4Addr) -> String {
|
||||
format!(
|
||||
"NOTIFY * HTTP/1.1\r\nHOST: 239.255.255.250:1900\r\nCACHE-CONTROL: max-age={MAX_AGE}\r\nLOCATION: {}\r\nNT: {nt}\r\nNTS: ssdp:alive\r\nSERVER: {}\r\nUSN: {}\r\nBOOTID.UPNP.ORG: 1\r\nCONFIGID.UPNP.ORG: 1\r\n\r\n",
|
||||
self.location(ip),
|
||||
self.server,
|
||||
self.usn(nt),
|
||||
)
|
||||
}
|
||||
|
||||
/// Which search targets we answer, for an M-SEARCH `ST` header.
|
||||
pub fn targets_for(&self, st: &str) -> Vec<String> {
|
||||
let own = format!("uuid:{}", self.uuid);
|
||||
match st {
|
||||
"ssdp:all" => vec![DIAL_ST.into(), "upnp:rootdevice".into(), own],
|
||||
"upnp:rootdevice" => vec!["upnp:rootdevice".into()],
|
||||
s if s == DIAL_ST || s == own => vec![s.to_string()],
|
||||
_ => vec![],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The local address used to reach `peer` (picks the right interface).
|
||||
pub fn local_ip_for(peer: Ipv4Addr) -> Option<Ipv4Addr> {
|
||||
let s = StdUdp::bind("0.0.0.0:0").ok()?;
|
||||
s.connect(SocketAddrV4::new(peer, PORT)).ok()?;
|
||||
match s.local_addr().ok()? {
|
||||
SocketAddr::V4(a) if !a.ip().is_unspecified() => Some(*a.ip()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
fn bind_multicast() -> Result<UdpSocket> {
|
||||
let sock = Socket::new(Domain::IPV4, Type::DGRAM, Some(Protocol::UDP))?;
|
||||
sock.set_reuse_address(true)?;
|
||||
#[cfg(unix)]
|
||||
sock.set_reuse_port(true)?;
|
||||
sock.bind(&SocketAddr::from((Ipv4Addr::UNSPECIFIED, PORT)).into()).context("binding udp/1900")?;
|
||||
sock.set_nonblocking(true)?;
|
||||
sock.set_multicast_loop_v4(true)?;
|
||||
sock.set_multicast_ttl_v4(2)?;
|
||||
Ok(UdpSocket::from_std(sock.into())?)
|
||||
}
|
||||
|
||||
fn parse_search(text: &str) -> Option<(String, u64)> {
|
||||
let mut lines = text.split("\r\n");
|
||||
if !lines.next()?.starts_with("M-SEARCH") {
|
||||
return None;
|
||||
}
|
||||
let mut st = None;
|
||||
let mut mx = 1u64;
|
||||
let mut man_ok = false;
|
||||
for line in lines {
|
||||
let Some((k, v)) = line.split_once(':') else { continue };
|
||||
let v = v.trim();
|
||||
match k.trim().to_ascii_uppercase().as_str() {
|
||||
"ST" => st = Some(v.to_string()),
|
||||
"MX" => mx = v.parse().unwrap_or(1),
|
||||
"MAN" => man_ok = v.trim_matches('"') == "ssdp:discover",
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
man_ok.then_some(())?;
|
||||
Some((st?, mx.clamp(1, 5)))
|
||||
}
|
||||
|
||||
/// Runs forever: answers searches and re-announces every few minutes.
|
||||
pub async fn run(announce: Announce) -> Result<()> {
|
||||
let sock = Arc::new(bind_multicast()?);
|
||||
// Joining fails while the network is down; keep retrying.
|
||||
let joiner = sock.clone();
|
||||
let notifier_ann = announce.clone();
|
||||
tokio::spawn(async move {
|
||||
let mut joined = false;
|
||||
let mut tick = 0u32;
|
||||
loop {
|
||||
if !joined {
|
||||
match joiner.join_multicast_v4(GROUP, Ipv4Addr::UNSPECIFIED) {
|
||||
Ok(()) => {
|
||||
log::info!("ssdp: listening on 239.255.255.250:1900");
|
||||
joined = true;
|
||||
tick = 0;
|
||||
}
|
||||
Err(e) => log::debug!("ssdp: join: {e}"),
|
||||
}
|
||||
}
|
||||
// Announce soon after joining, then every 5 minutes.
|
||||
if joined && tick % 60 == 1 {
|
||||
if let Some(ip) = local_ip_for(GROUP) {
|
||||
for nt in ["upnp:rootdevice", DIAL_ST] {
|
||||
let msg = notifier_ann.notify(nt, ip);
|
||||
let _ = joiner.send_to(msg.as_bytes(), (GROUP, PORT)).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
tick = tick.wrapping_add(1);
|
||||
tokio::time::sleep(Duration::from_secs(5)).await;
|
||||
}
|
||||
});
|
||||
|
||||
let mut buf = [0u8; 2048];
|
||||
loop {
|
||||
let (n, from) = match sock.recv_from(&mut buf).await {
|
||||
Ok(v) => v,
|
||||
Err(e) => {
|
||||
log::debug!("ssdp recv: {e}");
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let Ok(text) = std::str::from_utf8(&buf[..n]) else { continue };
|
||||
let Some((st, mx)) = parse_search(text) else { continue };
|
||||
let SocketAddr::V4(peer) = from else { continue };
|
||||
let targets = announce.targets_for(&st);
|
||||
if targets.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let Some(ip) = local_ip_for(*peer.ip()) else { continue };
|
||||
log::debug!("ssdp: M-SEARCH {st} from {peer}");
|
||||
let sock = sock.clone();
|
||||
let announce = announce.clone();
|
||||
tokio::spawn(async move {
|
||||
// Spread replies over part of MX, as the spec asks.
|
||||
let delay = (u64::from(peer.port()) * 37 % (mx * 250)).min(900);
|
||||
tokio::time::sleep(Duration::from_millis(delay)).await;
|
||||
for t in targets {
|
||||
let _ = sock.send_to(announce.search_response(&t, ip).as_bytes(), peer).await;
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_m_search() {
|
||||
let msg = "M-SEARCH * HTTP/1.1\r\nHOST: 239.255.255.250:1900\r\nMAN: \"ssdp:discover\"\r\nMX: 1\r\nST: urn:dial-multiscreen-org:service:dial:1\r\n\r\n";
|
||||
assert_eq!(parse_search(msg), Some((DIAL_ST.to_string(), 1)));
|
||||
assert_eq!(parse_search("NOTIFY * HTTP/1.1\r\n\r\n"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn answers_only_known_targets() {
|
||||
let a = Announce { uuid: "abc".into(), http_port: 56789, server: "x".into() };
|
||||
assert_eq!(a.targets_for(DIAL_ST), vec![DIAL_ST.to_string()]);
|
||||
assert!(a.targets_for("urn:schemas-upnp-org:device:MediaRenderer:1").is_empty());
|
||||
let r = a.search_response(DIAL_ST, Ipv4Addr::new(10, 0, 0, 7));
|
||||
assert!(r.contains("LOCATION: http://10.0.0.7:56789/dd.xml\r\n"));
|
||||
assert!(r.contains("USN: uuid:abc::urn:dial-multiscreen-org:service:dial:1\r\n"));
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "sf-ipc"
|
||||
description = "Shared types for SmartFox: app manifests, settings and IPC messages"
|
||||
description = "Shared types for Fennec OS: app manifests, settings and IPC messages"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
283
crates/sf-ipc/src/launch.rs
Normal file
283
crates/sf-ipc/src/launch.rs
Normal file
@@ -0,0 +1,283 @@
|
||||
//! How apps are started: the command line for a web app (Chromium in kiosk or
|
||||
//! app mode with its own profile) or an exec app. Shared by the launcher
|
||||
//! (local testing on a desktop) and sf-core (the TV).
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
|
||||
use crate::{AppKind, AppManifest, Settings, paths, sandbox};
|
||||
|
||||
/// Environment variable carrying the app id into the app's processes. The
|
||||
/// compositor reads it from `/proc/<pid>/environ` to tell windows apart.
|
||||
pub const APP_ENV: &str = "SMARTFOX_APP";
|
||||
|
||||
pub struct Browser {
|
||||
pub exe: PathBuf,
|
||||
/// Full version, used to build a realistic user agent.
|
||||
pub version: String,
|
||||
}
|
||||
|
||||
pub fn find_browser() -> Option<Browser> {
|
||||
let mut candidates: Vec<PathBuf> = Vec::new();
|
||||
if let Ok(p) = std::env::var("SMARTFOX_BROWSER") {
|
||||
candidates.push(p.into());
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
for base in ["ProgramFiles", "ProgramFiles(x86)", "LOCALAPPDATA"] {
|
||||
if let Some(b) = std::env::var_os(base) {
|
||||
let b = PathBuf::from(b);
|
||||
candidates.push(b.join(r"Google\Chrome\Application\chrome.exe"));
|
||||
candidates.push(b.join(r"Chromium\Application\chrome.exe"));
|
||||
candidates.push(b.join(r"Microsoft\Edge\Application\msedge.exe"));
|
||||
}
|
||||
}
|
||||
}
|
||||
#[cfg(not(windows))]
|
||||
{
|
||||
for name in ["chromium", "chromium-browser", "google-chrome-stable", "google-chrome"] {
|
||||
for dir in ["/usr/bin", "/usr/local/bin", "/snap/bin"] {
|
||||
candidates.push(Path::new(dir).join(name));
|
||||
}
|
||||
}
|
||||
}
|
||||
let exe = candidates.into_iter().find(|p| p.is_file())?;
|
||||
let version = browser_version(&exe).unwrap_or_else(|| "141.0.0.0".into());
|
||||
Some(Browser { exe, version })
|
||||
}
|
||||
|
||||
fn browser_version(exe: &Path) -> Option<String> {
|
||||
// Windows installs keep a folder named after the version next to the exe.
|
||||
if cfg!(windows) {
|
||||
let dir = exe.parent()?;
|
||||
let mut versions: Vec<String> = std::fs::read_dir(dir)
|
||||
.ok()?
|
||||
.flatten()
|
||||
.filter_map(|e| e.file_name().into_string().ok())
|
||||
.filter(|n| n.split('.').count() == 4 && n.split('.').all(|p| p.parse::<u32>().is_ok()))
|
||||
.collect();
|
||||
versions.sort_by_key(|v| v.split('.').map(|p| p.parse::<u32>().unwrap_or(0)).collect::<Vec<_>>());
|
||||
return versions.pop();
|
||||
}
|
||||
let out = Command::new(exe).arg("--version").output().ok()?;
|
||||
String::from_utf8_lossy(&out.stdout)
|
||||
.split_whitespace()
|
||||
.find(|w| w.chars().next().is_some_and(|c| c.is_ascii_digit()) && w.contains('.'))
|
||||
.map(str::to_string)
|
||||
}
|
||||
|
||||
fn default_user_agent(version: &str) -> String {
|
||||
let platform = if cfg!(windows) { "Windows NT 10.0; Win64; x64" } else { "X11; Linux x86_64" };
|
||||
let major = version.split('.').next().unwrap_or("141");
|
||||
format!("Mozilla/5.0 ({platform}) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/{major}.0.0.0 Safari/537.36")
|
||||
}
|
||||
|
||||
pub struct LaunchOptions<'a> {
|
||||
/// Per-app browser profiles live in `<data_dir>/profiles/<id>`.
|
||||
pub data_dir: &'a Path,
|
||||
pub fullscreen: bool,
|
||||
/// Windowed mode: open the app exactly over the launcher (x, y, w, h).
|
||||
pub bounds: Option<(i32, i32, u32, u32)>,
|
||||
/// Extra query string for the start URL (DIAL launch parameters).
|
||||
pub query: Option<&'a str>,
|
||||
}
|
||||
|
||||
/// A program with its arguments and environment, before it is (maybe) put
|
||||
/// into the sandbox.
|
||||
struct Inner {
|
||||
program: String,
|
||||
args: Vec<String>,
|
||||
env: Vec<(String, String)>,
|
||||
}
|
||||
|
||||
/// The bwrap binary if `app` runs sandboxed (`sandbox` module). Store apps
|
||||
/// never run without it. Official apps run unsandboxed when bwrap is missing
|
||||
/// (an older image under a newer shell) or with `SMARTFOX_SANDBOX=off`
|
||||
/// (debugging), with a warning.
|
||||
fn sandbox_for(app: &AppManifest) -> Result<Option<PathBuf>> {
|
||||
if app.origin == crate::Origin::Store {
|
||||
anyhow::ensure!(cfg!(target_os = "linux"), "store apps only run on the TV (Linux)");
|
||||
return sandbox::bwrap_path().context("bubblewrap (bwrap) is not installed, and store apps only run sandboxed").map(Some);
|
||||
}
|
||||
if !cfg!(target_os = "linux") || !app.sandboxed() {
|
||||
return Ok(None);
|
||||
}
|
||||
if std::env::var("SMARTFOX_SANDBOX").is_ok_and(|v| v == "off") {
|
||||
log::warn!("{}: SMARTFOX_SANDBOX=off, running without a sandbox", app.id);
|
||||
return Ok(None);
|
||||
}
|
||||
let bwrap = sandbox::bwrap_path();
|
||||
if bwrap.is_none() {
|
||||
log::warn!("{}: bubblewrap is not installed, running without a sandbox", app.id);
|
||||
}
|
||||
Ok(bwrap)
|
||||
}
|
||||
|
||||
/// The command that starts `app`. Not spawned yet, so callers can wrap it
|
||||
/// (sf-core runs it inside a systemd scope).
|
||||
pub fn command(app: &AppManifest, settings: &Settings, opts: &LaunchOptions) -> Result<Command> {
|
||||
let bwrap = sandbox_for(app)?;
|
||||
// Where the app's files are, as the app sees them.
|
||||
let root = if bwrap.is_some() { PathBuf::from(sandbox::APP_DIR) } else { app.dir.clone() };
|
||||
let data = paths::app_data_dir(&app.id);
|
||||
let inner = match app.kind {
|
||||
AppKind::Web => web_command(app, settings, opts, &root, bwrap.is_some().then_some(data.as_path()))?,
|
||||
AppKind::Exec => {
|
||||
let line = app.resolved_exec(&root);
|
||||
let (prog, args) = line.split_first().context("empty exec command")?;
|
||||
Inner { program: prog.clone(), args: args.to_vec(), env: Vec::new() }
|
||||
}
|
||||
AppKind::Builtin => bail!("built-in app has no process"),
|
||||
};
|
||||
let mut env = inner.env;
|
||||
env.extend(app.env.iter().map(|(k, v)| (k.clone(), settings.expand(v))));
|
||||
|
||||
let mut cmd = match bwrap {
|
||||
Some(bwrap) => {
|
||||
std::fs::create_dir_all(&data).with_context(|| format!("creating {}", data.display()))?;
|
||||
// Store apps sit behind symlinks (store/apps/<id> -> ../store-<id>/current).
|
||||
let app_dir = std::fs::canonicalize(&app.dir).unwrap_or_else(|_| app.dir.clone());
|
||||
let permissions = app.permissions();
|
||||
let spec = sandbox::Spec {
|
||||
app_id: &app.id,
|
||||
app_dir: &app_dir,
|
||||
data_dir: &data,
|
||||
extra_rw: Vec::new(),
|
||||
permissions: &permissions,
|
||||
env,
|
||||
program: inner.program,
|
||||
args: inner.args,
|
||||
};
|
||||
let cmd = sandbox::command(&bwrap, &spec, &sandbox::Host::current());
|
||||
log::info!("{}: sandboxed, permissions: {:?}", app.id, permissions.iter().map(|p| p.key()).collect::<Vec<_>>());
|
||||
cmd
|
||||
}
|
||||
None => {
|
||||
let mut cmd = Command::new(&inner.program);
|
||||
cmd.args(&inner.args).envs(env).env("SMARTFOX_APP_DIR", &app.dir);
|
||||
cmd
|
||||
}
|
||||
};
|
||||
cmd.env(APP_ENV, &app.id);
|
||||
// Own process group, so stopping the app also ends its helper processes.
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::process::CommandExt;
|
||||
cmd.process_group(0);
|
||||
}
|
||||
Ok(cmd)
|
||||
}
|
||||
|
||||
/// Adds `query` to `url`, before any `#fragment`.
|
||||
pub fn with_query(url: &str, query: Option<&str>) -> String {
|
||||
let Some(q) = query.map(|q| q.trim_start_matches(['?', '&'])).filter(|q| !q.is_empty()) else {
|
||||
return url.to_string();
|
||||
};
|
||||
let (base, frag) = match url.find('#') {
|
||||
Some(i) => (&url[..i], &url[i..]),
|
||||
None => (url, ""),
|
||||
};
|
||||
let sep = if base.contains('?') { '&' } else { '?' };
|
||||
format!("{base}{sep}{q}{frag}")
|
||||
}
|
||||
|
||||
/// First-run preferences for an app profile: no translate prompt, Hungarian
|
||||
/// content language. Existing profiles are left alone.
|
||||
fn seed_profile(profile: &Path) -> Result<()> {
|
||||
let prefs = profile.join("Default").join("Preferences");
|
||||
if prefs.exists() {
|
||||
return Ok(());
|
||||
}
|
||||
std::fs::create_dir_all(prefs.parent().unwrap())?;
|
||||
std::fs::write(
|
||||
&prefs,
|
||||
r#"{"translate":{"enabled":false},"intl":{"accept_languages":"hu-HU,hu,en"},"browser":{"has_seen_welcome_page":true}}"#,
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The browser command for a web app. `sandbox_home`: the app's data folder
|
||||
/// when it runs sandboxed; its Chromium profile then lives in there.
|
||||
fn web_command(app: &AppManifest, settings: &Settings, opts: &LaunchOptions, root: &Path, sandbox_home: Option<&Path>) -> Result<Inner> {
|
||||
let browser = find_browser().context("no Chromium/Chrome/Edge found (set SMARTFOX_BROWSER)")?;
|
||||
let url = app.resolved_url(settings).filter(|u| !u.is_empty()).context("app has no URL")?;
|
||||
if url.starts_with('/') {
|
||||
bail!("URL is not set (check settings: {url})");
|
||||
}
|
||||
let url = with_query(&url, opts.query);
|
||||
let old_profile = opts.data_dir.join("profiles").join(&app.id);
|
||||
let profile = match sandbox_home {
|
||||
Some(home) => {
|
||||
let profile = home.join("chromium");
|
||||
// Profiles from before the sandbox (logins, settings) move along.
|
||||
if old_profile.is_dir() && !profile.exists() {
|
||||
std::fs::create_dir_all(home)?;
|
||||
if let Err(e) = std::fs::rename(&old_profile, &profile) {
|
||||
log::warn!("{}: moving the browser profile: {e}", app.id);
|
||||
}
|
||||
}
|
||||
profile
|
||||
}
|
||||
None => old_profile,
|
||||
};
|
||||
seed_profile(&profile)?;
|
||||
|
||||
let ua = match (&app.web.user_agent, &app.web.user_agent_suffix) {
|
||||
(Some(ua), _) => ua.clone(),
|
||||
(None, Some(suffix)) => format!("{} {suffix}", default_user_agent(&browser.version)),
|
||||
(None, None) => default_user_agent(&browser.version),
|
||||
};
|
||||
|
||||
let mut args: Vec<String> = vec![
|
||||
format!("--user-data-dir={}", profile.display()),
|
||||
format!("--user-agent={ua}"),
|
||||
"--no-first-run".into(),
|
||||
"--no-default-browser-check".into(),
|
||||
"--disable-session-crashed-bubble".into(),
|
||||
"--hide-crash-restore-bubble".into(),
|
||||
"--disable-features=Translate,TranslateUI,MediaRouter,LocalNetworkAccessChecks".into(),
|
||||
"--lang=hu".into(),
|
||||
"--accept-lang=hu-HU,hu,en".into(),
|
||||
// Dark first paint instead of a white flash before the page draws.
|
||||
"--force-dark-mode".into(),
|
||||
"--autoplay-policy=no-user-gesture-required".into(),
|
||||
"--overscroll-history-navigation=0".into(),
|
||||
];
|
||||
if opts.fullscreen {
|
||||
args.extend(["--kiosk".into(), url]);
|
||||
} else {
|
||||
args.push(format!("--app={url}"));
|
||||
match opts.bounds {
|
||||
Some((x, y, w, h)) => args.extend([format!("--window-position={x},{y}"), format!("--window-size={w},{h}")]),
|
||||
None => args.push("--window-size=1600,900".into()),
|
||||
}
|
||||
}
|
||||
let mut env = Vec::new();
|
||||
if cfg!(target_os = "linux") {
|
||||
// Chromium on Linux picks its UI language from the environment, not --lang.
|
||||
env.push(("LANGUAGE".to_string(), "hu".to_string()));
|
||||
args.push("--enable-features=VaapiVideoDecoder,VaapiIgnoreDriverChecks,PlatformHEVCDecoderSupport".into());
|
||||
if std::env::var_os("WAYLAND_DISPLAY").is_some() {
|
||||
args.push("--ozone-platform=wayland".into());
|
||||
}
|
||||
}
|
||||
for ext in &app.web.extensions {
|
||||
args.push(format!("--load-extension={}", root.join(ext).display()));
|
||||
}
|
||||
Ok(Inner { program: browser.exe.to_string_lossy().into_owned(), args, env })
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn adds_query() {
|
||||
assert_eq!(with_query("https://www.youtube.com/tv", Some("a=1&b=2")), "https://www.youtube.com/tv?a=1&b=2");
|
||||
assert_eq!(with_query("https://x/tv?x=1#f", Some("?a=1")), "https://x/tv?x=1&a=1#f");
|
||||
assert_eq!(with_query("https://x/", None), "https://x/");
|
||||
assert_eq!(with_query("https://x/", Some("")), "https://x/");
|
||||
}
|
||||
}
|
||||
@@ -1,9 +1,14 @@
|
||||
//! Shared types for SmartFox components (launcher, core daemon, remote daemon).
|
||||
//! Shared types for Fennec OS components (launcher, core daemon, remote daemon,
|
||||
//! compositor).
|
||||
|
||||
pub mod launch;
|
||||
pub mod manifest;
|
||||
pub mod message;
|
||||
pub mod paths;
|
||||
pub mod sandbox;
|
||||
pub mod settings;
|
||||
pub mod store;
|
||||
|
||||
pub use manifest::{AppKind, AppManifest, load_apps};
|
||||
pub use manifest::{AppKind, AppManifest, Origin, Permission, load_apps};
|
||||
pub use message::{CoreEvent, LauncherRequest};
|
||||
pub use settings::Settings;
|
||||
|
||||
@@ -1,5 +1,13 @@
|
||||
//! App manifests: one `app.toml` per folder under the apps directory.
|
||||
//!
|
||||
//! Apps come from two places:
|
||||
//! - factory apps (the image) and official packages (`sf-app-<id>`, signed
|
||||
//! with the Fennec OS key);
|
||||
//! - the store: third-party apps from their own GitHub/Gitea/GitLab repos,
|
||||
//! published in their own repo (docs/store.md). These always run sandboxed and
|
||||
//! can never replace an official app.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
@@ -18,6 +26,101 @@ pub enum AppKind {
|
||||
Builtin,
|
||||
}
|
||||
|
||||
/// Where an app was loaded from.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub enum Origin {
|
||||
/// The image or an official package.
|
||||
#[default]
|
||||
Official,
|
||||
/// A store package from a third-party repo: always sandboxed.
|
||||
Store,
|
||||
}
|
||||
|
||||
/// What a sandboxed app may reach besides its own files and the screen
|
||||
/// (the Wayland socket). Shown to the user before installing.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "kebab-case")]
|
||||
pub enum Permission {
|
||||
/// Internet and the local network.
|
||||
Network,
|
||||
/// Hardware graphics and video decoding (/dev/dri).
|
||||
Gpu,
|
||||
/// Sound output (PipeWire / PulseAudio socket).
|
||||
Audio,
|
||||
/// Game controllers: /dev/input, /dev/hidraw*, /dev/uinput.
|
||||
Gamepad,
|
||||
/// The user's D-Bus session bus (unfiltered).
|
||||
DbusSession,
|
||||
/// The system D-Bus (unfiltered).
|
||||
DbusSystem,
|
||||
/// Every device in /dev.
|
||||
Devices,
|
||||
}
|
||||
|
||||
impl Permission {
|
||||
pub const ALL: [Permission; 7] = [
|
||||
Permission::Network,
|
||||
Permission::Gpu,
|
||||
Permission::Audio,
|
||||
Permission::Gamepad,
|
||||
Permission::DbusSession,
|
||||
Permission::DbusSystem,
|
||||
Permission::Devices,
|
||||
];
|
||||
|
||||
/// Name used in app.toml and store.toml.
|
||||
pub fn key(self) -> &'static str {
|
||||
match self {
|
||||
Permission::Network => "network",
|
||||
Permission::Gpu => "gpu",
|
||||
Permission::Audio => "audio",
|
||||
Permission::Gamepad => "gamepad",
|
||||
Permission::DbusSession => "dbus-session",
|
||||
Permission::DbusSystem => "dbus-system",
|
||||
Permission::Devices => "devices",
|
||||
}
|
||||
}
|
||||
|
||||
pub fn from_key(key: &str) -> Option<Permission> {
|
||||
Permission::ALL.into_iter().find(|p| p.key() == key)
|
||||
}
|
||||
|
||||
/// Hungarian label for the store screen.
|
||||
pub fn label(self) -> &'static str {
|
||||
match self {
|
||||
Permission::Network => "Internet és helyi hálózat",
|
||||
Permission::Gpu => "Grafikus gyorsítás",
|
||||
Permission::Audio => "Hang",
|
||||
Permission::Gamepad => "Játékvezérlők",
|
||||
Permission::DbusSession => "Munkamenet D-Bus",
|
||||
Permission::DbusSystem => "Rendszer D-Bus",
|
||||
Permission::Devices => "Minden eszköz (/dev)",
|
||||
}
|
||||
}
|
||||
|
||||
/// Worth a warning: the app can reach far outside its sandbox.
|
||||
pub fn risky(self) -> bool {
|
||||
matches!(self, Permission::DbusSession | Permission::DbusSystem | Permission::Devices)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct SandboxOptions {
|
||||
/// Run in a bubblewrap sandbox. Only official apps may turn it off
|
||||
/// (system receivers like AirPlay); store apps are always sandboxed.
|
||||
/// Unset: on, except for official background services.
|
||||
#[serde(default)]
|
||||
pub enabled: Option<bool>,
|
||||
#[serde(default)]
|
||||
pub permissions: Vec<Permission>,
|
||||
}
|
||||
|
||||
impl Default for SandboxOptions {
|
||||
fn default() -> Self {
|
||||
SandboxOptions { enabled: None, permissions: Vec::new() }
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
pub struct AppManifest {
|
||||
pub id: String,
|
||||
@@ -59,9 +162,26 @@ pub struct AppManifest {
|
||||
/// launcher tile only opens the details sheet.
|
||||
#[serde(default)]
|
||||
pub service: bool,
|
||||
#[serde(default)]
|
||||
pub sandbox: SandboxOptions,
|
||||
/// Extra environment for the app's process.
|
||||
#[serde(default)]
|
||||
pub env: BTreeMap<String, String>,
|
||||
/// Legacy store manifest field. Older signed releases may still contain it.
|
||||
#[serde(default)]
|
||||
pub public_key: Option<String>,
|
||||
/// Store apps: source code / home page, shown on the store screen.
|
||||
#[serde(default)]
|
||||
pub homepage: Option<String>,
|
||||
#[serde(default)]
|
||||
pub author: Option<String>,
|
||||
#[serde(default)]
|
||||
pub license: Option<String>,
|
||||
/// Folder the manifest was loaded from (not serialized).
|
||||
#[serde(skip)]
|
||||
pub dir: PathBuf,
|
||||
#[serde(skip)]
|
||||
pub origin: Origin,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
@@ -96,6 +216,79 @@ impl AppManifest {
|
||||
pub fn resolved_url(&self, settings: &Settings) -> Option<String> {
|
||||
self.url.as_ref().map(|u| settings.expand(u))
|
||||
}
|
||||
|
||||
/// The command line with `${app}` replaced by `app_root` (where the app's
|
||||
/// files are: its folder, or /app inside the sandbox). A relative program
|
||||
/// path with a slash (`bin/hello`) is inside the app folder too; a bare
|
||||
/// name (`uxplay`) is looked up in PATH.
|
||||
pub fn resolved_exec(&self, app_root: &Path) -> Vec<String> {
|
||||
let root = app_root.to_string_lossy();
|
||||
let mut line: Vec<String> = self.exec.iter().flatten().map(|a| a.replace("${app}", &root)).collect();
|
||||
if let Some(first) = line.first_mut() {
|
||||
if first.contains('/') && !first.starts_with('/') {
|
||||
*first = format!("{}/{}", root.trim_end_matches('/'), first.trim_start_matches("./"));
|
||||
}
|
||||
}
|
||||
line
|
||||
}
|
||||
|
||||
/// What the app may reach from its sandbox. Web apps always get what a
|
||||
/// browser needs.
|
||||
pub fn permissions(&self) -> Vec<Permission> {
|
||||
let mut p = self.sandbox.permissions.clone();
|
||||
if self.kind == AppKind::Web {
|
||||
p.extend([Permission::Network, Permission::Gpu, Permission::Audio]);
|
||||
}
|
||||
p.sort();
|
||||
p.dedup();
|
||||
p
|
||||
}
|
||||
|
||||
/// Store apps always run sandboxed; official ones unless they opt out.
|
||||
pub fn sandboxed(&self) -> bool {
|
||||
self.origin == Origin::Store || self.sandbox.enabled.unwrap_or(!self.service)
|
||||
}
|
||||
|
||||
/// An image file shipped with the app (`icon = "icon.png"`), if `icon`
|
||||
/// isn't one of the launcher's built-in icon names.
|
||||
pub fn icon_file(&self) -> Option<PathBuf> {
|
||||
let lower = self.icon.to_ascii_lowercase();
|
||||
if ![".png", ".svg", ".jpg", ".jpeg"].iter().any(|ext| lower.ends_with(ext)) {
|
||||
return None;
|
||||
}
|
||||
if self.icon.contains("..") || Path::new(&self.icon).is_absolute() {
|
||||
return None;
|
||||
}
|
||||
let path = self.dir.join(&self.icon);
|
||||
path.is_file().then_some(path)
|
||||
}
|
||||
|
||||
/// Rules a store app must follow (checked by sf-update before installing
|
||||
/// and by the launcher when loading).
|
||||
pub fn check_store_rules(&self) -> Result<()> {
|
||||
anyhow::ensure!(is_store_id(&self.id), "store app id {:?} must be a reverse domain name (io.github.user.app)", self.id);
|
||||
anyhow::ensure!(self.kind != AppKind::Builtin, "store apps can't be built-in");
|
||||
anyhow::ensure!(!self.service, "store apps can't be background services");
|
||||
anyhow::ensure!(self.dial.is_none(), "store apps can't register for DIAL");
|
||||
anyhow::ensure!(self.sandbox.enabled != Some(false), "store apps can't turn off the sandbox");
|
||||
match self.kind {
|
||||
AppKind::Exec => anyhow::ensure!(!self.resolved_exec(Path::new("/app")).is_empty(), "exec is missing"),
|
||||
AppKind::Web => anyhow::ensure!(self.url.as_deref().is_some_and(|u| u.starts_with("https://")), "web apps need an https:// url"),
|
||||
AppKind::Builtin => {}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// Store app ids are reverse domain names with at least one dot
|
||||
/// (`io.github.user.app`). Official app ids never have a dot, so a store app
|
||||
/// can't take the place of one.
|
||||
pub fn is_store_id(id: &str) -> bool {
|
||||
let parts: Vec<&str> = id.split('.').collect();
|
||||
id.len() <= 128
|
||||
&& parts.len() >= 2
|
||||
&& parts.iter().all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_'))
|
||||
&& parts[0].bytes().all(|b| b.is_ascii_lowercase() || b.is_ascii_digit())
|
||||
}
|
||||
|
||||
/// Loads every `*/app.toml` under `dir`, sorted by `order` then name.
|
||||
@@ -128,6 +321,12 @@ pub fn load_apps_from(dirs: &[PathBuf]) -> Result<Vec<AppManifest>> {
|
||||
}
|
||||
found = true;
|
||||
for app in load_apps(dir)? {
|
||||
// Official ids have no dot; a store app here (developed inside
|
||||
// the apps folder) belongs to the store, not the factory set.
|
||||
if is_store_id(&app.id) {
|
||||
log::info!("skipping {}: a store app id in an official apps folder", app.id);
|
||||
continue;
|
||||
}
|
||||
match apps.iter_mut().find(|a| a.id == app.id) {
|
||||
Some(old) if version_cmp(&app.version, &old.version).is_ge() => *old = app,
|
||||
Some(_) => {}
|
||||
@@ -140,16 +339,37 @@ pub fn load_apps_from(dirs: &[PathBuf]) -> Result<Vec<AppManifest>> {
|
||||
Ok(apps)
|
||||
}
|
||||
|
||||
/// Official apps from `dirs` (see `load_apps_from`), plus store apps from
|
||||
/// `store`. A store app is skipped if it breaks the store rules or has the id
|
||||
/// of an official app.
|
||||
pub fn load_all(dirs: &[PathBuf], store: Option<&Path>) -> Result<Vec<AppManifest>> {
|
||||
let mut apps = load_apps_from(dirs)?;
|
||||
if let Some(store) = store.filter(|d| d.is_dir()) {
|
||||
for mut app in load_apps(store)? {
|
||||
app.origin = Origin::Store;
|
||||
if let Err(e) = app.check_store_rules() {
|
||||
log::warn!("skipping store app {}: {e:#}", app.dir.display());
|
||||
} else if apps.iter().any(|a| a.id == app.id) {
|
||||
log::warn!("skipping store app {}: an app with this id is already installed", app.id);
|
||||
} else {
|
||||
apps.push(app);
|
||||
}
|
||||
}
|
||||
sort_apps(&mut apps);
|
||||
}
|
||||
Ok(apps)
|
||||
}
|
||||
|
||||
fn sort_apps(apps: &mut [AppManifest]) {
|
||||
apps.sort_by(|a, b| a.order.cmp(&b.order).then_with(|| a.name.cmp(&b.name)));
|
||||
}
|
||||
|
||||
/// Compares dotted numeric versions ("1.10.0" > "1.9.2"); anything that
|
||||
/// isn't a number compares as 0.
|
||||
/// Compares dotted numeric versions ("1.10.0" > "1.9.2"), up to four parts
|
||||
/// (the Steam launcher is 1.0.0.87); anything that isn't a number compares as 0.
|
||||
pub fn version_cmp(a: &str, b: &str) -> std::cmp::Ordering {
|
||||
let parts = |v: &str| -> Vec<u64> { v.split(['.', '-', '+']).take(3).map(|p| p.parse().unwrap_or(0)).collect() };
|
||||
let parts = |v: &str| -> Vec<u64> { v.split(['.', '-', '+']).take(4).map(|p| p.parse().unwrap_or(0)).collect() };
|
||||
let (a, b) = (parts(a), parts(b));
|
||||
(0..3).map(|i| a.get(i).unwrap_or(&0).cmp(b.get(i).unwrap_or(&0))).find(|o| o.is_ne()).unwrap_or(std::cmp::Ordering::Equal)
|
||||
(0..4).map(|i| a.get(i).unwrap_or(&0).cmp(b.get(i).unwrap_or(&0))).find(|o| o.is_ne()).unwrap_or(std::cmp::Ordering::Equal)
|
||||
}
|
||||
|
||||
fn load_one(path: &Path) -> Result<AppManifest> {
|
||||
@@ -174,7 +394,7 @@ mod tests {
|
||||
accent = "#E50914"
|
||||
palette = ["#ff3b3b", "#7a0a10", "#0c0203"]
|
||||
[web]
|
||||
user_agent_suffix = "SMART-TV SmartFox/0.1"
|
||||
user_agent_suffix = "SMART-TV FennecOS/0.1"
|
||||
"##,
|
||||
)
|
||||
.unwrap();
|
||||
@@ -191,5 +411,49 @@ mod tests {
|
||||
assert_eq!(version_cmp("1.10.0", "1.9.2"), Greater);
|
||||
assert_eq!(version_cmp("0.2", "0.2.0"), Equal);
|
||||
assert_eq!(version_cmp("0.1.9", "0.2.0"), Less);
|
||||
assert_eq!(version_cmp("1.0.0.87", "1.0.0.9"), Greater);
|
||||
assert_eq!(version_cmp("1.0.0", "1.0.0.0"), Equal);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn store_ids() {
|
||||
assert!(is_store_id("io.github.user.app"));
|
||||
assert!(is_store_id("org.example.My_App-2"));
|
||||
assert!(!is_store_id("youtube"));
|
||||
assert!(!is_store_id("IO.github.x"));
|
||||
assert!(!is_store_id("io..x"));
|
||||
assert!(!is_store_id("io.x/../y"));
|
||||
assert!(!is_store_id(".io.x"));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn exec_and_permissions() {
|
||||
let app: AppManifest = toml::from_str(
|
||||
r#"
|
||||
id = "io.github.fox.hello"
|
||||
name = "Hello"
|
||||
kind = "exec"
|
||||
exec = ["bin/hello", "--data", "${app}/share"]
|
||||
[sandbox]
|
||||
permissions = ["network", "gamepad"]
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(app.resolved_exec(Path::new("/app")), ["/app/bin/hello", "--data", "/app/share"]);
|
||||
assert_eq!(app.permissions(), [Permission::Network, Permission::Gamepad]);
|
||||
assert!(app.sandboxed());
|
||||
app.check_store_rules().unwrap();
|
||||
|
||||
let mut bad = app.clone();
|
||||
bad.sandbox.enabled = Some(false);
|
||||
assert!(bad.check_store_rules().is_err());
|
||||
bad = app.clone();
|
||||
bad.id = "youtube".into();
|
||||
assert!(bad.check_store_rules().is_err());
|
||||
|
||||
let web: AppManifest = toml::from_str("id = 'a'\nname = 'A'\nkind = 'web'\nurl = 'https://x'\n").unwrap();
|
||||
assert_eq!(web.permissions(), [Permission::Network, Permission::Gpu, Permission::Audio]);
|
||||
let path: AppManifest = toml::from_str("id = 'a'\nname = 'A'\nkind = 'exec'\nexec = ['uxplay', '-n']\n").unwrap();
|
||||
assert_eq!(path.resolved_exec(Path::new("/x")), ["uxplay", "-n"]);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,23 +1,82 @@
|
||||
//! Messages between the launcher and the core daemon (newline-delimited JSON
|
||||
//! over a unix socket). The core daemon itself comes in phase 3.
|
||||
//! Messages between the launcher and the core daemon: newline-delimited JSON
|
||||
//! over the core socket (`paths::core_socket`).
|
||||
//!
|
||||
//! The launcher sends `LauncherRequest`s; the core sends `CoreEvent`s to
|
||||
//! every connected client (and `Hello` right after connecting).
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum LauncherRequest {
|
||||
Launch { app_id: String },
|
||||
/// Bring the launcher back to the front (freezes the foreground app).
|
||||
/// Start the app, or bring it back if it waits in the background.
|
||||
Launch {
|
||||
app_id: String,
|
||||
/// Extra query string for the start URL (DIAL uses this).
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
query: Option<String>,
|
||||
},
|
||||
/// Show the launcher. The foreground app is frozen in the background if
|
||||
/// the compositor can switch windows, otherwise it is closed.
|
||||
GoHome,
|
||||
SetSetting { key: String, value: String },
|
||||
/// Close the app.
|
||||
Stop { app_id: String },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Serialize, Deserialize)]
|
||||
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(tag = "type", rename_all = "snake_case")]
|
||||
pub enum CoreEvent {
|
||||
AppStarted { app_id: String },
|
||||
/// First message on every connection.
|
||||
Hello {
|
||||
/// True if apps are kept (frozen) in the background on Home.
|
||||
switching: bool,
|
||||
/// The app in the foreground, if any.
|
||||
#[serde(default)]
|
||||
foreground: Option<String>,
|
||||
},
|
||||
/// An app came to the front: newly started or thawed.
|
||||
AppStarted {
|
||||
app_id: String,
|
||||
/// Started from a phone (DIAL), not from the launcher.
|
||||
#[serde(default)]
|
||||
cast: bool,
|
||||
},
|
||||
/// The app's process ended.
|
||||
AppStopped { app_id: String },
|
||||
/// Something connected over DIAL/AirPlay/Miracast.
|
||||
CastConnected { app_id: String, device: String },
|
||||
/// The cast session ended.
|
||||
CastEnded { app_id: String },
|
||||
Toast { text: String },
|
||||
}
|
||||
|
||||
impl LauncherRequest {
|
||||
pub fn to_line(&self) -> String {
|
||||
let mut s = serde_json::to_string(self).unwrap_or_default();
|
||||
s.push('\n');
|
||||
s
|
||||
}
|
||||
}
|
||||
|
||||
impl CoreEvent {
|
||||
pub fn to_line(&self) -> String {
|
||||
let mut s = serde_json::to_string(self).unwrap_or_default();
|
||||
s.push('\n');
|
||||
s
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn round_trips() {
|
||||
let r = LauncherRequest::Launch { app_id: "youtube".into(), query: None };
|
||||
assert_eq!(r.to_line(), "{\"type\":\"launch\",\"app_id\":\"youtube\"}\n");
|
||||
let back: LauncherRequest = serde_json::from_str(r.to_line().trim()).unwrap();
|
||||
assert_eq!(back, r);
|
||||
let e: CoreEvent = serde_json::from_str(r#"{"type":"app_started","app_id":"netflex"}"#).unwrap();
|
||||
assert_eq!(e, CoreEvent::AppStarted { app_id: "netflex".into(), cast: false });
|
||||
}
|
||||
}
|
||||
|
||||
78
crates/sf-ipc/src/paths.rs
Normal file
78
crates/sf-ipc/src/paths.rs
Normal file
@@ -0,0 +1,78 @@
|
||||
//! Where the Fennec OS sockets and files live.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
/// `$XDG_RUNTIME_DIR`, or the temp dir.
|
||||
pub fn runtime_dir() -> PathBuf {
|
||||
std::env::var_os("XDG_RUNTIME_DIR").map(PathBuf::from).unwrap_or_else(std::env::temp_dir)
|
||||
}
|
||||
|
||||
fn from_env(var: &str, default: &str) -> PathBuf {
|
||||
match std::env::var_os(var) {
|
||||
Some(p) => p.into(),
|
||||
None => runtime_dir().join(default),
|
||||
}
|
||||
}
|
||||
|
||||
/// Launcher command socket (`home`, `remote <state>`, `power`, `wake`).
|
||||
pub fn launcher_socket() -> PathBuf {
|
||||
from_env("SMARTFOX_SOCKET", "smartfox.sock")
|
||||
}
|
||||
|
||||
/// sf-core: app lifecycle (JSON lines, see `message`).
|
||||
pub fn core_socket() -> PathBuf {
|
||||
from_env("SMARTFOX_CORE_SOCKET", "smartfox-core.sock")
|
||||
}
|
||||
|
||||
/// sf-compositor control socket (`focus launcher`, `focus <app-id>`).
|
||||
pub fn wm_socket() -> PathBuf {
|
||||
from_env("SMARTFOX_WM_SOCKET", "smartfox-wm.sock")
|
||||
}
|
||||
|
||||
/// The settings file: `$SMARTFOX_SETTINGS`, else `<config>/smartfox/settings.toml`.
|
||||
pub fn settings_file() -> PathBuf {
|
||||
if let Ok(p) = std::env::var("SMARTFOX_SETTINGS") {
|
||||
return p.into();
|
||||
}
|
||||
let base = std::env::var_os("XDG_CONFIG_HOME")
|
||||
.map(PathBuf::from)
|
||||
.or_else(|| std::env::var_os("APPDATA").map(PathBuf::from))
|
||||
.or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config")))
|
||||
.unwrap_or_else(|| PathBuf::from("."));
|
||||
base.join("smartfox").join("settings.toml")
|
||||
}
|
||||
|
||||
/// An app's private data folder; its `$HOME` inside the sandbox:
|
||||
/// `$XDG_DATA_HOME/smartfox/apps/<id>` (default `~/.local/share/...`).
|
||||
pub fn app_data_dir(id: &str) -> PathBuf {
|
||||
let base = std::env::var_os("XDG_DATA_HOME")
|
||||
.map(PathBuf::from)
|
||||
.or_else(|| std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".local").join("share")))
|
||||
.or_else(|| std::env::var_os("LOCALAPPDATA").map(PathBuf::from))
|
||||
.unwrap_or_else(|| PathBuf::from("."));
|
||||
base.join("smartfox").join("apps").join(id)
|
||||
}
|
||||
|
||||
/// Installed store apps (`/var/lib/sf-pkg/store/apps/<id>`), written by sf-update.
|
||||
pub const STORE_APPS: &str = "/var/lib/sf-pkg/store/apps";
|
||||
|
||||
/// Looks for an `apps` folder next to the binary or above the cwd (dev
|
||||
/// checkout), else the installed one.
|
||||
pub fn apps_dir() -> PathBuf {
|
||||
let mut starts = vec![];
|
||||
if let Ok(cwd) = std::env::current_dir() {
|
||||
starts.push(cwd);
|
||||
}
|
||||
if let Ok(exe) = std::env::current_exe() {
|
||||
starts.extend(exe.parent().map(Path::to_path_buf));
|
||||
}
|
||||
for start in starts {
|
||||
for dir in start.ancestors() {
|
||||
let candidate = dir.join("apps");
|
||||
if candidate.join("netflex").is_dir() {
|
||||
return candidate;
|
||||
}
|
||||
}
|
||||
}
|
||||
PathBuf::from("/usr/share/smartfox/apps")
|
||||
}
|
||||
350
crates/sf-ipc/src/sandbox.rs
Normal file
350
crates/sf-ipc/src/sandbox.rs
Normal file
@@ -0,0 +1,350 @@
|
||||
//! App sandbox: every app runs in its own bubblewrap (`bwrap`) container,
|
||||
//! the same building block Flatpak uses.
|
||||
//!
|
||||
//! Inside the sandbox an app sees:
|
||||
//! - the system read-only (`/usr`, `/etc`), no other user's or app's files;
|
||||
//! - its own files read-only at `/app`;
|
||||
//! - its own data folder as `$HOME` (on the host:
|
||||
//! `~/.local/share/smartfox/apps/<id>`), the only writable place that lasts;
|
||||
//! - the Wayland socket (it can show a window), nothing else from
|
||||
//! `$XDG_RUNTIME_DIR` (no launcher, sf-core or compositor sockets);
|
||||
//! - fresh /tmp, /run, /var and its own PID, IPC and UTS namespaces;
|
||||
//! - and only what its permissions allow (`Permission`): network, GPU,
|
||||
//! sound, game controllers, D-Bus, devices.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::Command;
|
||||
|
||||
use crate::manifest::Permission;
|
||||
|
||||
/// Where the app's own files are inside the sandbox.
|
||||
pub const APP_DIR: &str = "/app";
|
||||
|
||||
/// Environment variables passed through from the session when set.
|
||||
const PASS_ENV: [&str; 7] = ["LANG", "LANGUAGE", "LC_ALL", "TZ", "XCURSOR_THEME", "XCURSOR_SIZE", "RUST_LOG"];
|
||||
|
||||
/// What a host path is, for building the mount list (a function so tests
|
||||
/// can fake the file system).
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub enum Entry {
|
||||
Missing,
|
||||
Dir,
|
||||
Other,
|
||||
Symlink(PathBuf),
|
||||
/// There, but we may not read it (bwrap's `--*-bind-try` fails on that).
|
||||
Denied,
|
||||
}
|
||||
|
||||
pub fn probe(path: &Path) -> Entry {
|
||||
if let Err(e) = std::fs::metadata(path) {
|
||||
if e.kind() == std::io::ErrorKind::PermissionDenied {
|
||||
return Entry::Denied;
|
||||
}
|
||||
}
|
||||
match std::fs::symlink_metadata(path) {
|
||||
Err(_) => Entry::Missing,
|
||||
Ok(m) if m.file_type().is_symlink() => std::fs::read_link(path).map(Entry::Symlink).unwrap_or(Entry::Missing),
|
||||
Ok(m) if m.is_dir() => Entry::Dir,
|
||||
Ok(_) => Entry::Other,
|
||||
}
|
||||
}
|
||||
|
||||
/// The session the app is started from.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Host {
|
||||
pub uid: u32,
|
||||
pub user: String,
|
||||
pub home: PathBuf,
|
||||
pub runtime_dir: PathBuf,
|
||||
pub wayland_display: Option<String>,
|
||||
pub hostname: Option<String>,
|
||||
/// Allowed variables from the session (`PASS_ENV`).
|
||||
pub env: Vec<(String, String)>,
|
||||
/// /dev/hidraw* (controllers that talk raw HID, like DualSense).
|
||||
pub hidraw: Vec<PathBuf>,
|
||||
}
|
||||
|
||||
impl Host {
|
||||
pub fn current() -> Host {
|
||||
let var = |k: &str| std::env::var(k).ok().filter(|v| !v.is_empty());
|
||||
let home = var("HOME").map(PathBuf::from).unwrap_or_else(|| PathBuf::from("/tmp"));
|
||||
let hidraw = std::fs::read_dir("/dev")
|
||||
.map(|d| d.flatten().map(|e| e.path()).filter(|p| p.file_name().is_some_and(|n| n.to_string_lossy().starts_with("hidraw"))).collect())
|
||||
.unwrap_or_default();
|
||||
Host {
|
||||
uid: current_uid(),
|
||||
user: var("USER").unwrap_or_else(|| "tv".into()),
|
||||
home,
|
||||
runtime_dir: crate::paths::runtime_dir(),
|
||||
wayland_display: var("WAYLAND_DISPLAY"),
|
||||
hostname: std::fs::read_to_string("/etc/hostname").ok().map(|h| h.trim().to_string()).filter(|h| !h.is_empty()),
|
||||
env: PASS_ENV.iter().filter_map(|k| var(k).map(|v| (k.to_string(), v))).collect(),
|
||||
hidraw,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn current_uid() -> u32 {
|
||||
use std::os::unix::fs::MetadataExt;
|
||||
// The owner of our own /proc entry is our uid (no libc needed).
|
||||
std::fs::metadata("/proc/self").map(|m| m.uid()).unwrap_or(1000)
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn current_uid() -> u32 {
|
||||
1000
|
||||
}
|
||||
|
||||
/// One sandboxed process.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Spec<'a> {
|
||||
pub app_id: &'a str,
|
||||
/// The app's files (host path), read-only at `/app`.
|
||||
pub app_dir: &'a Path,
|
||||
/// The app's private data (host path), mounted as `$HOME`.
|
||||
pub data_dir: &'a Path,
|
||||
/// More writable folders, at the same path inside (a browser profile).
|
||||
pub extra_rw: Vec<PathBuf>,
|
||||
pub permissions: &'a [Permission],
|
||||
/// Extra environment for the app.
|
||||
pub env: Vec<(String, String)>,
|
||||
pub program: String,
|
||||
pub args: Vec<String>,
|
||||
}
|
||||
|
||||
pub fn bwrap_path() -> Option<PathBuf> {
|
||||
if let Ok(p) = std::env::var("SMARTFOX_BWRAP") {
|
||||
return Some(p.into());
|
||||
}
|
||||
["/usr/bin/bwrap", "/usr/local/bin/bwrap"].iter().map(PathBuf::from).find(|p| p.is_file())
|
||||
}
|
||||
|
||||
/// The bwrap command for `spec`.
|
||||
pub fn command(bwrap: &Path, spec: &Spec, host: &Host) -> Command {
|
||||
let mut cmd = Command::new(bwrap);
|
||||
cmd.args(args(spec, host, &probe));
|
||||
cmd
|
||||
}
|
||||
|
||||
/// The bwrap arguments. Mount order matters: later mounts go on top.
|
||||
pub fn args(spec: &Spec, host: &Host, fs: &dyn Fn(&Path) -> Entry) -> Vec<String> {
|
||||
let has = |p: Permission| spec.permissions.contains(&p);
|
||||
let mut a: Vec<String> = Vec::new();
|
||||
let mut push = |items: &[&str]| a.extend(items.iter().map(|s| s.to_string()));
|
||||
|
||||
push(&["--die-with-parent", "--unshare-all"]);
|
||||
if has(Permission::Network) {
|
||||
push(&["--share-net"]);
|
||||
}
|
||||
if host.uid == 0 {
|
||||
// Unprivileged bwrap drops every capability by itself; as root
|
||||
// (development) do it explicitly.
|
||||
push(&["--cap-drop", "ALL"]);
|
||||
}
|
||||
if let Some(h) = &host.hostname {
|
||||
push(&["--hostname", h]);
|
||||
}
|
||||
|
||||
// The system, read-only. /bin, /lib... are symlinks into /usr on Debian.
|
||||
push(&["--ro-bind", "/usr", "/usr"]);
|
||||
for top in ["/bin", "/sbin", "/lib", "/lib32", "/lib64", "/libx32"] {
|
||||
match fs(Path::new(top)) {
|
||||
Entry::Symlink(t) => push(&["--symlink", &t.to_string_lossy(), top]),
|
||||
Entry::Dir => push(&["--ro-bind", top, top]),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
push(&["--ro-bind", "/etc", "/etc", "--proc", "/proc"]);
|
||||
|
||||
// Devices.
|
||||
if has(Permission::Devices) {
|
||||
push(&["--dev-bind", "/dev", "/dev"]);
|
||||
} else {
|
||||
push(&["--dev", "/dev", "--tmpfs", "/dev/shm"]);
|
||||
if has(Permission::Gpu) {
|
||||
push(&["--dev-bind-try", "/dev/dri", "/dev/dri"]);
|
||||
}
|
||||
if has(Permission::Gamepad) {
|
||||
push(&["--dev-bind-try", "/dev/input", "/dev/input", "--dev-bind-try", "/dev/uinput", "/dev/uinput"]);
|
||||
for h in &host.hidraw {
|
||||
let h = h.to_string_lossy();
|
||||
push(&["--dev-bind-try", &h, &h]);
|
||||
}
|
||||
}
|
||||
}
|
||||
if has(Permission::Gpu) || has(Permission::Gamepad) || has(Permission::Devices) {
|
||||
push(&["--ro-bind", "/sys", "/sys"]);
|
||||
}
|
||||
|
||||
// Fresh writable scratch space.
|
||||
push(&["--tmpfs", "/tmp", "--tmpfs", "/var", "--tmpfs", "/run", "--dir", "/var/tmp", "--symlink", "../run", "/var/run"]);
|
||||
push(&["--ro-bind-try", "/var/cache/fontconfig", "/var/cache/fontconfig"]);
|
||||
if has(Permission::Gamepad) || has(Permission::Devices) {
|
||||
// Hotplug of controllers (SDL, Steam) goes through udev.
|
||||
push(&["--ro-bind-try", "/run/udev", "/run/udev"]);
|
||||
}
|
||||
if has(Permission::Network) {
|
||||
// /etc/resolv.conf points at systemd-resolved's stub file on the TV;
|
||||
// elsewhere (WSL: /mnt/wsl/resolv.conf) bind whatever it points at.
|
||||
push(&["--ro-bind-try", "/run/systemd/resolve", "/run/systemd/resolve"]);
|
||||
if let Entry::Symlink(t) = fs(Path::new("/etc/resolv.conf")) {
|
||||
let target = Path::new("/etc").join(t);
|
||||
let target = target.to_string_lossy();
|
||||
if !target.starts_with("/run/systemd/resolve/") && !target.starts_with("/etc/") && !target.starts_with("/usr/") {
|
||||
push(&["--ro-bind-try", &target, &target]);
|
||||
}
|
||||
}
|
||||
}
|
||||
if has(Permission::DbusSystem) {
|
||||
push(&["--ro-bind-try", "/run/dbus/system_bus_socket", "/run/dbus/system_bus_socket"]);
|
||||
}
|
||||
|
||||
// The session's runtime dir: only the sockets the app may use.
|
||||
let rt = host.runtime_dir.to_string_lossy().to_string();
|
||||
push(&["--perms", "0700", "--dir", &rt]);
|
||||
let mut socket = |name: &str| {
|
||||
let p = format!("{rt}/{name}");
|
||||
if fs(Path::new(&p)) != Entry::Denied {
|
||||
push(&["--ro-bind-try", &p, &p]);
|
||||
}
|
||||
};
|
||||
if let Some(wl) = &host.wayland_display {
|
||||
socket(wl);
|
||||
}
|
||||
if has(Permission::Audio) {
|
||||
socket("pipewire-0");
|
||||
socket("pulse/native");
|
||||
}
|
||||
if has(Permission::DbusSession) {
|
||||
socket("bus");
|
||||
}
|
||||
|
||||
// $HOME is the app's own data folder (at the real home path, so programs
|
||||
// that remember absolute paths keep working).
|
||||
let home = host.home.to_string_lossy().to_string();
|
||||
if let Entry::Symlink(t) = fs(Path::new("/home")) {
|
||||
push(&["--symlink", &t.to_string_lossy(), "/home"]);
|
||||
}
|
||||
push(&["--bind", &spec.data_dir.to_string_lossy(), &home]);
|
||||
for p in &spec.extra_rw {
|
||||
let p = p.to_string_lossy();
|
||||
push(&["--bind", &p, &p]);
|
||||
}
|
||||
push(&["--ro-bind", &spec.app_dir.to_string_lossy(), APP_DIR, "--chdir", &home]);
|
||||
|
||||
// A clean environment.
|
||||
push(&["--clearenv"]);
|
||||
let mut env: Vec<(String, String)> = vec![
|
||||
("PATH".into(), "/usr/local/bin:/usr/bin:/bin:/usr/games".into()),
|
||||
("HOME".into(), home.clone()),
|
||||
("USER".into(), host.user.clone()),
|
||||
("LOGNAME".into(), host.user.clone()),
|
||||
("SHELL".into(), "/bin/sh".into()),
|
||||
("XDG_RUNTIME_DIR".into(), rt.clone()),
|
||||
("XDG_SESSION_TYPE".into(), "wayland".into()),
|
||||
("SMARTFOX_APP".into(), spec.app_id.into()),
|
||||
("SMARTFOX_APP_DIR".into(), APP_DIR.into()),
|
||||
];
|
||||
if let Some(wl) = &host.wayland_display {
|
||||
env.push(("WAYLAND_DISPLAY".into(), wl.clone()));
|
||||
}
|
||||
if has(Permission::DbusSession) {
|
||||
env.push(("DBUS_SESSION_BUS_ADDRESS".into(), format!("unix:path={rt}/bus")));
|
||||
}
|
||||
env.extend(host.env.iter().cloned());
|
||||
env.extend(spec.env.iter().cloned());
|
||||
for (k, v) in env {
|
||||
push(&["--setenv", &k, &v]);
|
||||
}
|
||||
|
||||
push(&["--", &spec.program]);
|
||||
a.extend(spec.args.iter().cloned());
|
||||
a
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn host() -> Host {
|
||||
Host {
|
||||
uid: 1000,
|
||||
user: "tv".into(),
|
||||
home: "/var/home/tv".into(),
|
||||
runtime_dir: "/run/user/1000".into(),
|
||||
wayland_display: Some("wayland-1".into()),
|
||||
hostname: Some("smartfox".into()),
|
||||
env: vec![("LANG".into(), "C.UTF-8".into())],
|
||||
hidraw: vec!["/dev/hidraw0".into()],
|
||||
}
|
||||
}
|
||||
|
||||
fn fake_fs(p: &Path) -> Entry {
|
||||
match p.to_str().unwrap() {
|
||||
"/bin" => Entry::Symlink("usr/bin".into()),
|
||||
"/lib" => Entry::Symlink("usr/lib".into()),
|
||||
"/lib64" => Entry::Symlink("usr/lib64".into()),
|
||||
"/home" => Entry::Symlink("var/home".into()),
|
||||
_ => Entry::Missing,
|
||||
}
|
||||
}
|
||||
|
||||
fn has_seq(args: &[String], seq: &[&str]) -> bool {
|
||||
args.windows(seq.len()).any(|w| w.iter().zip(seq).all(|(a, b)| a == b))
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn minimal_sandbox() {
|
||||
let spec = Spec {
|
||||
app_id: "io.github.fox.hello",
|
||||
app_dir: Path::new("/var/lib/sf-pkg/store-io.github.fox.hello/1.0.0"),
|
||||
data_dir: Path::new("/var/home/tv/.local/share/smartfox/apps/io.github.fox.hello"),
|
||||
extra_rw: vec![],
|
||||
permissions: &[],
|
||||
env: vec![("FOO".into(), "bar".into())],
|
||||
program: "/app/bin/hello".into(),
|
||||
args: vec!["--x".into()],
|
||||
};
|
||||
let a = args(&spec, &host(), &fake_fs);
|
||||
assert!(has_seq(&a, &["--unshare-all"]));
|
||||
assert!(!a.contains(&"--share-net".to_string()));
|
||||
assert!(!a.iter().any(|s| s == "/dev/dri" || s == "/sys"));
|
||||
assert!(!a.iter().any(|s| s.contains("pipewire") || s.ends_with("/bus")));
|
||||
assert!(has_seq(&a, &["--symlink", "usr/bin", "/bin"]));
|
||||
assert!(has_seq(&a, &["--ro-bind-try", "/run/user/1000/wayland-1", "/run/user/1000/wayland-1"]));
|
||||
assert!(has_seq(&a, &["--bind", "/var/home/tv/.local/share/smartfox/apps/io.github.fox.hello", "/var/home/tv"]));
|
||||
assert!(has_seq(&a, &["--ro-bind", "/var/lib/sf-pkg/store-io.github.fox.hello/1.0.0", "/app"]));
|
||||
assert!(has_seq(&a, &["--setenv", "SMARTFOX_APP", "io.github.fox.hello"]));
|
||||
assert!(has_seq(&a, &["--setenv", "FOO", "bar"]));
|
||||
assert!(has_seq(&a, &["--", "/app/bin/hello", "--x"]));
|
||||
assert_eq!(a.last().unwrap(), "--x");
|
||||
// /run must be fresh before the runtime dir and sockets go in.
|
||||
let run = a.iter().position(|s| s == "/run").unwrap();
|
||||
let sock = a.iter().position(|s| s == "/run/user/1000/wayland-1").unwrap();
|
||||
assert!(run < sock);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn permissions_open_doors() {
|
||||
let perms = [Permission::Network, Permission::Gpu, Permission::Audio, Permission::Gamepad, Permission::DbusSession];
|
||||
let spec = Spec {
|
||||
app_id: "steam",
|
||||
app_dir: Path::new("/usr/share/smartfox/apps/steam"),
|
||||
data_dir: Path::new("/d"),
|
||||
extra_rw: vec!["/var/home/tv/.config/smartfox/profiles/steam".into()],
|
||||
permissions: &perms,
|
||||
env: vec![],
|
||||
program: "/app/x".into(),
|
||||
args: vec![],
|
||||
};
|
||||
let a = args(&spec, &host(), &fake_fs);
|
||||
assert!(a.contains(&"--share-net".to_string()));
|
||||
assert!(has_seq(&a, &["--dev-bind-try", "/dev/dri", "/dev/dri"]));
|
||||
assert!(has_seq(&a, &["--dev-bind-try", "/dev/hidraw0", "/dev/hidraw0"]));
|
||||
assert!(has_seq(&a, &["--ro-bind", "/sys", "/sys"]));
|
||||
assert!(has_seq(&a, &["--ro-bind-try", "/run/user/1000/pipewire-0", "/run/user/1000/pipewire-0"]));
|
||||
assert!(has_seq(&a, &["--setenv", "DBUS_SESSION_BUS_ADDRESS", "unix:path=/run/user/1000/bus"]));
|
||||
assert!(has_seq(&a, &["--bind", "/var/home/tv/.config/smartfox/profiles/steam", "/var/home/tv/.config/smartfox/profiles/steam"]));
|
||||
}
|
||||
}
|
||||
180
crates/sf-ipc/src/store.rs
Normal file
180
crates/sf-ipc/src/store.rs
Normal file
@@ -0,0 +1,180 @@
|
||||
//! The app store's files, shared by the launcher and sf-update (docs/store.md).
|
||||
//!
|
||||
//! /var/lib/smartfox/store.toml what the user wants: sources, apps and
|
||||
//! the permissions they approved (the
|
||||
//! launcher writes it, user tv)
|
||||
//! /var/lib/sf-pkg/store/catalog.json what the sources offer, and why an
|
||||
//! update is held back (sf-update, root)
|
||||
//! /var/lib/sf-pkg/store/apps/<id> installed store apps (sf-update)
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::Path;
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
use crate::manifest::Permission;
|
||||
|
||||
pub const WANTED_FILE: &str = "/var/lib/smartfox/store.toml";
|
||||
pub const CATALOG_FILE: &str = "/var/lib/sf-pkg/store/catalog.json";
|
||||
/// Package (folder) name of a store app in /var/lib/sf-pkg.
|
||||
pub const PACKAGE_PREFIX: &str = "store-";
|
||||
/// The file a catalog repo keeps on its default branch.
|
||||
pub const INDEX_FILE: &str = "smartfox-store.toml";
|
||||
/// Largest store.toml sf-update reads.
|
||||
pub const MAX_WANTED: u64 = 256 * 1024;
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct Wanted {
|
||||
/// Repos the user added: app repos and catalogs.
|
||||
#[serde(default)]
|
||||
pub sources: Vec<String>,
|
||||
/// Installed (or to be installed) apps by id.
|
||||
#[serde(default)]
|
||||
pub apps: BTreeMap<String, WantedApp>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
|
||||
pub struct WantedApp {
|
||||
/// The repo the app comes from (canonical https URL).
|
||||
pub source: String,
|
||||
/// Permissions the user approved; an update that asks for more waits
|
||||
/// for a new approval.
|
||||
#[serde(default)]
|
||||
pub permissions: Vec<Permission>,
|
||||
}
|
||||
|
||||
impl Wanted {
|
||||
pub fn parse(text: &str) -> Result<Wanted> {
|
||||
toml::from_str(text).context("store.toml")
|
||||
}
|
||||
|
||||
pub fn load(path: &Path) -> Result<Wanted> {
|
||||
match std::fs::read_to_string(path) {
|
||||
Ok(text) => Wanted::parse(&text),
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => Ok(Wanted::default()),
|
||||
Err(e) => Err(e).with_context(|| format!("reading {}", path.display())),
|
||||
}
|
||||
}
|
||||
|
||||
/// Writes atomically (the updater may read it at any time).
|
||||
pub fn save(&self, path: &Path) -> Result<()> {
|
||||
let tmp = path.with_extension("toml.tmp");
|
||||
std::fs::write(&tmp, toml::to_string_pretty(self)?).with_context(|| format!("writing {}", tmp.display()))?;
|
||||
std::fs::rename(&tmp, path).with_context(|| format!("writing {}", path.display()))?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
/// `smartfox-store.toml` in a catalog repo.
|
||||
#[derive(Debug, Clone, Default, Deserialize)]
|
||||
pub struct Index {
|
||||
#[serde(default)]
|
||||
pub name: String,
|
||||
#[serde(default)]
|
||||
pub description: String,
|
||||
/// App repo addresses.
|
||||
#[serde(default)]
|
||||
pub apps: Vec<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
pub struct Catalog {
|
||||
/// Unix time of the last refresh (0: never).
|
||||
#[serde(default)]
|
||||
pub updated_at: u64,
|
||||
#[serde(default)]
|
||||
pub sources: Vec<SourceInfo>,
|
||||
#[serde(default)]
|
||||
pub apps: Vec<CatalogApp>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
pub struct SourceInfo {
|
||||
/// As in store.toml.
|
||||
pub url: String,
|
||||
/// "app" or "catalog"
|
||||
#[serde(default)]
|
||||
pub kind: String,
|
||||
#[serde(default)]
|
||||
pub name: String,
|
||||
/// Apps found in it.
|
||||
#[serde(default)]
|
||||
pub apps: usize,
|
||||
#[serde(default)]
|
||||
pub error: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
pub struct CatalogApp {
|
||||
pub id: String,
|
||||
pub name: String,
|
||||
pub version: String,
|
||||
#[serde(default)]
|
||||
pub kind: String,
|
||||
#[serde(default)]
|
||||
pub category: String,
|
||||
#[serde(default)]
|
||||
pub description: String,
|
||||
#[serde(default)]
|
||||
pub author: String,
|
||||
#[serde(default)]
|
||||
pub homepage: String,
|
||||
#[serde(default)]
|
||||
pub license: String,
|
||||
#[serde(default)]
|
||||
pub accent: String,
|
||||
#[serde(default)]
|
||||
pub permissions: Vec<Permission>,
|
||||
/// The app's repo (canonical https URL).
|
||||
pub source: String,
|
||||
/// The catalog it was listed in, if any.
|
||||
#[serde(default)]
|
||||
pub catalog: Option<String>,
|
||||
pub package_url: String,
|
||||
/// Installed version, if any.
|
||||
#[serde(default)]
|
||||
pub installed: Option<String>,
|
||||
/// Why the newest version isn't installed: "permissions" (asks for more
|
||||
/// than approved).
|
||||
#[serde(default)]
|
||||
pub blocked: Option<String>,
|
||||
}
|
||||
|
||||
impl Catalog {
|
||||
pub fn load(path: &Path) -> Option<Catalog> {
|
||||
serde_json::from_str(&std::fs::read_to_string(path).ok()?).ok()
|
||||
}
|
||||
|
||||
pub fn app(&self, id: &str) -> Option<&CatalogApp> {
|
||||
self.apps.iter().find(|a| a.id == id)
|
||||
}
|
||||
}
|
||||
|
||||
/// Permissions in `want` that `approved` doesn't have.
|
||||
pub fn missing_permissions(want: &[Permission], approved: &[Permission]) -> Vec<Permission> {
|
||||
want.iter().filter(|p| !approved.contains(p)).copied().collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn wanted_round_trip() {
|
||||
let w = Wanted::parse(
|
||||
r#"
|
||||
sources = ["https://github.com/fox/store"]
|
||||
[apps."io.github.fox.hello"]
|
||||
source = "https://github.com/fox/hello"
|
||||
permissions = ["network", "audio"]
|
||||
"#,
|
||||
)
|
||||
.unwrap();
|
||||
assert_eq!(w.apps["io.github.fox.hello"].permissions, [Permission::Network, Permission::Audio]);
|
||||
let again = Wanted::parse(&toml::to_string_pretty(&w).unwrap()).unwrap();
|
||||
assert_eq!(w, again);
|
||||
assert!(Wanted::parse("[apps.x]\nsource = 'a'\npermissions = ['root']\n").is_err());
|
||||
assert_eq!(missing_permissions(&[Permission::Network, Permission::Gpu], &[Permission::Network]), [Permission::Gpu]);
|
||||
}
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "sf-launcher"
|
||||
description = "SmartFox TV launcher: Slint UI on top of a Liquid Glass OpenGL layer"
|
||||
description = "Fennec OS TV launcher: Slint UI on top of a Liquid Glass OpenGL layer"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
# Slint is used under GPL-3.0 (or its royalty-free license on desktop).
|
||||
@@ -8,11 +8,14 @@ license = "GPL-3.0-only"
|
||||
|
||||
[dependencies]
|
||||
sf-ipc.workspace = true
|
||||
sf-ui = { path = "../sf-ui", default-features = false }
|
||||
anyhow.workspace = true
|
||||
log.workspace = true
|
||||
env_logger.workspace = true
|
||||
serde_json.workspace = true
|
||||
slint = { version = "1.18", default-features = false, features = ["std", "backend-default", "renderer-femtovg", "compat-1-2"] }
|
||||
serde.workspace = true
|
||||
ureq = "3"
|
||||
slint = { version = "1.18", default-features = false, features = ["std", "backend-default", "renderer-femtovg", "compat-1-2", "image-default-formats"] }
|
||||
glow = "0.16"
|
||||
png = "0.18"
|
||||
chrono = { version = "0.4", default-features = false, features = ["clock", "std"] }
|
||||
|
||||
@@ -1,3 +1,7 @@
|
||||
fn main() {
|
||||
slint_build::compile("ui/app.slint").expect("compiling ui/app.slint");
|
||||
// The Onest font comes from sf-ui's Slint library ("@sf-ui/fonts/...").
|
||||
let sf_ui = std::env::var("DEP_SF_UI_UI_DIR").expect("sf-ui must be a direct dependency");
|
||||
let config = slint_build::CompilerConfiguration::new()
|
||||
.with_library_paths(std::collections::HashMap::from([("sf-ui".to_string(), sf_ui.into())]));
|
||||
slint_build::compile_with_config("ui/app.slint", config).expect("compiling ui/app.slint");
|
||||
}
|
||||
|
||||
65
crates/sf-launcher/src/core_client.rs
Normal file
65
crates/sf-launcher/src/core_client.rs
Normal file
@@ -0,0 +1,65 @@
|
||||
#![cfg_attr(not(unix), allow(dead_code))]
|
||||
//! Connection to sf-core. On the TV sf-core starts, freezes and closes apps;
|
||||
//! without it (desktop testing) the launcher starts apps itself.
|
||||
|
||||
use sf_ipc::{CoreEvent, LauncherRequest};
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct CoreClient {
|
||||
#[cfg(unix)]
|
||||
stream: std::sync::Arc<std::sync::Mutex<std::os::unix::net::UnixStream>>,
|
||||
}
|
||||
|
||||
impl CoreClient {
|
||||
/// Connects if sf-core is running. `on_event` runs on the Slint event loop.
|
||||
#[cfg(unix)]
|
||||
pub fn connect(on_event: impl Fn(CoreEvent) + Send + Sync + Clone + 'static) -> Option<Self> {
|
||||
use std::io::{BufRead, BufReader};
|
||||
use std::os::unix::net::UnixStream;
|
||||
|
||||
let path = sf_ipc::paths::core_socket();
|
||||
// sf-core may start a moment after the launcher.
|
||||
let stream = (0..20).find_map(|i| {
|
||||
if i > 0 {
|
||||
std::thread::sleep(std::time::Duration::from_millis(100));
|
||||
}
|
||||
UnixStream::connect(&path).ok()
|
||||
});
|
||||
let Some(stream) = stream else {
|
||||
log::info!("no sf-core at {}, starting apps locally", path.display());
|
||||
return None;
|
||||
};
|
||||
log::info!("connected to sf-core");
|
||||
let reader = stream.try_clone().ok()?;
|
||||
std::thread::spawn(move || {
|
||||
for line in BufReader::new(reader).lines().map_while(Result::ok) {
|
||||
match serde_json::from_str::<CoreEvent>(&line) {
|
||||
Ok(ev) => {
|
||||
let f = on_event.clone();
|
||||
let _ = slint::invoke_from_event_loop(move || f(ev));
|
||||
}
|
||||
Err(e) => log::warn!("sf-core: bad event {line:?}: {e}"),
|
||||
}
|
||||
}
|
||||
log::warn!("sf-core connection closed");
|
||||
});
|
||||
Some(CoreClient { stream: std::sync::Arc::new(std::sync::Mutex::new(stream)) })
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
pub fn connect(_on_event: impl Fn(CoreEvent) + Send + Sync + Clone + 'static) -> Option<Self> {
|
||||
None
|
||||
}
|
||||
|
||||
pub fn send(&self, req: LauncherRequest) {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::io::Write;
|
||||
if let Err(e) = self.stream.lock().unwrap().write_all(req.to_line().as_bytes()) {
|
||||
log::error!("sf-core: {e}");
|
||||
}
|
||||
}
|
||||
#[cfg(not(unix))]
|
||||
let _ = req;
|
||||
}
|
||||
}
|
||||
@@ -17,7 +17,7 @@ use slint::ComponentHandle;
|
||||
use slint::platform::{Key, WindowEvent};
|
||||
|
||||
use crate::App;
|
||||
use crate::glass::GlassRenderer;
|
||||
use sf_ui::render::GlassRenderer;
|
||||
|
||||
pub struct Snapshot {
|
||||
path: Option<PathBuf>,
|
||||
|
||||
@@ -1,49 +0,0 @@
|
||||
//! "Liquid Glass" layer: an OpenGL pass under the Slint UI that draws the
|
||||
//! animated backdrop and the frosted, refracting glass panels.
|
||||
|
||||
mod renderer;
|
||||
mod shaders;
|
||||
|
||||
pub use renderer::GlassRenderer;
|
||||
|
||||
/// Panels drawn per frame at most (each one is its own small draw call).
|
||||
pub const MAX_RECTS: usize = 48;
|
||||
/// Members of one merged (liquid) group at most.
|
||||
pub const MAX_GROUP: usize = 4;
|
||||
|
||||
/// One glass panel in physical pixels (top-left origin).
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct Panel {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
pub w: f32,
|
||||
pub h: f32,
|
||||
pub radius: f32,
|
||||
/// 0..1, brightens the rim and adds the accent glow.
|
||||
pub focus: f32,
|
||||
pub alpha: f32,
|
||||
/// Mip level used for the frost (higher = blurrier). Negative = nested glass.
|
||||
pub blur: f32,
|
||||
pub glow: [f32; 3],
|
||||
/// Consecutive panels with the same group (> 0) melt into one shape.
|
||||
pub group: f32,
|
||||
/// rgb + amount.
|
||||
pub tint: [f32; 4],
|
||||
}
|
||||
|
||||
/// Everything the renderer needs for one frame.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Frame {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub scale: f32,
|
||||
pub time: f32,
|
||||
/// Backdrop palette (highlight, mid, deep), already crossfaded.
|
||||
pub palette: [f32; 9],
|
||||
/// 1 = top shelf visible (bright backdrop), 0 = scrolled down into the grid.
|
||||
pub shelf: f32,
|
||||
pub light: [f32; 2],
|
||||
/// Backdrop zoom (1 = none), used for the launch fly-in.
|
||||
pub zoom: f32,
|
||||
pub rects: Vec<Panel>,
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
#![cfg_attr(not(unix), allow(dead_code))]
|
||||
//! Tiny command socket so other SmartFox components (the remote daemon) can
|
||||
//! Tiny command socket so other Fennec OS components (the remote daemon) can
|
||||
//! reach the launcher even while an app has focus.
|
||||
//! Protocol: one command per line:
|
||||
//! `home` bring the launcher to the front
|
||||
|
||||
@@ -8,7 +8,7 @@ use std::cell::RefCell;
|
||||
use slint::ComponentHandle;
|
||||
|
||||
use crate::App;
|
||||
use crate::glass::Panel;
|
||||
use sf_ui::render::Panel;
|
||||
|
||||
pub struct Request {
|
||||
pub title: String,
|
||||
|
||||
@@ -1,27 +1,30 @@
|
||||
//! SmartFox launcher.
|
||||
//! Fennec OS launcher.
|
||||
//!
|
||||
//! Slint draws text and icons; the `glass` module draws the animated backdrop
|
||||
//! and frosted glass panels underneath via a rendering notifier.
|
||||
//! Slint draws text and icons; sf-ui's glass renderer draws the animated
|
||||
//! backdrop and frosted glass panels underneath via a rendering notifier.
|
||||
|
||||
mod glass;
|
||||
mod core_client;
|
||||
mod ipc;
|
||||
mod devshot;
|
||||
mod keyboard;
|
||||
mod power;
|
||||
mod runtime;
|
||||
mod settings_screen;
|
||||
mod shelf;
|
||||
mod status;
|
||||
mod store_screen;
|
||||
mod system;
|
||||
#[cfg(windows)]
|
||||
mod winfade;
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::rc::Rc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use chrono::{Datelike, Local, Timelike};
|
||||
use glass::{Frame, GlassRenderer, Panel};
|
||||
use sf_ui::render::{Frame, GlassRenderer, Panel};
|
||||
use sf_ipc::{AppKind, AppManifest, Settings};
|
||||
use slint::{ComponentHandle, Model, ModelRc, SharedString, VecModel};
|
||||
|
||||
@@ -33,18 +36,22 @@ const CROSSFADE: f32 = 0.35;
|
||||
struct Options {
|
||||
/// Factory apps, then installed app packages (`--apps` may repeat).
|
||||
apps_dirs: Vec<PathBuf>,
|
||||
/// Installed store apps (sandboxed; docs/store.md).
|
||||
store_dir: Option<PathBuf>,
|
||||
settings_path: PathBuf,
|
||||
fullscreen: bool,
|
||||
}
|
||||
|
||||
fn parse_args() -> Options {
|
||||
let mut apps_dirs = Vec::new();
|
||||
let mut store_dir = None;
|
||||
let mut settings_path = None;
|
||||
let mut fullscreen = false;
|
||||
let mut args = std::env::args().skip(1);
|
||||
while let Some(a) = args.next() {
|
||||
match a.as_str() {
|
||||
"--apps" => apps_dirs.extend(args.next().map(PathBuf::from)),
|
||||
"--store-apps" => store_dir = args.next().map(PathBuf::from),
|
||||
"--settings" => settings_path = args.next().map(PathBuf::from),
|
||||
"--fullscreen" | "-f" => fullscreen = true,
|
||||
other => log::warn!("unknown argument {other}"),
|
||||
@@ -56,6 +63,7 @@ fn parse_args() -> Options {
|
||||
} else {
|
||||
apps_dirs
|
||||
},
|
||||
store_dir,
|
||||
settings_path: settings_path.unwrap_or_else(default_settings_path),
|
||||
fullscreen,
|
||||
}
|
||||
@@ -114,12 +122,20 @@ fn palette_of(app: &AppManifest) -> [f32; 9] {
|
||||
out
|
||||
}
|
||||
|
||||
fn entry_of(app: &AppManifest, settings: &Settings) -> AppEntry {
|
||||
/// `services`: sf-core runs the background receivers. Without it (an older
|
||||
/// image, or a desktop) a receiver tile starts the app like any other.
|
||||
/// Demo mode (Windows) shows receivers as running, like on the TV.
|
||||
fn entry_of(app: &AppManifest, settings: &Settings, services: bool) -> AppEntry {
|
||||
let (kind, kind_label, target) = match app.kind {
|
||||
AppKind::Web => ("web", "Webes alkalmazás (Chromium)", app.resolved_url(settings).unwrap_or_default()),
|
||||
AppKind::Exec => ("exec", "Natív alkalmazás", app.exec.clone().unwrap_or_default().join(" ")),
|
||||
AppKind::Builtin => ("builtin", "Beépített", String::new()),
|
||||
_ if app.service && services => ("service", "Mindig fut a háttérben", app.exec.clone().unwrap_or_default().join(" ")),
|
||||
AppKind::Web => ("web", "Webes alkalmazás", app.resolved_url(settings).unwrap_or_default()),
|
||||
AppKind::Exec => ("exec", "Alkalmazás", app.exec.clone().unwrap_or_default().join(" ")),
|
||||
AppKind::Builtin => ("builtin", "A rendszer része", String::new()),
|
||||
};
|
||||
let host = if kind == "web" { host_of(&target) } else { String::new() };
|
||||
let kind_label = if app.origin == sf_ipc::Origin::Store { "Store app · saját sandboxban" } else { kind_label };
|
||||
let image = app.icon_file().and_then(|p| slint::Image::load_from_path(&p).map_err(|e| log::warn!("{}: icon {}: {e:?}", app.id, p.display())).ok());
|
||||
let initial = app.name.chars().next().map(|c| c.to_uppercase().to_string()).unwrap_or_default();
|
||||
AppEntry {
|
||||
id: app.id.clone().into(),
|
||||
name: app.name.clone().into(),
|
||||
@@ -130,9 +146,132 @@ fn entry_of(app: &AppManifest, settings: &Settings) -> AppEntry {
|
||||
kind: kind.into(),
|
||||
kind_label: kind_label.into(),
|
||||
target: target.into(),
|
||||
version: app.version.clone().into(),
|
||||
host: host.into(),
|
||||
facts: ModelRc::default(),
|
||||
has_image: image.is_some(),
|
||||
image: image.unwrap_or_default(),
|
||||
initial: initial.into(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Starts the launcher again, in the same process (same pid, so the
|
||||
/// compositor and sf-core carry on and running apps stay as they are): the
|
||||
/// simplest way to pick up a changed app list after a store install.
|
||||
fn restart_launcher() {
|
||||
log::info!("app list changed, restarting the launcher");
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::process::CommandExt;
|
||||
let Ok(exe) = std::env::current_exe() else { return };
|
||||
let err = std::process::Command::new(exe).args(std::env::args_os().skip(1)).exec();
|
||||
log::error!("restarting the launcher: {err}");
|
||||
}
|
||||
}
|
||||
|
||||
/// "https://netflex.example.com/" -> "netflex.example.com".
|
||||
fn host_of(url: &str) -> String {
|
||||
let rest = url.split_once("://").map_or(url, |(_, r)| r);
|
||||
rest.trim_end_matches('/').to_string()
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// sf-core is running (receivers in the background, DIAL casting).
|
||||
static CORE_UP: Cell<bool> = const { Cell::new(false) };
|
||||
}
|
||||
|
||||
/// Live lines under the focused app's name on the home screen.
|
||||
fn facts_for(entry: &AppEntry, st: &status::Status) -> Vec<Fact> {
|
||||
let fact = |icon: &str, text: &str, tone: &str| Fact { icon: icon.into(), text: text.into(), tone: tone.into() };
|
||||
// The status capsule already shows the network; facts repeat it only as a warning.
|
||||
let offline = st.net == "none";
|
||||
let net = |out: &mut Vec<Fact>| {
|
||||
if offline {
|
||||
out.push(fact("alert", "Nincs hálózat", "warn"));
|
||||
}
|
||||
};
|
||||
let core = CORE_UP.with(Cell::get);
|
||||
match entry.id.as_str() {
|
||||
"youtube" => {
|
||||
let mut out = Vec::new();
|
||||
if core {
|
||||
out.push(fact("cast", "Telefonról is indítható", ""));
|
||||
}
|
||||
net(&mut out);
|
||||
out
|
||||
}
|
||||
"airplay" | "miracast" => {
|
||||
let mut out = Vec::new();
|
||||
if entry.kind == "service" {
|
||||
out.push(fact("check", "Látható „Fennec OS” néven", "ok"));
|
||||
}
|
||||
if entry.id == "miracast" {
|
||||
out.push(fact("alert", "Kísérleti", "warn"));
|
||||
}
|
||||
net(&mut out);
|
||||
out
|
||||
}
|
||||
"settings" => {
|
||||
let mut out = Vec::new();
|
||||
match st.remote_battery {
|
||||
Some(b) => out.push(fact("remote", &format!("Siri Remote · {b}%"), if b <= 15 { "warn" } else { "" })),
|
||||
None if st.remote_connected => out.push(fact("remote", "Siri Remote", "")),
|
||||
None => {}
|
||||
}
|
||||
net(&mut out);
|
||||
if let Some(d) = &st.display {
|
||||
out.push(fact("display", d, ""));
|
||||
}
|
||||
out
|
||||
}
|
||||
_ => {
|
||||
let mut out = Vec::new();
|
||||
net(&mut out);
|
||||
out
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Status capsule and the facts of every app.
|
||||
fn apply_status(ui: &App, st: &status::Status) {
|
||||
ui.set_net_icon(st.net.into());
|
||||
ui.set_net_label(st.net_label.clone().into());
|
||||
ui.set_remote_battery(st.remote_battery.map_or(-1, i32::from));
|
||||
let apps = ui.get_apps();
|
||||
for i in 0..apps.row_count() {
|
||||
if let Some(mut entry) = apps.row_data(i) {
|
||||
entry.facts = ModelRc::new(VecModel::from(facts_for(&entry, st)));
|
||||
apps.set_row_data(i, entry);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Top Shelf cards; artwork that does not load falls back to the title.
|
||||
fn apply_shelf(ui: &App, shelf: shelf::Shelf, dir: &Path) {
|
||||
let items: Vec<ShelfItem> = shelf
|
||||
.items
|
||||
.into_iter()
|
||||
.map(|item| {
|
||||
let image = item.image.as_ref().and_then(|name| match slint::Image::load_from_path(&dir.join(name)) {
|
||||
Ok(img) => Some(img),
|
||||
Err(e) => {
|
||||
log::info!("shelf artwork {name}: {e:?}");
|
||||
None
|
||||
}
|
||||
});
|
||||
ShelfItem {
|
||||
title: item.title.into(),
|
||||
detail: item.detail.into(),
|
||||
has_image: image.is_some(),
|
||||
image: image.unwrap_or_default(),
|
||||
progress: item.progress,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
ui.set_shelf_title(shelf.title.into());
|
||||
ui.set_shelf_items(ModelRc::new(VecModel::from(items)));
|
||||
}
|
||||
|
||||
/// Backdrop colours, eased towards the focused app's palette every frame.
|
||||
struct Backdrop {
|
||||
palette: [f32; 9],
|
||||
@@ -175,6 +314,7 @@ fn card_rects(ui: &App, scale: f32, accents: &[[f32; 3]]) -> Vec<Panel> {
|
||||
let (fx, fy, active, intro) = (ui.get_focus_x(), ui.get_focus_y(), ui.get_row_active(), ui.get_intro());
|
||||
let (lift, press_in, press) = (ui.get_lift(), ui.get_press_in(), ui.get_press());
|
||||
let scroll = ui.get_grid_scroll();
|
||||
let shelf = ui.get_shelf_t();
|
||||
let menu_t = ui.get_menu_t().clamp(0.0, 1.0);
|
||||
let focus_index = ui.get_focus_index().max(0) as usize;
|
||||
let hidden = (1.0 - ui.get_launch_t()) * (1.0 - ui.get_sheet_t()) * ui.get_dim();
|
||||
@@ -184,6 +324,8 @@ fn card_rects(ui: &App, scale: f32, accents: &[[f32; 3]]) -> Vec<Panel> {
|
||||
let s = 1.0 + (lift - press_in * press) * f;
|
||||
let appear = (intro * 2.2 - col * 0.12 - row * 0.2 - 0.4).clamp(0.0, 1.0);
|
||||
let others = if i == focus_index { 1.0 } else { 1.0 - 0.55 * menu_t };
|
||||
// Lower rows stay hidden under the shelf (no sliver at the screen edge).
|
||||
let others = if row > 0.0 { others * (1.0 - shelf) } else { others };
|
||||
let (w, h) = (cw * s, ch * s);
|
||||
let x = row_x + col * (cw + gap) + (cw - w) / 2.0;
|
||||
let y = row_y + row * step - scroll + (ch - h) / 2.0 + (1.0 - appear) * 60.0 * u;
|
||||
@@ -222,7 +364,8 @@ fn card_rects(ui: &App, scale: f32, accents: &[[f32; 3]]) -> Vec<Panel> {
|
||||
}
|
||||
|
||||
const DAYS: [&str; 7] = ["hétfő", "kedd", "szerda", "csütörtök", "péntek", "szombat", "vasárnap"];
|
||||
const MONTHS: [&str; 12] = ["jan.", "febr.", "márc.", "ápr.", "máj.", "jún.", "júl.", "aug.", "szept.", "okt.", "nov.", "dec."];
|
||||
const MONTHS: [&str; 12] =
|
||||
["január", "február", "március", "április", "május", "június", "július", "augusztus", "szeptember", "október", "november", "december"];
|
||||
|
||||
fn update_clock(ui: &App) {
|
||||
let now = Local::now();
|
||||
@@ -296,6 +439,73 @@ fn show_toast(ui: &App, text: impl Into<SharedString>, timer: &slint::Timer) {
|
||||
});
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
/// The app sf-core shows in the foreground, as far as the UI knows.
|
||||
static CORE_APP: RefCell<Option<String>> = const { RefCell::new(None) };
|
||||
static CORE_TOAST: slint::Timer = slint::Timer::default();
|
||||
}
|
||||
|
||||
fn app_name(apps: &[AppManifest], id: &str) -> String {
|
||||
apps.iter().find(|a| a.id == id).map(|a| a.name.clone()).unwrap_or_else(|| id.to_string())
|
||||
}
|
||||
|
||||
/// Shows an app as running: the launch morph covers the home screen.
|
||||
fn show_running(ui: &App, apps: &[AppManifest], id: &str) {
|
||||
let Some(index) = apps.iter().position(|a| a.id == id) else { return };
|
||||
CORE_APP.with(|c| *c.borrow_mut() = Some(id.to_string()));
|
||||
ui.set_focus_index(index as i32);
|
||||
ui.set_menu_open(false);
|
||||
ui.set_sheet_open(false);
|
||||
ui.set_settings_open(false);
|
||||
// The splash (with its loading bar) stays until the compositor fades the
|
||||
// app in on top of it, which waits for the page to load.
|
||||
ui.set_launching(true);
|
||||
}
|
||||
|
||||
/// Events from sf-core (apps starting and stopping, casting).
|
||||
fn on_core_event(ui: &App, apps: &[AppManifest], ev: sf_ipc::CoreEvent) {
|
||||
use sf_ipc::CoreEvent::*;
|
||||
let toast = |text: String| CORE_TOAST.with(|t| show_toast(ui, text, t));
|
||||
match ev {
|
||||
Hello { foreground, switching } => {
|
||||
log::info!("sf-core: switching={switching} foreground={foreground:?}");
|
||||
if let Some(id) = foreground {
|
||||
show_running(ui, apps, &id);
|
||||
}
|
||||
}
|
||||
AppStarted { app_id, cast } => {
|
||||
let current = CORE_APP.with(|c| c.borrow().clone());
|
||||
if current.as_deref() != Some(app_id.as_str()) || !ui.get_launching() {
|
||||
show_running(ui, apps, &app_id);
|
||||
} else {
|
||||
CORE_APP.with(|c| *c.borrow_mut() = Some(app_id.clone()));
|
||||
}
|
||||
if cast {
|
||||
toast(format!("{}: indítás telefonról", app_name(apps, &app_id)));
|
||||
}
|
||||
}
|
||||
AppStopped { app_id } => {
|
||||
let was_shown = CORE_APP.with(|c| {
|
||||
let mut c = c.borrow_mut();
|
||||
let shown = c.as_deref() == Some(app_id.as_str());
|
||||
if shown {
|
||||
*c = None;
|
||||
}
|
||||
shown
|
||||
});
|
||||
if was_shown {
|
||||
// Reverse morph: the full-screen glass shrinks back into the card.
|
||||
ui.set_launching(false);
|
||||
ui.set_app_ready(false);
|
||||
toast(format!("{} bezárva", app_name(apps, &app_id)));
|
||||
}
|
||||
}
|
||||
CastConnected { app_id, device } => toast(format!("{}: {device} csatlakozott", app_name(apps, &app_id))),
|
||||
CastEnded { app_id } => toast(format!("{}: a tükrözés véget ért", app_name(apps, &app_id))),
|
||||
Toast { text } => toast(text),
|
||||
}
|
||||
}
|
||||
|
||||
fn main() -> Result<()> {
|
||||
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
|
||||
let opts = parse_args();
|
||||
@@ -316,14 +526,18 @@ fn main() -> Result<()> {
|
||||
}
|
||||
let data_dir = opts.settings_path.parent().map(Path::to_path_buf).unwrap_or_else(|| PathBuf::from("."));
|
||||
|
||||
let apps = sf_ipc::manifest::load_apps_from(&opts.apps_dirs).with_context(|| format!("loading apps from {:?}", opts.apps_dirs))?;
|
||||
let apps = sf_ipc::manifest::load_all(&opts.apps_dirs, opts.store_dir.as_deref()).with_context(|| format!("loading apps from {:?}", opts.apps_dirs))?;
|
||||
log::info!("{} apps from {:?}", apps.len(), opts.apps_dirs);
|
||||
system::confirm_shell_trial();
|
||||
|
||||
let ui = App::new()?;
|
||||
let entries: Vec<AppEntry> = apps.iter().map(|a| entry_of(a, &settings)).collect();
|
||||
let entries: Vec<AppEntry> = apps.iter().map(|a| entry_of(a, &settings, true)).collect();
|
||||
ui.set_apps(ModelRc::new(VecModel::from(entries)));
|
||||
let _screen = settings_screen::Screen::install(&ui, opts.settings_path.clone());
|
||||
let store = store_screen::Screen::install(&ui);
|
||||
if !system::demo() {
|
||||
store.on_apps_changed(restart_launcher);
|
||||
}
|
||||
keyboard::install(&ui);
|
||||
power::configure_from(&settings);
|
||||
power::install(&ui, opts.settings_path.clone());
|
||||
@@ -349,9 +563,41 @@ fn main() -> Result<()> {
|
||||
});
|
||||
}
|
||||
|
||||
// Launching. Locally the launcher starts apps itself; on the TV this moves to sf-core.
|
||||
// Launching. On the TV sf-core starts apps (and keeps them frozen in the
|
||||
// background on Home); without it the launcher starts them itself.
|
||||
let toast_timer = Rc::new(slint::Timer::default());
|
||||
let running: Rc<RefCell<Option<(String, std::process::Child)>>> = Rc::default();
|
||||
let core = {
|
||||
let weak = ui.as_weak();
|
||||
let apps = apps.clone();
|
||||
core_client::CoreClient::connect(move |ev| {
|
||||
let Some(ui) = weak.upgrade() else { return };
|
||||
on_core_event(&ui, &apps, ev);
|
||||
})
|
||||
};
|
||||
if core.is_none() {
|
||||
let entries: Vec<AppEntry> = apps.iter().map(|a| entry_of(a, &settings, system::demo())).collect();
|
||||
ui.set_apps(ModelRc::new(VecModel::from(entries)));
|
||||
}
|
||||
CORE_UP.with(|c| c.set(core.is_some()));
|
||||
apply_status(&ui, &status::Status { net: "wired", ..Default::default() });
|
||||
{
|
||||
let weak = ui.as_weak();
|
||||
status::spawn(move |st| {
|
||||
let _ = weak.upgrade_in_event_loop(move |ui| apply_status(&ui, &st));
|
||||
});
|
||||
}
|
||||
{
|
||||
let weak = ui.as_weak();
|
||||
let source = shelf::Source {
|
||||
server: settings.get("netflex_server").map(str::to_string),
|
||||
token: settings.get("netflex_token").filter(|t| !t.is_empty()).map(str::to_string),
|
||||
dir: data_dir.join("cache").join("shelf"),
|
||||
};
|
||||
shelf::spawn(source, move |shelf, dir| {
|
||||
let _ = weak.upgrade_in_event_loop(move |ui| apply_shelf(&ui, shelf, &dir));
|
||||
});
|
||||
}
|
||||
{
|
||||
let weak = ui.as_weak();
|
||||
let apps = apps.clone();
|
||||
@@ -360,20 +606,27 @@ fn main() -> Result<()> {
|
||||
let running = running.clone();
|
||||
let data_dir = data_dir.clone();
|
||||
let fullscreen = opts.fullscreen;
|
||||
let core = core.clone();
|
||||
ui.on_launch(move |index| {
|
||||
let Some(ui) = weak.upgrade() else { return };
|
||||
let Some(app) = apps.get(index as usize) else { return };
|
||||
ui.set_launch_detail("indítása…".into());
|
||||
ui.set_app_ready(false);
|
||||
if let Some(core) = &core {
|
||||
CORE_APP.with(|c| *c.borrow_mut() = Some(app.id.clone()));
|
||||
core.send(sf_ipc::LauncherRequest::Launch { app_id: app.id.clone(), query: None });
|
||||
return;
|
||||
}
|
||||
if let Some((_, mut old)) = running.borrow_mut().take() {
|
||||
runtime::stop(&mut old);
|
||||
}
|
||||
ui.set_launch_detail("indítása…".into());
|
||||
ui.set_app_ready(false);
|
||||
let pos = ui.window().position();
|
||||
let size = ui.window().size();
|
||||
let opts = runtime::LaunchOptions {
|
||||
let opts = sf_ipc::launch::LaunchOptions {
|
||||
data_dir: &data_dir,
|
||||
fullscreen,
|
||||
bounds: Some((pos.x, pos.y, size.width, size.height)),
|
||||
query: None,
|
||||
};
|
||||
match runtime::launch(app, &settings, &opts) {
|
||||
Ok(child) => {
|
||||
@@ -382,7 +635,7 @@ fn main() -> Result<()> {
|
||||
{
|
||||
// Keep the window hidden until the morph finishes and the page loads.
|
||||
let weak = ui.as_weak();
|
||||
let not_before = std::time::Instant::now() + Duration::from_millis(950);
|
||||
let not_before = std::time::Instant::now() + Duration::from_millis(720);
|
||||
winfade::reveal_when_ready(child.id(), not_before, move || {
|
||||
let _ = weak.upgrade_in_event_loop(|ui| ui.set_app_ready(true));
|
||||
});
|
||||
@@ -399,22 +652,38 @@ fn main() -> Result<()> {
|
||||
}
|
||||
{
|
||||
let running = running.clone();
|
||||
let core = core.clone();
|
||||
ui.on_cancel_launch(move || {
|
||||
// Back pressed on the launch splash: close the app that is starting.
|
||||
if let Some(core) = &core {
|
||||
if let Some(id) = CORE_APP.with(|c| c.borrow_mut().take()) {
|
||||
core.send(sf_ipc::LauncherRequest::Stop { app_id: id });
|
||||
}
|
||||
return;
|
||||
}
|
||||
if let Some((name, mut child)) = running.borrow_mut().take() {
|
||||
log::info!("closing {name}");
|
||||
runtime::stop(&mut child);
|
||||
}
|
||||
});
|
||||
}
|
||||
// Global "home" (remote's TV button): close the foreground app and play the reverse morph.
|
||||
// Global "home" (remote's TV button): the foreground app goes to the
|
||||
// background (sf-core) or closes, and the reverse morph plays.
|
||||
{
|
||||
let weak = ui.as_weak();
|
||||
let core = core.clone();
|
||||
ipc::listen(move |cmd| {
|
||||
let Some(ui) = weak.upgrade() else { return };
|
||||
match cmd {
|
||||
ipc::Command::Home => {
|
||||
log::info!("home");
|
||||
ui.invoke_cancel_launch();
|
||||
match &core {
|
||||
Some(core) => {
|
||||
CORE_APP.with(|c| *c.borrow_mut() = None);
|
||||
core.send(sf_ipc::LauncherRequest::GoHome);
|
||||
}
|
||||
None => ui.invoke_cancel_launch(),
|
||||
}
|
||||
ui.set_launching(false);
|
||||
ui.set_app_ready(false);
|
||||
ui.set_sheet_open(false);
|
||||
@@ -527,10 +796,13 @@ fn main() -> Result<()> {
|
||||
scale,
|
||||
time,
|
||||
palette: bd.palette,
|
||||
shelf: ui.get_shelf_t(),
|
||||
brightness: ui.get_shelf_t(),
|
||||
light: [angle.cos(), angle.sin()],
|
||||
zoom: 1.0 + 0.35 * ui.get_launch_t() * ui.get_launch_t(),
|
||||
images: &[],
|
||||
video: None,
|
||||
rects,
|
||||
quality: Default::default(),
|
||||
};
|
||||
drop(bd);
|
||||
// SAFETY: called on the UI thread with the Slint GL context current.
|
||||
|
||||
@@ -1,178 +1,24 @@
|
||||
//! Starts apps. Web apps run in a Chromium-family browser in app/kiosk mode
|
||||
//! with a per-app profile; exec apps are spawned directly.
|
||||
//!
|
||||
//! This lives in the launcher for local testing; on the TV it moves into the
|
||||
//! sf-core daemon (systemd scopes, freeze/thaw).
|
||||
//! Starts apps locally, when no sf-core is running (desktop testing). The
|
||||
//! command line comes from `sf_ipc::launch`; on the TV sf-core does this.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::process::{Child, Command};
|
||||
use std::process::Child;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use sf_ipc::{AppKind, AppManifest, Settings};
|
||||
|
||||
pub struct Browser {
|
||||
pub exe: PathBuf,
|
||||
/// Full version, used to build a realistic user agent.
|
||||
pub version: String,
|
||||
}
|
||||
|
||||
pub fn find_browser() -> Option<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)>,
|
||||
}
|
||||
use anyhow::{Context, Result};
|
||||
use sf_ipc::launch::{LaunchOptions, command};
|
||||
use sf_ipc::{AppManifest, Settings};
|
||||
|
||||
pub fn launch(app: &AppManifest, settings: &Settings, opts: &LaunchOptions) -> Result<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()))
|
||||
let mut cmd = command(app, settings, opts)?;
|
||||
log::info!("{} {:?}", cmd.get_program().to_string_lossy(), cmd.get_args().collect::<Vec<_>>());
|
||||
cmd.spawn().with_context(|| format!("starting {}", cmd.get_program().to_string_lossy()))
|
||||
}
|
||||
|
||||
/// Stops an app and everything it started.
|
||||
pub fn stop(child: &mut Child) {
|
||||
#[cfg(unix)]
|
||||
{
|
||||
// The app runs in its own process group (see launch_web).
|
||||
use std::process::Command;
|
||||
// The app runs in its own process group (see sf_ipc::launch::command).
|
||||
let _ = Command::new("kill").arg("-TERM").arg("--").arg(format!("-{}", child.id())).status();
|
||||
for _ in 0..20 {
|
||||
if matches!(child.try_wait(), Ok(Some(_))) {
|
||||
|
||||
@@ -10,7 +10,7 @@ use std::time::{Duration, Instant};
|
||||
|
||||
use slint::{ComponentHandle, ModelRc, SharedString, VecModel};
|
||||
|
||||
use crate::system::{self, BtDevice, DeviceInfo, Display, Mode, NetInfo, RemoteDebug, Security, UpdateStatus, Wifi, WifiNetwork};
|
||||
use crate::system::{self, AudioOutput, BtAudioDevice, BtDevice, DeviceInfo, Display, Mode, NetInfo, RemoteDebug, Security, UpdateStatus, Wifi, WifiNetwork};
|
||||
use crate::power;
|
||||
use crate::{App, SettingRow, keyboard};
|
||||
|
||||
@@ -19,9 +19,10 @@ const KEEP_SECS: u64 = 15;
|
||||
|
||||
const DISPLAY: i32 = 0;
|
||||
const DEVICES: i32 = 1;
|
||||
const NETWORK: i32 = 2;
|
||||
const ENERGY: i32 = 3;
|
||||
const SYSTEM: i32 = 4;
|
||||
const AUDIO: i32 = 2;
|
||||
const NETWORK: i32 = 3;
|
||||
const ENERGY: i32 = 4;
|
||||
const SYSTEM: i32 = 5;
|
||||
|
||||
#[derive(Clone, PartialEq)]
|
||||
enum Action {
|
||||
@@ -42,6 +43,9 @@ enum Action {
|
||||
Back,
|
||||
PairRemote,
|
||||
ReplaceRemote,
|
||||
AudioOutput(String),
|
||||
BtAudioScan,
|
||||
BtAudioConnect(String),
|
||||
Restart,
|
||||
ConfirmRestart,
|
||||
RemoteDebug,
|
||||
@@ -82,6 +86,10 @@ struct Pending {
|
||||
enum Loaded {
|
||||
Display(Result<Display, String>),
|
||||
Devices(Result<Vec<BtDevice>, String>),
|
||||
Audio(Result<Vec<AudioOutput>, String>),
|
||||
BtAudio(Result<Vec<BtAudioDevice>, String>),
|
||||
AudioDone(Result<String, String>),
|
||||
BtAudioScanDone(Result<Vec<BtAudioDevice>, String>),
|
||||
Net(NetInfo),
|
||||
Wifi(Result<Option<Wifi>, String>),
|
||||
/// A Wi-Fi action finished: notice text, or the error. `retry` reopens the
|
||||
@@ -105,6 +113,8 @@ struct State {
|
||||
parent_row: i32,
|
||||
display: Option<Result<Display, String>>,
|
||||
devices: Option<Result<Vec<BtDevice>, String>>,
|
||||
audio: Option<Result<Vec<AudioOutput>, String>>,
|
||||
bt_audio: Option<Result<Vec<BtAudioDevice>, String>>,
|
||||
net: Option<NetInfo>,
|
||||
/// Ok(None) = no Wi-Fi adapter.
|
||||
wifi: Option<Result<Option<Wifi>, String>>,
|
||||
@@ -187,6 +197,8 @@ impl Screen {
|
||||
parent_row: 0,
|
||||
display: None,
|
||||
devices: None,
|
||||
audio: None,
|
||||
bt_audio: None,
|
||||
net: None,
|
||||
wifi: None,
|
||||
wifi_pending: None,
|
||||
@@ -205,13 +217,27 @@ impl Screen {
|
||||
SCREEN.with(|s| *s.borrow_mut() = Some(screen.clone()));
|
||||
|
||||
let s = screen.clone();
|
||||
// In store mode (app.slint set-mode) the same pane belongs to store_screen.
|
||||
let store_mode = |s: &Screen| s.ui.upgrade().is_some_and(|ui| ui.get_set_mode() == "store");
|
||||
ui.on_settings_opened(move || {
|
||||
if store_mode(&s) {
|
||||
if let Some(store) = crate::store_screen::current() {
|
||||
store.opened();
|
||||
}
|
||||
return;
|
||||
}
|
||||
s.state.borrow_mut().notice.clear();
|
||||
s.refresh_all();
|
||||
s.rebuild(None);
|
||||
});
|
||||
let s = screen.clone();
|
||||
ui.on_settings_nav_changed(move |i| {
|
||||
if store_mode(&s) {
|
||||
if let Some(store) = crate::store_screen::current() {
|
||||
store.nav_changed(i);
|
||||
}
|
||||
return;
|
||||
}
|
||||
{
|
||||
let mut st = s.state.borrow_mut();
|
||||
st.category = i;
|
||||
@@ -226,9 +252,15 @@ impl Screen {
|
||||
s.rebuild(Some(0));
|
||||
});
|
||||
let s = screen.clone();
|
||||
ui.on_settings_activate(move |i| s.activate(i));
|
||||
ui.on_settings_activate(move |i| match crate::store_screen::current().filter(|_| store_mode(&s)) {
|
||||
Some(store) => store.activate(i),
|
||||
None => s.activate(i),
|
||||
});
|
||||
let s = screen.clone();
|
||||
ui.on_settings_back(move || s.run(Action::Back));
|
||||
ui.on_settings_back(move || match crate::store_screen::current().filter(|_| store_mode(&s)) {
|
||||
Some(store) => store.back(),
|
||||
None => s.run(Action::Back),
|
||||
});
|
||||
|
||||
// Ticks the confirm countdown and keeps device/network rows fresh.
|
||||
let s = Rc::downgrade(&screen);
|
||||
@@ -255,12 +287,14 @@ impl Screen {
|
||||
}
|
||||
|
||||
fn is_open(&self) -> bool {
|
||||
self.ui.upgrade().is_some_and(|ui| ui.get_settings_open())
|
||||
self.ui.upgrade().is_some_and(|ui| ui.get_settings_open() && ui.get_set_mode() != "store")
|
||||
}
|
||||
|
||||
fn refresh_all(&self) {
|
||||
post(|| Loaded::Display(system::display().map_err(|e| format!("{e:#}"))));
|
||||
post(|| Loaded::Devices(system::bt_devices().map_err(|e| format!("{e:#}"))));
|
||||
post(|| Loaded::Audio(system::audio_outputs().map_err(|e| format!("{e:#}"))));
|
||||
post(|| Loaded::BtAudio(system::bt_audio_devices().map_err(|e| format!("{e:#}"))));
|
||||
post(|| Loaded::Net(system::network()));
|
||||
post(|| Loaded::Wifi(wifi_result(system::wifi())));
|
||||
post(|| Loaded::RemoteDebug(system::remote_debug()));
|
||||
@@ -292,6 +326,10 @@ impl Screen {
|
||||
}
|
||||
match category {
|
||||
DEVICES => post(|| Loaded::Devices(system::bt_devices().map_err(|e| format!("{e:#}")))),
|
||||
AUDIO => {
|
||||
post(|| Loaded::Audio(system::audio_outputs().map_err(|e| format!("{e:#}"))));
|
||||
post(|| Loaded::BtAudio(system::bt_audio_devices().map_err(|e| format!("{e:#}"))));
|
||||
}
|
||||
NETWORK => {
|
||||
post(|| Loaded::Net(system::network()));
|
||||
post(|| Loaded::Wifi(wifi_result(system::wifi())));
|
||||
@@ -382,6 +420,30 @@ impl Screen {
|
||||
match loaded {
|
||||
Loaded::Display(d) => self.state.borrow_mut().display = Some(d),
|
||||
Loaded::Devices(d) => self.state.borrow_mut().devices = Some(d),
|
||||
Loaded::Audio(d) => self.state.borrow_mut().audio = Some(d),
|
||||
Loaded::BtAudio(d) => self.state.borrow_mut().bt_audio = Some(d),
|
||||
Loaded::BtAudioScanDone(result) => {
|
||||
let mut st = self.state.borrow_mut();
|
||||
st.busy = false;
|
||||
match result {
|
||||
Ok(devices) => {
|
||||
st.notice = if devices.is_empty() { "Nem található Bluetooth hangeszköz.".into() } else { "Válaszd ki a hangeszközt a csatlakozáshoz.".into() };
|
||||
st.bt_audio = Some(Ok(devices));
|
||||
}
|
||||
Err(e) => st.notice = format!("Keresés sikertelen: {}", short_err(&e)),
|
||||
}
|
||||
}
|
||||
Loaded::AudioDone(result) => {
|
||||
let mut st = self.state.borrow_mut();
|
||||
st.busy = false;
|
||||
st.notice = match result {
|
||||
Ok(message) => message,
|
||||
Err(e) => format!("Hangkimenet: {}", short_err(&e)),
|
||||
};
|
||||
drop(st);
|
||||
post(|| Loaded::Audio(system::audio_outputs().map_err(|e| format!("{e:#}"))));
|
||||
post(|| Loaded::BtAudio(system::bt_audio_devices().map_err(|e| format!("{e:#}"))));
|
||||
}
|
||||
Loaded::Net(n) => self.state.borrow_mut().net = Some(n),
|
||||
Loaded::Wifi(w) => {
|
||||
if let Err(e) = &w {
|
||||
@@ -681,6 +743,33 @@ impl Screen {
|
||||
Loaded::Removed { name, result, then_pair: true }
|
||||
});
|
||||
}
|
||||
Action::AudioOutput(name) => {
|
||||
let label = match &self.state.borrow().audio {
|
||||
Some(Ok(outputs)) => outputs.iter().find(|o| o.name == name).map(|o| o.label.clone()),
|
||||
_ => None,
|
||||
}.unwrap_or_else(|| name.clone());
|
||||
self.state.borrow_mut().busy = true;
|
||||
self.rebuild(None);
|
||||
post(move || Loaded::AudioDone(system::set_audio_output(&name)
|
||||
.map(|()| format!("Hangkimenet: {label}"))
|
||||
.map_err(|e| format!("{e:#}"))));
|
||||
}
|
||||
Action::BtAudioScan => {
|
||||
self.state.borrow_mut().busy = true;
|
||||
self.rebuild(None);
|
||||
post(|| Loaded::BtAudioScanDone(system::bt_audio_scan().map_err(|e| format!("{e:#}"))));
|
||||
}
|
||||
Action::BtAudioConnect(addr) => {
|
||||
let label = match &self.state.borrow().bt_audio {
|
||||
Some(Ok(devices)) => devices.iter().find(|d| d.address == addr).map(|d| d.name.clone()),
|
||||
_ => None,
|
||||
}.unwrap_or_else(|| addr.clone());
|
||||
self.state.borrow_mut().busy = true;
|
||||
self.rebuild(None);
|
||||
post(move || Loaded::AudioDone(system::bt_audio_connect(&addr)
|
||||
.map(|()| format!("Hangkimenet: {label}"))
|
||||
.map_err(|e| format!("{e:#}"))));
|
||||
}
|
||||
Action::Restart => self.enter(Sub::Restart, 1),
|
||||
Action::ConfirmRestart => {
|
||||
log::info!("restarting the launcher (settings)");
|
||||
@@ -776,6 +865,10 @@ impl Screen {
|
||||
/// Pushes the current page to Slint. `row` moves the focus (clamped).
|
||||
fn rebuild(&self, row: Option<i32>) {
|
||||
let Some(ui) = self.ui.upgrade() else { return };
|
||||
// The pane shows the App Store: its rows are store_screen's.
|
||||
if ui.get_set_mode() == "store" {
|
||||
return;
|
||||
}
|
||||
let (title, subtitle, rows, actions) = self.page();
|
||||
let len = rows.len() as i32;
|
||||
let in_sub = self.state.borrow().sub != Sub::None;
|
||||
@@ -978,13 +1071,39 @@ impl Screen {
|
||||
notice_or("Párosított eszközök. Válassz ki egyet az eltávolításhoz."),
|
||||
)
|
||||
}
|
||||
(Sub::None, AUDIO) => {
|
||||
match &st.audio {
|
||||
None => push(row("Hangkimenetek lekérdezése…", "", "", "info"), Action::None),
|
||||
Some(Err(e)) => push(row("A hangrendszer nem érhető el", "", short_err(e), "info"), Action::None),
|
||||
Some(Ok(outputs)) if outputs.is_empty() => push(row("Nincs elérhető hangkimenet", "", "", "info"), Action::None),
|
||||
Some(Ok(outputs)) => {
|
||||
for output in outputs {
|
||||
let kind = if output.bluetooth { "Bluetooth" } else { "Vezetékes / HDMI" };
|
||||
push(row(output.label.clone(), if output.selected { "✓" } else { "" }, kind, "option"), Action::AudioOutput(output.name.clone()));
|
||||
}
|
||||
}
|
||||
}
|
||||
match &st.bt_audio {
|
||||
Some(Ok(devices)) => for device in devices {
|
||||
let sink_address = device.address.replace(':', "_").to_ascii_uppercase();
|
||||
let shown_as_output = device.connected && matches!(&st.audio, Some(Ok(outputs)) if outputs.iter().any(|o| o.name.to_ascii_uppercase().contains(&sink_address)));
|
||||
if shown_as_output { continue; }
|
||||
let status = if device.connected { "Csatlakozva" } else if device.paired { "Párosítva" } else { "Új eszköz" };
|
||||
push(row(device.name.clone(), status, "Bluetooth hangeszköz", "device"), Action::BtAudioConnect(device.address.clone()));
|
||||
},
|
||||
Some(Err(e)) => push(row("Bluetooth nem érhető el", "", short_err(e), "info"), Action::None),
|
||||
None => {}
|
||||
}
|
||||
push(row(if st.busy { "Folyamatban…" } else { "Bluetooth hangeszközök keresése" }, "", "Kapcsold be az eszköz párosítási módját", "action"), Action::BtAudioScan);
|
||||
("Hangkimenet".to_string(), notice_or("Válaszd ki, hol szóljon a TV. Bluetooth eszközhöz indíts keresést."))
|
||||
}
|
||||
(Sub::None, NETWORK) => {
|
||||
match &st.net {
|
||||
None => push(row("Hálózat lekérdezése…", "", "", "info"), Action::None),
|
||||
Some(n) => {
|
||||
let conn = match (&n.iface, n.ip.is_some(), n.wireless) {
|
||||
(Some(i), true, true) => format!("Wi-Fi · {i}"),
|
||||
(Some(i), true, false) => format!("Vezetékes · {i}"),
|
||||
(Some(_), true, true) => "Wi-Fi".to_string(),
|
||||
(Some(_), true, false) => "Vezetékes".to_string(),
|
||||
_ => "Nincs kapcsolat".to_string(),
|
||||
};
|
||||
push(row("Kapcsolat", conn, "", "info"), Action::None);
|
||||
@@ -1002,7 +1121,8 @@ impl Screen {
|
||||
(false, true) => "Be",
|
||||
(false, false) => "Ki",
|
||||
};
|
||||
push(row("Wi-Fi", value, w.iface.clone(), "action"), Action::WifiPower);
|
||||
let joined = w.networks.iter().find(|n| n.connected).map(|n| format!("Csatlakozva: {}", n.name));
|
||||
push(row("Wi-Fi", value, joined.unwrap_or_default(), "action"), Action::WifiPower);
|
||||
if w.powered {
|
||||
if w.networks.is_empty() {
|
||||
let text = if w.scanning { "Hálózatok keresése…" } else { "Nincs elérhető hálózat" };
|
||||
@@ -1066,7 +1186,7 @@ impl Screen {
|
||||
(Sub::None, _) => {
|
||||
let info = st.info.clone().unwrap_or_default();
|
||||
push(row("Eszköz neve", info.hostname, "", "info"), Action::None);
|
||||
push(row("SmartFox", format!("v{}", env!("CARGO_PKG_VERSION")), "", "info"), Action::None);
|
||||
push(row("Fennec OS", format!("v{}", env!("CARGO_PKG_VERSION")), "", "info"), Action::None);
|
||||
push(row("Operációs rendszer", info.os, "", "info"), Action::None);
|
||||
push(row("Kernel", info.kernel, "", "info"), Action::None);
|
||||
let ip = st.net.as_ref().and_then(|n| n.ip.clone());
|
||||
@@ -1096,8 +1216,8 @@ impl Screen {
|
||||
}
|
||||
|
||||
/// Glass for the settings screen. Mirrors the geometry in ui/settings.slint.
|
||||
pub fn glass(ui: &App, scale: f32) -> Vec<crate::glass::Panel> {
|
||||
use crate::glass::Panel;
|
||||
pub fn glass(ui: &App, scale: f32) -> Vec<sf_ui::render::Panel> {
|
||||
use sf_ui::render::Panel;
|
||||
use slint::Model;
|
||||
|
||||
let t = ui.get_set_t();
|
||||
@@ -1120,51 +1240,63 @@ pub fn glass(ui: &App, scale: f32) -> Vec<crate::glass::Panel> {
|
||||
tint,
|
||||
};
|
||||
let white = [1.0, 1.0, 1.0];
|
||||
let (sx, sy, sw, sh) = (ui.get_sp_x(), ui.get_sp_y(), ui.get_sp_w(), ui.get_sp_h());
|
||||
let mut out = vec![panel(sx, sy, sw, sh, 52.0 * u, 0.15 * t, t, 3.6, [0.79, 0.83, 0.88], [0.04, 0.043, 0.063, 0.40])];
|
||||
// The on-screen keyboard takes over the pane: categories and rows fade out.
|
||||
// The on-screen keyboard takes over the screen: categories and rows fade out.
|
||||
let content = t * (1.0 - ui.get_kb_t());
|
||||
let mut out = Vec::new();
|
||||
|
||||
// Category column: focus glides with nav-pos, the selected one stays lit.
|
||||
// Category column: no glass at rest. The selected category keeps a faint
|
||||
// pill while the rows are focused; the focused one is a white pill.
|
||||
let (nx, ny, nw, nh, nstep) = (ui.get_nav_x(), ui.get_nav_y(), ui.get_nav_w(), ui.get_nav_h(), ui.get_nav_step());
|
||||
let (nav_pos, nav_active) = (ui.get_nav_pos(), ui.get_nav_active());
|
||||
for i in 0..ui.get_set_nav_count() {
|
||||
let sel = (1.0 - (nav_pos - i as f32).abs()).max(0.0);
|
||||
let f = sel * nav_active;
|
||||
let amount = 0.10 * sel * (1.0 - nav_active) + 0.86 * f;
|
||||
if amount <= 0.002 {
|
||||
continue;
|
||||
}
|
||||
let s = 1.0 + 0.03 * f;
|
||||
let (w, h) = (nw * s, nh * s);
|
||||
let y = ny + i as f32 * nstep;
|
||||
out.push(panel(nx - (w - nw) / 2.0, y - (h - nh) / 2.0, w, h, 26.0 * u * s, f, content, -1.0, white, [1.0, 1.0, 1.0, 0.035 + 0.16 * sel + 0.66 * f]));
|
||||
out.push(panel(nx - (w - nw) / 2.0, y - (h - nh) / 2.0, w, h, h / 2.0, f, content, -1.0, white, [1.0, 1.0, 1.0, amount]));
|
||||
}
|
||||
// Back chip.
|
||||
out.push(panel(nx, sy + sh - 92.0 * u, 300.0 * u, 56.0 * u, 28.0 * u, 0.0, t, -1.0, white, [1.0, 1.0, 1.0, 0.03]));
|
||||
|
||||
// Rows, scrolled and faded at the edges of the list area.
|
||||
// One grouped platter behind the visible rows.
|
||||
let (rx, ry, rw) = (ui.get_rows_x(), ui.get_rows_y(), ui.get_rows_w());
|
||||
let (rh, rstep, view, scroll) = (ui.get_set_row_h(), ui.get_set_row_step(), ui.get_rows_view_h(), ui.get_rows_scroll());
|
||||
let rows = ui.get_set_rows();
|
||||
let n = rows.row_count();
|
||||
if n > 0 {
|
||||
let visible = (n as f32 * rstep).min(view);
|
||||
let pad = 8.0 * u;
|
||||
out.push(panel(rx, ry - pad, rw, visible + 2.0 * pad, 32.0 * u, 0.0, content, 2.2, white, [0.04, 0.045, 0.06, 0.30]));
|
||||
}
|
||||
|
||||
// Focus pill on the focused row (rows are inset by the platter padding).
|
||||
let inset = 8.0 * u;
|
||||
let (row_pos, active) = (ui.get_row_pos(), ui.get_content_active());
|
||||
for (j, row) in ui.get_set_rows().iter().enumerate() {
|
||||
for (j, row) in rows.iter().enumerate() {
|
||||
let top = ry + j as f32 * rstep - scroll;
|
||||
let over = (ry - top).max(top + rh - (ry + view)) / rh;
|
||||
let vis = (1.0 - over).clamp(0.0, 1.0);
|
||||
if vis <= 0.01 {
|
||||
let f = (1.0 - (row_pos - j as f32).abs()).max(0.0) * active;
|
||||
if vis <= 0.01 || f <= 0.002 {
|
||||
continue;
|
||||
}
|
||||
let f = (1.0 - (row_pos - j as f32).abs()).max(0.0) * active;
|
||||
let s = 1.0 + 0.02 * f;
|
||||
let (w, h) = (rw * s, rh * s);
|
||||
let (x0, w0) = (rx + inset, rw - 2.0 * inset);
|
||||
let s = 1.0 + 0.015 * f;
|
||||
let (w, h) = (w0 * s, rh * s);
|
||||
let (glow, tint) = if row.kind == "danger" {
|
||||
let red = [1.0, 0.27, 0.23];
|
||||
(red, [1.0, 0.27, 0.23, 0.10 + 0.72 * f])
|
||||
([1.0, 0.27, 0.23], [1.0, 0.27, 0.23, 0.86 * f])
|
||||
} else {
|
||||
(white, [1.0, 1.0, 1.0, 0.04 + 0.80 * f])
|
||||
(white, [1.0, 1.0, 1.0, 0.88 * f])
|
||||
};
|
||||
out.push(panel(rx - (w - rw) / 2.0, top - (h - rh) / 2.0, w, h, 24.0 * u * s, f, content * vis, -1.0, glow, tint));
|
||||
out.push(panel(x0 - (w - w0) / 2.0, top - (h - rh) / 2.0, w, h, 24.0 * u * s, f, content * vis, -1.0, glow, tint));
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Value and detail for the Updates row: "2 frissítés" / "SmartFox felület 0.2.0 · YouTube 1.1.0".
|
||||
/// Value and detail for the Updates row: "2 frissítés" / "Fennec OS felület 0.2.0 · YouTube 1.1.0".
|
||||
fn update_summary(u: &UpdateStatus) -> (String, String) {
|
||||
let checked = || {
|
||||
use chrono::TimeZone;
|
||||
|
||||
296
crates/sf-launcher/src/shelf.rs
Normal file
296
crates/sf-launcher/src/shelf.rs
Normal file
@@ -0,0 +1,296 @@
|
||||
//! Top Shelf content for Netflex on the home screen. Optional: the home screen
|
||||
//! is complete without it (the shelf then shows the app itself).
|
||||
//!
|
||||
//! Sources, first that answers wins:
|
||||
//! 1. the Netflex server's `/api/home` with `netflex_token` from settings.toml:
|
||||
//! continue watching, else the first catalog row. Artwork comes through the
|
||||
//! server's image cache (`/api/img`), like in the Netflex apps;
|
||||
//! 2. Cinemeta's public "popular movies" list (the catalog Netflex browses).
|
||||
//!
|
||||
//! The last good result is kept in `<data_dir>/cache/shelf/` and shown at
|
||||
//! start, so the shelf survives restarts without a network.
|
||||
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Cards the home screen shows.
|
||||
const MAX_ITEMS: usize = 4;
|
||||
const REFRESH: Duration = Duration::from_secs(15 * 60);
|
||||
const CINEMETA_TOP: &str = "https://v3-cinemeta.strem.io/catalog/movie/top.json";
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
pub struct Item {
|
||||
pub title: String,
|
||||
pub detail: String,
|
||||
/// Artwork file name inside the cache folder.
|
||||
pub image: Option<String>,
|
||||
/// 0..1 watched; 0 = no progress bar.
|
||||
pub progress: f32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
||||
pub struct Shelf {
|
||||
pub title: String,
|
||||
pub items: Vec<Item>,
|
||||
}
|
||||
|
||||
pub struct Source {
|
||||
/// Netflex server base URL ("https://netflex.example").
|
||||
pub server: Option<String>,
|
||||
pub token: Option<String>,
|
||||
/// `<data_dir>/cache/shelf`.
|
||||
pub dir: PathBuf,
|
||||
}
|
||||
|
||||
/// Loads the cached shelf, then refreshes it every 15 minutes on a background
|
||||
/// thread. `on_update` gets the shelf and the folder its images are in.
|
||||
pub fn spawn(source: Source, on_update: impl Fn(Shelf, PathBuf) + Send + 'static) {
|
||||
let spawned = std::thread::Builder::new().name("shelf".into()).spawn(move || {
|
||||
let cache = source.dir.join("shelf.json");
|
||||
if let Some(shelf) = std::fs::read_to_string(&cache).ok().and_then(|t| serde_json::from_str::<Shelf>(&t).ok()) {
|
||||
on_update(shelf, source.dir.clone());
|
||||
}
|
||||
let agent: ureq::Agent = ureq::Agent::config_builder()
|
||||
.timeout_global(Some(Duration::from_secs(20)))
|
||||
.user_agent(concat!("FennecOS-launcher/", env!("CARGO_PKG_VERSION")))
|
||||
.build()
|
||||
.into();
|
||||
loop {
|
||||
match fetch(&agent, &source) {
|
||||
Ok(shelf) if !shelf.items.is_empty() => {
|
||||
if let Err(e) = std::fs::write(&cache, serde_json::to_string(&shelf).unwrap_or_default()) {
|
||||
log::warn!("shelf cache: {e}");
|
||||
}
|
||||
prune(&source.dir, &shelf);
|
||||
on_update(shelf, source.dir.clone());
|
||||
}
|
||||
Ok(_) => log::info!("shelf: nothing to show"),
|
||||
Err(e) => log::info!("shelf: {e:#}"),
|
||||
}
|
||||
std::thread::sleep(REFRESH);
|
||||
}
|
||||
});
|
||||
if let Err(e) = spawned {
|
||||
log::warn!("shelf thread: {e}");
|
||||
}
|
||||
}
|
||||
|
||||
fn fetch(agent: &ureq::Agent, source: &Source) -> Result<Shelf> {
|
||||
std::fs::create_dir_all(&source.dir).with_context(|| format!("creating {}", source.dir.display()))?;
|
||||
if let (Some(server), Some(token)) = (&source.server, &source.token) {
|
||||
match netflex(agent, server.trim_end_matches('/'), token, &source.dir) {
|
||||
Ok(shelf) if !shelf.items.is_empty() => return Ok(shelf),
|
||||
Ok(_) => {}
|
||||
Err(e) => log::info!("shelf: Netflex: {e:#}"),
|
||||
}
|
||||
}
|
||||
cinemeta(agent, &source.dir)
|
||||
}
|
||||
|
||||
// ---- Netflex -----------------------------------------------------------------
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Title {
|
||||
id: String,
|
||||
title: String,
|
||||
backdrop: Option<String>,
|
||||
year_label: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Continue {
|
||||
title: Title,
|
||||
season: Option<u32>,
|
||||
episode: Option<u32>,
|
||||
position: Option<f64>,
|
||||
duration: Option<f64>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Row {
|
||||
title: String,
|
||||
items: Vec<Title>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Home {
|
||||
#[serde(default)]
|
||||
rows: Vec<Row>,
|
||||
#[serde(default)]
|
||||
continue_watching: Vec<Continue>,
|
||||
}
|
||||
|
||||
fn netflex(agent: &ureq::Agent, server: &str, token: &str, dir: &Path) -> Result<Shelf> {
|
||||
let auth = format!("Bearer {token}");
|
||||
let resp = agent.get(format!("{server}/api/home")).header("Authorization", &auth).call().context("/api/home")?;
|
||||
let home: Home = serde_json::from_str(&read_text(resp, 4 << 20)?).context("parsing /api/home")?;
|
||||
let image = |t: &Title| {
|
||||
let url = t.backdrop.as_deref()?;
|
||||
let req = agent.get(format!("{server}/api/img")).query("u", url).header("Authorization", &auth);
|
||||
download(req, dir, &t.id)
|
||||
};
|
||||
if !home.continue_watching.is_empty() {
|
||||
let items = home
|
||||
.continue_watching
|
||||
.iter()
|
||||
.take(MAX_ITEMS)
|
||||
.map(|c| {
|
||||
let (pos, dur) = (c.position.unwrap_or(0.0), c.duration.unwrap_or(0.0));
|
||||
let left = if dur > pos && pos > 0.0 { Some(((dur - pos) / 60.0).ceil() as u32) } else { None };
|
||||
let detail = match (c.season, c.episode, left) {
|
||||
(Some(s), Some(e), Some(m)) => format!("{s}. évad, {e}. rész · még {m} perc"),
|
||||
(Some(s), Some(e), None) => format!("{s}. évad, {e}. rész"),
|
||||
(_, _, Some(m)) => format!("Még {m} perc"),
|
||||
_ => c.title.year_label.clone().unwrap_or_default(),
|
||||
};
|
||||
let progress = if dur > 0.0 { (pos / dur).clamp(0.0, 1.0) as f32 } else { 0.0 };
|
||||
Item { title: c.title.title.clone(), detail, image: image(&c.title), progress }
|
||||
})
|
||||
.collect();
|
||||
return Ok(Shelf { title: "Folytatás".into(), items });
|
||||
}
|
||||
let Some(row) = home.rows.into_iter().find(|r| !r.items.is_empty()) else {
|
||||
return Ok(Shelf::default());
|
||||
};
|
||||
let items = row
|
||||
.items
|
||||
.iter()
|
||||
.take(MAX_ITEMS)
|
||||
.map(|t| Item { title: t.title.clone(), detail: t.year_label.clone().unwrap_or_default(), image: image(t), progress: 0.0 })
|
||||
.collect();
|
||||
Ok(Shelf { title: row.title, items })
|
||||
}
|
||||
|
||||
// ---- Cinemeta ------------------------------------------------------------------
|
||||
|
||||
#[derive(Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
struct Meta {
|
||||
id: String,
|
||||
name: String,
|
||||
background: Option<String>,
|
||||
release_info: Option<String>,
|
||||
imdb_rating: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct Catalog {
|
||||
metas: Vec<Meta>,
|
||||
}
|
||||
|
||||
fn cinemeta(agent: &ureq::Agent, dir: &Path) -> Result<Shelf> {
|
||||
let resp = agent.get(CINEMETA_TOP).call().context("Cinemeta")?;
|
||||
let catalog: Catalog = serde_json::from_str(&read_text(resp, 8 << 20)?).context("parsing Cinemeta")?;
|
||||
let items = catalog
|
||||
.metas
|
||||
.iter()
|
||||
.filter(|m| m.background.is_some())
|
||||
.take(MAX_ITEMS)
|
||||
.map(|m| {
|
||||
let rating = m.imdb_rating.as_ref().filter(|r| !r.trim().is_empty());
|
||||
let year = m.release_info.as_ref().filter(|y| !y.trim().is_empty());
|
||||
let detail = match (year, rating) {
|
||||
(Some(y), Some(r)) => format!("{y} · IMDb {r}"),
|
||||
(Some(y), None) => y.clone(),
|
||||
(None, Some(r)) => format!("IMDb {r}"),
|
||||
(None, None) => String::new(),
|
||||
};
|
||||
let image = m.background.as_deref().and_then(|url| download(agent.get(url), dir, &m.id));
|
||||
Item { title: m.name.clone(), detail, image, progress: 0.0 }
|
||||
})
|
||||
.collect();
|
||||
Ok(Shelf { title: "Népszerű filmek".into(), items })
|
||||
}
|
||||
|
||||
// ---- files ---------------------------------------------------------------------
|
||||
|
||||
fn read_text(resp: ureq::http::Response<ureq::Body>, limit: u64) -> Result<String> {
|
||||
let mut text = String::new();
|
||||
resp.into_body().into_reader().take(limit + 1).read_to_string(&mut text)?;
|
||||
if text.len() as u64 > limit {
|
||||
bail!("response is too large");
|
||||
}
|
||||
Ok(text)
|
||||
}
|
||||
|
||||
const IMAGE_EXTS: [&str; 3] = ["jpg", "png", "webp"];
|
||||
|
||||
/// Image type from the first bytes (the decoder picks it by extension).
|
||||
fn image_ext(bytes: &[u8]) -> Option<&'static str> {
|
||||
match bytes {
|
||||
[0xff, 0xd8, ..] => Some("jpg"),
|
||||
[0x89, b'P', b'N', b'G', ..] => Some("png"),
|
||||
[b'R', b'I', b'F', b'F', _, _, _, _, b'W', b'E', b'B', b'P', ..] => Some("webp"),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Saves the artwork as `<id>.<ext>`, reusing a file that is already there.
|
||||
fn download(req: ureq::RequestBuilder<ureq::typestate::WithoutBody>, dir: &Path, id: &str) -> Option<String> {
|
||||
let stem: String = id.chars().filter(|c| c.is_ascii_alphanumeric() || *c == '-' || *c == '_').collect();
|
||||
if stem.is_empty() {
|
||||
return None;
|
||||
}
|
||||
if let Some(name) = IMAGE_EXTS.iter().map(|ext| format!("{stem}.{ext}")).find(|n| dir.join(n).exists()) {
|
||||
return Some(name);
|
||||
}
|
||||
let result = (|| -> Result<String> {
|
||||
let resp = req.call()?;
|
||||
let mut bytes = Vec::new();
|
||||
resp.into_body().into_reader().take(8 << 20).read_to_end(&mut bytes)?;
|
||||
let ext = image_ext(&bytes).context("not a JPEG, PNG or WebP image")?;
|
||||
let name = format!("{stem}.{ext}");
|
||||
let tmp = dir.join(format!("{stem}.part"));
|
||||
std::fs::write(&tmp, &bytes)?;
|
||||
std::fs::rename(&tmp, dir.join(&name))?;
|
||||
Ok(name)
|
||||
})();
|
||||
match result {
|
||||
Ok(name) => Some(name),
|
||||
Err(e) => {
|
||||
log::info!("shelf: artwork for {id}: {e:#}");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes artwork the current shelf no longer uses.
|
||||
fn prune(dir: &Path, shelf: &Shelf) {
|
||||
let keep: Vec<&str> = shelf.items.iter().filter_map(|i| i.image.as_deref()).collect();
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return };
|
||||
for e in entries.flatten() {
|
||||
let name = e.file_name().to_string_lossy().to_string();
|
||||
let artwork = name.rsplit_once('.').is_some_and(|(_, ext)| IMAGE_EXTS.contains(&ext) || ext == "part");
|
||||
if artwork && !keep.contains(&name.as_str()) {
|
||||
let _ = std::fs::remove_file(e.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn sniffs_image_types() {
|
||||
assert_eq!(image_ext(&[0xff, 0xd8, 0xff, 0xe0]), Some("jpg"));
|
||||
assert_eq!(image_ext(b"\x89PNG\r\n"), Some("png"));
|
||||
assert_eq!(image_ext(b"RIFF\0\0\0\0WEBPVP8 "), Some("webp"));
|
||||
assert_eq!(image_ext(b"<html>"), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_netflex_home() {
|
||||
let json = r#"{"rows":[{"id":"popular-movie","title":"Népszerű filmek","items":[{"type":"movie","id":"tt1","tmdbId":null,"title":"A","originalTitle":null,"overview":null,"poster":null,"backdrop":"https://x/b.jpg","year":2024,"yearLabel":"2024","rating":7.1,"genres":[]}]}],
|
||||
"continueWatching":[{"title":{"type":"tv","id":"tt2","title":"B","backdrop":null,"yearLabel":"2021–"},"season":2,"episode":3,"position":600,"duration":2400,"updatedAt":"2026-10-01T10:00:00Z"}]}"#;
|
||||
let home: Home = serde_json::from_str(json).unwrap();
|
||||
assert_eq!(home.rows[0].items[0].year_label.as_deref(), Some("2024"));
|
||||
assert_eq!(home.continue_watching[0].season, Some(2));
|
||||
}
|
||||
}
|
||||
70
crates/sf-launcher/src/status.rs
Normal file
70
crates/sf-launcher/src/status.rs
Normal file
@@ -0,0 +1,70 @@
|
||||
//! Live TV state for the home screen: network, the Siri Remote's battery and
|
||||
//! the display mode. The probes shell out (ip, busctl, bluetoothctl,
|
||||
//! wlr-randr), so they run on a background thread.
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use crate::system;
|
||||
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
pub struct Status {
|
||||
/// "wired" | "wifi" | "none" (icon names in ui/icons.slint).
|
||||
pub net: &'static str,
|
||||
/// "Vezetékes hálózat", the Wi-Fi name, or "Nincs hálózat".
|
||||
pub net_label: String,
|
||||
pub remote_battery: Option<u8>,
|
||||
pub remote_connected: bool,
|
||||
/// "4K UHD · 60 Hz".
|
||||
pub display: Option<String>,
|
||||
}
|
||||
|
||||
pub fn probe() -> Status {
|
||||
let info = system::network();
|
||||
let (net, net_label) = match (&info.iface, info.wireless) {
|
||||
(None, _) => ("none", "Nincs hálózat".to_string()),
|
||||
(Some(_), false) => ("wired", "Vezetékes hálózat".to_string()),
|
||||
(Some(_), true) => {
|
||||
let name = system::wifi()
|
||||
.ok()
|
||||
.flatten()
|
||||
.and_then(|w| w.networks.into_iter().find(|n| n.connected).map(|n| n.name));
|
||||
("wifi", name.unwrap_or_else(|| "Wi-Fi".into()))
|
||||
}
|
||||
};
|
||||
let remote = system::bt_devices().ok().and_then(|d| d.into_iter().find(|d| d.remote));
|
||||
let display = system::display().ok().and_then(|d| {
|
||||
d.current_mode().map(|m| {
|
||||
let hz = m.hz.round() as u32;
|
||||
match m.name() {
|
||||
"" => format!("{} × {} · {hz} Hz", m.w, m.h),
|
||||
name => format!("{name} · {hz} Hz"),
|
||||
}
|
||||
})
|
||||
});
|
||||
Status {
|
||||
net,
|
||||
net_label,
|
||||
remote_battery: remote.as_ref().and_then(|r| r.battery),
|
||||
remote_connected: remote.as_ref().is_some_and(|r| r.connected),
|
||||
display,
|
||||
}
|
||||
}
|
||||
|
||||
/// Probes now and then every 20 s; `on_change` runs (on the probe thread)
|
||||
/// whenever something changed.
|
||||
pub fn spawn(on_change: impl Fn(Status) + Send + 'static) {
|
||||
let spawned = std::thread::Builder::new().name("status".into()).spawn(move || {
|
||||
let mut last: Option<Status> = None;
|
||||
loop {
|
||||
let now = probe();
|
||||
if last.as_ref() != Some(&now) {
|
||||
on_change(now.clone());
|
||||
last = Some(now);
|
||||
}
|
||||
std::thread::sleep(Duration::from_secs(20));
|
||||
}
|
||||
});
|
||||
if let Err(e) = spawned {
|
||||
log::warn!("status thread: {e}");
|
||||
}
|
||||
}
|
||||
609
crates/sf-launcher/src/store_screen.rs
Normal file
609
crates/sf-launcher/src/store_screen.rs
Normal file
@@ -0,0 +1,609 @@
|
||||
//! The App Store screen (docs/store.md). It reuses the settings pane: the
|
||||
//! same Slint view and glass, in "store" mode (`set-mode`), with its own
|
||||
//! categories and rows.
|
||||
//!
|
||||
//! The launcher runs as user tv and can't install anything: it writes what
|
||||
//! the user wants into store.toml and asks sf-update (root) to act on it
|
||||
//! (`store` request). It reads back what the sources offer from catalog.json
|
||||
//! and sf-update's progress from status.json.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::path::PathBuf;
|
||||
use std::rc::Rc;
|
||||
use std::time::Duration;
|
||||
|
||||
use sf_ipc::Permission;
|
||||
use sf_ipc::store::{CATALOG_FILE, Catalog, CatalogApp, SourceInfo, WANTED_FILE, Wanted, WantedApp, missing_permissions};
|
||||
use slint::{ComponentHandle, ModelRc, SharedString, VecModel};
|
||||
|
||||
use crate::system::{self, UpdateStatus};
|
||||
use crate::{App, SettingRow, keyboard};
|
||||
|
||||
// Categories, as in app.slint (set-categories in store mode): Felfedezés,
|
||||
// Telepítve, Források (anything else).
|
||||
const DISCOVER: i32 = 0;
|
||||
const INSTALLED: i32 = 1;
|
||||
|
||||
#[derive(Clone, PartialEq)]
|
||||
enum Action {
|
||||
None,
|
||||
App(String),
|
||||
Install(String),
|
||||
Approve(String),
|
||||
Uninstall(String),
|
||||
UninstallWithData(String),
|
||||
Source(String),
|
||||
AddSource,
|
||||
RemoveSource(String),
|
||||
Refresh,
|
||||
Back,
|
||||
}
|
||||
|
||||
#[derive(Clone, PartialEq)]
|
||||
enum Sub {
|
||||
None,
|
||||
App(String),
|
||||
Source(String),
|
||||
}
|
||||
|
||||
struct State {
|
||||
category: i32,
|
||||
sub: Sub,
|
||||
parent_row: i32,
|
||||
wanted: Wanted,
|
||||
catalog: Option<Catalog>,
|
||||
status: Option<UpdateStatus>,
|
||||
notice: String,
|
||||
actions: Vec<Action>,
|
||||
/// Ids of installed store apps last time we looked; a change reloads the
|
||||
/// launcher's app list once the store is closed.
|
||||
installed: Vec<String>,
|
||||
reload_pending: bool,
|
||||
}
|
||||
|
||||
pub struct Screen {
|
||||
ui: slint::Weak<App>,
|
||||
state: RefCell<State>,
|
||||
on_apps_changed: RefCell<Option<Box<dyn Fn()>>>,
|
||||
timer: slint::Timer,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static SCREEN: RefCell<Option<Rc<Screen>>> = const { RefCell::new(None) };
|
||||
/// Demo (Windows / SMARTFOX_DEMO_SYSTEM): store.toml and catalog in memory.
|
||||
static DEMO: RefCell<Option<(Wanted, Catalog)>> = const { RefCell::new(None) };
|
||||
}
|
||||
|
||||
pub fn current() -> Option<Rc<Screen>> {
|
||||
SCREEN.with(|s| s.borrow().clone())
|
||||
}
|
||||
|
||||
fn row(title: impl Into<SharedString>, value: impl Into<SharedString>, detail: impl Into<SharedString>, kind: &str) -> SettingRow {
|
||||
SettingRow { title: title.into(), value: value.into(), detail: detail.into(), kind: kind.into(), level: 0, lock: false }
|
||||
}
|
||||
|
||||
fn short(text: &str, max: usize) -> String {
|
||||
let line = text.lines().next().unwrap_or(text);
|
||||
if line.chars().count() > max { format!("{}…", line.chars().take(max).collect::<String>()) } else { line.to_string() }
|
||||
}
|
||||
|
||||
/// "github.com/fox/app" for display.
|
||||
fn pretty_source(url: &str) -> String {
|
||||
url.trim_start_matches("https://").to_string()
|
||||
}
|
||||
|
||||
fn permissions_text(perms: &[Permission]) -> String {
|
||||
if perms.is_empty() {
|
||||
return "Nem kér külön engedélyt".into();
|
||||
}
|
||||
perms.iter().map(|p| p.label()).collect::<Vec<_>>().join(", ")
|
||||
}
|
||||
|
||||
fn wanted_path() -> PathBuf {
|
||||
std::env::var_os("SMARTFOX_STORE_FILE").map(PathBuf::from).unwrap_or_else(|| WANTED_FILE.into())
|
||||
}
|
||||
|
||||
fn demo_catalog() -> Catalog {
|
||||
let app = |id: &str, name: &str, cat: &str, desc: &str, perms: Vec<Permission>| CatalogApp {
|
||||
id: id.into(),
|
||||
name: name.into(),
|
||||
version: "1.2.0".into(),
|
||||
kind: "exec".into(),
|
||||
category: cat.into(),
|
||||
description: desc.into(),
|
||||
author: "Példa Fejlesztő".into(),
|
||||
homepage: format!("https://github.com/example/{name}"),
|
||||
license: "MIT".into(),
|
||||
permissions: perms,
|
||||
source: format!("https://github.com/example/{}", name.to_lowercase()),
|
||||
catalog: Some("https://github.com/example/fennec-catalog".into()),
|
||||
..Default::default()
|
||||
};
|
||||
Catalog {
|
||||
updated_at: 1_792_800_000,
|
||||
sources: vec![SourceInfo {
|
||||
url: "https://github.com/example/fennec-catalog".into(),
|
||||
kind: "catalog".into(),
|
||||
name: "Példa katalógus".into(),
|
||||
apps: 3,
|
||||
error: None,
|
||||
}],
|
||||
apps: vec![
|
||||
app("io.github.example.retro", "RetroArch", "Játékok · Emulátor", "Régi konzolok játékai kontrollerrel.", vec![Permission::Gpu, Permission::Audio, Permission::Gamepad]),
|
||||
app("io.github.example.radio", "Rádió", "Zene", "Internetes rádióállomások.", vec![Permission::Network, Permission::Audio]),
|
||||
app("io.github.example.clock", "Óra", "Eszköz", "Nagy óra és időjárás a TV-n.", vec![Permission::Network]),
|
||||
],
|
||||
}
|
||||
}
|
||||
|
||||
fn load_wanted() -> Wanted {
|
||||
if system::demo() {
|
||||
return DEMO.with(|d| d.borrow().as_ref().map(|(w, _)| w.clone())).unwrap_or_default();
|
||||
}
|
||||
Wanted::load(&wanted_path()).unwrap_or_else(|e| {
|
||||
log::warn!("store: {e:#}");
|
||||
Wanted::default()
|
||||
})
|
||||
}
|
||||
|
||||
fn load_catalog() -> Option<Catalog> {
|
||||
if system::demo() {
|
||||
return DEMO.with(|d| {
|
||||
let mut d = d.borrow_mut();
|
||||
let (_, c) = d.get_or_insert_with(|| (Wanted::default(), demo_catalog()));
|
||||
Some(c.clone())
|
||||
});
|
||||
}
|
||||
Catalog::load(std::path::Path::new(CATALOG_FILE))
|
||||
}
|
||||
|
||||
impl Screen {
|
||||
pub fn install(ui: &App) -> Rc<Screen> {
|
||||
let screen = Rc::new(Screen {
|
||||
ui: ui.as_weak(),
|
||||
state: RefCell::new(State {
|
||||
category: 0,
|
||||
sub: Sub::None,
|
||||
parent_row: 0,
|
||||
wanted: Wanted::default(),
|
||||
catalog: None,
|
||||
status: None,
|
||||
notice: String::new(),
|
||||
actions: Vec::new(),
|
||||
installed: Vec::new(),
|
||||
reload_pending: false,
|
||||
}),
|
||||
on_apps_changed: RefCell::new(None),
|
||||
timer: slint::Timer::default(),
|
||||
});
|
||||
SCREEN.with(|s| *s.borrow_mut() = Some(screen.clone()));
|
||||
screen.state.borrow_mut().installed = installed_ids();
|
||||
|
||||
// While open: follow sf-update's progress and the catalog. Once closed
|
||||
// after apps were installed or removed: reload the app list.
|
||||
let weak = Rc::downgrade(&screen);
|
||||
screen.timer.start(slint::TimerMode::Repeated, Duration::from_secs(2), move || {
|
||||
let Some(s) = weak.upgrade() else { return };
|
||||
if s.is_open() {
|
||||
s.reload();
|
||||
} else if std::mem::take(&mut s.state.borrow_mut().reload_pending) {
|
||||
if let Some(f) = s.on_apps_changed.borrow().as_ref() {
|
||||
f();
|
||||
}
|
||||
}
|
||||
});
|
||||
screen
|
||||
}
|
||||
|
||||
/// Called after the store is closed if store apps were installed or removed.
|
||||
pub fn on_apps_changed(&self, f: impl Fn() + 'static) {
|
||||
*self.on_apps_changed.borrow_mut() = Some(Box::new(f));
|
||||
}
|
||||
|
||||
fn is_open(&self) -> bool {
|
||||
self.ui.upgrade().is_some_and(|ui| ui.get_settings_open() && ui.get_set_mode() == "store")
|
||||
}
|
||||
|
||||
pub fn opened(&self) {
|
||||
{
|
||||
let mut st = self.state.borrow_mut();
|
||||
st.notice.clear();
|
||||
st.sub = Sub::None;
|
||||
st.category = 0;
|
||||
}
|
||||
self.reload();
|
||||
self.rebuild(Some(0));
|
||||
}
|
||||
|
||||
pub fn nav_changed(&self, i: i32) {
|
||||
{
|
||||
let mut st = self.state.borrow_mut();
|
||||
st.category = i;
|
||||
st.sub = Sub::None;
|
||||
st.notice.clear();
|
||||
}
|
||||
self.rebuild(Some(0));
|
||||
}
|
||||
|
||||
pub fn activate(&self, index: i32) {
|
||||
let action = self.state.borrow().actions.get(index as usize).cloned().unwrap_or(Action::None);
|
||||
if !matches!(action, Action::None) && self.state.borrow().sub == Sub::None {
|
||||
self.state.borrow_mut().parent_row = index;
|
||||
}
|
||||
self.run(action);
|
||||
}
|
||||
|
||||
pub fn back(&self) {
|
||||
self.run(Action::Back);
|
||||
}
|
||||
|
||||
/// Re-reads store.toml, catalog.json and status.json.
|
||||
fn reload(&self) {
|
||||
let wanted = load_wanted();
|
||||
let catalog = load_catalog();
|
||||
let status = system::update_status();
|
||||
{
|
||||
let mut st = self.state.borrow_mut();
|
||||
st.wanted = wanted;
|
||||
st.catalog = catalog;
|
||||
st.status = status;
|
||||
}
|
||||
let now = installed_ids();
|
||||
let changed = {
|
||||
let mut st = self.state.borrow_mut();
|
||||
let changed = st.installed != now;
|
||||
st.installed = now;
|
||||
changed
|
||||
};
|
||||
if changed {
|
||||
self.state.borrow_mut().reload_pending = true;
|
||||
}
|
||||
if self.is_open() {
|
||||
self.rebuild(None);
|
||||
}
|
||||
}
|
||||
|
||||
fn busy(&self) -> bool {
|
||||
self.state.borrow().status.as_ref().is_some_and(UpdateStatus::busy)
|
||||
}
|
||||
|
||||
/// Saves store.toml and asks sf-update to act on it.
|
||||
fn save(&self, notice: &str, f: impl FnOnce(&mut Wanted)) {
|
||||
let mut wanted = load_wanted();
|
||||
f(&mut wanted);
|
||||
let result = if system::demo() {
|
||||
DEMO.with(|d| {
|
||||
let mut d = d.borrow_mut();
|
||||
let (w, c) = d.get_or_insert_with(|| (Wanted::default(), demo_catalog()));
|
||||
*w = wanted.clone();
|
||||
for app in &mut c.apps {
|
||||
app.installed = w.apps.contains_key(&app.id).then(|| app.version.clone());
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
} else {
|
||||
wanted.save(&wanted_path()).and_then(|()| system::request_update("store"))
|
||||
};
|
||||
self.state.borrow_mut().notice = match result {
|
||||
Ok(()) => notice.to_string(),
|
||||
Err(e) => {
|
||||
log::warn!("store: {e:#}");
|
||||
format!("Nem sikerült: {}", short(&format!("{e:#}"), 60))
|
||||
}
|
||||
};
|
||||
self.reload();
|
||||
}
|
||||
|
||||
fn app(&self, id: &str) -> Option<CatalogApp> {
|
||||
self.state.borrow().catalog.as_ref().and_then(|c| c.app(id).cloned())
|
||||
}
|
||||
|
||||
fn enter(&self, sub: Sub) {
|
||||
self.state.borrow_mut().sub = sub;
|
||||
self.rebuild(Some(0));
|
||||
}
|
||||
|
||||
fn leave(&self) {
|
||||
let parent = {
|
||||
let mut st = self.state.borrow_mut();
|
||||
st.sub = Sub::None;
|
||||
st.parent_row
|
||||
};
|
||||
self.rebuild(Some(parent));
|
||||
}
|
||||
|
||||
fn run(&self, action: Action) {
|
||||
let with_data = matches!(action, Action::UninstallWithData(_));
|
||||
match action {
|
||||
Action::None => {}
|
||||
Action::Back => {
|
||||
if self.state.borrow().sub != Sub::None {
|
||||
self.leave();
|
||||
}
|
||||
}
|
||||
Action::App(id) => self.enter(Sub::App(id)),
|
||||
Action::Source(url) => self.enter(Sub::Source(url)),
|
||||
Action::Install(id) | Action::Approve(id) => {
|
||||
let Some(app) = self.app(&id) else { return };
|
||||
if self.busy() {
|
||||
return;
|
||||
}
|
||||
let notice = format!("{} telepítése…", app.name);
|
||||
self.save(¬ice, |w| {
|
||||
w.apps.insert(app.id.clone(), WantedApp { source: app.source.clone(), permissions: app.permissions.clone() });
|
||||
});
|
||||
}
|
||||
Action::Uninstall(id) | Action::UninstallWithData(id) => {
|
||||
let name = self.app(&id).map(|a| a.name).unwrap_or_else(|| id.clone());
|
||||
self.save(&format!("{name} eltávolítva."), |w| {
|
||||
w.apps.remove(&id);
|
||||
});
|
||||
if with_data && sf_ipc::manifest::is_store_id(&id) {
|
||||
let dir = sf_ipc::paths::app_data_dir(&id);
|
||||
if dir.is_dir() {
|
||||
if let Err(e) = std::fs::remove_dir_all(&dir) {
|
||||
log::warn!("removing {}: {e}", dir.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
self.leave();
|
||||
}
|
||||
Action::RemoveSource(url) => {
|
||||
self.save("Forrás eltávolítva. Az innen telepített appok megmaradnak.", |w| {
|
||||
w.sources.retain(|s| sf_ipc_canonical(s) != url);
|
||||
});
|
||||
self.leave();
|
||||
}
|
||||
Action::Refresh => {
|
||||
if self.busy() {
|
||||
return;
|
||||
}
|
||||
self.save("Források frissítése…", |_| {});
|
||||
}
|
||||
Action::AddSource => self.ask_source(None),
|
||||
}
|
||||
}
|
||||
|
||||
/// On-screen keyboard for a repo address.
|
||||
fn ask_source(&self, error: Option<String>) {
|
||||
let Some(ui) = self.ui.upgrade() else { return };
|
||||
keyboard::open(
|
||||
&ui,
|
||||
keyboard::Request {
|
||||
title: "Forrás hozzáadása".into(),
|
||||
subtitle: "Egy app vagy egy katalógus repója GitHubon, Giteán vagy GitLabon, pl. github.com/valaki/app".into(),
|
||||
placeholder: "github.com/felhasználó/repó".into(),
|
||||
secret: false,
|
||||
submit_label: "Hozzáadás".into(),
|
||||
min_len: 5,
|
||||
max_len: 200,
|
||||
error,
|
||||
on_submit: Box::new(|text| {
|
||||
if let Some(s) = current() {
|
||||
s.add_source(text);
|
||||
}
|
||||
}),
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
fn add_source(&self, text: String) {
|
||||
let url = sf_ipc_canonical(&text);
|
||||
if !looks_like_repo(&url) {
|
||||
self.ask_source(Some("Ez nem egy repó címe (host/tulajdonos/repó).".into()));
|
||||
return;
|
||||
}
|
||||
if load_wanted().sources.iter().any(|s| sf_ipc_canonical(s) == url) {
|
||||
self.state.borrow_mut().notice = "Ez a forrás már szerepel.".into();
|
||||
self.rebuild(None);
|
||||
return;
|
||||
}
|
||||
// Kept as typed: a gitlab:/gitea: prefix tells sf-update the forge of a self-hosted server.
|
||||
let typed = text.trim().trim_end_matches('/').to_string();
|
||||
self.save(&format!("{} hozzáadva, az appjai hamarosan megjelennek.", pretty_source(&url)), |w| w.sources.push(typed));
|
||||
}
|
||||
|
||||
fn rebuild(&self, row: Option<i32>) {
|
||||
let Some(ui) = self.ui.upgrade() else { return };
|
||||
let (title, subtitle, rows, actions) = self.page();
|
||||
let len = rows.len() as i32;
|
||||
let in_sub = self.state.borrow().sub != Sub::None;
|
||||
let focused = self.state.borrow().actions.get(ui.get_set_row().max(0) as usize).cloned();
|
||||
let same_item = match (row, focused) {
|
||||
(None, Some(a)) if a != Action::None => actions.iter().position(|b| *b == a).map(|i| i as i32),
|
||||
_ => None,
|
||||
};
|
||||
self.state.borrow_mut().actions = actions;
|
||||
ui.set_set_title(title.into());
|
||||
ui.set_set_subtitle(subtitle.into());
|
||||
ui.set_set_rows(ModelRc::new(VecModel::from(rows)));
|
||||
ui.set_set_sub(in_sub);
|
||||
let target = row.or(same_item).unwrap_or_else(|| ui.get_set_row());
|
||||
ui.set_set_row(target.clamp(0, (len - 1).max(0)));
|
||||
}
|
||||
|
||||
fn page(&self) -> (String, String, Vec<SettingRow>, Vec<Action>) {
|
||||
let st = self.state.borrow();
|
||||
let mut rows = Vec::new();
|
||||
let mut actions = Vec::new();
|
||||
let mut push = |r: SettingRow, a: Action| {
|
||||
rows.push(r);
|
||||
actions.push(a);
|
||||
};
|
||||
let busy = st.status.as_ref().is_some_and(UpdateStatus::busy);
|
||||
let progress = st.status.as_ref().filter(|s| s.busy()).map(|s| match s.state.as_str() {
|
||||
"checking" => "Források lekérdezése…".to_string(),
|
||||
"downloading" => format!("Letöltés: {}", s.message),
|
||||
_ => "Telepítés…".to_string(),
|
||||
});
|
||||
let error = st.status.as_ref().filter(|s| s.state == "error").map(|s| format!("Hiba: {}", short(&s.message, 70)));
|
||||
let notice_or = |text: &str| progress.clone().or_else(|| (!st.notice.is_empty()).then(|| st.notice.clone())).or(error.clone()).unwrap_or_else(|| text.to_string());
|
||||
let catalog = st.catalog.clone().unwrap_or_default();
|
||||
|
||||
let (title, subtitle) = match (&st.sub, st.category) {
|
||||
(Sub::App(id), _) => match catalog.app(id) {
|
||||
None => {
|
||||
push(row("Vissza", "", "", "action"), Action::Back);
|
||||
(id.clone(), "Ez az app már nem érhető el a forrásaidban.".to_string())
|
||||
}
|
||||
Some(app) => {
|
||||
let want = st.wanted.apps.get(&app.id);
|
||||
let missing = want.map(|w| missing_permissions(&app.permissions, &w.permissions)).unwrap_or_default();
|
||||
match (&app.installed, want) {
|
||||
(None, None) => push(row(if busy { "Folyamatban…" } else { "Telepítés" }, "", "Az engedélyeket lent látod", "action"), Action::Install(app.id.clone())),
|
||||
(None, Some(_)) => push(row("Telepítés folyamatban…", "", "", "info"), Action::None),
|
||||
(Some(_), _) if !missing.is_empty() => push(
|
||||
row("Frissítés jóváhagyása", "", format!("Új engedélyt kér: {}", permissions_text(&missing)), "action"),
|
||||
Action::Approve(app.id.clone()),
|
||||
),
|
||||
_ => {}
|
||||
}
|
||||
let version = match &app.installed {
|
||||
Some(i) if i != &app.version => format!("{i} → {}", app.version),
|
||||
Some(i) => i.clone(),
|
||||
None => app.version.clone(),
|
||||
};
|
||||
push(row("Verzió", version, "", "info"), Action::None);
|
||||
for p in &app.permissions {
|
||||
let value = if p.risky() { "Kockázatos" } else { "" };
|
||||
push(row(p.label(), value, "Engedély", "info"), Action::None);
|
||||
}
|
||||
if app.permissions.is_empty() {
|
||||
push(row("Engedélyek", "Nem kér", "Csak a saját fájljait és a képernyőt éri el", "info"), Action::None);
|
||||
}
|
||||
if !app.author.is_empty() {
|
||||
push(row("Szerző", app.author.clone(), "", "info"), Action::None);
|
||||
}
|
||||
push(row("Forrás", pretty_source(&app.source), app.license.clone(), "info"), Action::None);
|
||||
if want.is_some() || app.installed.is_some() {
|
||||
push(row("Eltávolítás", "", "Az adatai megmaradnak", "danger"), Action::Uninstall(app.id.clone()));
|
||||
push(row("Eltávolítás az adataival együtt", "", "", "danger"), Action::UninstallWithData(app.id.clone()));
|
||||
}
|
||||
push(row("Vissza", "", "", "action"), Action::Back);
|
||||
let what = if app.category.is_empty() { String::new() } else { format!("{} · ", app.category) };
|
||||
(app.name.clone(), notice_or(&format!("{what}{}", app.description)))
|
||||
}
|
||||
},
|
||||
(Sub::Source(url), _) => {
|
||||
let info = catalog.sources.iter().find(|s| &s.url == url).cloned();
|
||||
push(row("Forrás eltávolítása", "", "Az innen telepített appok megmaradnak", "danger"), Action::RemoveSource(url.clone()));
|
||||
push(row("Vissza", "", "", "action"), Action::Back);
|
||||
let detail = match info {
|
||||
Some(i) if i.error.is_some() => format!("Hiba: {}", short(i.error.as_deref().unwrap_or(""), 80)),
|
||||
Some(i) if i.kind == "catalog" => format!("Katalógus · {} app", i.apps),
|
||||
Some(_) => "App-repó".to_string(),
|
||||
None => "Még nincs lekérdezve.".to_string(),
|
||||
};
|
||||
(pretty_source(url), detail)
|
||||
}
|
||||
(Sub::None, DISCOVER) => {
|
||||
let offer: Vec<&CatalogApp> = catalog.apps.iter().filter(|a| a.installed.is_none() && !st.wanted.apps.contains_key(&a.id)).collect();
|
||||
if st.wanted.sources.is_empty() && catalog.apps.is_empty() {
|
||||
push(row("Forrás hozzáadása", "", "GitHub, Gitea vagy GitLab repó", "action"), Action::AddSource);
|
||||
} else if offer.is_empty() {
|
||||
push(row("Nincs több telepíthető app", "", "Adj hozzá forrást a Források alatt", "info"), Action::None);
|
||||
}
|
||||
for a in offer {
|
||||
let detail = if a.category.is_empty() { pretty_source(&a.source) } else { a.category.clone() };
|
||||
push(row(a.name.clone(), a.version.clone(), detail, "choice"), Action::App(a.id.clone()));
|
||||
}
|
||||
("Felfedezés".to_string(), notice_or("Nyílt forrású appok a forrásaidból. Mindegyik a saját sandboxában fut."))
|
||||
}
|
||||
(Sub::None, INSTALLED) => {
|
||||
if st.wanted.apps.is_empty() {
|
||||
push(row("Még nincs telepített app", "", "", "info"), Action::None);
|
||||
}
|
||||
for (id, want) in &st.wanted.apps {
|
||||
let app = catalog.app(id);
|
||||
let name = app.map(|a| a.name.clone()).unwrap_or_else(|| id.clone());
|
||||
let (value, detail) = match app {
|
||||
None => ("…".to_string(), pretty_source(&want.source)),
|
||||
Some(a) if a.installed.is_none() => ("Telepítés…".to_string(), a.version.clone()),
|
||||
Some(a) if a.blocked.as_deref() == Some("permissions") => (a.installed.clone().unwrap_or_default(), "Új engedélyt kér · jóváhagyás".to_string()),
|
||||
Some(a) if a.installed.as_deref() != Some(a.version.as_str()) => {
|
||||
(format!("{} → {}", a.installed.clone().unwrap_or_default(), a.version), "Frissítés letöltés alatt".to_string())
|
||||
}
|
||||
Some(a) => (a.version.clone(), if a.category.is_empty() { pretty_source(&a.source) } else { a.category.clone() }),
|
||||
};
|
||||
push(row(name, value, detail, "choice"), Action::App(id.clone()));
|
||||
}
|
||||
("Telepítve".to_string(), notice_or("A store appok a többi csomaggal együtt frissülnek (Beállítások → Rendszer → Frissítések)."))
|
||||
}
|
||||
(Sub::None, _) => {
|
||||
push(row("Forrás hozzáadása", "", "GitHub, Gitea vagy GitLab repó", "action"), Action::AddSource);
|
||||
for url in &st.wanted.sources {
|
||||
let url = sf_ipc_canonical(url);
|
||||
let info = catalog.sources.iter().find(|s| s.url == url);
|
||||
let (value, detail) = match info {
|
||||
None => ("…".to_string(), "Lekérdezés…".to_string()),
|
||||
Some(i) if i.error.is_some() => ("Hiba".to_string(), short(i.error.as_deref().unwrap_or(""), 60)),
|
||||
Some(i) if i.kind == "catalog" => (format!("{} app", i.apps), if i.name.is_empty() { "Katalógus".into() } else { i.name.clone() }),
|
||||
Some(i) => ("App".to_string(), i.name.clone()),
|
||||
};
|
||||
push(row(pretty_source(&url), value, detail, "choice"), Action::Source(url.clone()));
|
||||
}
|
||||
let checked = if catalog.updated_at > 0 {
|
||||
use chrono::TimeZone;
|
||||
chrono::Local.timestamp_opt(catalog.updated_at as i64, 0).single().map(|t| t.format("Lekérdezve: %m. %d. %H:%M").to_string()).unwrap_or_default()
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
push(row(if busy { "Folyamatban…" } else { "Frissítés most" }, "", checked, "action"), Action::Refresh);
|
||||
("Források".to_string(), notice_or("Minden app a saját repójában él. Egy katalógus-repó sok appot hoz egyszerre."))
|
||||
}
|
||||
};
|
||||
drop(push);
|
||||
(title, subtitle, rows, actions)
|
||||
}
|
||||
}
|
||||
|
||||
/// Ids of the installed store apps (folders under the store apps dir).
|
||||
fn installed_ids() -> Vec<String> {
|
||||
if system::demo() {
|
||||
return DEMO.with(|d| d.borrow().as_ref().map(|(w, _)| w.apps.keys().cloned().collect()).unwrap_or_default());
|
||||
}
|
||||
let mut ids: Vec<String> = std::fs::read_dir(sf_ipc::paths::STORE_APPS)
|
||||
.map(|d| d.flatten().filter(|e| e.path().join("app.toml").exists()).filter_map(|e| e.file_name().into_string().ok()).collect())
|
||||
.unwrap_or_default();
|
||||
ids.sort();
|
||||
ids
|
||||
}
|
||||
|
||||
/// `https://host/owner/repo` from what was typed: the same form sf-update
|
||||
/// uses in catalog.json (forge::Repo::url), so sources can be matched up.
|
||||
fn sf_ipc_canonical(input: &str) -> String {
|
||||
let s = input.trim();
|
||||
let (prefix, rest) = match s.split_once(':') {
|
||||
Some((p @ ("github" | "gitea" | "forgejo" | "gitlab"), r)) => (Some(p), r),
|
||||
_ => (None, s),
|
||||
};
|
||||
let rest = rest.trim_start_matches('/').trim_start_matches("https://").split(['?', '#']).next().unwrap_or("").trim_end_matches('/');
|
||||
let rest = rest.strip_suffix(".git").unwrap_or(rest);
|
||||
let (host, path) = rest.split_once('/').unwrap_or((rest, ""));
|
||||
match prefix {
|
||||
Some("github") if !host.contains('.') => format!("https://github.com/{rest}"),
|
||||
_ => format!("https://{}/{path}", host.to_ascii_lowercase()),
|
||||
}
|
||||
}
|
||||
|
||||
fn looks_like_repo(url: &str) -> bool {
|
||||
let rest = url.trim_start_matches("https://");
|
||||
let parts: Vec<&str> = rest.split('/').collect();
|
||||
parts.len() >= 3 && parts[0].contains('.') && parts.iter().all(|p| !p.is_empty() && !p.contains(' '))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn source_addresses() {
|
||||
assert_eq!(sf_ipc_canonical("github.com/fox/app.git"), "https://github.com/fox/app");
|
||||
assert_eq!(sf_ipc_canonical("github:fox/app"), "https://github.com/fox/app");
|
||||
assert_eq!(sf_ipc_canonical("gitlab:Git.x.org/a/b/"), "https://git.x.org/a/b");
|
||||
assert!(looks_like_repo("https://github.com/fox/app"));
|
||||
assert!(looks_like_repo(&sf_ipc_canonical("gitlab:git.x.org/a/b")));
|
||||
assert!(!looks_like_repo("https://github.com/fox"));
|
||||
assert!(!looks_like_repo("https://hello"));
|
||||
}
|
||||
}
|
||||
@@ -439,6 +439,142 @@ pub fn bt_remove(addr: &str) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// ---- audio ---------------------------------------------------------------
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AudioOutput {
|
||||
pub name: String,
|
||||
pub label: String,
|
||||
pub bluetooth: bool,
|
||||
pub selected: bool,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct BtAudioDevice {
|
||||
pub address: String,
|
||||
pub name: String,
|
||||
pub paired: bool,
|
||||
pub connected: bool,
|
||||
}
|
||||
|
||||
static DEMO_AUDIO: Mutex<Option<String>> = Mutex::new(None);
|
||||
|
||||
pub fn audio_outputs() -> Result<Vec<AudioOutput>> {
|
||||
if demo() {
|
||||
let selected = DEMO_AUDIO.lock().unwrap().clone().unwrap_or_else(|| "hdmi".into());
|
||||
return Ok(vec![
|
||||
AudioOutput { name: "hdmi".into(), label: "TV · HDMI".into(), bluetooth: false, selected: selected == "hdmi" },
|
||||
AudioOutput { name: "airpods".into(), label: "AirPods Pro".into(), bluetooth: true, selected: selected == "airpods" },
|
||||
]);
|
||||
}
|
||||
let t = Duration::from_secs(4);
|
||||
let default = run("pactl", &["get-default-sink"], t)?.trim().to_string();
|
||||
let json = run("pactl", &["--format=json", "list", "sinks"], t)?;
|
||||
let sinks: serde_json::Value = serde_json::from_str(&json).context("parsing audio outputs")?;
|
||||
let sinks = sinks.as_array().context("audio outputs are not a list")?;
|
||||
let mut outputs = Vec::new();
|
||||
for sink in sinks {
|
||||
let Some(name) = sink.get("name").and_then(|v| v.as_str()) else { continue };
|
||||
if name == "auto_null" { continue; }
|
||||
let label = sink.get("description").and_then(|v| v.as_str()).unwrap_or(name).to_string();
|
||||
let bluetooth = name.starts_with("bluez_output.");
|
||||
outputs.push(AudioOutput { name: name.into(), label, bluetooth, selected: name == default });
|
||||
}
|
||||
outputs.sort_by_key(|o| (!o.selected, o.bluetooth, o.label.to_lowercase()));
|
||||
Ok(outputs)
|
||||
}
|
||||
|
||||
pub fn set_audio_output(name: &str) -> Result<()> {
|
||||
if demo() {
|
||||
*DEMO_AUDIO.lock().unwrap() = Some(name.into());
|
||||
return Ok(());
|
||||
}
|
||||
// Only accept a sink currently reported by PipeWire.
|
||||
if !audio_outputs()?.iter().any(|o| o.name == name) {
|
||||
bail!("A hangkimenet már nem érhető el");
|
||||
}
|
||||
run("pactl", &["set-default-sink", name], Duration::from_secs(4))?;
|
||||
// Move streams that were already playing when the output changed.
|
||||
if let Ok(streams) = run("pactl", &["list", "short", "sink-inputs"], Duration::from_secs(4)) {
|
||||
for line in streams.lines() {
|
||||
if let Some(index) = line.split_whitespace().next().filter(|s| s.parse::<u32>().is_ok()) {
|
||||
if let Err(e) = run("pactl", &["move-sink-input", index, name], Duration::from_secs(4)) {
|
||||
log::warn!("moving audio stream {index}: {e:#}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn audio_device_info(addr: &str, fallback: &str, info: &str) -> Option<BtAudioDevice> {
|
||||
let device = parse_info(addr, fallback, info);
|
||||
let audio = ["audio-headphones", "audio-headset", "audio-card", "audio-speakers"]
|
||||
.contains(&device.icon.as_str())
|
||||
|| info.lines().any(|line| line.contains("Audio Sink") || line.contains("0000110b"));
|
||||
(audio && !device.remote).then(|| BtAudioDevice {
|
||||
address: addr.into(), name: device.name,
|
||||
paired: info.lines().any(|line| line.trim() == "Paired: yes"),
|
||||
connected: device.connected,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn bt_audio_devices() -> Result<Vec<BtAudioDevice>> {
|
||||
if demo() {
|
||||
return Ok(vec![BtAudioDevice { address: "4C:87:5D:0E:22:9B".into(), name: "AirPods Pro".into(), paired: true, connected: false }]);
|
||||
}
|
||||
let t = Duration::from_secs(4);
|
||||
let list = run("bluetoothctl", &["devices"], t)?;
|
||||
let mut devices = Vec::new();
|
||||
for (addr, name) in parse_device_list(&list) {
|
||||
let info = run("bluetoothctl", &["info", &addr], t).unwrap_or_default();
|
||||
if let Some(device) = audio_device_info(&addr, &name, &info) {
|
||||
devices.push(device);
|
||||
}
|
||||
}
|
||||
devices.sort_by_key(|d| (!d.connected, !d.paired, d.name.to_lowercase()));
|
||||
Ok(devices)
|
||||
}
|
||||
|
||||
pub fn bt_audio_scan() -> Result<Vec<BtAudioDevice>> {
|
||||
if !demo() {
|
||||
// Keep scanning long enough for headphones in pairing mode to appear.
|
||||
let result = run("bluetoothctl", &["--timeout", "8", "scan", "on"], Duration::from_secs(10))?;
|
||||
if result.contains("Failed") || result.contains("No default controller") {
|
||||
bail!("{}", result.trim());
|
||||
}
|
||||
}
|
||||
bt_audio_devices()
|
||||
}
|
||||
|
||||
pub fn bt_audio_connect(addr: &str) -> Result<()> {
|
||||
if demo() {
|
||||
*DEMO_AUDIO.lock().unwrap() = Some("airpods".into());
|
||||
return Ok(());
|
||||
}
|
||||
if !is_mac(addr) { bail!("Érvénytelen Bluetooth cím"); }
|
||||
let t = Duration::from_secs(25);
|
||||
let info = run("bluetoothctl", &["info", addr], Duration::from_secs(4))?;
|
||||
if !info.lines().any(|line| line.trim() == "Paired: yes") {
|
||||
let result = run("bluetoothctl", &["pair", addr], t)?;
|
||||
if result.contains("Failed") { bail!("{}", result.trim()); }
|
||||
}
|
||||
let trust = run("bluetoothctl", &["trust", addr], Duration::from_secs(5))?;
|
||||
if trust.contains("Failed") { bail!("{}", trust.trim()); }
|
||||
let result = run("bluetoothctl", &["connect", addr], t)?;
|
||||
if result.contains("Failed") && !result.contains("AlreadyConnected") { bail!("{}", result.trim()); }
|
||||
let sink_prefix = format!("bluez_output.{}", addr.replace(':', "_")).to_ascii_uppercase();
|
||||
for _ in 0..20 {
|
||||
if let Ok(outputs) = audio_outputs() {
|
||||
if let Some(output) = outputs.iter().find(|o| o.name.to_ascii_uppercase().starts_with(&sink_prefix)) {
|
||||
return set_audio_output(&output.name);
|
||||
}
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(500));
|
||||
}
|
||||
bail!("A Bluetooth eszköz csatlakozott, de még nem jelent meg hangkimenetként")
|
||||
}
|
||||
|
||||
// ---- network & device info -------------------------------------------------
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
@@ -877,7 +1013,7 @@ pub struct UpdateStatus {
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct UpdatePackage {
|
||||
/// Display name ("SmartFox felület", "YouTube").
|
||||
/// Display name ("Fennec OS felület", "YouTube").
|
||||
pub title: String,
|
||||
pub installed: String,
|
||||
pub available: Option<String>,
|
||||
@@ -906,14 +1042,14 @@ impl UpdateStatus {
|
||||
}
|
||||
}
|
||||
|
||||
/// "sf-shell" -> "SmartFox felület", "sf-app-youtube" -> the app's name.
|
||||
/// "sf-shell" -> "Fennec OS felület", "sf-app-youtube" -> the app's name.
|
||||
fn package_title(name: &str) -> String {
|
||||
if name == "sf-shell" {
|
||||
return "SmartFox felület".into();
|
||||
return "Fennec OS felület".into();
|
||||
}
|
||||
let id = name.strip_prefix("sf-app-").unwrap_or(name);
|
||||
let id = name.strip_prefix("sf-app-").or_else(|| name.strip_prefix(sf_ipc::store::PACKAGE_PREFIX)).unwrap_or(name);
|
||||
let dirs = [PathBuf::from("/usr/share/smartfox/apps"), PathBuf::from("/var/lib/sf-pkg/apps")];
|
||||
sf_ipc::manifest::load_apps_from(&dirs)
|
||||
sf_ipc::manifest::load_all(&dirs, Some(Path::new(sf_ipc::paths::STORE_APPS)))
|
||||
.ok()
|
||||
.and_then(|apps| apps.into_iter().find(|a| a.id == id).map(|a| a.name))
|
||||
.unwrap_or_else(|| id.to_string())
|
||||
@@ -930,8 +1066,8 @@ pub fn update_status() -> Option<UpdateStatus> {
|
||||
staged: None,
|
||||
};
|
||||
let packages = match step {
|
||||
0 => vec![pkg("SmartFox felület", "0.1.0", "0.2.0"), pkg("YouTube", "1.0.0", "1.1.0"), pkg("Netflex", "1.0.0", "1.0.0")],
|
||||
_ => vec![pkg("SmartFox felület", "0.2.0", "0.2.0"), pkg("YouTube", "1.1.0", "1.1.0")],
|
||||
0 => vec![pkg("Fennec OS felület", "0.1.0", "0.2.0"), pkg("YouTube", "1.0.0", "1.1.0"), pkg("Netflex", "1.0.0", "1.0.0")],
|
||||
_ => vec![pkg("Fennec OS felület", "0.2.0", "0.2.0"), pkg("YouTube", "1.1.0", "1.1.0")],
|
||||
};
|
||||
return Some(UpdateStatus { state: "idle".into(), message: String::new(), checked_at: 1_792_800_000, packages });
|
||||
}
|
||||
@@ -1021,6 +1157,16 @@ mod tests {
|
||||
assert_eq!(d.name, "Nappali távirányító");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identifies_only_bluetooth_audio_devices() {
|
||||
let headphones = "Alias: AirPods Pro\nIcon: audio-headphones\nPaired: yes\nConnected: no\n";
|
||||
let audio = audio_device_info("4C:87:5D:0E:22:9B", "AirPods", headphones).unwrap();
|
||||
assert_eq!(audio.name, "AirPods Pro");
|
||||
assert!(audio.paired && !audio.connected);
|
||||
let remote = "Icon: input-gaming\nModalias: bluetooth:v004Cp0315d0001\nPaired: yes\n";
|
||||
assert!(audio_device_info("F0:B3:EC:12:7A:41", "Siri Remote", remote).is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_iwd_objects() {
|
||||
let objects: serde_json::Value = serde_json::from_str(
|
||||
|
||||
@@ -86,11 +86,12 @@ pub fn reveal_when_ready(pid: u32, not_before: Instant, on_shown: impl FnOnce()
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(30));
|
||||
}
|
||||
let fade = Duration::from_millis(340);
|
||||
// Same crossfade as sf-compositor on the TV.
|
||||
let fade = Duration::from_millis(560);
|
||||
let t0 = Instant::now();
|
||||
while t0.elapsed() < fade {
|
||||
let x = t0.elapsed().as_secs_f32() / fade.as_secs_f32();
|
||||
let eased = 1.0 - (1.0 - x).powi(3);
|
||||
let eased = if x < 0.5 { 4.0 * x * x * x } else { 1.0 - (-2.0 * x + 2.0).powi(3) / 2.0 };
|
||||
set_alpha(hwnd, (eased * 255.0) as u8);
|
||||
std::thread::sleep(Duration::from_millis(8));
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
@@ -3,6 +3,59 @@
|
||||
export component AppIcon inherits Rectangle {
|
||||
in property <string> icon;
|
||||
in property <color> ink: #ffffff;
|
||||
// Store apps bring their own picture (app.toml: icon = "icon.png").
|
||||
in property <image> image;
|
||||
in property <bool> has-image: false;
|
||||
// No picture and no built-in icon: the app name's first letter.
|
||||
in property <string> letter;
|
||||
property <bool> builtin: root.icon == "netflex" || root.icon == "youtube" || root.icon == "airplay" || root.icon == "miracast" || root.icon == "settings" || root.icon == "store" || root.icon == "steam";
|
||||
|
||||
if root.has-image: Image {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
source: root.image;
|
||||
image-fit: contain;
|
||||
}
|
||||
|
||||
if !root.has-image && !root.builtin: Text {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
horizontal-alignment: center;
|
||||
vertical-alignment: center;
|
||||
text: root.letter;
|
||||
font-size: root.height * 0.72;
|
||||
font-weight: 700;
|
||||
color: root.ink;
|
||||
}
|
||||
|
||||
if root.icon == "store": Rectangle {
|
||||
// App Store: a shopping bag with a handle.
|
||||
Path {
|
||||
width: 100%; height: 100%;
|
||||
viewbox-width: 32; viewbox-height: 32;
|
||||
commands: "M6.5 11h19l-1.4 15a2.5 2.5 0 0 1-2.5 2.3H10.4a2.5 2.5 0 0 1-2.5-2.3z";
|
||||
fill: @linear-gradient(180deg, #8cc4ff 0%, #3d7fe0 100%);
|
||||
}
|
||||
Path {
|
||||
width: 100%; height: 100%;
|
||||
viewbox-width: 32; viewbox-height: 32;
|
||||
commands: "M11.5 14V9.5a4.5 4.5 0 0 1 9 0V14";
|
||||
stroke: root.ink;
|
||||
stroke-width: 2.4px;
|
||||
stroke-line-cap: round;
|
||||
}
|
||||
}
|
||||
|
||||
if root.icon == "steam": Rectangle {
|
||||
// Steam mark: the piston and valve in a disc (Simple Icons, CC0).
|
||||
Path {
|
||||
width: 100%; height: 100%;
|
||||
viewbox-x: -3; viewbox-y: -3;
|
||||
viewbox-width: 30; viewbox-height: 30;
|
||||
commands: "M11.979 0C5.678 0 .511 4.86.022 11.037l6.432 2.658c.545-.371 1.203-.59 1.912-.59.063 0 .125.004.188.006l2.861-4.142V8.91c0-2.495 2.028-4.524 4.524-4.524 2.494 0 4.524 2.031 4.524 4.527s-2.03 4.525-4.524 4.525h-.105l-4.076 2.911c0 .052.004.105.004.159 0 1.875-1.515 3.396-3.39 3.396-1.635 0-3.016-1.173-3.331-2.727L.436 15.27C1.862 20.307 6.486 24 11.979 24c6.627 0 11.999-5.373 11.999-12S18.605 0 11.979 0zM7.54 18.21l-1.473-.61c.262.543.714.999 1.314 1.25 1.297.539 2.793-.076 3.332-1.375.263-.63.264-1.319.005-1.949s-.75-1.121-1.377-1.383c-.624-.26-1.29-.249-1.878-.03l1.523.63c.956.4 1.409 1.5 1.009 2.455-.397.957-1.497 1.41-2.454 1.012H7.54zm11.415-9.303c0-1.662-1.353-3.015-3.015-3.015-1.665 0-3.015 1.353-3.015 3.015 0 1.665 1.35 3.015 3.015 3.015 1.663 0 3.015-1.35 3.015-3.015zm-5.273-.005c0-1.252 1.013-2.266 2.265-2.266 1.249 0 2.266 1.014 2.266 2.266 0 1.251-1.017 2.265-2.266 2.265-1.253 0-2.265-1.014-2.265-2.265z";
|
||||
fill: @linear-gradient(160deg, #ffffff 0%, #c7e4f8 100%);
|
||||
}
|
||||
}
|
||||
|
||||
if root.icon == "netflex": Rectangle {
|
||||
// Netflex mark: mirrored "N" in three ribbons (from netflex/apps/web/public/favicon.svg).
|
||||
@@ -107,7 +160,7 @@ export component AppIcon inherits Rectangle {
|
||||
}
|
||||
}
|
||||
|
||||
// SmartFox brand mark: a geometric fox head.
|
||||
// Fennec OS brand mark: a geometric fox head.
|
||||
export component FoxMark inherits Rectangle {
|
||||
Path {
|
||||
width: 100%; height: 100%;
|
||||
@@ -293,3 +346,273 @@ export component PowerIcon inherits Rectangle {
|
||||
stroke-line-cap: round;
|
||||
}
|
||||
}
|
||||
|
||||
export component AudioIcon inherits Rectangle {
|
||||
in property <color> ink: #ffffff;
|
||||
Path {
|
||||
width: 100%; height: 100%;
|
||||
viewbox-width: 32; viewbox-height: 32;
|
||||
commands: "M5 12h6l7-6v20l-7-6H5zM22 12a6 6 0 0 1 0 8M25 8a11 11 0 0 1 0 16";
|
||||
stroke: root.ink;
|
||||
stroke-width: 2.2px;
|
||||
stroke-line-cap: round;
|
||||
stroke-line-join: round;
|
||||
}
|
||||
}
|
||||
|
||||
// Siri Remote, front view (status capsule, facts).
|
||||
export component RemoteIcon inherits Rectangle {
|
||||
in property <color> ink: #ffffff;
|
||||
Path {
|
||||
width: 100%; height: 100%;
|
||||
viewbox-width: 32; viewbox-height: 32;
|
||||
commands: "M12.5 3h7a3 3 0 0 1 3 3v20a3 3 0 0 1-3 3h-7a3 3 0 0 1-3-3V6a3 3 0 0 1 3-3z";
|
||||
stroke: root.ink;
|
||||
stroke-width: 2.2px;
|
||||
stroke-line-join: round;
|
||||
}
|
||||
Path {
|
||||
width: 100%; height: 100%;
|
||||
viewbox-width: 32; viewbox-height: 32;
|
||||
commands: "M12.6 10.5a3.4 3.4 0 1 0 6.8 0a3.4 3.4 0 1 0-6.8 0zM13.5 18.5a1.3 1.3 0 1 0 2.6 0a1.3 1.3 0 1 0-2.6 0zM15.9 18.5a1.3 1.3 0 1 0 2.6 0a1.3 1.3 0 1 0-2.6 0z";
|
||||
fill: root.ink;
|
||||
}
|
||||
}
|
||||
|
||||
// Wired network (ethernet plug).
|
||||
export component WiredIcon inherits Rectangle {
|
||||
in property <color> ink: #ffffff;
|
||||
Path {
|
||||
width: 100%; height: 100%;
|
||||
viewbox-width: 32; viewbox-height: 32;
|
||||
commands: "M9 6h14a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2h-3v4h-8v-4H9a2 2 0 0 1-2-2V8a2 2 0 0 1 2-2zM16 23v5M12.5 10.5v3M16 10.5v3M19.5 10.5v3";
|
||||
stroke: root.ink;
|
||||
stroke-width: 2.2px;
|
||||
stroke-line-cap: round;
|
||||
stroke-line-join: round;
|
||||
}
|
||||
}
|
||||
|
||||
// Cast from a phone: screen with broadcast arcs in the corner.
|
||||
export component CastIcon inherits Rectangle {
|
||||
in property <color> ink: #ffffff;
|
||||
Path {
|
||||
width: 100%; height: 100%;
|
||||
viewbox-width: 32; viewbox-height: 32;
|
||||
commands: "M4 11V8.5A2.5 2.5 0 0 1 6.5 6h19A2.5 2.5 0 0 1 28 8.5v15a2.5 2.5 0 0 1-2.5 2.5H17M4 16.5a9.5 9.5 0 0 1 9.5 9.5M4 21.5a4.5 4.5 0 0 1 4.5 4.5";
|
||||
stroke: root.ink;
|
||||
stroke-width: 2.2px;
|
||||
stroke-line-cap: round;
|
||||
stroke-line-join: round;
|
||||
}
|
||||
Path {
|
||||
width: 100%; height: 100%;
|
||||
viewbox-width: 32; viewbox-height: 32;
|
||||
commands: "M3 26a1.5 1.5 0 1 0 3 0a1.5 1.5 0 1 0-3 0z";
|
||||
fill: root.ink;
|
||||
}
|
||||
}
|
||||
|
||||
// Home media server.
|
||||
export component ServerIcon inherits Rectangle {
|
||||
in property <color> ink: #ffffff;
|
||||
Path {
|
||||
width: 100%; height: 100%;
|
||||
viewbox-width: 32; viewbox-height: 32;
|
||||
commands: "M7 5h18a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2V7a2 2 0 0 1 2-2zM7 18h18a2 2 0 0 1 2 2v5a2 2 0 0 1-2 2H7a2 2 0 0 1-2-2v-5a2 2 0 0 1 2-2z";
|
||||
stroke: root.ink;
|
||||
stroke-width: 2.2px;
|
||||
stroke-line-join: round;
|
||||
}
|
||||
Path {
|
||||
width: 100%; height: 100%;
|
||||
viewbox-width: 32; viewbox-height: 32;
|
||||
commands: "M9.5 9.5a1.4 1.4 0 1 0 2.8 0a1.4 1.4 0 1 0-2.8 0zM9.5 22.5a1.4 1.4 0 1 0 2.8 0a1.4 1.4 0 1 0-2.8 0z";
|
||||
fill: root.ink;
|
||||
}
|
||||
}
|
||||
|
||||
export component CheckIcon inherits Rectangle {
|
||||
in property <color> ink: #ffffff;
|
||||
Path {
|
||||
width: 100%; height: 100%;
|
||||
viewbox-width: 32; viewbox-height: 32;
|
||||
commands: "M7 16.5l6 6L25.5 10";
|
||||
stroke: root.ink;
|
||||
stroke-width: 3px;
|
||||
stroke-line-cap: round;
|
||||
stroke-line-join: round;
|
||||
}
|
||||
}
|
||||
|
||||
export component AlertIcon inherits Rectangle {
|
||||
in property <color> ink: #ffffff;
|
||||
Path {
|
||||
width: 100%; height: 100%;
|
||||
viewbox-width: 32; viewbox-height: 32;
|
||||
commands: "M16 8v10";
|
||||
stroke: root.ink;
|
||||
stroke-width: 3px;
|
||||
stroke-line-cap: round;
|
||||
}
|
||||
Path {
|
||||
width: 100%; height: 100%;
|
||||
viewbox-width: 32; viewbox-height: 32;
|
||||
commands: "M14.2 24a1.8 1.8 0 1 0 3.6 0a1.8 1.8 0 1 0-3.6 0z";
|
||||
fill: root.ink;
|
||||
}
|
||||
}
|
||||
|
||||
export component ChevronIcon inherits Rectangle {
|
||||
in property <color> ink: #ffffff;
|
||||
Path {
|
||||
width: 100%; height: 100%;
|
||||
viewbox-width: 32; viewbox-height: 32;
|
||||
commands: "M12 7l9 9-9 9";
|
||||
stroke: root.ink;
|
||||
stroke-width: 2.6px;
|
||||
stroke-line-cap: round;
|
||||
stroke-line-join: round;
|
||||
}
|
||||
}
|
||||
|
||||
// Remote buttons in the pairing drawing.
|
||||
export component BackGlyph inherits Rectangle {
|
||||
in property <color> ink: #ffffff;
|
||||
Path {
|
||||
width: 100%; height: 100%;
|
||||
viewbox-width: 32; viewbox-height: 32;
|
||||
commands: "M19 8l-8 8 8 8";
|
||||
stroke: root.ink;
|
||||
stroke-width: 3px;
|
||||
stroke-line-cap: round;
|
||||
stroke-line-join: round;
|
||||
}
|
||||
}
|
||||
|
||||
export component TvGlyph inherits Rectangle {
|
||||
in property <color> ink: #ffffff;
|
||||
Path {
|
||||
width: 100%; height: 100%;
|
||||
viewbox-width: 32; viewbox-height: 32;
|
||||
commands: "M7.5 8h17a1.5 1.5 0 0 1 1.5 1.5v11a1.5 1.5 0 0 1-1.5 1.5h-17A1.5 1.5 0 0 1 6 20.5v-11A1.5 1.5 0 0 1 7.5 8zM12 25.5h8";
|
||||
stroke: root.ink;
|
||||
stroke-width: 2.6px;
|
||||
stroke-line-cap: round;
|
||||
stroke-line-join: round;
|
||||
}
|
||||
}
|
||||
|
||||
export component PlayPauseGlyph inherits Rectangle {
|
||||
in property <color> ink: #ffffff;
|
||||
Path {
|
||||
width: 100%; height: 100%;
|
||||
viewbox-width: 32; viewbox-height: 32;
|
||||
commands: "M6 9.5v13l9-6.5z";
|
||||
fill: root.ink;
|
||||
}
|
||||
Path {
|
||||
width: 100%; height: 100%;
|
||||
viewbox-width: 32; viewbox-height: 32;
|
||||
commands: "M19.5 10v12M25 10v12";
|
||||
stroke: root.ink;
|
||||
stroke-width: 2.8px;
|
||||
stroke-line-cap: round;
|
||||
}
|
||||
}
|
||||
|
||||
export component MuteGlyph inherits Rectangle {
|
||||
in property <color> ink: #ffffff;
|
||||
Path {
|
||||
width: 100%; height: 100%;
|
||||
viewbox-width: 32; viewbox-height: 32;
|
||||
commands: "M5 12.5h4.5L16 7v18l-6.5-5.5H5z";
|
||||
fill: root.ink;
|
||||
}
|
||||
Path {
|
||||
width: 100%; height: 100%;
|
||||
viewbox-width: 32; viewbox-height: 32;
|
||||
commands: "M20.5 12.5l7 7M27.5 12.5l-7 7";
|
||||
stroke: root.ink;
|
||||
stroke-width: 2.6px;
|
||||
stroke-line-cap: round;
|
||||
}
|
||||
}
|
||||
|
||||
export component PlusGlyph inherits Rectangle {
|
||||
in property <color> ink: #ffffff;
|
||||
Path {
|
||||
width: 100%; height: 100%;
|
||||
viewbox-width: 32; viewbox-height: 32;
|
||||
commands: "M16 8v16M8 16h16";
|
||||
stroke: root.ink;
|
||||
stroke-width: 3px;
|
||||
stroke-line-cap: round;
|
||||
}
|
||||
}
|
||||
|
||||
export component MinusGlyph inherits Rectangle {
|
||||
in property <color> ink: #ffffff;
|
||||
Path {
|
||||
width: 100%; height: 100%;
|
||||
viewbox-width: 32; viewbox-height: 32;
|
||||
commands: "M8 16h16";
|
||||
stroke: root.ink;
|
||||
stroke-width: 3px;
|
||||
stroke-line-cap: round;
|
||||
}
|
||||
}
|
||||
|
||||
export component PowerGlyph inherits Rectangle {
|
||||
in property <color> ink: #ffffff;
|
||||
Path {
|
||||
width: 100%; height: 100%;
|
||||
viewbox-width: 32; viewbox-height: 32;
|
||||
commands: "M10.3 9.6a9 9 0 1 0 11.4 0M16 5.5v10";
|
||||
stroke: root.ink;
|
||||
stroke-width: 3px;
|
||||
stroke-line-cap: round;
|
||||
}
|
||||
}
|
||||
|
||||
// One icon by name, for data-driven rows (home screen facts).
|
||||
export component NamedIcon inherits Rectangle {
|
||||
in property <string> name;
|
||||
in property <color> ink: #ffffff;
|
||||
if root.name == "remote": RemoteIcon { width: 100%; height: 100%; ink: root.ink; }
|
||||
if root.name == "wifi": WifiIcon { width: 100%; height: 100%; ink: root.ink; }
|
||||
if root.name == "wired": WiredIcon { width: 100%; height: 100%; ink: root.ink; }
|
||||
if root.name == "display": DisplayIcon { width: 100%; height: 100%; ink: root.ink; }
|
||||
if root.name == "cast": CastIcon { width: 100%; height: 100%; ink: root.ink; }
|
||||
if root.name == "server": ServerIcon { width: 100%; height: 100%; ink: root.ink; }
|
||||
if root.name == "check": CheckIcon { width: 100%; height: 100%; ink: root.ink; }
|
||||
if root.name == "alert": AlertIcon { width: 100%; height: 100%; ink: root.ink; }
|
||||
if root.name == "bluetooth": BluetoothIcon { width: 100%; height: 100%; ink: root.ink; }
|
||||
}
|
||||
|
||||
// Store screen categories (settings.slint NavIcon 5..7).
|
||||
export component StoreIcon inherits Rectangle {
|
||||
in property <color> ink: #ffffff;
|
||||
Path {
|
||||
width: 100%; height: 100%;
|
||||
viewbox-width: 32; viewbox-height: 32;
|
||||
commands: "M6.5 11h19l-1.4 15a2.5 2.5 0 0 1-2.5 2.3H10.4a2.5 2.5 0 0 1-2.5-2.3zM11.5 14V9.5a4.5 4.5 0 0 1 9 0V14";
|
||||
stroke: root.ink;
|
||||
stroke-width: 2.2px;
|
||||
stroke-line-cap: round;
|
||||
stroke-line-join: round;
|
||||
}
|
||||
}
|
||||
|
||||
export component LinkIcon inherits Rectangle {
|
||||
in property <color> ink: #ffffff;
|
||||
Path {
|
||||
width: 100%; height: 100%;
|
||||
viewbox-width: 32; viewbox-height: 32;
|
||||
commands: "M14 18a5 5 0 0 0 7.1 0l4-4a5 5 0 0 0-7.1-7.1l-1.5 1.5M18 14a5 5 0 0 0-7.1 0l-4 4a5 5 0 0 0 7.1 7.1l1.5-1.5";
|
||||
stroke: root.ink;
|
||||
stroke-width: 2.4px;
|
||||
stroke-line-cap: round;
|
||||
stroke-line-join: round;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// On-screen keyboard in the tvOS style: one horizontal row of characters,
|
||||
// the text field above it and the mode chips below.
|
||||
//
|
||||
// Drawn inside the settings pane, which stays; the settings content fades out.
|
||||
// Opens in place of the settings content, which fades out.
|
||||
// Only text and icons are drawn here. The glass (field, key track, focus lens,
|
||||
// chips) comes from `keyboard::glass` in Rust, which mirrors the geometry the
|
||||
// App exports (kb-* properties): keep the two in sync.
|
||||
@@ -16,7 +16,6 @@ export component KeyboardView inherits Rectangle {
|
||||
in property <length> pane-y;
|
||||
in property <length> pane-w;
|
||||
in property <length> pane-h;
|
||||
in property <length> back-x;
|
||||
in property <length> field-x;
|
||||
in property <length> field-y;
|
||||
in property <length> field-w;
|
||||
@@ -50,24 +49,23 @@ export component KeyboardView inherits Rectangle {
|
||||
// ---- heading ----------------------------------------------------------
|
||||
Text {
|
||||
x: root.pane-x;
|
||||
y: root.pane-y + 58 * root.u;
|
||||
y: root.pane-y + 88 * root.u;
|
||||
width: root.pane-w;
|
||||
horizontal-alignment: center;
|
||||
text: root.title;
|
||||
font-family: "Inter Display";
|
||||
font-weight: 800;
|
||||
font-size: 46 * root.u;
|
||||
letter-spacing: -1.2 * root.u;
|
||||
font-weight: 700;
|
||||
font-size: 48 * root.u;
|
||||
letter-spacing: -0.8 * root.u;
|
||||
color: #ffffff;
|
||||
overflow: elide;
|
||||
}
|
||||
Text {
|
||||
x: root.pane-x + 80 * root.u;
|
||||
y: root.pane-y + 128 * root.u;
|
||||
y: root.pane-y + 160 * root.u;
|
||||
width: root.pane-w - 160 * root.u;
|
||||
horizontal-alignment: center;
|
||||
text: root.subtitle;
|
||||
font-size: 23 * root.u;
|
||||
font-size: 24 * root.u;
|
||||
color: #ffffffa8;
|
||||
overflow: elide;
|
||||
}
|
||||
@@ -114,12 +112,12 @@ export component KeyboardView inherits Rectangle {
|
||||
}
|
||||
Text {
|
||||
x: root.field-x;
|
||||
y: root.field-y + root.field-h + 18 * root.u;
|
||||
y: root.field-y + root.field-h + 20 * root.u;
|
||||
width: root.field-w;
|
||||
horizontal-alignment: center;
|
||||
text: root.hint;
|
||||
font-size: 21 * root.u;
|
||||
color: root.hint-error ? #ff8278 : #ffffff8c;
|
||||
font-size: 22 * root.u;
|
||||
color: root.hint-error ? #ff8278 : #ffffff99;
|
||||
}
|
||||
|
||||
// ---- key row ---------------------------------------------------------------
|
||||
@@ -175,16 +173,4 @@ export component KeyboardView inherits Rectangle {
|
||||
: self.f > 0.5 ? #121317 : self.selected ? #ff9a5c : #ffffffc8;
|
||||
}
|
||||
|
||||
Text {
|
||||
x: root.back-x;
|
||||
y: root.pane-y + root.pane-h - 92 * root.u;
|
||||
width: 300 * root.u;
|
||||
height: 56 * root.u;
|
||||
horizontal-alignment: center;
|
||||
vertical-alignment: center;
|
||||
text: "‹ Mégse · Vissza";
|
||||
font-size: 21 * root.u;
|
||||
font-weight: 500;
|
||||
color: #ffffffc0;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
// First-run pairing guide for the Apple Siri Remote. The frosted pane behind
|
||||
// it is drawn by the glass layer (see `glass-over` in app.slint).
|
||||
|
||||
import { BackGlyph, TvGlyph, PlayPauseGlyph, MuteGlyph, PlusGlyph, MinusGlyph, PowerGlyph, CheckIcon, AlertIcon } from "icons.slint";
|
||||
|
||||
// Pulsing ring that draws the eye to a button.
|
||||
component Pulse inherits Rectangle {
|
||||
in property <length> size;
|
||||
@@ -17,9 +19,12 @@ component Pulse inherits Rectangle {
|
||||
|
||||
component RemoteButton inherits Rectangle {
|
||||
in property <length> u;
|
||||
// back | tv | playpause | mute | plus
|
||||
in property <string> glyph;
|
||||
in property <bool> hot;
|
||||
in property <color> accent;
|
||||
property <color> ink: self.hot ? self.accent.brighter(0.5) : #e8e8ea;
|
||||
property <length> g: 26 * self.u;
|
||||
width: 52 * self.u;
|
||||
height: self.width;
|
||||
border-radius: self.width / 2;
|
||||
@@ -40,14 +45,11 @@ component RemoteButton inherits Rectangle {
|
||||
x: (parent.width - self.width) / 2;
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
Text {
|
||||
text: root.glyph;
|
||||
color: root.hot ? root.accent.brighter(0.5) : #e8e8ea;
|
||||
font-size: 24 * root.u;
|
||||
font-weight: 600;
|
||||
horizontal-alignment: center;
|
||||
vertical-alignment: center;
|
||||
}
|
||||
if root.glyph == "back": BackGlyph { x: (parent.width - self.width) / 2; y: (parent.height - self.height) / 2; width: root.g; height: root.g; ink: root.ink; }
|
||||
if root.glyph == "tv": TvGlyph { x: (parent.width - self.width) / 2; y: (parent.height - self.height) / 2; width: root.g; height: root.g; ink: root.ink; }
|
||||
if root.glyph == "playpause": PlayPauseGlyph { x: (parent.width - self.width) / 2; y: (parent.height - self.height) / 2; width: root.g; height: root.g; ink: root.ink; }
|
||||
if root.glyph == "mute": MuteGlyph { x: (parent.width - self.width) / 2; y: (parent.height - self.height) / 2; width: root.g; height: root.g; ink: root.ink; }
|
||||
if root.glyph == "plus": PlusGlyph { x: (parent.width - self.width) / 2; y: (parent.height - self.height) / 2; width: root.g; height: root.g; ink: root.ink; }
|
||||
}
|
||||
|
||||
// Apple Siri Remote (2nd gen, aluminium), drawn front-on.
|
||||
@@ -57,7 +59,9 @@ export component SiriRemote inherits Rectangle {
|
||||
width: 150 * self.u;
|
||||
height: 560 * self.u;
|
||||
border-radius: 44 * self.u;
|
||||
background: @linear-gradient(90deg, #8d929a 0%, #d9dde2 22%, #f1f3f5 45%, #c6cad0 75%, #959aa2 100%);
|
||||
background: #c4c8ce;
|
||||
border-width: 2px;
|
||||
border-color: #ffffff40;
|
||||
drop-shadow-blur: 30 * self.u;
|
||||
drop-shadow-color: #000000a0;
|
||||
drop-shadow-offset-y: 16 * self.u;
|
||||
@@ -79,12 +83,12 @@ export component SiriRemote inherits Rectangle {
|
||||
height: 18 * root.u;
|
||||
border-radius: self.width / 2;
|
||||
background: #1b1b1d;
|
||||
Text {
|
||||
text: "⏻";
|
||||
color: #d0d0d4;
|
||||
font-size: 11 * root.u;
|
||||
horizontal-alignment: center;
|
||||
vertical-alignment: center;
|
||||
PowerGlyph {
|
||||
x: (parent.width - self.width) / 2;
|
||||
y: (parent.height - self.height) / 2;
|
||||
width: 12 * root.u;
|
||||
height: 12 * root.u;
|
||||
ink: #d0d0d4;
|
||||
}
|
||||
}
|
||||
// Clickpad: outer touch ring and center.
|
||||
@@ -118,10 +122,10 @@ export component SiriRemote inherits Rectangle {
|
||||
// Button grid below the clickpad.
|
||||
property <length> col1: 18 * root.u;
|
||||
property <length> col2: root.width - 18 * root.u - 52 * root.u;
|
||||
RemoteButton { u: root.u; accent: root.accent; x: root.col1; y: 200 * root.u; glyph: "‹"; hot: true; }
|
||||
RemoteButton { u: root.u; accent: root.accent; x: root.col2; y: 200 * root.u; glyph: "▭"; }
|
||||
RemoteButton { u: root.u; accent: root.accent; x: root.col1; y: 268 * root.u; glyph: "⏯"; }
|
||||
RemoteButton { u: root.u; accent: root.accent; x: root.col1; y: 336 * root.u; glyph: "🔇"; }
|
||||
RemoteButton { u: root.u; accent: root.accent; x: root.col1; y: 200 * root.u; glyph: "back"; hot: true; }
|
||||
RemoteButton { u: root.u; accent: root.accent; x: root.col2; y: 200 * root.u; glyph: "tv"; }
|
||||
RemoteButton { u: root.u; accent: root.accent; x: root.col1; y: 268 * root.u; glyph: "playpause"; }
|
||||
RemoteButton { u: root.u; accent: root.accent; x: root.col1; y: 336 * root.u; glyph: "mute"; }
|
||||
// Volume rocker: + is the one to hold.
|
||||
Rectangle {
|
||||
x: root.col2;
|
||||
@@ -135,19 +139,16 @@ export component SiriRemote inherits Rectangle {
|
||||
accent: root.accent;
|
||||
x: 0;
|
||||
y: 0;
|
||||
glyph: "+";
|
||||
glyph: "plus";
|
||||
hot: true;
|
||||
background: transparent;
|
||||
}
|
||||
Text {
|
||||
y: parent.height - 52 * root.u;
|
||||
width: parent.width;
|
||||
height: 52 * root.u;
|
||||
text: "−";
|
||||
color: #e8e8ea;
|
||||
font-size: 24 * root.u;
|
||||
horizontal-alignment: center;
|
||||
vertical-alignment: center;
|
||||
MinusGlyph {
|
||||
x: (parent.width - self.width) / 2;
|
||||
y: parent.height - 52 * root.u + (52 * root.u - self.height) / 2;
|
||||
width: 26 * root.u;
|
||||
height: 26 * root.u;
|
||||
ink: #e8e8ea;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -157,81 +158,76 @@ component Step inherits Rectangle {
|
||||
in property <int> n;
|
||||
in property <string> label;
|
||||
in property <color> accent;
|
||||
height: 70 * self.u;
|
||||
Rectangle {
|
||||
// The glass bead behind the number is drawn by the glass layer (app.slint),
|
||||
// on the same 48 px square.
|
||||
Text {
|
||||
x: 0;
|
||||
y: 4 * root.u;
|
||||
width: 40 * root.u;
|
||||
height: self.width;
|
||||
// The glass bead behind the number is drawn by the glass layer (app.slint).
|
||||
Text {
|
||||
text: root.n;
|
||||
color: root.accent.brighter(0.6);
|
||||
font-size: 20 * root.u;
|
||||
font-weight: 700;
|
||||
horizontal-alignment: center;
|
||||
vertical-alignment: center;
|
||||
}
|
||||
y: 0;
|
||||
width: 48 * root.u;
|
||||
height: 48 * root.u;
|
||||
text: root.n;
|
||||
color: root.accent.brighter(0.6);
|
||||
font-size: 22 * root.u;
|
||||
font-weight: 700;
|
||||
horizontal-alignment: center;
|
||||
vertical-alignment: center;
|
||||
}
|
||||
Text {
|
||||
x: 60 * root.u;
|
||||
y: 10 * root.u;
|
||||
width: parent.width - 60 * root.u;
|
||||
x: 72 * root.u;
|
||||
y: 6 * root.u;
|
||||
width: parent.width - 72 * root.u;
|
||||
text: root.label;
|
||||
wrap: word-wrap;
|
||||
font-size: 24 * root.u;
|
||||
color: #ffffffd8;
|
||||
font-size: 26 * root.u;
|
||||
color: #ffffffe0;
|
||||
}
|
||||
}
|
||||
|
||||
// Pane content; `state` is the remote status from sf-remote.
|
||||
// Pane content; `state` is the remote status from sf-remote. The text column
|
||||
// starts at (content-x, content-y); `steps` and `pill-y` are offsets from
|
||||
// there, shared with the glass beads and pills in app.slint.
|
||||
export component PairingGuide inherits Rectangle {
|
||||
in property <length> u;
|
||||
in property <string> state;
|
||||
in property <color> accent: #ff7a35;
|
||||
in property <length> content-x;
|
||||
in property <length> content-y;
|
||||
in property <[length]> steps;
|
||||
in property <length> pill-y;
|
||||
property <bool> ok: self.state == "paired" || self.state == "connected";
|
||||
property <bool> broken: self.state == "no-adapter";
|
||||
|
||||
SiriRemote {
|
||||
u: root.u;
|
||||
accent: root.accent;
|
||||
x: 120 * root.u;
|
||||
x: (root.content-x - self.width) / 2;
|
||||
y: (parent.height - self.height) / 2;
|
||||
}
|
||||
|
||||
Rectangle {
|
||||
x: 420 * root.u;
|
||||
y: 70 * root.u;
|
||||
width: parent.width - 420 * root.u - 80 * root.u;
|
||||
height: parent.height - 140 * root.u;
|
||||
x: root.content-x;
|
||||
y: root.content-y;
|
||||
width: parent.width - root.content-x - 88 * root.u;
|
||||
height: parent.height - root.content-y;
|
||||
|
||||
Text {
|
||||
x: 0;
|
||||
y: 0;
|
||||
text: "ELSŐ LÉPÉS";
|
||||
font-size: 20 * root.u;
|
||||
font-weight: 600;
|
||||
letter-spacing: 3 * root.u;
|
||||
color: root.accent.brighter(0.3);
|
||||
}
|
||||
Text {
|
||||
x: 0;
|
||||
y: 34 * root.u;
|
||||
width: parent.width;
|
||||
text: "Párosítsd a Siri Remote-ot";
|
||||
wrap: word-wrap;
|
||||
font-family: "Inter Display";
|
||||
font-weight: 800;
|
||||
font-size: 58 * root.u;
|
||||
letter-spacing: -1.6 * root.u;
|
||||
font-weight: 700;
|
||||
font-size: 52 * root.u;
|
||||
letter-spacing: -1 * root.u;
|
||||
color: #ffffff;
|
||||
overflow: elide;
|
||||
}
|
||||
Step {
|
||||
u: root.u;
|
||||
accent: root.accent;
|
||||
x: 0;
|
||||
y: 150 * root.u;
|
||||
y: root.steps[0];
|
||||
width: parent.width;
|
||||
height: 64 * root.u;
|
||||
n: 1;
|
||||
label: "Vidd a távirányítót a TV közelébe.";
|
||||
}
|
||||
@@ -239,33 +235,34 @@ export component PairingGuide inherits Rectangle {
|
||||
u: root.u;
|
||||
accent: root.accent;
|
||||
x: 0;
|
||||
y: 226 * root.u;
|
||||
y: root.steps[1];
|
||||
width: parent.width;
|
||||
height: 100 * root.u;
|
||||
n: 2;
|
||||
label: "Tartsd nyomva egyszerre a Vissza (‹) és a Hangerő + gombot kb. 5 másodpercig.";
|
||||
label: "Tartsd nyomva egyszerre a Vissza és a Hangerő + gombot, kb. 5 másodpercig.";
|
||||
}
|
||||
Step {
|
||||
u: root.u;
|
||||
accent: root.accent;
|
||||
x: 0;
|
||||
y: 330 * root.u;
|
||||
y: root.steps[2];
|
||||
width: parent.width;
|
||||
height: 64 * root.u;
|
||||
n: 3;
|
||||
label: "Engedd el. A TV magától megtalálja és párosítja.";
|
||||
}
|
||||
|
||||
// Live status.
|
||||
// Live status, on the glass pill drawn by app.slint (520 x 64).
|
||||
Rectangle {
|
||||
x: 0;
|
||||
y: parent.height - 70 * root.u;
|
||||
y: root.pill-y;
|
||||
width: 520 * root.u;
|
||||
height: 64 * root.u;
|
||||
// Glass pill (tinted by state) is drawn by the glass layer (app.slint).
|
||||
|
||||
// Searching: three breathing dots. Done: check mark. Error: "!".
|
||||
// Searching: three breathing dots. Done: check mark. Error: alert.
|
||||
if !root.ok && !root.broken: HorizontalLayout {
|
||||
x: 26 * root.u;
|
||||
width: 60 * root.u;
|
||||
x: 0;
|
||||
width: 56 * root.u;
|
||||
spacing: 8 * root.u;
|
||||
alignment: start;
|
||||
for i in 3: Rectangle {
|
||||
@@ -278,41 +275,47 @@ export component PairingGuide inherits Rectangle {
|
||||
opacity: 0.25 + 0.75 * abs(sin(self.p * 180deg));
|
||||
}
|
||||
}
|
||||
if root.ok || root.broken: Text {
|
||||
x: 26 * root.u;
|
||||
width: 40 * root.u;
|
||||
height: parent.height;
|
||||
text: root.ok ? "✓" : "!";
|
||||
color: root.ok ? #34c759 : #ff9f0a;
|
||||
font-size: 30 * root.u;
|
||||
font-weight: 800;
|
||||
vertical-alignment: center;
|
||||
if root.ok: CheckIcon {
|
||||
x: 24 * root.u;
|
||||
y: (parent.height - self.height) / 2;
|
||||
width: 32 * root.u;
|
||||
height: 32 * root.u;
|
||||
ink: #34c759;
|
||||
}
|
||||
if root.broken: AlertIcon {
|
||||
x: 24 * root.u;
|
||||
y: (parent.height - self.height) / 2;
|
||||
width: 32 * root.u;
|
||||
height: 32 * root.u;
|
||||
ink: #ff9f0a;
|
||||
}
|
||||
Text {
|
||||
x: 92 * root.u;
|
||||
width: parent.width - 110 * root.u;
|
||||
x: root.ok || root.broken ? 72 * root.u : 64 * root.u;
|
||||
width: parent.width - 96 * root.u;
|
||||
height: parent.height;
|
||||
vertical-alignment: center;
|
||||
font-size: 24 * root.u;
|
||||
font-weight: 500;
|
||||
color: #ffffff;
|
||||
text: root.ok ? "Sikeres párosítás!"
|
||||
overflow: elide;
|
||||
text: root.ok ? "Sikeres párosítás"
|
||||
: root.broken ? "Nem található Bluetooth adapter"
|
||||
: root.state == "pairing" ? "Párosítás…"
|
||||
: "Távirányító keresése…";
|
||||
}
|
||||
}
|
||||
// Skip chip (glass in app.slint, 200 x 64).
|
||||
Text {
|
||||
x: 556 * root.u;
|
||||
y: parent.height - 68 * root.u;
|
||||
width: 204 * root.u;
|
||||
height: 60 * root.u;
|
||||
x: 544 * root.u;
|
||||
y: root.pill-y;
|
||||
width: 200 * root.u;
|
||||
height: 64 * root.u;
|
||||
horizontal-alignment: center;
|
||||
vertical-alignment: center;
|
||||
text: "Kihagyás · Esc";
|
||||
font-size: 21 * root.u;
|
||||
font-weight: 500;
|
||||
color: #ffffffc0;
|
||||
text: "Kihagyás";
|
||||
font-size: 24 * root.u;
|
||||
font-weight: 600;
|
||||
color: #ffffffd0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,10 +1,11 @@
|
||||
// Settings screen: categories on the left, rows on the right.
|
||||
// Settings screen: categories on the left, the selected page's rows on one
|
||||
// grouped platter on the right.
|
||||
//
|
||||
// Only text and icons are drawn here. The glass (pane, rows, chips) comes from
|
||||
// `settings_screen::glass` in Rust, which mirrors the geometry below: keep the
|
||||
// row/nav formulas (position, focus `f`, visibility `vis`) in sync with it.
|
||||
// Only text and icons are drawn here. The glass (platter, focus pills) comes
|
||||
// from `settings_screen::glass` in Rust, which mirrors the geometry below: keep
|
||||
// the row/nav formulas (position, focus `f`, visibility `vis`) in sync with it.
|
||||
|
||||
import { WifiIcon, BluetoothIcon, InfoIcon, DisplayIcon, PowerIcon, SignalIcon, LockIcon } from "icons.slint";
|
||||
import { WifiIcon, BluetoothIcon, InfoIcon, DisplayIcon, AudioIcon, PowerIcon, SignalIcon, LockIcon, ChevronIcon, StoreIcon, CheckIcon, LinkIcon } from "icons.slint";
|
||||
|
||||
export struct SettingRow {
|
||||
title: string,
|
||||
@@ -22,9 +23,14 @@ component NavIcon inherits Rectangle {
|
||||
in property <color> ink;
|
||||
if root.index == 0: DisplayIcon { width: 100%; height: 100%; ink: root.ink; }
|
||||
if root.index == 1: BluetoothIcon { width: 100%; height: 100%; ink: root.ink; }
|
||||
if root.index == 2: WifiIcon { width: 100%; height: 100%; ink: root.ink; }
|
||||
if root.index == 3: PowerIcon { width: 100%; height: 100%; ink: root.ink; }
|
||||
if root.index == 4: InfoIcon { width: 100%; height: 100%; ink: root.ink; }
|
||||
if root.index == 2: AudioIcon { width: 100%; height: 100%; ink: root.ink; }
|
||||
if root.index == 3: WifiIcon { width: 100%; height: 100%; ink: root.ink; }
|
||||
if root.index == 4: PowerIcon { width: 100%; height: 100%; ink: root.ink; }
|
||||
if root.index == 5: InfoIcon { width: 100%; height: 100%; ink: root.ink; }
|
||||
// App Store mode: Felfedezés, Telepítve, Források.
|
||||
if root.index == 6: StoreIcon { width: 100%; height: 100%; ink: root.ink; }
|
||||
if root.index == 7: CheckIcon { width: 100%; height: 100%; ink: root.ink; }
|
||||
if root.index == 8: LinkIcon { width: 100%; height: 100%; ink: root.ink; }
|
||||
}
|
||||
|
||||
export component SettingsView inherits Rectangle {
|
||||
@@ -52,38 +58,47 @@ export component SettingsView inherits Rectangle {
|
||||
in property <string> subtitle;
|
||||
in property <[SettingRow]> rows;
|
||||
in property <[string]> categories;
|
||||
// The same pane serves the App Store (app.slint set-mode).
|
||||
in property <string> heading: "Beállítások";
|
||||
in property <int> icon-base: 0;
|
||||
|
||||
// Row text is inset from the platter edge by the focus pill's margin.
|
||||
property <length> inset: 8 * root.u;
|
||||
property <length> pad: 28 * root.u;
|
||||
|
||||
// ---- left column ----------------------------------------------------
|
||||
Text {
|
||||
x: root.nav-x + 8 * root.u;
|
||||
y: root.pane-y + 50 * root.u;
|
||||
text: "Beállítások";
|
||||
font-family: "Inter Display";
|
||||
font-weight: 800;
|
||||
font-size: 50 * root.u;
|
||||
letter-spacing: -1.5 * root.u;
|
||||
x: root.nav-x;
|
||||
y: root.pane-y;
|
||||
width: root.nav-w;
|
||||
height: 88 * root.u;
|
||||
vertical-alignment: center;
|
||||
text: root.heading;
|
||||
font-weight: 700;
|
||||
font-size: 56 * root.u;
|
||||
letter-spacing: -1 * root.u;
|
||||
color: #ffffff;
|
||||
}
|
||||
|
||||
for name[i] in root.categories: Rectangle {
|
||||
property <float> f: max(0, 1 - abs(root.nav-pos - i)) * root.nav-active;
|
||||
property <float> sel: max(0, 1 - abs(root.nav-pos - i));
|
||||
property <color> ink: self.f > 0.5 ? #121317 : #ffffff.with-alpha(0.72 + 0.28 * self.sel);
|
||||
property <color> ink: self.f > 0.5 ? #121317 : #ffffff.with-alpha(0.62 + 0.38 * self.sel);
|
||||
x: root.nav-x;
|
||||
y: root.nav-y + i * root.nav-step;
|
||||
width: root.nav-w;
|
||||
height: root.nav-h;
|
||||
NavIcon {
|
||||
x: 28 * root.u;
|
||||
x: 24 * root.u;
|
||||
y: (parent.height - self.height) / 2;
|
||||
width: 34 * root.u;
|
||||
height: 34 * root.u;
|
||||
index: i;
|
||||
width: 32 * root.u;
|
||||
height: 32 * root.u;
|
||||
index: i + root.icon-base;
|
||||
ink: parent.ink;
|
||||
}
|
||||
Text {
|
||||
x: 82 * root.u;
|
||||
width: parent.width - 100 * root.u;
|
||||
x: 76 * root.u;
|
||||
width: parent.width - 96 * root.u;
|
||||
height: parent.height;
|
||||
vertical-alignment: center;
|
||||
text: name;
|
||||
@@ -94,46 +109,35 @@ export component SettingsView inherits Rectangle {
|
||||
}
|
||||
}
|
||||
|
||||
Text {
|
||||
x: root.nav-x;
|
||||
y: root.pane-y + root.pane-h - 92 * root.u;
|
||||
width: 300 * root.u;
|
||||
height: 56 * root.u;
|
||||
horizontal-alignment: center;
|
||||
vertical-alignment: center;
|
||||
text: "‹ Vissza · Esc";
|
||||
font-size: 21 * root.u;
|
||||
font-weight: 500;
|
||||
color: #ffffffc0;
|
||||
}
|
||||
|
||||
// ---- right column ---------------------------------------------------
|
||||
Text {
|
||||
x: root.rows-x + 8 * root.u;
|
||||
y: root.pane-y + 44 * root.u;
|
||||
width: root.rows-w - 16 * root.u;
|
||||
x: root.rows-x + root.inset + root.pad;
|
||||
y: root.nav-y;
|
||||
width: root.rows-w - 2 * (root.inset + root.pad);
|
||||
height: root.nav-h;
|
||||
vertical-alignment: center;
|
||||
text: root.title;
|
||||
font-family: "Inter Display";
|
||||
font-weight: 800;
|
||||
font-weight: 700;
|
||||
font-size: 40 * root.u;
|
||||
letter-spacing: -1 * root.u;
|
||||
color: #ffffff;
|
||||
overflow: elide;
|
||||
}
|
||||
Text {
|
||||
x: root.rows-x + 8 * root.u;
|
||||
y: root.pane-y + 102 * root.u;
|
||||
width: root.rows-w - 16 * root.u;
|
||||
height: 64 * root.u;
|
||||
x: root.rows-x + root.inset + root.pad;
|
||||
y: root.nav-y + root.nav-h;
|
||||
width: root.rows-w - 2 * (root.inset + root.pad);
|
||||
height: root.rows-y - root.nav-y - root.nav-h - 24 * root.u;
|
||||
text: root.subtitle;
|
||||
wrap: word-wrap;
|
||||
overflow: elide;
|
||||
font-size: 21 * root.u;
|
||||
font-size: 24 * root.u;
|
||||
color: #ffffffa8;
|
||||
}
|
||||
|
||||
for row[j] in root.rows: r := Rectangle {
|
||||
property <float> f: max(0, 1 - abs(root.row-pos - j)) * root.content-active;
|
||||
// Focus on this row or the one above hides the hairline between them.
|
||||
property <float> f-above: max(0, 1 - abs(root.row-pos - (j - 1))) * root.content-active;
|
||||
property <length> top: root.rows-y + j * root.row-step - root.rows-scroll;
|
||||
property <float> over: max(root.rows-y - self.top, self.top + root.row-h - (root.rows-y + root.rows-view-h)) / root.row-h;
|
||||
property <float> vis: clamp(1 - self.over, 0, 1);
|
||||
@@ -143,17 +147,25 @@ export component SettingsView inherits Rectangle {
|
||||
property <color> ink-dim: self.hot ? (self.danger ? #ffffffd0 : #121317b0) : #ffffff99;
|
||||
property <bool> chevron: row.kind == "choice" || row.kind == "device";
|
||||
property <bool> network: row.kind == "network";
|
||||
x: root.rows-x;
|
||||
x: root.rows-x + root.inset;
|
||||
y: self.top;
|
||||
width: root.rows-w;
|
||||
width: root.rows-w - 2 * root.inset;
|
||||
height: root.row-h;
|
||||
opacity: self.vis;
|
||||
visible: self.vis > 0.01;
|
||||
|
||||
if j > 0: Rectangle {
|
||||
x: root.pad;
|
||||
y: 0;
|
||||
width: parent.width - 2 * root.pad;
|
||||
height: 1.5 * root.u;
|
||||
background: #ffffff1f;
|
||||
opacity: 1 - clamp(max(r.f, r.f-above) * 2, 0, 1);
|
||||
}
|
||||
Text {
|
||||
x: 30 * root.u;
|
||||
y: row.detail == "" ? (parent.height - self.height) / 2 : 15 * root.u;
|
||||
width: parent.width * 0.55;
|
||||
x: root.pad;
|
||||
y: row.detail == "" ? (parent.height - self.height) / 2 : 14 * root.u;
|
||||
width: parent.width * 0.56;
|
||||
text: row.title;
|
||||
font-size: 26 * root.u;
|
||||
font-weight: 600;
|
||||
@@ -161,45 +173,43 @@ export component SettingsView inherits Rectangle {
|
||||
overflow: elide;
|
||||
}
|
||||
if row.detail != "": Text {
|
||||
x: 30 * root.u;
|
||||
y: 51 * root.u;
|
||||
width: parent.width * 0.55;
|
||||
x: root.pad;
|
||||
y: 50 * root.u;
|
||||
width: parent.width * 0.56;
|
||||
text: row.detail;
|
||||
font-size: 19 * root.u;
|
||||
font-size: 21 * root.u;
|
||||
color: r.ink-dim;
|
||||
overflow: elide;
|
||||
}
|
||||
Text {
|
||||
x: parent.width * 0.4;
|
||||
width: parent.width * 0.6 - (r.network ? 124 : r.chevron ? 64 : 32) * root.u;
|
||||
width: parent.width * 0.6 - (r.network ? 120 : r.chevron ? 64 : root.pad / root.u) * root.u;
|
||||
height: parent.height;
|
||||
horizontal-alignment: right;
|
||||
vertical-alignment: center;
|
||||
text: row.value;
|
||||
font-size: row.kind == "option" ? 30 * root.u : 23 * root.u;
|
||||
font-size: row.kind == "option" ? 28 * root.u : 24 * root.u;
|
||||
font-weight: row.kind == "option" ? 700 : 400;
|
||||
color: row.kind == "option" ? (r.hot ? #121317 : #ff9a5c) : r.ink-dim;
|
||||
overflow: elide;
|
||||
}
|
||||
if r.chevron: Text {
|
||||
x: parent.width - 50 * root.u;
|
||||
if r.chevron: ChevronIcon {
|
||||
x: parent.width - root.pad - self.width + 4 * root.u;
|
||||
y: (parent.height - self.height) / 2;
|
||||
width: 24 * root.u;
|
||||
height: parent.height;
|
||||
vertical-alignment: center;
|
||||
text: "›";
|
||||
font-size: 36 * root.u;
|
||||
color: r.ink-dim;
|
||||
height: 24 * root.u;
|
||||
ink: r.ink-dim;
|
||||
}
|
||||
// Wi-Fi network: lock (protected) and signal strength on the right.
|
||||
if r.network && row.lock: LockIcon {
|
||||
x: parent.width - 104 * root.u;
|
||||
x: parent.width - root.pad - 34 * root.u - 16 * root.u - self.width;
|
||||
y: (parent.height - self.height) / 2;
|
||||
width: 24 * root.u;
|
||||
height: 24 * root.u;
|
||||
ink: r.ink-dim;
|
||||
}
|
||||
if r.network: SignalIcon {
|
||||
x: parent.width - 66 * root.u;
|
||||
x: parent.width - root.pad - self.width;
|
||||
y: (parent.height - self.height) / 2;
|
||||
width: 34 * root.u;
|
||||
height: 34 * root.u;
|
||||
|
||||
16
crates/sf-miracast/Cargo.toml
Normal file
16
crates/sf-miracast/Cargo.toml
Normal file
@@ -0,0 +1,16 @@
|
||||
[package]
|
||||
name = "sf-miracast"
|
||||
description = "Experimental Miracast (Wi-Fi Display) sink for Fennec OS: iwd P2P + WFD RTSP + GStreamer"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
anyhow.workspace = true
|
||||
log.workspace = true
|
||||
env_logger.workspace = true
|
||||
|
||||
[target.'cfg(target_os = "linux")'.dependencies]
|
||||
tokio = { version = "1", features = ["rt", "net", "time", "io-util", "macros", "process", "signal", "sync"] }
|
||||
libc = "0.2"
|
||||
zbus = { version = "5", default-features = false, features = ["tokio"] }
|
||||
301
crates/sf-miracast/src/linux.rs
Normal file
301
crates/sf-miracast/src/linux.rs
Normal file
@@ -0,0 +1,301 @@
|
||||
//! iwd P2P control, the RTSP session loop and the GStreamer player.
|
||||
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::io::Write;
|
||||
use std::process::Stdio;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use tokio::io::{AsyncReadExt, AsyncWriteExt};
|
||||
use tokio::net::TcpStream;
|
||||
use zbus::Connection;
|
||||
use zbus::zvariant::{OwnedObjectPath, OwnedValue, Value};
|
||||
|
||||
use crate::rtsp::{Event, Message, SOURCE_PORT, Sink};
|
||||
|
||||
const IWD: &str = "net.connman.iwd";
|
||||
const P2P_DEVICE: &str = "net.connman.iwd.p2p.Device";
|
||||
const P2P_PEER: &str = "net.connman.iwd.p2p.Peer";
|
||||
const P2P_DISPLAY: &str = "net.connman.iwd.p2p.Display";
|
||||
const SERVICE_MANAGER: &str = "net.connman.iwd.p2p.ServiceManager";
|
||||
const RTP_PORT: u16 = 1028;
|
||||
/// A source peer must be visible this long before we connect to it.
|
||||
const SETTLE: Duration = Duration::from_secs(2);
|
||||
|
||||
type Props = HashMap<String, OwnedValue>;
|
||||
type Objects = HashMap<OwnedObjectPath, HashMap<String, Props>>;
|
||||
|
||||
fn event(text: &str) {
|
||||
let mut out = std::io::stdout().lock();
|
||||
let _ = writeln!(out, "SF-EVENT {text}");
|
||||
let _ = out.flush();
|
||||
}
|
||||
|
||||
fn get_bool(p: &Props, k: &str) -> Option<bool> {
|
||||
p.get(k).and_then(|v| bool::try_from(v.try_clone().ok()?).ok())
|
||||
}
|
||||
|
||||
fn get_str(p: &Props, k: &str) -> Option<String> {
|
||||
p.get(k).and_then(|v| String::try_from(v.try_clone().ok()?).ok())
|
||||
}
|
||||
|
||||
fn get_u16(p: &Props, k: &str) -> Option<u16> {
|
||||
p.get(k).and_then(|v| u16::try_from(v.try_clone().ok()?).ok())
|
||||
}
|
||||
|
||||
async fn objects(conn: &Connection) -> Result<Objects> {
|
||||
let om = zbus::fdo::ObjectManagerProxy::builder(conn).destination(IWD)?.path("/")?.build().await?;
|
||||
let raw = om.get_managed_objects().await?;
|
||||
Ok(raw
|
||||
.into_iter()
|
||||
.map(|(path, ifaces)| (path, ifaces.into_iter().map(|(k, v)| (k.to_string(), v)).collect()))
|
||||
.collect())
|
||||
}
|
||||
|
||||
async fn proxy<'a>(conn: &Connection, path: &'a str, iface: &'a str) -> Result<zbus::Proxy<'a>> {
|
||||
Ok(zbus::Proxy::new(conn, IWD, path, iface).await?)
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct Peer {
|
||||
path: String,
|
||||
name: String,
|
||||
connected: bool,
|
||||
ip: Option<String>,
|
||||
source: bool,
|
||||
port: u16,
|
||||
}
|
||||
|
||||
fn peers(objs: &Objects) -> Vec<Peer> {
|
||||
objs.iter()
|
||||
.filter_map(|(path, ifaces)| {
|
||||
let p = ifaces.get(P2P_PEER)?;
|
||||
let display = ifaces.get(P2P_DISPLAY);
|
||||
Some(Peer {
|
||||
path: path.to_string(),
|
||||
name: get_str(p, "Name").unwrap_or_else(|| "telefon".into()),
|
||||
connected: get_bool(p, "Connected").unwrap_or(false),
|
||||
ip: get_str(p, "ConnectedIP"),
|
||||
source: display.and_then(|d| get_bool(d, "Source")).unwrap_or(false),
|
||||
port: display.and_then(|d| get_u16(d, "Port")).filter(|p| *p != 0).unwrap_or(SOURCE_PORT),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub fn run(name: String) -> Result<()> {
|
||||
let rt = tokio::runtime::Builder::new_current_thread().enable_all().build()?;
|
||||
rt.block_on(main_loop(name))
|
||||
}
|
||||
|
||||
async fn main_loop(name: String) -> Result<()> {
|
||||
let conn = Connection::system().await.context("system D-Bus")?;
|
||||
let mut setup_for: Option<String> = None;
|
||||
let mut warned = false;
|
||||
let mut first_seen: HashMap<String, Instant> = HashMap::new();
|
||||
let mut backoff: HashMap<String, Instant> = HashMap::new();
|
||||
|
||||
loop {
|
||||
tokio::time::sleep(Duration::from_secs(1)).await;
|
||||
let objs = match objects(&conn).await {
|
||||
Ok(o) => o,
|
||||
Err(e) => {
|
||||
if !warned {
|
||||
log::warn!("iwd: {e:#}");
|
||||
warned = true;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_secs(9)).await;
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let Some(device) = objs.iter().find(|(_, i)| i.contains_key(P2P_DEVICE)).map(|(p, _)| p.to_string()) else {
|
||||
if !warned {
|
||||
log::warn!("no Wi-Fi Direct (P2P) capable Wi-Fi device; Miracast is unavailable");
|
||||
warned = true;
|
||||
}
|
||||
setup_for = None;
|
||||
tokio::time::sleep(Duration::from_secs(9)).await;
|
||||
continue;
|
||||
};
|
||||
warned = false;
|
||||
if setup_for.as_deref() != Some(device.as_str()) {
|
||||
match setup(&conn, &device, &name).await {
|
||||
Ok(()) => {
|
||||
log::info!("Wi-Fi Display sink \"{name}\" ready on {device}");
|
||||
setup_for = Some(device.clone());
|
||||
}
|
||||
Err(e) => {
|
||||
log::error!("p2p setup: {e:#}");
|
||||
tokio::time::sleep(Duration::from_secs(10)).await;
|
||||
continue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let now = Instant::now();
|
||||
backoff.retain(|_, until| *until > now);
|
||||
let list = peers(&objs);
|
||||
let visible: HashSet<String> = list.iter().map(|p| p.path.clone()).collect();
|
||||
first_seen.retain(|k, _| visible.contains(k));
|
||||
|
||||
// Already connected (e.g. we connected in an earlier round).
|
||||
let target = match list.iter().find(|p| p.connected) {
|
||||
Some(p) => Some(p.clone()),
|
||||
None => {
|
||||
let candidate = list.iter().find(|p| p.source && !backoff.contains_key(&p.path)).cloned();
|
||||
match candidate {
|
||||
Some(p) if now.duration_since(*first_seen.entry(p.path.clone()).or_insert(now)) >= SETTLE => {
|
||||
log::info!("connecting to {} ({})", p.name, p.path);
|
||||
match proxy(&conn, &p.path, P2P_PEER).await?.call_method("Connect", &()).await {
|
||||
Ok(_) => Some(p),
|
||||
Err(e) => {
|
||||
log::warn!("connect {}: {e}", p.name);
|
||||
backoff.insert(p.path.clone(), now + Duration::from_secs(60));
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
};
|
||||
let Some(peer) = target else { continue };
|
||||
|
||||
// Wait for the peer's IP (DHCP on the P2P link).
|
||||
let mut ip = peer.ip.clone();
|
||||
for _ in 0..30 {
|
||||
if ip.is_some() {
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(500)).await;
|
||||
ip = objects(&conn).await.ok().and_then(|o| peers(&o).into_iter().find(|p| p.path == peer.path)?.ip);
|
||||
}
|
||||
match ip {
|
||||
Some(ip) => {
|
||||
if let Err(e) = session(&ip, peer.port, &peer.name).await {
|
||||
log::warn!("session with {}: {e:#}", peer.name);
|
||||
}
|
||||
}
|
||||
None => log::warn!("{}: no IP address on the P2P link", peer.name),
|
||||
}
|
||||
event("ended");
|
||||
if let Ok(p) = proxy(&conn, &peer.path, P2P_PEER).await {
|
||||
let _ = p.call_method("Disconnect", &()).await;
|
||||
}
|
||||
backoff.insert(peer.path.clone(), Instant::now() + Duration::from_secs(10));
|
||||
// iwd stops discovery while connected; ask again.
|
||||
if let Ok(d) = proxy(&conn, &device, P2P_DEVICE).await {
|
||||
let _ = d.call_method("RequestDiscovery", &()).await;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn setup(conn: &Connection, device: &str, name: &str) -> Result<()> {
|
||||
let dev = proxy(conn, device, P2P_DEVICE).await?;
|
||||
dev.set_property("Name", name).await.context("setting the P2P name")?;
|
||||
dev.set_property("Enabled", true).await.context("enabling P2P")?;
|
||||
let mut props: HashMap<&str, Value> = HashMap::new();
|
||||
props.insert("Source", Value::from(false));
|
||||
props.insert("Sink", Value::from(true));
|
||||
props.insert("Port", Value::from(SOURCE_PORT));
|
||||
props.insert("HasAudio", Value::from(true));
|
||||
let sm = proxy(conn, "/net/connman/iwd", SERVICE_MANAGER).await?;
|
||||
if let Err(e) = sm.call_method("RegisterDisplayService", &(props,)).await {
|
||||
// Already registered by an earlier run of this connection is fine.
|
||||
if !e.to_string().contains("AlreadyExists") {
|
||||
bail!("RegisterDisplayService: {e}");
|
||||
}
|
||||
}
|
||||
// Discovery also keeps us visible to phones.
|
||||
dev.call_method("RequestDiscovery", &()).await.context("RequestDiscovery")?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// One WFD session: RTSP with the phone, the player while streaming.
|
||||
async fn session(ip: &str, port: u16, name: &str) -> Result<()> {
|
||||
log::info!("rtsp: connecting to {ip}:{port}");
|
||||
let mut stream = None;
|
||||
for _ in 0..20 {
|
||||
match TcpStream::connect((ip, port)).await {
|
||||
Ok(s) => {
|
||||
stream = Some(s);
|
||||
break;
|
||||
}
|
||||
Err(_) => tokio::time::sleep(Duration::from_millis(500)).await,
|
||||
}
|
||||
}
|
||||
let mut stream = stream.context("the phone's RTSP server did not answer")?;
|
||||
let mut sink = Sink::new(RTP_PORT);
|
||||
let mut player: Option<tokio::process::Child> = None;
|
||||
let mut buf: Vec<u8> = Vec::new();
|
||||
let result = loop {
|
||||
let mut chunk = [0u8; 4096];
|
||||
let read = tokio::select! {
|
||||
r = tokio::time::timeout(Duration::from_secs(75), stream.read(&mut chunk)) => r,
|
||||
status = async { match player.as_mut() { Some(p) => p.wait().await, None => std::future::pending().await } } => {
|
||||
log::warn!("player exited: {status:?}");
|
||||
break Ok(());
|
||||
}
|
||||
};
|
||||
let n = match read {
|
||||
Ok(Ok(0)) => break Ok(()),
|
||||
Ok(Ok(n)) => n,
|
||||
Ok(Err(e)) => break Err(e.into()),
|
||||
Err(_) => break Err(anyhow::anyhow!("no keep-alive from the phone")),
|
||||
};
|
||||
buf.extend_from_slice(&chunk[..n]);
|
||||
let mut teardown = false;
|
||||
while let Some((msg, used)) = Message::parse(&buf) {
|
||||
buf.drain(..used);
|
||||
log::debug!("rtsp <- {:?}", msg.start);
|
||||
let (out, events) = sink.handle(&msg);
|
||||
for m in out {
|
||||
log::debug!("rtsp -> {:?}", m.start);
|
||||
stream.write_all(&m.to_bytes()).await?;
|
||||
}
|
||||
for ev in events {
|
||||
match ev {
|
||||
Event::Playing if player.is_none() => {
|
||||
player = Some(start_player()?);
|
||||
event(&format!("connected {name}"));
|
||||
}
|
||||
Event::Teardown => teardown = true,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
if teardown {
|
||||
break Ok(());
|
||||
}
|
||||
};
|
||||
if let Some(mut p) = player {
|
||||
let _ = p.kill().await;
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
/// MPEG-TS over RTP on RTP_PORT, decoded by whatever GStreamer finds best
|
||||
/// (VA-API on the N100), full screen on Wayland.
|
||||
fn start_player() -> Result<tokio::process::Child> {
|
||||
let caps = "application/x-rtp,media=video,clock-rate=90000,encoding-name=MP2T";
|
||||
let pipeline = format!(
|
||||
"udpsrc port={RTP_PORT} caps=\"{caps}\" ! rtpjitterbuffer latency=120 ! rtpmp2tdepay ! decodebin3 name=d \
|
||||
d. ! queue ! waylandsink fullscreen=true sync=false \
|
||||
d. ! queue ! audioconvert ! audioresample ! autoaudiosink sync=false"
|
||||
);
|
||||
log::info!("player: gst-launch-1.0 {pipeline}");
|
||||
let mut std_cmd = std::process::Command::new("sh");
|
||||
std_cmd.arg("-c").arg(format!("exec gst-launch-1.0 -q {pipeline}"));
|
||||
// Dies with us, so no stray player keeps the RTP port.
|
||||
// SAFETY: prctl is async-signal-safe.
|
||||
unsafe {
|
||||
use std::os::unix::process::CommandExt;
|
||||
std_cmd.pre_exec(|| {
|
||||
libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGTERM);
|
||||
Ok(())
|
||||
});
|
||||
}
|
||||
let mut cmd = tokio::process::Command::from(std_cmd);
|
||||
cmd.stdin(Stdio::null()).stdout(Stdio::null()).kill_on_drop(true);
|
||||
cmd.spawn().context("starting gst-launch-1.0 (gstreamer1.0-tools)")
|
||||
}
|
||||
42
crates/sf-miracast/src/main.rs
Normal file
42
crates/sf-miracast/src/main.rs
Normal file
@@ -0,0 +1,42 @@
|
||||
#![cfg_attr(not(target_os = "linux"), allow(dead_code))]
|
||||
//! sf-miracast: experimental Miracast (Wi-Fi Display) sink.
|
||||
//!
|
||||
//! 1. Registers the TV as a Wi-Fi Display sink with iwd and keeps P2P
|
||||
//! discovery on, so phones list "Fennec OS" under Smart View / Cast screen.
|
||||
//! 2. iwd doesn't accept incoming P2P connections; it answers "try later"
|
||||
//! and the phone waits for us to connect. So when a phone that is looking
|
||||
//! for a screen (a WFD source peer) shows up, we connect to it.
|
||||
//! 3. Over the P2P link we talk WFD RTSP with the phone (`rtsp`) and play
|
||||
//! the MPEG-TS/RTP stream with GStreamer (`gst-launch-1.0`, VA-API).
|
||||
//!
|
||||
//! sf-core reads `SF-EVENT connected <name>` / `SF-EVENT ended` from stdout.
|
||||
|
||||
mod rtsp;
|
||||
|
||||
#[cfg(target_os = "linux")]
|
||||
mod linux;
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
// zbus logs every D-Bus handshake at info level; keep that out of the session log.
|
||||
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info"))
|
||||
.filter_module("zbus", log::LevelFilter::Warn)
|
||||
.filter_module("tracing", log::LevelFilter::Warn)
|
||||
.init();
|
||||
let mut name = "Fennec OS".to_string();
|
||||
let mut args = std::env::args().skip(1);
|
||||
while let Some(a) = args.next() {
|
||||
match a.as_str() {
|
||||
"--name" => name = args.next().unwrap_or(name),
|
||||
other => log::warn!("unknown argument {other}"),
|
||||
}
|
||||
}
|
||||
#[cfg(target_os = "linux")]
|
||||
{
|
||||
linux::run(name)
|
||||
}
|
||||
#[cfg(not(target_os = "linux"))]
|
||||
{
|
||||
let _ = name;
|
||||
anyhow::bail!("sf-miracast needs Linux (iwd + GStreamer)")
|
||||
}
|
||||
}
|
||||
296
crates/sf-miracast/src/rtsp.rs
Normal file
296
crates/sf-miracast/src/rtsp.rs
Normal file
@@ -0,0 +1,296 @@
|
||||
//! Wi-Fi Display (Miracast) RTSP, sink side. The phone (source) runs the
|
||||
//! RTSP server; we connect and answer its capability questions (M1–M4), it
|
||||
//! triggers SETUP/PLAY (M5–M7), keeps the session alive (M16) and finally
|
||||
//! asks for TEARDOWN. The stream itself is MPEG-TS over RTP to `rtp_port`.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
/// Default WFD RTSP port of the source.
|
||||
pub const SOURCE_PORT: u16 = 7236;
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Start {
|
||||
Request { method: String, uri: String },
|
||||
Response { status: u16 },
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Message {
|
||||
pub start: Start,
|
||||
pub headers: Vec<(String, String)>,
|
||||
pub body: String,
|
||||
}
|
||||
|
||||
impl Message {
|
||||
pub fn request(method: &str, uri: &str, cseq: u32) -> Self {
|
||||
Message {
|
||||
start: Start::Request { method: method.into(), uri: uri.into() },
|
||||
headers: vec![("CSeq".into(), cseq.to_string())],
|
||||
body: String::new(),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn response(status: u16, cseq: &str) -> Self {
|
||||
Message { start: Start::Response { status }, headers: vec![("CSeq".into(), cseq.into())], body: String::new() }
|
||||
}
|
||||
|
||||
pub fn header(&self, name: &str) -> Option<&str> {
|
||||
self.headers.iter().find(|(k, _)| k.eq_ignore_ascii_case(name)).map(|(_, v)| v.as_str())
|
||||
}
|
||||
|
||||
fn with(mut self, k: &str, v: impl Into<String>) -> Self {
|
||||
self.headers.push((k.into(), v.into()));
|
||||
self
|
||||
}
|
||||
|
||||
fn with_body(mut self, body: String) -> Self {
|
||||
self.body = body;
|
||||
self
|
||||
}
|
||||
|
||||
pub fn to_bytes(&self) -> Vec<u8> {
|
||||
let mut out = match &self.start {
|
||||
Start::Request { method, uri } => format!("{method} {uri} RTSP/1.0\r\n"),
|
||||
Start::Response { status } => format!("RTSP/1.0 {status} {}\r\n", if *status == 200 { "OK" } else { "Error" }),
|
||||
};
|
||||
for (k, v) in &self.headers {
|
||||
out.push_str(&format!("{k}: {v}\r\n"));
|
||||
}
|
||||
if !self.body.is_empty() {
|
||||
out.push_str("Content-Type: text/parameters\r\n");
|
||||
out.push_str(&format!("Content-Length: {}\r\n", self.body.len()));
|
||||
}
|
||||
out.push_str("\r\n");
|
||||
out.push_str(&self.body);
|
||||
out.into_bytes()
|
||||
}
|
||||
|
||||
/// Parses one message from the front of `buf`; returns it and the bytes used.
|
||||
pub fn parse(buf: &[u8]) -> Option<(Message, usize)> {
|
||||
let head_end = buf.windows(4).position(|w| w == b"\r\n\r\n")?;
|
||||
let head = std::str::from_utf8(&buf[..head_end]).ok()?;
|
||||
let mut lines = head.split("\r\n");
|
||||
let first = lines.next()?;
|
||||
let start = if let Some(rest) = first.strip_prefix("RTSP/1.0 ") {
|
||||
Start::Response { status: rest.split(' ').next()?.parse().ok()? }
|
||||
} else {
|
||||
let mut p = first.split(' ');
|
||||
Start::Request { method: p.next()?.to_string(), uri: p.next()?.to_string() }
|
||||
};
|
||||
let headers: Vec<(String, String)> = lines
|
||||
.filter_map(|l| l.split_once(':'))
|
||||
.map(|(k, v)| (k.trim().to_string(), v.trim().to_string()))
|
||||
.collect();
|
||||
let len: usize = headers
|
||||
.iter()
|
||||
.find(|(k, _)| k.eq_ignore_ascii_case("content-length"))
|
||||
.and_then(|(_, v)| v.parse().ok())
|
||||
.unwrap_or(0);
|
||||
let total = head_end + 4 + len;
|
||||
if buf.len() < total {
|
||||
return None;
|
||||
}
|
||||
let body = String::from_utf8_lossy(&buf[head_end + 4..total]).into_owned();
|
||||
Some((Message { start, headers, body }, total))
|
||||
}
|
||||
}
|
||||
|
||||
/// `name: value` lines of a text/parameters body.
|
||||
pub fn parse_params(body: &str) -> Vec<(String, String)> {
|
||||
body.lines()
|
||||
.filter_map(|l| {
|
||||
let l = l.trim();
|
||||
if l.is_empty() {
|
||||
return None;
|
||||
}
|
||||
Some(match l.split_once(':') {
|
||||
Some((k, v)) => (k.trim().to_string(), v.trim().to_string()),
|
||||
None => (l.to_string(), String::new()),
|
||||
})
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Event {
|
||||
/// PLAY accepted: the stream is coming.
|
||||
Playing,
|
||||
Paused,
|
||||
/// The source ended the session.
|
||||
Teardown,
|
||||
}
|
||||
|
||||
/// The sink's side of one WFD session.
|
||||
pub struct Sink {
|
||||
cseq: u32,
|
||||
pending: HashMap<u32, String>,
|
||||
rtp_port: u16,
|
||||
presentation_url: Option<String>,
|
||||
session: Option<String>,
|
||||
}
|
||||
|
||||
impl Sink {
|
||||
pub fn new(rtp_port: u16) -> Self {
|
||||
Sink { cseq: 0, pending: HashMap::new(), rtp_port, presentation_url: None, session: None }
|
||||
}
|
||||
|
||||
fn next_request(&mut self, method: &str, uri: &str) -> Message {
|
||||
self.cseq += 1;
|
||||
self.pending.insert(self.cseq, method.to_string());
|
||||
let mut m = Message::request(method, uri, self.cseq);
|
||||
if let Some(s) = &self.session {
|
||||
m = m.with("Session", s.clone());
|
||||
}
|
||||
m
|
||||
}
|
||||
|
||||
/// What we can play. H.264 CBP/CHP up to 1080p (VA-API decodes it), AAC and LPCM audio.
|
||||
fn capability(&self, name: &str) -> String {
|
||||
match name {
|
||||
"wfd_video_formats" => "00 00 03 10 0001ffff 1fffffff 00001fff 00 0000 0000 00 none none".into(),
|
||||
"wfd_audio_codecs" => "LPCM 00000003 00, AAC 00000007 00".into(),
|
||||
"wfd_client_rtp_ports" => format!("RTP/AVP/UDP;unicast {} 0 mode=play", self.rtp_port),
|
||||
"wfd_content_protection" | "wfd_display_edid" | "wfd_coupled_sink" | "wfd_uibc_capability" => "none".into(),
|
||||
"wfd_connector_type" => "05".into(),
|
||||
"wfd_standby_resume_capability" => "none".into(),
|
||||
_ => "none".into(),
|
||||
}
|
||||
}
|
||||
|
||||
fn url(&self) -> String {
|
||||
self.presentation_url.clone().unwrap_or_else(|| "rtsp://localhost/wfd1.0/streamid=0".into())
|
||||
}
|
||||
|
||||
/// Handles one message from the source; returns what to send back and
|
||||
/// what happened.
|
||||
pub fn handle(&mut self, msg: &Message) -> (Vec<Message>, Vec<Event>) {
|
||||
let mut out = vec![];
|
||||
let mut events = vec![];
|
||||
let cseq = msg.header("CSeq").unwrap_or("0").to_string();
|
||||
match &msg.start {
|
||||
Start::Request { method, .. } => match method.as_str() {
|
||||
// M1: the source asks what we support; then we ask it (M2).
|
||||
"OPTIONS" => {
|
||||
out.push(Message::response(200, &cseq).with("Public", "org.wfa.wfd1.0, GET_PARAMETER, SET_PARAMETER"));
|
||||
out.push(self.next_request("OPTIONS", "*").with("Require", "org.wfa.wfd1.0"));
|
||||
}
|
||||
// M3 (capabilities) or M16 (keep-alive, empty body).
|
||||
"GET_PARAMETER" => {
|
||||
let body: String = parse_params(&msg.body)
|
||||
.into_iter()
|
||||
.map(|(k, _)| format!("{k}: {}\r\n", self.capability(&k)))
|
||||
.collect();
|
||||
out.push(Message::response(200, &cseq).with_body(body));
|
||||
}
|
||||
// M4 (chosen formats, presentation URL) or M5 (trigger).
|
||||
"SET_PARAMETER" => {
|
||||
out.push(Message::response(200, &cseq));
|
||||
for (k, v) in parse_params(&msg.body) {
|
||||
match k.as_str() {
|
||||
"wfd_presentation_URL" => {
|
||||
self.presentation_url = v.split_whitespace().next().map(str::to_string);
|
||||
}
|
||||
"wfd_trigger_method" => match v.as_str() {
|
||||
"SETUP" => {
|
||||
let req = self.next_request("SETUP", &self.url()).with(
|
||||
"Transport",
|
||||
format!("RTP/AVP/UDP;unicast;client_port={}", self.rtp_port),
|
||||
);
|
||||
out.push(req);
|
||||
}
|
||||
"PLAY" => out.push(self.next_request("PLAY", &self.url())),
|
||||
"PAUSE" => out.push(self.next_request("PAUSE", &self.url())),
|
||||
"TEARDOWN" => {
|
||||
out.push(self.next_request("TEARDOWN", &self.url()));
|
||||
events.push(Event::Teardown);
|
||||
}
|
||||
_ => {}
|
||||
},
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => out.push(Message::response(501, &cseq)),
|
||||
},
|
||||
Start::Response { status } => {
|
||||
let method = msg.header("CSeq").and_then(|c| c.parse().ok()).and_then(|c: u32| self.pending.remove(&c));
|
||||
match (method.as_deref(), *status) {
|
||||
(Some("SETUP"), 200) => {
|
||||
self.session = msg.header("Session").map(|s| s.split(';').next().unwrap_or(s).trim().to_string());
|
||||
out.push(self.next_request("PLAY", &self.url()));
|
||||
}
|
||||
(Some("PLAY"), 200) => events.push(Event::Playing),
|
||||
(Some("PAUSE"), 200) => events.push(Event::Paused),
|
||||
(Some(m), s) if s != 200 => log::warn!("rtsp: {m} failed with {s}"),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
(out, events)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn req(text: &str) -> Message {
|
||||
Message::parse(text.as_bytes()).unwrap().0
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_with_body() {
|
||||
let raw = b"GET_PARAMETER rtsp://localhost/wfd1.0 RTSP/1.0\r\nCSeq: 2\r\nContent-Length: 19\r\n\r\nwfd_video_formats\r\nextra";
|
||||
let (m, used) = Message::parse(raw).unwrap();
|
||||
assert_eq!(m.body, "wfd_video_formats\r\n");
|
||||
assert_eq!(used, raw.len() - 5);
|
||||
assert!(Message::parse(b"OPTIONS * RTSP/1.0\r\nCSeq: 1\r\n").is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn full_session() {
|
||||
let mut sink = Sink::new(1028);
|
||||
// M1 -> 200 + our M2
|
||||
let (out, _) = sink.handle(&req("OPTIONS * RTSP/1.0\r\nCSeq: 1\r\nRequire: org.wfa.wfd1.0\r\n\r\n"));
|
||||
assert_eq!(out.len(), 2);
|
||||
assert!(matches!(out[1].start, Start::Request { ref method, .. } if method == "OPTIONS"));
|
||||
// M3
|
||||
let body = "wfd_video_formats\r\nwfd_client_rtp_ports\r\nwfd_audio_codecs\r\n";
|
||||
let (out, _) = sink.handle(&req(&format!(
|
||||
"GET_PARAMETER rtsp://localhost/wfd1.0 RTSP/1.0\r\nCSeq: 2\r\nContent-Length: {}\r\n\r\n{body}",
|
||||
body.len()
|
||||
)));
|
||||
assert!(out[0].body.contains("wfd_client_rtp_ports: RTP/AVP/UDP;unicast 1028 0 mode=play\r\n"));
|
||||
// M4
|
||||
let body = "wfd_presentation_URL: rtsp://192.168.49.1/wfd1.0/streamid=0 none\r\n";
|
||||
sink.handle(&req(&format!(
|
||||
"SET_PARAMETER rtsp://localhost/wfd1.0 RTSP/1.0\r\nCSeq: 3\r\nContent-Length: {}\r\n\r\n{body}",
|
||||
body.len()
|
||||
)));
|
||||
// M5 SETUP trigger -> our M6
|
||||
let body = "wfd_trigger_method: SETUP\r\n";
|
||||
let (out, _) = sink.handle(&req(&format!(
|
||||
"SET_PARAMETER rtsp://localhost/wfd1.0 RTSP/1.0\r\nCSeq: 4\r\nContent-Length: {}\r\n\r\n{body}",
|
||||
body.len()
|
||||
)));
|
||||
let setup = &out[1];
|
||||
assert_eq!(setup.start, Start::Request { method: "SETUP".into(), uri: "rtsp://192.168.49.1/wfd1.0/streamid=0".into() });
|
||||
let setup_cseq = setup.header("CSeq").unwrap().to_string();
|
||||
// SETUP reply -> PLAY with session
|
||||
let (out, _) = sink.handle(&req(&format!("RTSP/1.0 200 OK\r\nCSeq: {setup_cseq}\r\nSession: 6B8B4567;timeout=30\r\n\r\n")));
|
||||
assert_eq!(out[0].header("Session"), Some("6B8B4567"));
|
||||
let play_cseq = out[0].header("CSeq").unwrap().to_string();
|
||||
let (_, ev) = sink.handle(&req(&format!("RTSP/1.0 200 OK\r\nCSeq: {play_cseq}\r\nSession: 6B8B4567\r\n\r\n")));
|
||||
assert_eq!(ev, vec![Event::Playing]);
|
||||
// M16 keep-alive
|
||||
let (out, _) = sink.handle(&req("GET_PARAMETER rtsp://localhost/wfd1.0 RTSP/1.0\r\nCSeq: 9\r\n\r\n"));
|
||||
assert_eq!(out[0].start, Start::Response { status: 200 });
|
||||
// Teardown trigger
|
||||
let body = "wfd_trigger_method: TEARDOWN\r\n";
|
||||
let (_, ev) = sink.handle(&req(&format!(
|
||||
"SET_PARAMETER rtsp://localhost/wfd1.0 RTSP/1.0\r\nCSeq: 10\r\nContent-Length: {}\r\n\r\n{body}",
|
||||
body.len()
|
||||
)));
|
||||
assert_eq!(ev, vec![Event::Teardown]);
|
||||
}
|
||||
}
|
||||
14
crates/sf-pack/Cargo.toml
Normal file
14
crates/sf-pack/Cargo.toml
Normal file
@@ -0,0 +1,14 @@
|
||||
[package]
|
||||
name = "sf-pack"
|
||||
description = "Fennec OS store app packaging (docs/store.md)"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
[dependencies]
|
||||
sf-ipc.workspace = true
|
||||
anyhow.workspace = true
|
||||
serde.workspace = true
|
||||
toml.workspace = true
|
||||
tar = "0.4"
|
||||
ruzstd = "0.8"
|
||||
220
crates/sf-pack/src/main.rs
Normal file
220
crates/sf-pack/src/main.rs
Normal file
@@ -0,0 +1,220 @@
|
||||
//! sf-pack: builds Fennec OS store packages (docs/store.md).
|
||||
//!
|
||||
//! sf-pack build <app-dir> [out-dir] app.toml + <id>-<version>.tar.zst
|
||||
//! sf-pack verify <out-dir> checks what `build` made
|
||||
//! sf-pack run <app-dir> runs the app the way the TV does: in the
|
||||
//! store sandbox (Linux, needs bwrap)
|
||||
//!
|
||||
//! The two files in out-dir are the release assets: upload them to a
|
||||
//! release of the app's repo (GitHub, Gitea or GitLab).
|
||||
|
||||
use std::io::Read;
|
||||
use std::path::{Path, PathBuf};
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use sf_ipc::AppManifest;
|
||||
|
||||
fn main() {
|
||||
let args: Vec<String> = std::env::args().skip(1).collect();
|
||||
if let Err(e) = run(&args) {
|
||||
eprintln!("sf-pack: {e:#}");
|
||||
std::process::exit(1);
|
||||
}
|
||||
}
|
||||
|
||||
fn run(args: &[String]) -> Result<()> {
|
||||
let arg = |i: usize| args.get(i).map(String::as_str);
|
||||
match arg(0) {
|
||||
Some("build") => {
|
||||
let dir = arg(1).context("usage: sf-pack build <app-dir> [out-dir]")?;
|
||||
build(Path::new(dir), Path::new(arg(2).unwrap_or("dist")))
|
||||
}
|
||||
Some("verify") => verify(Path::new(arg(1).unwrap_or("dist"))),
|
||||
Some("run") => run_app(Path::new(arg(1).context("usage: sf-pack run <app-dir>")?)),
|
||||
_ => bail!("usage: sf-pack build <app-dir> [out-dir] | verify [out-dir] | run <app-dir>"),
|
||||
}
|
||||
}
|
||||
|
||||
fn read_manifest(dir: &Path) -> Result<AppManifest> {
|
||||
let path = dir.join("app.toml");
|
||||
let text = std::fs::read_to_string(&path).with_context(|| format!("reading {}", path.display()))?;
|
||||
let mut app: AppManifest = toml::from_str(&text).with_context(|| format!("parsing {}", path.display()))?;
|
||||
app.dir = dir.to_path_buf();
|
||||
Ok(app)
|
||||
}
|
||||
|
||||
fn is_release(v: &str) -> bool {
|
||||
!v.is_empty() && v.split('.').count() <= 4 && v.split('.').all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit()))
|
||||
}
|
||||
|
||||
fn build(dir: &Path, out: &Path) -> Result<()> {
|
||||
let app = read_manifest(dir)?;
|
||||
app.check_store_rules().context("app.toml")?;
|
||||
if !is_release(&app.version) {
|
||||
bail!("version {:?} must be a release version like 1.2.3", app.version);
|
||||
}
|
||||
if app.icon.contains('.') && app.icon_file().is_none() {
|
||||
bail!("icon {} is missing from {}", app.icon, dir.display());
|
||||
}
|
||||
if let Some(exe) = app.resolved_exec(Path::new("/app")).first().and_then(|p| p.strip_prefix("/app/")) {
|
||||
let path = dir.join(exe);
|
||||
if !path.is_file() {
|
||||
bail!("exec {} is missing from {}", exe, dir.display());
|
||||
}
|
||||
check_executable(&path)?;
|
||||
}
|
||||
|
||||
std::fs::create_dir_all(out)?;
|
||||
let file = format!("{}-{}.tar.zst", app.id, app.version);
|
||||
let tar = pack_tar(dir, &app)?;
|
||||
let zst = ruzstd::encoding::compress_to_vec(&tar[..], ruzstd::encoding::CompressionLevel::Fastest);
|
||||
std::fs::write(out.join(&file), &zst)?;
|
||||
std::fs::copy(dir.join("app.toml"), out.join("app.toml"))?;
|
||||
println!("{}: {} ({} KiB)", app.id, out.join(&file).display(), zst.len() / 1024);
|
||||
println!("Release assets: app.toml, {file}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn check_executable(path: &Path) -> Result<()> {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
if std::fs::metadata(path)?.permissions().mode() & 0o111 == 0 {
|
||||
bail!("{} is not executable (chmod +x)", path.display());
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn check_executable(_path: &Path) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The package: the app folder plus pkg.toml, reproducible (sorted, no
|
||||
/// owners, fixed time).
|
||||
fn pack_tar(dir: &Path, app: &AppManifest) -> Result<Vec<u8>> {
|
||||
let mut files = Vec::new();
|
||||
collect(dir, Path::new(""), &mut files)?;
|
||||
files.sort();
|
||||
let mut b = tar::Builder::new(Vec::new());
|
||||
b.follow_symlinks(false);
|
||||
let pkg = format!("name = \"{}\"\nversion = \"{}\"\n", app.id, app.version);
|
||||
let mut h = header(tar::EntryType::Regular, 0o644, pkg.len() as u64);
|
||||
b.append_data(&mut h, "pkg.toml", pkg.as_bytes())?;
|
||||
for rel in files {
|
||||
let path = dir.join(&rel);
|
||||
let meta = std::fs::symlink_metadata(&path)?;
|
||||
let mode = file_mode(&meta);
|
||||
if meta.file_type().is_symlink() {
|
||||
let mut h = header(tar::EntryType::Symlink, 0o777, 0);
|
||||
b.append_link(&mut h, &rel, std::fs::read_link(&path)?)?;
|
||||
} else if meta.is_dir() {
|
||||
let mut h = header(tar::EntryType::Directory, 0o755, 0);
|
||||
b.append_data(&mut h, &rel, std::io::empty())?;
|
||||
} else {
|
||||
// Windows has no x bit: whatever is under bin/ is executable.
|
||||
let exec = mode & 0o111 != 0 || rel.starts_with("bin");
|
||||
let mut h = header(tar::EntryType::Regular, if exec { 0o755 } else { 0o644 }, meta.len());
|
||||
b.append_data(&mut h, &rel, std::fs::File::open(&path)?)?;
|
||||
}
|
||||
}
|
||||
Ok(b.into_inner()?)
|
||||
}
|
||||
|
||||
fn header(kind: tar::EntryType, mode: u32, size: u64) -> tar::Header {
|
||||
let mut h = tar::Header::new_gnu();
|
||||
h.set_entry_type(kind);
|
||||
h.set_mode(mode);
|
||||
h.set_size(size);
|
||||
h.set_mtime(0);
|
||||
h.set_uid(0);
|
||||
h.set_gid(0);
|
||||
h
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
fn file_mode(meta: &std::fs::Metadata) -> u32 {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
meta.permissions().mode()
|
||||
}
|
||||
|
||||
/// On Windows nothing is executable; binaries under bin/ are.
|
||||
#[cfg(not(unix))]
|
||||
fn file_mode(_meta: &std::fs::Metadata) -> u32 {
|
||||
0o644
|
||||
}
|
||||
|
||||
fn collect(root: &Path, rel: &Path, out: &mut Vec<PathBuf>) -> Result<()> {
|
||||
for e in std::fs::read_dir(root.join(rel))? {
|
||||
let e = e?;
|
||||
let name = e.file_name();
|
||||
if name == "pkg.toml" && rel.as_os_str().is_empty() {
|
||||
continue;
|
||||
}
|
||||
let r = rel.join(&name);
|
||||
out.push(r.clone());
|
||||
if e.file_type()?.is_dir() {
|
||||
collect(root, &r, out)?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn verify(out: &Path) -> Result<()> {
|
||||
let app = read_manifest(out)?;
|
||||
app.check_store_rules()?;
|
||||
let file = out.join(format!("{}-{}.tar.zst", app.id, app.version));
|
||||
let data = std::fs::read(&file).with_context(|| format!("reading {}", file.display()))?;
|
||||
let mut tar = Vec::new();
|
||||
ruzstd::decoding::StreamingDecoder::new(&data[..]).map_err(|e| anyhow::anyhow!("zstd: {e}"))?.read_to_end(&mut tar)?;
|
||||
let mut archive = tar::Archive::new(&tar[..]);
|
||||
let names: Vec<String> = archive.entries()?.filter_map(|e| e.ok()?.path().ok().map(|p| p.to_string_lossy().into_owned())).collect();
|
||||
if !names.iter().any(|n| n == "pkg.toml") || !names.iter().any(|n| n == "app.toml") {
|
||||
bail!("pkg.toml or app.toml missing from the package");
|
||||
}
|
||||
println!("{} {}: package OK, {} files", app.id, app.version, names.len());
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn builds_and_verifies() {
|
||||
let tmp = std::env::temp_dir().join(format!("sf-pack-test-{}", std::process::id()));
|
||||
let app = tmp.join("app");
|
||||
std::fs::create_dir_all(app.join("bin")).unwrap();
|
||||
std::fs::write(
|
||||
app.join("app.toml"),
|
||||
"id = \"io.github.fox.hello\"\nname = \"Hello\"\nversion = \"1.2.3\"\nkind = \"exec\"\nexec = [\"bin/hello\"]\n",
|
||||
)
|
||||
.unwrap();
|
||||
std::fs::write(app.join("bin/hello"), "#!/bin/sh\necho hi\n").unwrap();
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
std::fs::set_permissions(app.join("bin/hello"), std::fs::Permissions::from_mode(0o755)).unwrap();
|
||||
}
|
||||
let out = tmp.join("dist");
|
||||
build(&app, &out).unwrap();
|
||||
verify(&out).unwrap();
|
||||
std::fs::remove_dir_all(&tmp).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs an app folder as a store app: same sandbox, same permissions.
|
||||
fn run_app(dir: &Path) -> Result<()> {
|
||||
let mut app = read_manifest(dir)?;
|
||||
app.check_store_rules().context("app.toml")?;
|
||||
app.origin = sf_ipc::Origin::Store;
|
||||
let settings = sf_ipc::Settings::default();
|
||||
let data = std::env::temp_dir().join("sf-pack-run");
|
||||
let opts = sf_ipc::launch::LaunchOptions { data_dir: &data, fullscreen: false, bounds: None, query: None };
|
||||
let mut cmd = sf_ipc::launch::command(&app, &settings, &opts)?;
|
||||
eprintln!("data folder ($HOME inside): {}", sf_ipc::paths::app_data_dir(&app.id).display());
|
||||
if std::env::var_os("SF_PACK_SHOW").is_some() {
|
||||
eprintln!("{} {}", cmd.get_program().to_string_lossy(), cmd.get_args().map(|a| a.to_string_lossy()).collect::<Vec<_>>().join(" "));
|
||||
}
|
||||
let status = cmd.status().context("starting the app")?;
|
||||
std::process::exit(status.code().unwrap_or(1));
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "sf-remote"
|
||||
description = "SmartFox Apple Siri Remote driver: BLE GATT -> uinput keys + touch gestures"
|
||||
description = "Fennec OS Apple Siri Remote driver: BLE GATT -> uinput keys + touch gestures"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
|
||||
@@ -13,7 +13,7 @@ use evdev::{EventType, KeyCode};
|
||||
use crate::link::Link;
|
||||
|
||||
const ESC_HOLD: Duration = Duration::from_millis(800);
|
||||
const OWN_DEVICE: &str = "SmartFox Siri Remote";
|
||||
const OWN_DEVICE: &str = "Fennec OS Siri Remote";
|
||||
|
||||
pub fn spawn(link: Link) {
|
||||
std::thread::spawn(move || {
|
||||
|
||||
@@ -99,7 +99,7 @@ impl Keys {
|
||||
keys.insert(KeyCode::KEY_PAUSECD);
|
||||
let dev = VirtualDevice::builder()
|
||||
.context("opening /dev/uinput (is the user in the smartfox group?)")?
|
||||
.name("SmartFox Siri Remote")
|
||||
.name("Fennec OS Siri Remote")
|
||||
.with_keys(&keys)?
|
||||
.build()?;
|
||||
Ok(Self { dev: Some(dev) })
|
||||
@@ -244,6 +244,9 @@ async fn wake_target(adapter: &Adapter, dev: &Device) -> Option<wake::Target> {
|
||||
|
||||
/// Handles one connection until the remote disconnects.
|
||||
async fn serve(dev: &Device, keys: &mut Keys, step: i32, link: &Link) -> Result<()> {
|
||||
use bluer::{DeviceEvent, DeviceProperty};
|
||||
|
||||
let mut events = dev.events().await?;
|
||||
let mut reports = futures::stream::select_all(subscribe(dev).await?);
|
||||
let mut gestures = Gestures::new(step);
|
||||
let mut held: u16 = 0;
|
||||
@@ -253,9 +256,20 @@ async fn serve(dev: &Device, keys: &mut Keys, step: i32, link: &Link) -> Result<
|
||||
let mut held_since = Instant::now();
|
||||
let mut last_repeat = Instant::now();
|
||||
let mut tick = tokio::time::interval(Duration::from_millis(20));
|
||||
let mut connection_check = tokio::time::interval(Duration::from_secs(2));
|
||||
|
||||
loop {
|
||||
tokio::select! {
|
||||
event = events.next() => match event {
|
||||
Some(DeviceEvent::PropertyChanged(DeviceProperty::Connected(false))) | None => return Ok(()),
|
||||
Some(_) => {}
|
||||
},
|
||||
_ = connection_check.tick() => {
|
||||
// Notification streams can stay open after the GATT link goes away.
|
||||
if !dev.is_connected().await.unwrap_or(false) {
|
||||
return Ok(());
|
||||
}
|
||||
}
|
||||
item = reports.next() => {
|
||||
let Some(data) = item else { return Ok(()) };
|
||||
match protocol::parse(&data) {
|
||||
@@ -319,13 +333,16 @@ async fn serve(dev: &Device, keys: &mut Keys, step: i32, link: &Link) -> Result<
|
||||
}
|
||||
}
|
||||
|
||||
/// The remote advertises with a rotating private address. The controller's
|
||||
/// accept list only knows its identity address, so BlueZ's passive
|
||||
/// auto-connect never sees it. An active scan lets the kernel resolve the
|
||||
/// address with the bonded IRK; we connect as soon as an advert arrives.
|
||||
async fn wait_for_advert(adapter: &Adapter, dev: &Device) -> Result<()> {
|
||||
/// The remote advertises with a rotating private address. Keep discovery
|
||||
/// active while connecting so BlueZ can resolve that address with the bonded
|
||||
/// IRK. Also retry without an RSSI event: some controllers do not report one
|
||||
/// for an already known device after the remote restarts.
|
||||
async fn connect(adapter: &Adapter, dev: &Device) -> Result<bool> {
|
||||
use bluer::{DeviceEvent, DeviceProperty, DiscoveryFilter, DiscoveryTransport};
|
||||
|
||||
if dev.is_connected().await.unwrap_or(false) {
|
||||
return Ok(true);
|
||||
}
|
||||
adapter
|
||||
.set_discovery_filter(DiscoveryFilter {
|
||||
transport: DiscoveryTransport::Le,
|
||||
@@ -335,30 +352,48 @@ async fn wait_for_advert(adapter: &Adapter, dev: &Device) -> Result<()> {
|
||||
.await?;
|
||||
let mut discovery = adapter.discover_devices_with_changes().await?;
|
||||
let mut events = dev.events().await?;
|
||||
let mut recheck = tokio::time::interval(Duration::from_secs(2));
|
||||
let mut retry = tokio::time::interval(Duration::from_secs(5));
|
||||
retry.reset();
|
||||
loop {
|
||||
tokio::select! {
|
||||
// A connection may come up between our checks (e.g. a pending Connect()).
|
||||
_ = recheck.tick() => {
|
||||
if dev.is_connected().await.unwrap_or(false) {
|
||||
return Ok(());
|
||||
}
|
||||
// Removed in the launcher's settings: go back to pairing.
|
||||
if !dev.is_paired().await.unwrap_or(false) {
|
||||
anyhow::bail!("remote {} was unpaired", dev.address());
|
||||
}
|
||||
}
|
||||
let should_connect = tokio::select! {
|
||||
_ = retry.tick() => true,
|
||||
ev = events.next() => match ev {
|
||||
Some(DeviceEvent::PropertyChanged(DeviceProperty::Rssi(rssi))) => {
|
||||
log::info!("remote advertising (rssi {rssi}), connecting");
|
||||
return Ok(());
|
||||
true
|
||||
}
|
||||
Some(DeviceEvent::PropertyChanged(DeviceProperty::Connected(true))) => return Ok(()),
|
||||
Some(_) => {}
|
||||
Some(DeviceEvent::PropertyChanged(DeviceProperty::Connected(true))) => return Ok(true),
|
||||
Some(_) => false,
|
||||
None => anyhow::bail!("device event stream ended"),
|
||||
},
|
||||
// Keep the discovery session alive and drained.
|
||||
_ = discovery.next() => {}
|
||||
event = discovery.next() => {
|
||||
if event.is_none() {
|
||||
anyhow::bail!("discovery ended");
|
||||
}
|
||||
false
|
||||
}
|
||||
};
|
||||
if !should_connect {
|
||||
continue;
|
||||
}
|
||||
if dev.is_connected().await.unwrap_or(false) {
|
||||
return Ok(true);
|
||||
}
|
||||
// Removed in the launcher's settings: go back to pairing.
|
||||
if !dev.is_paired().await.unwrap_or(false) {
|
||||
anyhow::bail!("remote {} was unpaired", dev.address());
|
||||
}
|
||||
match tokio::time::timeout(Duration::from_secs(10), dev.connect()).await {
|
||||
Ok(Ok(())) => return Ok(true),
|
||||
Ok(Err(e)) if e.kind == bluer::ErrorKind::InProgress => {
|
||||
tokio::time::sleep(Duration::from_secs(2)).await;
|
||||
}
|
||||
Ok(Err(e)) => log::debug!("connect: {e}"),
|
||||
Err(_) => log::debug!("connect timed out"),
|
||||
}
|
||||
if dev.is_connected().await.unwrap_or(false) {
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -426,31 +461,6 @@ async fn pair_new(adapter: &Adapter, link: &Link) -> Result<Device> {
|
||||
}
|
||||
}
|
||||
|
||||
async fn connect(adapter: &Adapter, dev: &Device) -> Result<bool> {
|
||||
if dev.is_connected().await.unwrap_or(false) {
|
||||
return Ok(true);
|
||||
}
|
||||
wait_for_advert(adapter, dev).await?;
|
||||
if dev.is_connected().await.unwrap_or(false) {
|
||||
return Ok(true);
|
||||
}
|
||||
match tokio::time::timeout(Duration::from_secs(10), dev.connect()).await {
|
||||
Ok(Ok(())) => Ok(true),
|
||||
Ok(Err(e)) if e.kind == bluer::ErrorKind::InProgress => {
|
||||
tokio::time::sleep(Duration::from_secs(2)).await;
|
||||
Ok(false)
|
||||
}
|
||||
Ok(Err(e)) => {
|
||||
log::debug!("connect: {e}");
|
||||
Ok(false)
|
||||
}
|
||||
Err(_) => {
|
||||
log::debug!("connect timed out");
|
||||
Ok(false)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub fn run() -> Result<()> {
|
||||
let opts = parse_args();
|
||||
let link = Link::new(opts.home_socket.clone());
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
#![cfg_attr(not(target_os = "linux"), allow(dead_code))]
|
||||
|
||||
//! sf-remote: Apple Siri Remote driver for SmartFox.
|
||||
//! sf-remote: Apple Siri Remote driver for Fennec OS.
|
||||
//!
|
||||
//! Subscribes to the remote's HID report characteristics over BlueZ D-Bus
|
||||
//! (BlueZ's own HID plugin must be disabled, it drops these reports) and
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
//! on its USB device and the ports above it.
|
||||
//! 2. The kernel keeps scanning for the remote while suspended. It does that
|
||||
//! for devices on its connect list that carry the "remote wakeup" flag.
|
||||
//! BlueZ sets both only through its HID plugins, which SmartFox disables
|
||||
//! BlueZ sets both only through its HID plugins, which Fennec OS disables
|
||||
//! (they drop the Siri Remote's reports), so we send the two management
|
||||
//! commands ourselves: Add Device (auto-connect) and Set Device Flags.
|
||||
//!
|
||||
|
||||
30
crates/sf-ui/Cargo.toml
Normal file
30
crates/sf-ui/Cargo.toml
Normal file
@@ -0,0 +1,30 @@
|
||||
[package]
|
||||
name = "sf-ui"
|
||||
description = "SmartFox TV UI kit: Liquid Glass for Slint apps, TV components, artwork loading, video playback"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
# Slint is used under GPL-3.0 (its royalty-free license does not cover embedded
|
||||
# devices like a TV box), so apps built on sf-ui are GPL-3.0 too.
|
||||
license = "GPL-3.0-only"
|
||||
# Lets the build script of an app read DEP_SF_UI_UI_DIR (the Slint library).
|
||||
links = "sf_ui"
|
||||
build = "build.rs"
|
||||
|
||||
[features]
|
||||
default = ["images"]
|
||||
# Artwork over HTTP(S), decoded and scaled off the UI thread (images::Images).
|
||||
images = ["dep:ureq", "dep:image"]
|
||||
# Video playback with GStreamer (video::Player). Linux; needs GStreamer 1.22+.
|
||||
video = ["dep:gstreamer", "dep:gstreamer-app", "dep:gstreamer-video"]
|
||||
|
||||
[dependencies]
|
||||
anyhow.workspace = true
|
||||
log.workspace = true
|
||||
slint = { version = "1.18", default-features = false, features = ["std", "backend-default", "renderer-femtovg", "compat-1-2", "image-default-formats"] }
|
||||
glow = "0.16"
|
||||
png = "0.18"
|
||||
ureq = { version = "3", optional = true }
|
||||
image = { version = "0.25", optional = true, default-features = false, features = ["jpeg", "png", "webp"] }
|
||||
gstreamer = { version = "0.25", optional = true }
|
||||
gstreamer-app = { version = "0.25", optional = true }
|
||||
gstreamer-video = { version = "0.25", optional = true }
|
||||
7
crates/sf-ui/build.rs
Normal file
7
crates/sf-ui/build.rs
Normal file
@@ -0,0 +1,7 @@
|
||||
// Tells the build scripts of apps that depend on sf-ui where its Slint
|
||||
// library is: they read it as DEP_SF_UI_UI_DIR and map it to "@sf-ui".
|
||||
fn main() {
|
||||
let dir = std::path::Path::new(&std::env::var("CARGO_MANIFEST_DIR").unwrap()).join("ui");
|
||||
println!("cargo:ui_dir={}", dir.display());
|
||||
println!("cargo:rerun-if-changed=build.rs");
|
||||
}
|
||||
21
crates/sf-ui/gallery/Cargo.toml
Normal file
21
crates/sf-ui/gallery/Cargo.toml
Normal file
@@ -0,0 +1,21 @@
|
||||
[package]
|
||||
name = "sf-ui-gallery"
|
||||
description = "Every sf-ui component on one screen (example and visual test)"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license = "GPL-3.0-only"
|
||||
publish = false
|
||||
|
||||
[dependencies]
|
||||
sf-ui = { path = ".." }
|
||||
slint = "1.18"
|
||||
anyhow.workspace = true
|
||||
log.workspace = true
|
||||
env_logger.workspace = true
|
||||
|
||||
[features]
|
||||
# SF_UI_VIDEO=<uri>: plays a video as the backdrop (Linux, GStreamer).
|
||||
video = ["sf-ui/video"]
|
||||
|
||||
[build-dependencies]
|
||||
slint-build = "1.18"
|
||||
7
crates/sf-ui/gallery/build.rs
Normal file
7
crates/sf-ui/gallery/build.rs
Normal file
@@ -0,0 +1,7 @@
|
||||
fn main() {
|
||||
// sf-ui's build script publishes where its Slint library is.
|
||||
let sf_ui = std::env::var("DEP_SF_UI_UI_DIR").expect("sf-ui must be a direct dependency");
|
||||
let config = slint_build::CompilerConfiguration::new()
|
||||
.with_library_paths(std::collections::HashMap::from([("sf-ui".to_string(), sf_ui.into())]));
|
||||
slint_build::compile_with_config("ui/gallery.slint", config).expect("compiling ui/gallery.slint");
|
||||
}
|
||||
101
crates/sf-ui/gallery/src/main.rs
Normal file
101
crates/sf-ui/gallery/src/main.rs
Normal file
@@ -0,0 +1,101 @@
|
||||
//! sf-ui gallery: every component on one screen.
|
||||
//!
|
||||
//! cargo run -p sf-ui-gallery
|
||||
//! SF_UI_SIZE=1920x1080 SF_UI_KEYS="down right" SF_UI_SNAPSHOT=shot.png cargo run -p sf-ui-gallery
|
||||
|
||||
use std::time::Duration;
|
||||
|
||||
use slint::{ComponentHandle, Model, Rgba8Pixel, SharedPixelBuffer, VecModel};
|
||||
|
||||
slint::include_modules!();
|
||||
sf_ui::glue!(Gallery);
|
||||
|
||||
/// Stand-in artwork: a soft two-colour gradient with a light blob.
|
||||
fn artwork(a: [u8; 3], b: [u8; 3], w: u32, h: u32) -> SharedPixelBuffer<Rgba8Pixel> {
|
||||
let mut px = SharedPixelBuffer::<Rgba8Pixel>::new(w, h);
|
||||
let (cw, ch) = (w as f32, h as f32);
|
||||
for (i, p) in px.make_mut_slice().iter_mut().enumerate() {
|
||||
let (x, y) = ((i as u32 % w) as f32 / cw, (i as u32 / w) as f32 / ch);
|
||||
let t = (x * 0.6 + y * 0.4).clamp(0.0, 1.0);
|
||||
let d = ((x - 0.7).powi(2) + (y - 0.3).powi(2)).sqrt();
|
||||
let glow = (1.0 - d * 2.2).max(0.0).powi(2) * 0.55;
|
||||
let c = |k: usize| ((a[k] as f32 * (1.0 - t) + b[k] as f32 * t) * (1.0 - glow) + 255.0 * glow) as u8;
|
||||
*p = Rgba8Pixel { r: c(0), g: c(1), b: c(2), a: 255 };
|
||||
}
|
||||
px
|
||||
}
|
||||
|
||||
fn main() -> anyhow::Result<()> {
|
||||
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
|
||||
sf_ui::init()?;
|
||||
let ui = Gallery::new()?;
|
||||
ui.sf_ui_setup();
|
||||
|
||||
let colours = [
|
||||
([190, 70, 40], [30, 10, 40]),
|
||||
([30, 110, 160], [10, 20, 40]),
|
||||
([60, 140, 80], [10, 30, 20]),
|
||||
([170, 140, 40], [40, 20, 10]),
|
||||
([120, 60, 170], [20, 10, 40]),
|
||||
];
|
||||
let pictures: Vec<SharedPixelBuffer<Rgba8Pixel>> = colours.iter().map(|(a, b)| artwork(*a, *b, 640, 360)).collect();
|
||||
let images: Vec<slint::Image> = pictures.iter().map(|p| slint::Image::from_rgba8(p.clone())).collect();
|
||||
ui.set_art(slint::ModelRc::new(VecModel::from(images)));
|
||||
let weak = ui.as_weak();
|
||||
ui.on_search(move |text| {
|
||||
if let Some(ui) = weak.upgrade() {
|
||||
ui.set_typed(text);
|
||||
}
|
||||
});
|
||||
|
||||
let glass = sf_ui::Glass::install(&ui, |ui, panels| {
|
||||
panels.extend(ui.get_glass().iter());
|
||||
panels.extend(ui.get_glass_menu().iter());
|
||||
panels.extend(ui.get_glass_modal().iter());
|
||||
panels.extend(ui.get_glass_keyboard().iter());
|
||||
})?;
|
||||
glass.set_palette(sf_ui::Palette::from_hex(["#ffb27a", "#8a3d12", "#120805"]));
|
||||
|
||||
// SF_UI_VIDEO=<uri> (feature "video"): the film plays under the glass.
|
||||
#[cfg(feature = "video")]
|
||||
let _video = match std::env::var("SF_UI_VIDEO") {
|
||||
Ok(uri) => {
|
||||
sf_ui::video::init()?;
|
||||
log::info!("hardware decoding: {}", sf_ui::video::hardware_decoding());
|
||||
let player = std::rc::Rc::new(std::cell::RefCell::new(sf_ui::video::Player::new(&uri, Default::default())?));
|
||||
glass.set_video(Some(player.borrow().video()));
|
||||
let p = player.clone();
|
||||
let poll = slint::Timer::default();
|
||||
poll.start(slint::TimerMode::Repeated, Duration::from_millis(100), move || {
|
||||
let mut p = p.borrow_mut();
|
||||
for ev in p.poll() {
|
||||
log::info!("video: {ev:?}");
|
||||
if let sf_ui::video::Event::Ready { .. } = ev {
|
||||
log::info!("audio: {:?}", p.audio_tracks());
|
||||
log::info!("text: {:?}", p.text_tracks());
|
||||
}
|
||||
}
|
||||
});
|
||||
Some((player, poll))
|
||||
}
|
||||
Err(_) => None,
|
||||
};
|
||||
|
||||
// The focused card's artwork becomes the backdrop (crossfades), and the
|
||||
// light follows the focus.
|
||||
let weak = ui.as_weak();
|
||||
let mut shown: Option<usize> = None;
|
||||
let timer = slint::Timer::default();
|
||||
timer.start(slint::TimerMode::Repeated, Duration::from_millis(100), move || {
|
||||
let Some(ui) = weak.upgrade() else { return };
|
||||
let want = (ui.get_area() == 2).then(|| ui.get_card() as usize);
|
||||
if want != shown {
|
||||
shown = want;
|
||||
glass.set_backdrop(want.map(|i| sf_ui::Backdrop::new(pictures[i].clone()).dim(0.2)));
|
||||
}
|
||||
glass.set_light((ui.get_card() as f32 - 2.0) * 0.08);
|
||||
});
|
||||
|
||||
ui.run()?;
|
||||
Ok(())
|
||||
}
|
||||
181
crates/sf-ui/gallery/ui/gallery.slint
Normal file
181
crates/sf-ui/gallery/ui/gallery.slint
Normal file
@@ -0,0 +1,181 @@
|
||||
// sf-ui gallery: every component on one screen. Also the smallest complete
|
||||
// example of an sf-ui app: TvWindow root, one FocusScope that owns the
|
||||
// focus state, glass exported as [GlassRect] arrays for the Rust side.
|
||||
|
||||
import { TvWindow, Tv, SfText, GlassRect, GlassPane, GlassButton, GlassMenu, MenuItem, ProgressBar, ArtworkCard, Spinner, Keyboard, Icon, Headline, Title, Body, Label, Caption, SectionTitle } from "@sf-ui/sf-ui.slint";
|
||||
|
||||
// Rust needs these two globals (sf_ui::glue! wires SfText).
|
||||
export { Tv, SfText }
|
||||
|
||||
export component Gallery inherits TvWindow {
|
||||
title: "sf-ui gallery";
|
||||
forward-focus: keys;
|
||||
|
||||
in property <[image]> art;
|
||||
in-out property <float> progress: 0.36;
|
||||
in property <string> typed;
|
||||
callback search(string);
|
||||
|
||||
// Focus: 0 = buttons, 1 = menu, 2 = cards.
|
||||
in-out property <int> area: 0;
|
||||
in-out property <int> button: 0;
|
||||
in-out property <int> item: 1;
|
||||
in-out property <int> card: 0;
|
||||
in-out property <bool> kb-open;
|
||||
out property <float> kb-t: self.kb-open ? 1 : 0;
|
||||
animate kb-t { duration: 480ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
|
||||
// Content under the keyboard pane goes away completely before it arrives.
|
||||
property <float> dim: max(0, 1 - 1.6 * self.kb-t);
|
||||
|
||||
keys := FocusScope {
|
||||
key-pressed(event) => {
|
||||
if root.kb-open {
|
||||
return kb.key(event);
|
||||
}
|
||||
if event.text == Key.UpArrow {
|
||||
if root.area == 1 { root.item = max(0, root.item - 1); }
|
||||
if root.area == 2 { root.area = 0; }
|
||||
} else if event.text == Key.DownArrow {
|
||||
if root.area == 1 { if root.item < 4 { root.item += 1; } else { root.area = 2; } }
|
||||
if root.area == 0 { root.area = 2; }
|
||||
} else if event.text == Key.LeftArrow {
|
||||
if root.area == 0 { root.button = max(0, root.button - 1); }
|
||||
if root.area == 2 { root.card = max(0, root.card - 1); }
|
||||
if root.area == 1 { root.area = 0; }
|
||||
} else if event.text == Key.RightArrow {
|
||||
if root.area == 0 { if root.button < 2 { root.button += 1; } else { root.area = 1; } }
|
||||
if root.area == 2 { root.card = min(4, root.card + 1); }
|
||||
} else if event.text == Key.Return {
|
||||
if root.area == 0 && root.button == 1 {
|
||||
kb.reset();
|
||||
root.kb-open = true;
|
||||
} else if root.area == 0 && root.button == 0 {
|
||||
root.progress = root.progress > 0.9 ? 0 : root.progress + 0.1;
|
||||
}
|
||||
} else {
|
||||
return reject;
|
||||
}
|
||||
accept
|
||||
}
|
||||
}
|
||||
|
||||
// ---- heading ----
|
||||
Headline {
|
||||
x: Tv.safe-x;
|
||||
y: Tv.safe-y;
|
||||
text: "sf-ui";
|
||||
opacity: root.dim;
|
||||
}
|
||||
Caption {
|
||||
x: Tv.safe-x;
|
||||
y: Tv.safe-y + 72 * Tv.u;
|
||||
text: "Nyilak: mozgás · OK: kiválasztás · Keresés: billentyűzet";
|
||||
opacity: root.dim;
|
||||
}
|
||||
|
||||
// ---- a details pane with buttons ----
|
||||
pane := GlassPane {
|
||||
x: Tv.safe-x;
|
||||
y: 200 * Tv.u;
|
||||
width: 1040 * Tv.u;
|
||||
height: 520 * Tv.u;
|
||||
alpha: root.dim;
|
||||
VerticalLayout {
|
||||
padding: 56 * Tv.u;
|
||||
spacing: 20 * Tv.u;
|
||||
opacity: root.dim;
|
||||
Label { text: "Film · 2024 · 2 ó 16 p"; }
|
||||
Title { text: "A dűne második része"; }
|
||||
Body {
|
||||
text: "Paul Atreides egyesül Chanival és a fremenekkel, miközben bosszút áll a családját elpusztító összeesküvőkön.";
|
||||
vertical-stretch: 1;
|
||||
}
|
||||
HorizontalLayout {
|
||||
spacing: 24 * Tv.u;
|
||||
alignment: start;
|
||||
b0 := GlassButton { text: "Lejátszás"; icon: "play"; primary: true; nested: true; focused: root.area == 0 && root.button == 0; alpha: root.dim; }
|
||||
b1 := GlassButton { text: "Keresés"; icon: "search"; nested: true; focused: root.area == 0 && root.button == 1; alpha: root.dim; }
|
||||
b2 := GlassButton { icon: "plus"; nested: true; focused: root.area == 0 && root.button == 2; alpha: root.dim; }
|
||||
}
|
||||
bar := ProgressBar { value: root.progress; buffered: root.progress + 0.2; alpha: root.dim; }
|
||||
}
|
||||
}
|
||||
|
||||
// ---- a menu ----
|
||||
menu := GlassMenu {
|
||||
x: 1264 * Tv.u;
|
||||
y: 200 * Tv.u;
|
||||
title: "Hang";
|
||||
alpha: root.dim;
|
||||
focused-index: root.area == 1 ? root.item : -1;
|
||||
items: [
|
||||
{ text: "Magyar", detail: "5.1", checked: root.item == 0 },
|
||||
{ text: "Angol", detail: "Atmos", checked: root.item == 1 },
|
||||
{ text: "Angol — Kommentár", detail: "Sztereó", checked: root.item == 2 },
|
||||
{ text: "Német", detail: "5.1", checked: root.item == 3 },
|
||||
{ text: "Francia", detail: "Sztereó", checked: root.item == 4 },
|
||||
];
|
||||
}
|
||||
|
||||
// ---- artwork ----
|
||||
SectionTitle {
|
||||
x: Tv.safe-x;
|
||||
y: 760 * Tv.u;
|
||||
text: root.typed == "" ? "Népszerű" : "Keresés: " + root.typed;
|
||||
opacity: root.dim;
|
||||
}
|
||||
for i in 5: ArtworkCard {
|
||||
x: Tv.safe-x + i * 344 * Tv.u;
|
||||
y: 830 * Tv.u;
|
||||
width: 312 * Tv.u;
|
||||
height: 176 * Tv.u;
|
||||
image: i < root.art.length ? root.art[i] : @image-url("");
|
||||
placeholder: "Kártya \{i + 1}";
|
||||
progress: i == 1 ? 0.4 : -1;
|
||||
badge: i == 0 ? "Új rész" : "";
|
||||
focused: root.area == 2 && root.card == i;
|
||||
opacity: root.dim;
|
||||
}
|
||||
Spinner {
|
||||
x: 1264 * Tv.u + 560 * Tv.u - self.width;
|
||||
y: Tv.safe-y;
|
||||
opacity: root.dim;
|
||||
}
|
||||
|
||||
// ---- keyboard on a modal pane ----
|
||||
modal := GlassPane {
|
||||
x: (root.width - self.width) / 2;
|
||||
y: (root.height - self.height) / 2;
|
||||
width: 1720 * Tv.u;
|
||||
height: 760 * Tv.u;
|
||||
radius: 56 * Tv.u;
|
||||
frost: 3.8;
|
||||
tint: Tv.smoke.with-alpha(0.48);
|
||||
glow: Tv.orange;
|
||||
alpha: root.kb-t;
|
||||
kb := Keyboard {
|
||||
x: 0;
|
||||
y: 96 * Tv.u;
|
||||
width: parent.width;
|
||||
title: "Keresés";
|
||||
subtitle: "Filmek és sorozatok címe";
|
||||
placeholder: "Cím";
|
||||
submit-label: "Keresés";
|
||||
min-length: 2;
|
||||
alpha: root.kb-t;
|
||||
submitted(text) => {
|
||||
root.kb-open = false;
|
||||
root.search(text);
|
||||
}
|
||||
cancelled => {
|
||||
root.kb-open = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// ---- glass, in drawing order ----
|
||||
out property <[GlassRect]> glass: [pane.glass, b0.glass, b1.glass, b2.glass, bar.glass];
|
||||
out property <[GlassRect]> glass-menu: menu.glass;
|
||||
out property <[GlassRect]> glass-modal: [modal.glass];
|
||||
out property <[GlassRect]> glass-keyboard: kb.glass;
|
||||
}
|
||||
103
crates/sf-ui/src/dev.rs
Normal file
103
crates/sf-ui/src/dev.rs
Normal file
@@ -0,0 +1,103 @@
|
||||
//! Dev helper, built into every [`crate::Glass`] window: scripted key presses
|
||||
//! and a PNG snapshot of the window, so a UI can be checked (by you, a CI job
|
||||
//! or an AI) without anyone at the screen.
|
||||
//!
|
||||
//! - `SF_UI_SIZE=1920x1080`: physical window size.
|
||||
//! - `SF_UI_KEYS="down down right enter wait esc"`: keys sent one by one
|
||||
//! (left, right, up, down, enter, esc, back = esc, backspace, space;
|
||||
//! a single character types it, `wait` = pause,
|
||||
//! `hold` = enter held 0.8 s), starting after 1.5 s, every 0.6 s.
|
||||
//! - `SF_UI_SNAPSHOT=out.png`: saves the frame and quits, 1.5 s after the
|
||||
//! last key (or after `SF_UI_SNAPSHOT_MS` milliseconds).
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::path::PathBuf;
|
||||
use std::rc::Rc;
|
||||
use std::time::Duration;
|
||||
|
||||
use slint::ComponentHandle;
|
||||
use slint::platform::{Key, WindowEvent};
|
||||
|
||||
const FIRST_KEY_MS: u64 = 1500;
|
||||
const KEY_STEP_MS: u64 = 600;
|
||||
|
||||
/// A snapshot waiting to be taken (shared with the rendering notifier).
|
||||
#[derive(Default)]
|
||||
pub(crate) struct Snapshot {
|
||||
pub(crate) path: RefCell<Option<PathBuf>>,
|
||||
pub(crate) due: Cell<bool>,
|
||||
}
|
||||
|
||||
pub(crate) fn setup<C: ComponentHandle + 'static>(ui: &C) -> Rc<Snapshot> {
|
||||
let snap = Rc::new(Snapshot::default());
|
||||
if let Some((w, h)) = std::env::var("SF_UI_SIZE").ok().and_then(|s| {
|
||||
let (w, h) = s.split_once('x')?;
|
||||
Some((w.trim().parse().ok()?, h.trim().parse().ok()?))
|
||||
}) {
|
||||
ui.window().set_size(slint::PhysicalSize::new(w, h));
|
||||
}
|
||||
|
||||
let keys: Vec<String> =
|
||||
std::env::var("SF_UI_KEYS").map(|s| s.split_whitespace().map(str::to_string).collect()).unwrap_or_default();
|
||||
let mut at = FIRST_KEY_MS;
|
||||
for k in &keys {
|
||||
let hold = k == "hold";
|
||||
let text: Option<slint::SharedString> = match k.to_lowercase().as_str() {
|
||||
"hold" | "enter" => Some(Key::Return.into()),
|
||||
"left" => Some(Key::LeftArrow.into()),
|
||||
"right" => Some(Key::RightArrow.into()),
|
||||
"up" => Some(Key::UpArrow.into()),
|
||||
"down" => Some(Key::DownArrow.into()),
|
||||
"esc" | "back" => Some(Key::Escape.into()),
|
||||
"backspace" => Some(Key::Backspace.into()),
|
||||
"space" => Some(" ".into()),
|
||||
"wait" => None,
|
||||
_ if k.chars().count() == 1 => Some(k.as_str().into()),
|
||||
_ => None,
|
||||
};
|
||||
let start = at;
|
||||
at += if hold { 2 * KEY_STEP_MS } else { KEY_STEP_MS };
|
||||
let Some(text) = text else { continue };
|
||||
let weak = ui.as_weak();
|
||||
let t = text.clone();
|
||||
slint::Timer::single_shot(Duration::from_millis(start), move || {
|
||||
if let Some(ui) = weak.upgrade() {
|
||||
ui.window().dispatch_event(WindowEvent::KeyPressed { text: t.clone() });
|
||||
if !hold {
|
||||
ui.window().dispatch_event(WindowEvent::KeyReleased { text: t });
|
||||
}
|
||||
}
|
||||
});
|
||||
if hold {
|
||||
let weak = ui.as_weak();
|
||||
slint::Timer::single_shot(Duration::from_millis(start + 800), move || {
|
||||
if let Some(ui) = weak.upgrade() {
|
||||
ui.window().dispatch_event(WindowEvent::KeyReleased { text });
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(path) = std::env::var_os("SF_UI_SNAPSHOT").map(PathBuf::from) {
|
||||
let ms = std::env::var("SF_UI_SNAPSHOT_MS").ok().and_then(|s| s.parse().ok()).unwrap_or(at + 1500);
|
||||
*snap.path.borrow_mut() = Some(path);
|
||||
let s = snap.clone();
|
||||
slint::Timer::single_shot(Duration::from_millis(ms), move || s.due.set(true));
|
||||
}
|
||||
snap
|
||||
}
|
||||
|
||||
/// Writes top-down RGBA8 pixels as a PNG.
|
||||
pub(crate) fn save_png(path: &std::path::Path, w: u32, h: u32, rgba: &[u8]) -> anyhow::Result<()> {
|
||||
let file = std::io::BufWriter::new(std::fs::File::create(path)?);
|
||||
let mut enc = png::Encoder::new(file, w, h);
|
||||
enc.set_color(png::ColorType::Rgba);
|
||||
enc.set_depth(png::BitDepth::Eight);
|
||||
// The window has no meaningful alpha: make every pixel opaque.
|
||||
let mut data = rgba.to_vec();
|
||||
for px in data.chunks_exact_mut(4) {
|
||||
px[3] = 255;
|
||||
}
|
||||
enc.write_header()?.write_image_data(&data)?;
|
||||
Ok(())
|
||||
}
|
||||
386
crates/sf-ui/src/glass.rs
Normal file
386
crates/sf-ui/src/glass.rs
Normal file
@@ -0,0 +1,386 @@
|
||||
//! The Liquid Glass layer for a Slint window: install it once, then tell it
|
||||
//! each frame which panels to draw (usually the `[GlassRect]` arrays your
|
||||
//! .slint file exports), and set the backdrop (palette, picture, video).
|
||||
//!
|
||||
//! ```ignore
|
||||
//! sf_ui::init()?; // before creating the window
|
||||
//! let ui = App::new()?;
|
||||
//! ui.sf_ui_setup(); // from sf_ui::glue!(App)
|
||||
//! let glass = sf_ui::Glass::install(&ui, |ui, panels| {
|
||||
//! panels.extend(ui.get_glass().iter());
|
||||
//! })?;
|
||||
//! glass.set_palette(sf_ui::Palette::from_hex(["#ffb27a", "#8a3d12", "#120805"]));
|
||||
//! ui.run()?;
|
||||
//! ```
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
use std::time::Instant;
|
||||
|
||||
use slint::{ComponentHandle, Rgba8Pixel, SharedPixelBuffer};
|
||||
|
||||
use crate::render::{Frame, GlassRenderer, ImageDraw, ImageId, Nv12Frame, Panel, Quality, VideoDraw};
|
||||
use crate::Palette;
|
||||
|
||||
/// Time constant of palette and brightness changes (seconds).
|
||||
const EASE: f32 = 0.35;
|
||||
/// Crossfade time of pictures and video (seconds).
|
||||
const FADE: f32 = 0.45;
|
||||
|
||||
/// A picture for the backdrop (artwork behind a details page, a hero...).
|
||||
/// Glass panels refract and frost it like the gradient.
|
||||
#[derive(Clone)]
|
||||
pub struct Backdrop {
|
||||
pixels: SharedPixelBuffer<Rgba8Pixel>,
|
||||
dim: f32,
|
||||
fade_left: f32,
|
||||
fade_bottom: f32,
|
||||
align: [f32; 2],
|
||||
sharp: bool,
|
||||
}
|
||||
|
||||
impl Backdrop {
|
||||
/// Defaults: slightly dimmed, darker towards the left and bottom (room
|
||||
/// for titles), sharp, cropped around the centre.
|
||||
pub fn new(pixels: SharedPixelBuffer<Rgba8Pixel>) -> Backdrop {
|
||||
Backdrop { pixels, dim: 0.12, fade_left: 0.75, fade_bottom: 0.6, align: [0.5, 0.35], sharp: true }
|
||||
}
|
||||
/// Darkens the whole picture: 0 = as is, 1 = black.
|
||||
pub fn dim(mut self, v: f32) -> Self {
|
||||
self.dim = v.clamp(0.0, 1.0);
|
||||
self
|
||||
}
|
||||
/// Darkening towards the left edge, 0..1.
|
||||
pub fn fade_left(mut self, v: f32) -> Self {
|
||||
self.fade_left = v.clamp(0.0, 1.0);
|
||||
self
|
||||
}
|
||||
/// Darkening towards the bottom edge, 0..1.
|
||||
pub fn fade_bottom(mut self, v: f32) -> Self {
|
||||
self.fade_bottom = v.clamp(0.0, 1.0);
|
||||
self
|
||||
}
|
||||
/// Which part stays visible when cropped (0..1 per axis, 0.5 = centre).
|
||||
pub fn align(mut self, x: f32, y: f32) -> Self {
|
||||
self.align = [x.clamp(0.0, 1.0), y.clamp(0.0, 1.0)];
|
||||
self
|
||||
}
|
||||
/// Soft: only the blurred low-resolution copy shows (a frosted wallpaper).
|
||||
pub fn soft(mut self) -> Self {
|
||||
self.sharp = false;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// Where video frames come from (see `sf_ui::video::Player`, or your own
|
||||
/// decoder). Called once per rendered frame on the UI thread.
|
||||
pub trait VideoSource {
|
||||
/// The newest frame since the last call, if any.
|
||||
fn take_frame(&self) -> Option<Box<dyn Nv12Frame + '_>>;
|
||||
}
|
||||
|
||||
/// Collects the glass panels of one frame, in logical pixels (the units of
|
||||
/// your .slint file). Draw order is push order: later panels lie on top.
|
||||
pub struct Panels {
|
||||
scale: f32,
|
||||
out: Vec<Panel>,
|
||||
}
|
||||
|
||||
impl Panels {
|
||||
/// One panel (logical px).
|
||||
pub fn push(&mut self, panel: impl Into<Panel>) {
|
||||
let p = panel.into();
|
||||
if p.alpha > 0.002 && p.w > 0.0 && p.h > 0.0 {
|
||||
self.out.push(p.scaled(self.scale));
|
||||
}
|
||||
}
|
||||
|
||||
/// Many panels, e.g. `panels.extend(ui.get_glass().iter())`.
|
||||
pub fn extend<T: Into<Panel>>(&mut self, panels: impl IntoIterator<Item = T>) {
|
||||
for p in panels {
|
||||
self.push(p);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Slot {
|
||||
backdrop: Backdrop,
|
||||
id: Option<ImageId>,
|
||||
alpha: f32,
|
||||
target: f32,
|
||||
}
|
||||
|
||||
struct State {
|
||||
palette: [f32; 9],
|
||||
palette_target: [f32; 9],
|
||||
brightness: f32,
|
||||
brightness_target: f32,
|
||||
images: Vec<Slot>,
|
||||
free: Vec<ImageId>,
|
||||
video: Option<Rc<dyn VideoSource>>,
|
||||
video_alpha: f32,
|
||||
video_on: bool,
|
||||
clear_video: bool,
|
||||
light: f32,
|
||||
zoom: f32,
|
||||
last: f32,
|
||||
quality: Quality,
|
||||
}
|
||||
|
||||
/// Handle to an installed glass layer (cheap to clone).
|
||||
#[derive(Clone)]
|
||||
pub struct Glass {
|
||||
state: Rc<RefCell<State>>,
|
||||
}
|
||||
|
||||
impl Glass {
|
||||
/// Draws the glass layer under `ui`'s window. `panels` runs before every
|
||||
/// frame and adds that frame's panels. The backdrop animates, so frames
|
||||
/// keep coming (vsync-limited).
|
||||
///
|
||||
/// Call [`crate::init`] before creating the window: the layer needs the
|
||||
/// OpenGL (FemtoVG) renderer.
|
||||
pub fn install<C: ComponentHandle + 'static>(
|
||||
ui: &C,
|
||||
mut panels: impl FnMut(&C, &mut Panels) + 'static,
|
||||
) -> anyhow::Result<Glass> {
|
||||
let neutral = Palette::NEUTRAL.to_floats();
|
||||
let state = Rc::new(RefCell::new(State {
|
||||
palette: neutral,
|
||||
palette_target: neutral,
|
||||
brightness: 1.0,
|
||||
brightness_target: 1.0,
|
||||
images: Vec::new(),
|
||||
free: Vec::new(),
|
||||
video: None,
|
||||
video_alpha: 0.0,
|
||||
video_on: false,
|
||||
clear_video: false,
|
||||
light: 0.0,
|
||||
zoom: 1.0,
|
||||
last: 0.0,
|
||||
quality: Quality::Full,
|
||||
}));
|
||||
let glass = Glass { state: state.clone() };
|
||||
let snapshot = crate::dev::setup(ui);
|
||||
let renderer: Rc<RefCell<Option<GlassRenderer>>> = Rc::default();
|
||||
let start = Instant::now();
|
||||
let weak = ui.as_weak();
|
||||
ui.window()
|
||||
.set_rendering_notifier(move |rs, api| match rs {
|
||||
slint::RenderingState::RenderingSetup => {
|
||||
let slint::GraphicsAPI::NativeOpenGL { get_proc_address } = api else {
|
||||
log::error!("sf-ui: the glass layer needs OpenGL (call sf_ui::init() first)");
|
||||
return;
|
||||
};
|
||||
let gl = unsafe { glow::Context::from_loader_function_cstr(|s| get_proc_address(s)) };
|
||||
match unsafe { GlassRenderer::new(gl) } {
|
||||
Ok(r) => *renderer.borrow_mut() = Some(r),
|
||||
Err(e) => log::error!("sf-ui: glass layer disabled: {e:#}"),
|
||||
}
|
||||
}
|
||||
slint::RenderingState::BeforeRendering => {
|
||||
let mut guard = renderer.borrow_mut();
|
||||
let (Some(ui), Some(r)) = (weak.upgrade(), guard.as_mut()) else { return };
|
||||
let time = start.elapsed().as_secs_f32();
|
||||
let size = ui.window().size();
|
||||
let scale = ui.window().scale_factor();
|
||||
let mut list = Panels { scale, out: Vec::new() };
|
||||
panels(&ui, &mut list);
|
||||
|
||||
let mut st = state.borrow_mut();
|
||||
let dt = (time - st.last).clamp(0.0, 0.25);
|
||||
st.last = time;
|
||||
st.step(dt);
|
||||
// SAFETY: the rendering notifier runs with the GL context current.
|
||||
unsafe { st.sync_images(r) };
|
||||
if std::mem::take(&mut st.clear_video) {
|
||||
r.clear_video();
|
||||
}
|
||||
let draws: Vec<ImageDraw> = st
|
||||
.images
|
||||
.iter()
|
||||
.filter_map(|s| {
|
||||
Some(ImageDraw {
|
||||
image: s.id?,
|
||||
alpha: s.alpha,
|
||||
dim: s.backdrop.dim,
|
||||
fade_left: s.backdrop.fade_left,
|
||||
fade_bottom: s.backdrop.fade_bottom,
|
||||
align: s.backdrop.align,
|
||||
sharp: s.backdrop.sharp,
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
let video = st.video.clone();
|
||||
let frame_box = video.as_ref().and_then(|v| v.take_frame());
|
||||
let angle = -2.25 + 0.10 * (time * 0.35).sin() + st.light;
|
||||
let frame = Frame {
|
||||
width: size.width,
|
||||
height: size.height,
|
||||
scale,
|
||||
time,
|
||||
palette: st.palette,
|
||||
brightness: st.brightness,
|
||||
light: [angle.cos(), angle.sin()],
|
||||
zoom: st.zoom,
|
||||
images: &draws,
|
||||
video: (st.video_alpha > 0.002 || frame_box.is_some())
|
||||
.then(|| VideoDraw { frame: frame_box.as_deref(), alpha: st.video_alpha }),
|
||||
rects: list.out,
|
||||
quality: st.quality,
|
||||
};
|
||||
drop(st);
|
||||
// SAFETY: as above.
|
||||
unsafe { r.render(&frame) };
|
||||
}
|
||||
slint::RenderingState::AfterRendering => {
|
||||
let Some(ui) = weak.upgrade() else { return };
|
||||
if snapshot.due.get() {
|
||||
if let (Some(path), Some(r)) = (snapshot.path.borrow_mut().take(), renderer.borrow().as_ref()) {
|
||||
let size = ui.window().size();
|
||||
// SAFETY: after Slint rendered, context current.
|
||||
let px = unsafe { r.read_pixels(size.width, size.height) };
|
||||
match crate::dev::save_png(&path, size.width, size.height, &px) {
|
||||
Ok(()) => log::info!("sf-ui: snapshot {}", path.display()),
|
||||
Err(e) => log::error!("sf-ui: snapshot {}: {e:#}", path.display()),
|
||||
}
|
||||
let _ = slint::quit_event_loop();
|
||||
}
|
||||
}
|
||||
ui.window().request_redraw();
|
||||
}
|
||||
slint::RenderingState::RenderingTeardown => {
|
||||
if let Some(mut r) = renderer.borrow_mut().take() {
|
||||
unsafe { r.destroy() };
|
||||
}
|
||||
// Textures died with the context: upload again if it comes back.
|
||||
for s in state.borrow_mut().images.iter_mut() {
|
||||
s.id = None;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
})
|
||||
.map_err(|e| anyhow::anyhow!("sf-ui: rendering notifier: {e:?}"))?;
|
||||
Ok(glass)
|
||||
}
|
||||
|
||||
/// The backdrop gradient's colours; eases over from the current ones.
|
||||
pub fn set_palette(&self, palette: Palette) {
|
||||
self.state.borrow_mut().palette_target = palette.to_floats();
|
||||
}
|
||||
|
||||
/// Backdrop brightness, 0..1 (1 = full). Lower it to calm the backdrop
|
||||
/// behind dense content.
|
||||
pub fn set_brightness(&self, v: f32) {
|
||||
self.state.borrow_mut().brightness_target = v.clamp(0.0, 1.0);
|
||||
}
|
||||
|
||||
/// A picture over the gradient (crossfades from the previous one), or
|
||||
/// `None` to fade back to the gradient.
|
||||
pub fn set_backdrop(&self, backdrop: Option<Backdrop>) {
|
||||
let mut st = self.state.borrow_mut();
|
||||
match backdrop {
|
||||
Some(b) => {
|
||||
// Already showing this very picture: keep it.
|
||||
if let Some(last) = st.images.last_mut() {
|
||||
if last.backdrop.pixels.as_bytes().as_ptr() == b.pixels.as_bytes().as_ptr() {
|
||||
last.backdrop = b;
|
||||
last.target = 1.0;
|
||||
return;
|
||||
}
|
||||
}
|
||||
st.images.push(Slot { backdrop: b, id: None, alpha: 0.0, target: 1.0 });
|
||||
}
|
||||
None => {
|
||||
for s in st.images.iter_mut() {
|
||||
s.target = 0.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Video as the backdrop (glass refracts the film), or `None` to fade it
|
||||
/// out. The source is polled once per frame.
|
||||
pub fn set_video(&self, source: Option<Rc<dyn VideoSource>>) {
|
||||
let mut st = self.state.borrow_mut();
|
||||
st.video_on = source.is_some();
|
||||
if source.is_some() {
|
||||
st.video = source;
|
||||
st.clear_video = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Turns the key light (radians, small values like ±0.3), e.g. to follow
|
||||
/// the focus across the screen.
|
||||
pub fn set_light(&self, offset: f32) {
|
||||
self.state.borrow_mut().light = offset;
|
||||
}
|
||||
|
||||
/// How much of the glass effect to draw ([`Quality::Light`] or
|
||||
/// [`Quality::Flat`] on weaker hardware).
|
||||
pub fn set_quality(&self, q: Quality) {
|
||||
self.state.borrow_mut().quality = q;
|
||||
}
|
||||
|
||||
/// Zooms the backdrop gradient (1 = none).
|
||||
pub fn set_zoom(&self, zoom: f32) {
|
||||
self.state.borrow_mut().zoom = zoom.max(0.1);
|
||||
}
|
||||
}
|
||||
|
||||
impl State {
|
||||
fn step(&mut self, dt: f32) {
|
||||
let k = 1.0 - (-dt / EASE).exp();
|
||||
for (c, t) in self.palette.iter_mut().zip(self.palette_target) {
|
||||
*c += (t - *c) * k;
|
||||
}
|
||||
self.brightness += (self.brightness_target - self.brightness) * k;
|
||||
|
||||
let fade = dt / FADE;
|
||||
for s in self.images.iter_mut() {
|
||||
s.alpha = if s.target > s.alpha { (s.alpha + fade).min(s.target) } else { (s.alpha - fade).max(s.target) };
|
||||
}
|
||||
// A picture fully covered by a newer, opaque one is no longer needed;
|
||||
// faded-out ones neither.
|
||||
let covered = self.images.iter().rposition(|s| s.alpha >= 0.999).unwrap_or(0);
|
||||
let mut i = 0;
|
||||
self.images.retain(|s| {
|
||||
let keep = i >= covered && !(s.target == 0.0 && s.alpha <= 0.0);
|
||||
i += 1;
|
||||
if !keep {
|
||||
if let Some(id) = s.id {
|
||||
self.free.push(id);
|
||||
}
|
||||
}
|
||||
keep
|
||||
});
|
||||
|
||||
let target = if self.video_on { 1.0 } else { 0.0 };
|
||||
self.video_alpha = if target > self.video_alpha {
|
||||
(self.video_alpha + dt / 0.3).min(1.0)
|
||||
} else {
|
||||
(self.video_alpha - dt / 0.3).max(0.0)
|
||||
};
|
||||
if !self.video_on && self.video_alpha <= 0.0 {
|
||||
self.video = None;
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn sync_images(&mut self, r: &mut GlassRenderer) {
|
||||
for id in self.free.drain(..) {
|
||||
unsafe { r.free_image(id) };
|
||||
}
|
||||
for s in self.images.iter_mut().filter(|s| s.id.is_none()) {
|
||||
let px = &s.backdrop.pixels;
|
||||
match unsafe { r.upload_image(px.width(), px.height(), px.as_bytes()) } {
|
||||
Ok(id) => s.id = Some(id),
|
||||
Err(e) => {
|
||||
log::warn!("sf-ui: backdrop picture: {e:#}");
|
||||
s.target = 0.0;
|
||||
s.alpha = 0.0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
259
crates/sf-ui/src/images.rs
Normal file
259
crates/sf-ui/src/images.rs
Normal file
@@ -0,0 +1,259 @@
|
||||
//! Artwork over HTTP(S): downloaded, decoded and scaled on worker threads,
|
||||
//! kept in a memory cache, handed to you on the UI thread.
|
||||
//!
|
||||
//! ```ignore
|
||||
//! let images = sf_ui::images::Images::new(256 << 20);
|
||||
//! images.load(&poster_url, (240, 360), move |img| card.set_image(img));
|
||||
//! ```
|
||||
//!
|
||||
//! Sizes are the size you show the picture at, in *physical* pixels (design
|
||||
//! px × the window's scale): the picture is scaled down to cover that box
|
||||
//! (never up), so a 4K TV gets sharper artwork and a 1080p one uses less memory.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::collections::{HashMap, VecDeque};
|
||||
use std::io::Read;
|
||||
use std::rc::{Rc, Weak};
|
||||
use std::sync::atomic::{AtomicU64, Ordering};
|
||||
use std::sync::mpsc;
|
||||
use std::sync::{Arc, Mutex};
|
||||
use std::time::Duration;
|
||||
|
||||
use slint::{Rgba8Pixel, SharedPixelBuffer};
|
||||
|
||||
/// Bigger downloads are refused.
|
||||
const MAX_DOWNLOAD: u64 = 24 << 20;
|
||||
const WORKERS: usize = 4;
|
||||
|
||||
type Pixels = SharedPixelBuffer<Rgba8Pixel>;
|
||||
type Key = (String, u32, u32);
|
||||
type Waiter = Box<dyn FnOnce(&Pixels)>;
|
||||
|
||||
struct Job {
|
||||
owner: u64,
|
||||
key: Key,
|
||||
}
|
||||
|
||||
struct Inner {
|
||||
id: u64,
|
||||
budget: usize,
|
||||
used: RefCell<usize>,
|
||||
cache: RefCell<HashMap<Key, Pixels>>,
|
||||
order: RefCell<VecDeque<Key>>,
|
||||
waiting: RefCell<HashMap<Key, Vec<Waiter>>>,
|
||||
jobs: Mutex<Option<mpsc::Sender<()>>>,
|
||||
queue: Arc<Mutex<VecDeque<Job>>>,
|
||||
}
|
||||
|
||||
thread_local! {
|
||||
static OWNERS: RefCell<HashMap<u64, Weak<Inner>>> = RefCell::new(HashMap::new());
|
||||
}
|
||||
|
||||
static NEXT_ID: AtomicU64 = AtomicU64::new(1);
|
||||
|
||||
/// The image loader and cache (cheap to clone; use it on the UI thread).
|
||||
#[derive(Clone)]
|
||||
pub struct Images {
|
||||
inner: Rc<Inner>,
|
||||
}
|
||||
|
||||
impl Images {
|
||||
/// `budget`: bytes of decoded pixels to keep (e.g. `256 << 20`).
|
||||
pub fn new(budget: usize) -> Images {
|
||||
let id = NEXT_ID.fetch_add(1, Ordering::Relaxed);
|
||||
let queue: Arc<Mutex<VecDeque<Job>>> = Arc::default();
|
||||
let (tx, rx) = mpsc::channel::<()>();
|
||||
let rx = Arc::new(Mutex::new(rx));
|
||||
let agent: ureq::Agent = ureq::Agent::config_builder()
|
||||
.timeout_global(Some(Duration::from_secs(30)))
|
||||
.user_agent("SmartFox sf-ui")
|
||||
.build()
|
||||
.into();
|
||||
for _ in 0..WORKERS {
|
||||
let rx = rx.clone();
|
||||
let queue = queue.clone();
|
||||
let agent = agent.clone();
|
||||
std::thread::spawn(move || {
|
||||
// Wake-ups come over the channel; the newest request is served first
|
||||
// (what the user looks at now), from the shared queue.
|
||||
while rx.lock().unwrap().recv().is_ok() {
|
||||
let Some(job) = queue.lock().unwrap().pop_back() else { continue };
|
||||
let result = fetch(&agent, &job.key.0, job.key.1, job.key.2);
|
||||
if let Err(e) = &result {
|
||||
log::debug!("image {}: {e:#}", job.key.0);
|
||||
}
|
||||
let (owner, key) = (job.owner, job.key);
|
||||
let _ = slint::invoke_from_event_loop(move || deliver(owner, key, result.ok()));
|
||||
}
|
||||
});
|
||||
}
|
||||
let inner = Rc::new(Inner {
|
||||
id,
|
||||
budget,
|
||||
used: RefCell::new(0),
|
||||
cache: RefCell::default(),
|
||||
order: RefCell::default(),
|
||||
waiting: RefCell::default(),
|
||||
jobs: Mutex::new(Some(tx)),
|
||||
queue,
|
||||
});
|
||||
OWNERS.with(|o| o.borrow_mut().insert(id, Rc::downgrade(&inner)));
|
||||
Images { inner }
|
||||
}
|
||||
|
||||
/// Loads `url` scaled to cover `size` (physical px) and calls `done` with
|
||||
/// it on the UI thread: at once if cached, later otherwise. On failure
|
||||
/// `done` is not called.
|
||||
pub fn load(&self, url: &str, size: (u32, u32), done: impl FnOnce(slint::Image) + 'static) {
|
||||
self.load_pixels(url, size, move |px| done(slint::Image::from_rgba8(px.clone())));
|
||||
}
|
||||
|
||||
/// Like [`Images::load`], but hands over the pixels (for
|
||||
/// [`crate::Backdrop`] or your own processing).
|
||||
pub fn load_pixels(&self, url: &str, size: (u32, u32), done: impl FnOnce(&Pixels) + 'static) {
|
||||
if url.is_empty() {
|
||||
return;
|
||||
}
|
||||
let key: Key = (url.to_string(), size.0.max(1), size.1.max(1));
|
||||
if let Some(px) = self.inner.cache.borrow().get(&key).cloned() {
|
||||
self.touch(&key);
|
||||
done(&px);
|
||||
return;
|
||||
}
|
||||
let mut waiting = self.inner.waiting.borrow_mut();
|
||||
if let Some(list) = waiting.get_mut(&key) {
|
||||
list.push(Box::new(done));
|
||||
return;
|
||||
}
|
||||
waiting.insert(key.clone(), vec![Box::new(done)]);
|
||||
drop(waiting);
|
||||
self.inner.queue.lock().unwrap().push_back(Job { owner: self.inner.id, key });
|
||||
if let Some(tx) = self.inner.jobs.lock().unwrap().as_ref() {
|
||||
let _ = tx.send(());
|
||||
}
|
||||
}
|
||||
|
||||
/// The cached picture, if it is already loaded.
|
||||
pub fn cached(&self, url: &str, size: (u32, u32)) -> Option<slint::Image> {
|
||||
let key: Key = (url.to_string(), size.0.max(1), size.1.max(1));
|
||||
self.inner.cache.borrow().get(&key).map(|px| slint::Image::from_rgba8(px.clone()))
|
||||
}
|
||||
|
||||
/// Drops requests that have not started yet (e.g. after leaving a screen).
|
||||
pub fn cancel_pending(&self) {
|
||||
let mut q = self.inner.queue.lock().unwrap();
|
||||
let mut waiting = self.inner.waiting.borrow_mut();
|
||||
for job in q.drain(..) {
|
||||
waiting.remove(&job.key);
|
||||
}
|
||||
}
|
||||
|
||||
fn touch(&self, key: &Key) {
|
||||
let mut order = self.inner.order.borrow_mut();
|
||||
if let Some(i) = order.iter().position(|k| k == key) {
|
||||
let k = order.remove(i).unwrap();
|
||||
order.push_back(k);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Inner {
|
||||
fn insert(&self, key: Key, px: Pixels) {
|
||||
let bytes = px.as_bytes().len();
|
||||
let mut cache = self.cache.borrow_mut();
|
||||
let mut order = self.order.borrow_mut();
|
||||
let mut used = self.used.borrow_mut();
|
||||
while *used + bytes > self.budget {
|
||||
let Some(old) = order.pop_front() else { break };
|
||||
if let Some(p) = cache.remove(&old) {
|
||||
*used -= p.as_bytes().len();
|
||||
}
|
||||
}
|
||||
*used += bytes;
|
||||
order.push_back(key.clone());
|
||||
cache.insert(key, px);
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Inner {
|
||||
fn drop(&mut self) {
|
||||
// Ends the worker threads.
|
||||
self.jobs.lock().unwrap().take();
|
||||
let id = self.id;
|
||||
let _ = OWNERS.try_with(|o| o.borrow_mut().remove(&id));
|
||||
}
|
||||
}
|
||||
|
||||
fn deliver(owner: u64, key: Key, px: Option<Pixels>) {
|
||||
let Some(inner) = OWNERS.with(|o| o.borrow().get(&owner).and_then(Weak::upgrade)) else { return };
|
||||
let waiters = inner.waiting.borrow_mut().remove(&key).unwrap_or_default();
|
||||
let Some(px) = px else { return };
|
||||
inner.insert(key, px.clone());
|
||||
for w in waiters {
|
||||
w(&px);
|
||||
}
|
||||
}
|
||||
|
||||
fn fetch(agent: &ureq::Agent, url: &str, w: u32, h: u32) -> anyhow::Result<Pixels> {
|
||||
let mut resp = agent.get(url).call()?;
|
||||
let mut bytes = Vec::new();
|
||||
resp.body_mut().as_reader().take(MAX_DOWNLOAD + 1).read_to_end(&mut bytes)?;
|
||||
anyhow::ensure!((bytes.len() as u64) <= MAX_DOWNLOAD, "larger than {MAX_DOWNLOAD} bytes");
|
||||
decode(&bytes, w, h)
|
||||
}
|
||||
|
||||
/// Decodes and scales down to cover `w` x `h` (never up).
|
||||
pub fn decode(bytes: &[u8], w: u32, h: u32) -> anyhow::Result<Pixels> {
|
||||
let img = image::load_from_memory(bytes)?;
|
||||
let (iw, ih) = (img.width().max(1), img.height().max(1));
|
||||
let k = (w as f32 / iw as f32).max(h as f32 / ih as f32);
|
||||
let img = if k < 0.98 {
|
||||
let (nw, nh) = (((iw as f32 * k).round() as u32).max(1), ((ih as f32 * k).round() as u32).max(1));
|
||||
img.resize_exact(nw, nh, image::imageops::FilterType::Triangle)
|
||||
} else {
|
||||
img
|
||||
};
|
||||
let rgba = img.into_rgba8();
|
||||
Ok(SharedPixelBuffer::clone_from_slice(rgba.as_raw(), rgba.width(), rgba.height()))
|
||||
}
|
||||
|
||||
/// The average colour of a picture (for a matching [`crate::Palette`]),
|
||||
/// leaning towards its saturated parts.
|
||||
pub fn average_color(px: &Pixels) -> slint::Color {
|
||||
let (mut r, mut g, mut b, mut n) = (0f64, 0f64, 0f64, 0f64);
|
||||
let bytes = px.as_bytes();
|
||||
for p in bytes.chunks_exact(4).step_by(7) {
|
||||
let (pr, pg, pb) = (p[0] as f64, p[1] as f64, p[2] as f64);
|
||||
let max = pr.max(pg).max(pb);
|
||||
let min = pr.min(pg).min(pb);
|
||||
let wgt = 0.15 + (max - min) / 255.0 + max / 510.0;
|
||||
r += pr * wgt;
|
||||
g += pg * wgt;
|
||||
b += pb * wgt;
|
||||
n += wgt;
|
||||
}
|
||||
if n == 0.0 {
|
||||
return slint::Color::from_rgb_u8(0x2a, 0x31, 0x40);
|
||||
}
|
||||
slint::Color::from_rgb_u8((r / n) as u8, (g / n) as u8, (b / n) as u8)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn scales_to_cover() {
|
||||
let mut png = Vec::new();
|
||||
let img = image::RgbaImage::from_pixel(400, 600, image::Rgba([200, 40, 30, 255]));
|
||||
image::DynamicImage::ImageRgba8(img)
|
||||
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
|
||||
.unwrap();
|
||||
let px = decode(&png, 100, 100).unwrap();
|
||||
assert_eq!((px.width(), px.height()), (100, 150));
|
||||
let px = decode(&png, 1000, 1000).unwrap();
|
||||
assert_eq!((px.width(), px.height()), (400, 600));
|
||||
let c = average_color(&px);
|
||||
assert!(c.red() > 150 && c.green() < 80);
|
||||
}
|
||||
}
|
||||
191
crates/sf-ui/src/lib.rs
Normal file
191
crates/sf-ui/src/lib.rs
Normal file
@@ -0,0 +1,191 @@
|
||||
//! sf-ui: the SmartFox TV UI kit for Slint apps.
|
||||
//!
|
||||
//! - **Liquid Glass** ([`Glass`]): the refracting, frosted glass of the
|
||||
//! SmartFox launcher, drawn by an OpenGL layer under your Slint UI, over an
|
||||
//! animated palette backdrop, a picture or a playing video.
|
||||
//! - **Slint components** (`@sf-ui/sf-ui.slint`): design tokens (`Tv`), text
|
||||
//! styles, glass panes, buttons, chips, a progress bar, an on-screen
|
||||
//! keyboard, icons and the Onest font.
|
||||
//! - **Images** ([`images::Images`], feature `images`): artwork over HTTP,
|
||||
//! decoded and scaled off the UI thread, cached.
|
||||
//! - **Video** (`video::Player`, feature `video`, Linux): GStreamer playback
|
||||
//! with hardware decoding, its frames shown as the glass backdrop.
|
||||
//!
|
||||
//! Guide: `docs/sf-ui.md` in the SmartFox repository.
|
||||
|
||||
pub mod render;
|
||||
|
||||
mod dev;
|
||||
mod glass;
|
||||
#[cfg(feature = "images")]
|
||||
pub mod images;
|
||||
pub mod text;
|
||||
#[cfg(feature = "video")]
|
||||
pub mod video;
|
||||
|
||||
pub use glass::{Backdrop, Glass, Panels, VideoSource};
|
||||
pub use render::{Matrix, Nv12Frame, Panel, Quality};
|
||||
|
||||
/// Selects Slint's OpenGL renderer (FemtoVG), which the glass layer draws
|
||||
/// with. Call it first in `main`, before creating any window.
|
||||
pub fn init() -> anyhow::Result<()> {
|
||||
slint::BackendSelector::new()
|
||||
.renderer_name("femtovg".into())
|
||||
.select()
|
||||
.map_err(|e| anyhow::anyhow!("selecting the femtovg (OpenGL) renderer: {e}"))
|
||||
}
|
||||
|
||||
/// The backdrop gradient's three colours: highlight, mid, deep. Use the
|
||||
/// `palette` of your app.toml, or one per screen / per focused item.
|
||||
#[derive(Debug, Clone, Copy, PartialEq)]
|
||||
pub struct Palette {
|
||||
pub highlight: slint::Color,
|
||||
pub mid: slint::Color,
|
||||
pub deep: slint::Color,
|
||||
}
|
||||
|
||||
impl Palette {
|
||||
/// The neutral system palette (no app colour).
|
||||
pub const NEUTRAL: Palette = Palette {
|
||||
highlight: slint::Color::from_rgb_u8(0x9a, 0xa4, 0xb5),
|
||||
mid: slint::Color::from_rgb_u8(0x2a, 0x31, 0x40),
|
||||
deep: slint::Color::from_rgb_u8(0x06, 0x07, 0x0a),
|
||||
};
|
||||
|
||||
pub fn new(highlight: slint::Color, mid: slint::Color, deep: slint::Color) -> Palette {
|
||||
Palette { highlight, mid, deep }
|
||||
}
|
||||
|
||||
/// From three "#rrggbb" strings (as in app.toml); bad ones fall back to
|
||||
/// the neutral palette's colour.
|
||||
pub fn from_hex(hex: [&str; 3]) -> Palette {
|
||||
let n = Palette::NEUTRAL;
|
||||
Palette {
|
||||
highlight: parse_hex(hex[0]).unwrap_or(n.highlight),
|
||||
mid: parse_hex(hex[1]).unwrap_or(n.mid),
|
||||
deep: parse_hex(hex[2]).unwrap_or(n.deep),
|
||||
}
|
||||
}
|
||||
|
||||
/// A palette from one colour, e.g. the average colour of a poster:
|
||||
/// a lighter highlight, the colour itself, a near-black deep tone.
|
||||
pub fn from_color(c: slint::Color) -> Palette {
|
||||
let [r, g, b] = rgb(c);
|
||||
let mix = |k: f32, t: f32| -> slint::Color {
|
||||
let f = |v: f32| ((v * k + t * (1.0 - k)).clamp(0.0, 1.0) * 255.0) as u8;
|
||||
slint::Color::from_rgb_u8(f(r), f(g), f(b))
|
||||
};
|
||||
Palette { highlight: mix(0.7, 1.0), mid: mix(0.55, 0.0), deep: mix(0.08, 0.0) }
|
||||
}
|
||||
|
||||
/// rgb 0..1 for the renderer.
|
||||
pub fn to_floats(self) -> [f32; 9] {
|
||||
let mut out = [0.0; 9];
|
||||
for (i, c) in [self.highlight, self.mid, self.deep].into_iter().enumerate() {
|
||||
out[i * 3..i * 3 + 3].copy_from_slice(&rgb(c));
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
/// "#rrggbb" or "rrggbb".
|
||||
pub fn parse_hex(hex: &str) -> Option<slint::Color> {
|
||||
let h = hex.trim().trim_start_matches('#');
|
||||
let v = u32::from_str_radix(h.get(..6)?, 16).ok()?;
|
||||
Some(slint::Color::from_rgb_u8((v >> 16) as u8, (v >> 8) as u8, v as u8))
|
||||
}
|
||||
|
||||
fn rgb(c: slint::Color) -> [f32; 3] {
|
||||
[c.red() as f32 / 255.0, c.green() as f32 / 255.0, c.blue() as f32 / 255.0]
|
||||
}
|
||||
|
||||
impl Panel {
|
||||
/// From the fields of a Slint `GlassRect` (used by [`glue!`]).
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn from_slint(
|
||||
x: f32,
|
||||
y: f32,
|
||||
w: f32,
|
||||
h: f32,
|
||||
r: f32,
|
||||
focus: f32,
|
||||
alpha: f32,
|
||||
blur: f32,
|
||||
glow: slint::Color,
|
||||
tint: slint::Color,
|
||||
group: i32,
|
||||
) -> Panel {
|
||||
let [tr, tg, tb] = rgb(tint);
|
||||
Panel {
|
||||
x,
|
||||
y,
|
||||
w,
|
||||
h,
|
||||
radius: r,
|
||||
focus,
|
||||
alpha,
|
||||
blur,
|
||||
glow: rgb(glow),
|
||||
group: group as f32,
|
||||
tint: [tr, tg, tb, tint.alpha() as f32 / 255.0],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Connects the types Slint generated in *your* crate to sf-ui. Put it once
|
||||
/// next to `slint::include_modules!()`, with your root component's name:
|
||||
///
|
||||
/// ```ignore
|
||||
/// slint::include_modules!();
|
||||
/// sf_ui::glue!(App);
|
||||
/// ```
|
||||
///
|
||||
/// It makes `GlassRect` convertible to [`Panel`] (so `panels.extend(...)`
|
||||
/// takes your `[GlassRect]` arrays) and adds `App::sf_ui_setup()`, which
|
||||
/// wires the Slint helper callbacks (`SfText`). Your main .slint file must
|
||||
/// export the helpers: `export { Tv, SfText } from "@sf-ui/sf-ui.slint";`.
|
||||
#[macro_export]
|
||||
macro_rules! glue {
|
||||
($app:ident) => {
|
||||
impl ::core::convert::From<GlassRect> for $crate::Panel {
|
||||
fn from(g: GlassRect) -> Self {
|
||||
$crate::Panel::from_slint(g.x, g.y, g.w, g.h, g.r, g.focus, g.alpha, g.blur, g.glow.color(), g.tint.color(), g.group)
|
||||
}
|
||||
}
|
||||
|
||||
impl $app {
|
||||
/// Wires the sf-ui Slint helpers (text editing for the keyboard).
|
||||
/// Call it once after creating the window.
|
||||
#[allow(dead_code)]
|
||||
pub fn sf_ui_setup(&self) {
|
||||
use ::slint::ComponentHandle as _;
|
||||
let t = self.global::<SfText>();
|
||||
t.on_drop_last(|s| $crate::text::drop_last(&s).into());
|
||||
t.on_dots(|n| $crate::text::dots(n.max(0) as usize).into());
|
||||
t.on_truncate(|s, n| $crate::text::truncate(&s, n.max(0) as usize).into());
|
||||
t.on_typable(|s| $crate::text::typable(&s).into());
|
||||
}
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn hex_colours() {
|
||||
assert_eq!(parse_hex("#ff7a35"), Some(slint::Color::from_rgb_u8(0xff, 0x7a, 0x35)));
|
||||
assert_eq!(parse_hex("121317"), Some(slint::Color::from_rgb_u8(0x12, 0x13, 0x17)));
|
||||
assert_eq!(parse_hex("#12"), None);
|
||||
let p = Palette::from_hex(["#ffffff", "nope", "#000000"]);
|
||||
assert_eq!(p.mid, Palette::NEUTRAL.mid);
|
||||
assert_eq!(p.to_floats()[0], 1.0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn panel_scaling() {
|
||||
let p = Panel { x: 10.0, y: 20.0, w: 30.0, h: 40.0, radius: 5.0, alpha: 1.0, ..Panel::default() }.scaled(2.0);
|
||||
assert_eq!((p.x, p.y, p.w, p.h, p.radius), (20.0, 40.0, 60.0, 80.0, 10.0));
|
||||
}
|
||||
}
|
||||
167
crates/sf-ui/src/render/mod.rs
Normal file
167
crates/sf-ui/src/render/mod.rs
Normal file
@@ -0,0 +1,167 @@
|
||||
//! The low-level Liquid Glass renderer: an OpenGL pass drawn *under* the
|
||||
//! Slint UI. Most apps use [`crate::Glass`] instead, which drives this from a
|
||||
//! Slint rendering notifier; use this module directly only if you need your
|
||||
//! own notifier (the launcher does, for its dev snapshots).
|
||||
//!
|
||||
//! Per frame: the backdrop (animated gradient, optional pictures, optional
|
||||
//! video) goes into a small mipmapped texture and onto the window; then every
|
||||
//! glass panel is drawn as its own quad, refracting and frosting that texture.
|
||||
|
||||
mod renderer;
|
||||
mod shaders;
|
||||
|
||||
pub use renderer::GlassRenderer;
|
||||
|
||||
/// Panels drawn per frame at most (each one is its own small draw call).
|
||||
pub const MAX_RECTS: usize = 48;
|
||||
/// Members of one merged (liquid) group at most.
|
||||
pub const MAX_GROUP: usize = 4;
|
||||
|
||||
/// One glass panel. In [`Frame`] it is in physical pixels (top-left origin);
|
||||
/// [`crate::Panels`] takes it in logical pixels and scales it.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq)]
|
||||
pub struct Panel {
|
||||
pub x: f32,
|
||||
pub y: f32,
|
||||
pub w: f32,
|
||||
pub h: f32,
|
||||
pub radius: f32,
|
||||
/// 0..1, brightens the rim and adds the accent glow.
|
||||
pub focus: f32,
|
||||
pub alpha: f32,
|
||||
/// Frost: mip level of the backdrop seen through it (higher = blurrier).
|
||||
/// Negative = nested glass that sits on another pane.
|
||||
pub blur: f32,
|
||||
/// Accent light (rgb 0..1) for focus glow and rim.
|
||||
pub glow: [f32; 3],
|
||||
/// Consecutive panels with the same group (> 0) melt into one shape.
|
||||
pub group: f32,
|
||||
/// rgb + amount (0..1).
|
||||
pub tint: [f32; 4],
|
||||
}
|
||||
|
||||
impl Panel {
|
||||
/// The same panel with every length multiplied by `k` (logical → physical).
|
||||
pub fn scaled(mut self, k: f32) -> Panel {
|
||||
self.x *= k;
|
||||
self.y *= k;
|
||||
self.w *= k;
|
||||
self.h *= k;
|
||||
self.radius *= k;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// A picture uploaded with [`GlassRenderer::upload_image`].
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
|
||||
pub struct ImageId(pub(crate) u32);
|
||||
|
||||
/// One picture on the backdrop, drawn over the gradient (and under the glass).
|
||||
#[derive(Debug, Clone, Copy)]
|
||||
pub struct ImageDraw {
|
||||
pub image: ImageId,
|
||||
/// 0..1, for crossfades.
|
||||
pub alpha: f32,
|
||||
/// Darkens the whole picture (0 = as is).
|
||||
pub dim: f32,
|
||||
/// Darkens towards the left edge (room for a title), 0..1.
|
||||
pub fade_left: f32,
|
||||
/// Darkens towards the bottom edge, 0..1.
|
||||
pub fade_bottom: f32,
|
||||
/// Which part stays visible when the picture is cropped to the screen
|
||||
/// (0..1 per axis, 0.5 = centre).
|
||||
pub align: [f32; 2],
|
||||
/// Drawn sharp at full resolution. When false only the soft (blurred,
|
||||
/// low resolution) copy shows, like a frosted wallpaper.
|
||||
pub sharp: bool,
|
||||
}
|
||||
|
||||
/// Colour matrix of a video frame.
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub enum Matrix {
|
||||
Bt601,
|
||||
#[default]
|
||||
Bt709,
|
||||
Bt2020,
|
||||
}
|
||||
|
||||
/// One decoded video frame in NV12: a full-size Y plane and a half-size
|
||||
/// plane of interleaved Cb/Cr bytes.
|
||||
pub trait Nv12Frame {
|
||||
fn width(&self) -> u32;
|
||||
fn height(&self) -> u32;
|
||||
/// Display aspect ratio (width / height, pixel aspect included).
|
||||
fn aspect(&self) -> f32 {
|
||||
self.width() as f32 / self.height().max(1) as f32
|
||||
}
|
||||
/// Plane 0 (Y) or 1 (CbCr): bytes and the stride (bytes per row).
|
||||
fn plane(&self, index: usize) -> (&[u8], usize);
|
||||
fn matrix(&self) -> Matrix {
|
||||
Matrix::Bt709
|
||||
}
|
||||
fn full_range(&self) -> bool {
|
||||
false
|
||||
}
|
||||
}
|
||||
|
||||
/// The video layer of a frame. The renderer keeps the last uploaded frame,
|
||||
/// so `frame` only needs to be set when a new one arrived.
|
||||
pub struct VideoDraw<'a> {
|
||||
pub frame: Option<&'a dyn Nv12Frame>,
|
||||
/// 0..1, for fading in.
|
||||
pub alpha: f32,
|
||||
}
|
||||
|
||||
/// How much of the glass effect to draw (weaker TVs: lighter modes).
|
||||
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
|
||||
pub enum Quality {
|
||||
/// Refraction, dispersion, Fresnel: the full Liquid Glass.
|
||||
#[default]
|
||||
Full,
|
||||
/// Frosted glass with the lit rim, no lensing.
|
||||
Light,
|
||||
/// No frost: tinted panes with the rim only.
|
||||
Flat,
|
||||
}
|
||||
|
||||
/// Everything the renderer needs for one frame.
|
||||
pub struct Frame<'a> {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
/// Physical pixels per logical pixel (glass sizes depend on it).
|
||||
pub scale: f32,
|
||||
/// Seconds since start (animation clock).
|
||||
pub time: f32,
|
||||
/// Backdrop palette (highlight, mid, deep), rgb 0..1 each.
|
||||
pub palette: [f32; 9],
|
||||
/// Backdrop brightness, 0..1 (1 = full).
|
||||
pub brightness: f32,
|
||||
/// Direction towards the key light (screen space, y down).
|
||||
pub light: [f32; 2],
|
||||
/// Backdrop zoom (1 = none), e.g. for a launch fly-in.
|
||||
pub zoom: f32,
|
||||
/// Pictures over the gradient, in drawing order.
|
||||
pub images: &'a [ImageDraw],
|
||||
pub video: Option<VideoDraw<'a>>,
|
||||
pub rects: Vec<Panel>,
|
||||
pub quality: Quality,
|
||||
}
|
||||
|
||||
impl Default for Frame<'_> {
|
||||
fn default() -> Self {
|
||||
Frame {
|
||||
width: 0,
|
||||
height: 0,
|
||||
scale: 1.0,
|
||||
time: 0.0,
|
||||
palette: crate::Palette::NEUTRAL.to_floats(),
|
||||
brightness: 1.0,
|
||||
light: [-0.63, -0.78],
|
||||
zoom: 1.0,
|
||||
images: &[],
|
||||
video: None,
|
||||
rects: Vec::new(),
|
||||
quality: Quality::Full,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,14 +1,18 @@
|
||||
//! OpenGL underlay drawn before Slint renders its items.
|
||||
//!
|
||||
//! Pass 1 renders the backdrop (a smooth gradient) into a small, mipmapped
|
||||
//! texture. Pass 2 upscales it to the window. Pass 3 draws every glass panel
|
||||
//! as its own quad, covering only the panel and its shadow, blended onto the
|
||||
//! window. Uniform locations are looked up once.
|
||||
//! Pass 1 renders the backdrop (gradient, then pictures, then video) into a
|
||||
//! small, mipmapped texture: that is what the glass refracts and frosts.
|
||||
//! Pass 2 puts the backdrop on the window: the small texture upscaled, then
|
||||
//! sharp pictures and the video at full resolution. Pass 3 draws every glass
|
||||
//! panel as its own quad, covering only the panel and its shadow. Uniform
|
||||
//! locations are looked up once; GL state is handed back to Slint untouched.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use glow::HasContext;
|
||||
|
||||
use super::shaders;
|
||||
use super::{Frame, MAX_GROUP, MAX_RECTS, Panel};
|
||||
use super::{Frame, ImageDraw, ImageId, MAX_GROUP, MAX_RECTS, Matrix, Nv12Frame, Panel};
|
||||
|
||||
/// The backdrop is blurry by design, so it never needs more than this width.
|
||||
const SCENE_MAX_W: i32 = 640;
|
||||
@@ -20,7 +24,7 @@ struct SceneLocs {
|
||||
time: Loc,
|
||||
pal: Loc,
|
||||
zoom: Loc,
|
||||
shelf: Loc,
|
||||
bright: Loc,
|
||||
}
|
||||
|
||||
struct BlitLocs {
|
||||
@@ -28,6 +32,27 @@ struct BlitLocs {
|
||||
time: Loc,
|
||||
}
|
||||
|
||||
struct ImageLocs {
|
||||
image: Loc,
|
||||
img: Loc,
|
||||
res: Loc,
|
||||
align: Loc,
|
||||
dim: Loc,
|
||||
fade_left: Loc,
|
||||
fade_bottom: Loc,
|
||||
alpha: Loc,
|
||||
}
|
||||
|
||||
struct VideoLocs {
|
||||
y: Loc,
|
||||
uv: Loc,
|
||||
res: Loc,
|
||||
aspect: Loc,
|
||||
matrix: Loc,
|
||||
full: Loc,
|
||||
alpha: Loc,
|
||||
}
|
||||
|
||||
struct GlassLocs {
|
||||
box_: Loc,
|
||||
res: Loc,
|
||||
@@ -40,6 +65,24 @@ struct GlassLocs {
|
||||
param: Loc,
|
||||
glow: Loc,
|
||||
tint: Loc,
|
||||
mode: Loc,
|
||||
}
|
||||
|
||||
struct Image {
|
||||
tex: glow::Texture,
|
||||
w: i32,
|
||||
h: i32,
|
||||
}
|
||||
|
||||
/// The last uploaded video frame.
|
||||
struct Video {
|
||||
y: glow::Texture,
|
||||
uv: glow::Texture,
|
||||
size: (i32, i32),
|
||||
aspect: f32,
|
||||
matrix: Matrix,
|
||||
full: bool,
|
||||
ready: bool,
|
||||
}
|
||||
|
||||
pub struct GlassRenderer {
|
||||
@@ -47,15 +90,22 @@ pub struct GlassRenderer {
|
||||
vao: glow::VertexArray,
|
||||
scene_prog: glow::Program,
|
||||
blit_prog: glow::Program,
|
||||
image_prog: glow::Program,
|
||||
video_prog: glow::Program,
|
||||
glass_prog: glow::Program,
|
||||
scene_locs: SceneLocs,
|
||||
blit_locs: BlitLocs,
|
||||
image_locs: ImageLocs,
|
||||
video_locs: VideoLocs,
|
||||
glass_locs: GlassLocs,
|
||||
fbo: glow::Framebuffer,
|
||||
tex: glow::Texture,
|
||||
tex_size: (i32, i32),
|
||||
/// RGBA16F if the driver can render to it (no banding in dark gradients).
|
||||
half_float: bool,
|
||||
images: HashMap<u32, Image>,
|
||||
next_image: u32,
|
||||
video: Option<Video>,
|
||||
}
|
||||
|
||||
/// GL state we touch and must hand back to the Slint renderer untouched.
|
||||
@@ -66,6 +116,7 @@ struct SavedState {
|
||||
framebuffer: i32,
|
||||
active_texture: i32,
|
||||
texture0: i32,
|
||||
texture1: i32,
|
||||
viewport: [i32; 4],
|
||||
blend: bool,
|
||||
blend_func: [i32; 4],
|
||||
@@ -74,6 +125,8 @@ struct SavedState {
|
||||
depth: bool,
|
||||
stencil: bool,
|
||||
cull: bool,
|
||||
unpack_alignment: i32,
|
||||
unpack_row_length: i32,
|
||||
}
|
||||
|
||||
impl GlassRenderer {
|
||||
@@ -92,6 +145,8 @@ impl GlassRenderer {
|
||||
|
||||
let scene_prog = link(&gl, header, shaders::VERTEX, shaders::SCENE)?;
|
||||
let blit_prog = link(&gl, header, shaders::VERTEX, shaders::BLIT)?;
|
||||
let image_prog = link(&gl, header, shaders::VERTEX, shaders::IMAGE)?;
|
||||
let video_prog = link(&gl, header, shaders::VERTEX, shaders::VIDEO)?;
|
||||
let glass_prog = link(&gl, header, shaders::QUAD_VERTEX, shaders::GLASS)?;
|
||||
let loc = |p: glow::Program, name: &str| gl.get_uniform_location(p, name);
|
||||
let scene_locs = SceneLocs {
|
||||
@@ -99,9 +154,28 @@ impl GlassRenderer {
|
||||
time: loc(scene_prog, "uTime"),
|
||||
pal: loc(scene_prog, "uPal"),
|
||||
zoom: loc(scene_prog, "uZoom"),
|
||||
shelf: loc(scene_prog, "uShelf"),
|
||||
bright: loc(scene_prog, "uBright"),
|
||||
};
|
||||
let blit_locs = BlitLocs { scene: loc(blit_prog, "uScene"), time: loc(blit_prog, "uTime") };
|
||||
let image_locs = ImageLocs {
|
||||
image: loc(image_prog, "uImage"),
|
||||
img: loc(image_prog, "uImg"),
|
||||
res: loc(image_prog, "uRes"),
|
||||
align: loc(image_prog, "uAlign"),
|
||||
dim: loc(image_prog, "uDim"),
|
||||
fade_left: loc(image_prog, "uFadeLeft"),
|
||||
fade_bottom: loc(image_prog, "uFadeBottom"),
|
||||
alpha: loc(image_prog, "uAlpha"),
|
||||
};
|
||||
let video_locs = VideoLocs {
|
||||
y: loc(video_prog, "uY"),
|
||||
uv: loc(video_prog, "uUV"),
|
||||
res: loc(video_prog, "uRes"),
|
||||
aspect: loc(video_prog, "uAspect"),
|
||||
matrix: loc(video_prog, "uMatrix"),
|
||||
full: loc(video_prog, "uFull"),
|
||||
alpha: loc(video_prog, "uAlpha"),
|
||||
};
|
||||
let glass_locs = GlassLocs {
|
||||
box_: loc(glass_prog, "uBox"),
|
||||
res: loc(glass_prog, "uRes"),
|
||||
@@ -114,6 +188,7 @@ impl GlassRenderer {
|
||||
param: loc(glass_prog, "uParam"),
|
||||
glow: loc(glass_prog, "uGlow"),
|
||||
tint: loc(glass_prog, "uTint"),
|
||||
mode: loc(glass_prog, "uMode"),
|
||||
};
|
||||
let vao = gl.create_vertex_array().map_err(anyhow::Error::msg)?;
|
||||
let fbo = gl.create_framebuffer().map_err(anyhow::Error::msg)?;
|
||||
@@ -124,14 +199,21 @@ impl GlassRenderer {
|
||||
vao,
|
||||
scene_prog,
|
||||
blit_prog,
|
||||
image_prog,
|
||||
video_prog,
|
||||
glass_prog,
|
||||
scene_locs,
|
||||
blit_locs,
|
||||
image_locs,
|
||||
video_locs,
|
||||
glass_locs,
|
||||
fbo,
|
||||
tex,
|
||||
tex_size: (0, 0),
|
||||
half_float: true,
|
||||
images: HashMap::new(),
|
||||
next_image: 1,
|
||||
video: None,
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -142,6 +224,8 @@ impl GlassRenderer {
|
||||
let mut viewport = [0; 4];
|
||||
gl.get_parameter_i32_slice(glow::VIEWPORT, &mut viewport);
|
||||
let active_texture = gl.get_parameter_i32(glow::ACTIVE_TEXTURE);
|
||||
gl.active_texture(glow::TEXTURE1);
|
||||
let texture1 = gl.get_parameter_i32(glow::TEXTURE_BINDING_2D);
|
||||
gl.active_texture(glow::TEXTURE0);
|
||||
SavedState {
|
||||
program: gl.get_parameter_i32(glow::CURRENT_PROGRAM),
|
||||
@@ -150,6 +234,7 @@ impl GlassRenderer {
|
||||
framebuffer: gl.get_parameter_i32(glow::FRAMEBUFFER_BINDING),
|
||||
active_texture,
|
||||
texture0: gl.get_parameter_i32(glow::TEXTURE_BINDING_2D),
|
||||
texture1,
|
||||
viewport,
|
||||
blend: gl.is_enabled(glow::BLEND),
|
||||
blend_func: [
|
||||
@@ -166,6 +251,8 @@ impl GlassRenderer {
|
||||
depth: gl.is_enabled(glow::DEPTH_TEST),
|
||||
stencil: gl.is_enabled(glow::STENCIL_TEST),
|
||||
cull: gl.is_enabled(glow::CULL_FACE),
|
||||
unpack_alignment: gl.get_parameter_i32(glow::UNPACK_ALIGNMENT),
|
||||
unpack_row_length: gl.get_parameter_i32(glow::UNPACK_ROW_LENGTH),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -178,6 +265,8 @@ impl GlassRenderer {
|
||||
gl.bind_vertex_array(nz(s.vao).map(glow::NativeVertexArray));
|
||||
gl.bind_buffer(glow::ARRAY_BUFFER, nz(s.array_buffer).map(glow::NativeBuffer));
|
||||
gl.bind_framebuffer(glow::FRAMEBUFFER, nz(s.framebuffer).map(glow::NativeFramebuffer));
|
||||
gl.active_texture(glow::TEXTURE1);
|
||||
gl.bind_texture(glow::TEXTURE_2D, nz(s.texture1).map(glow::NativeTexture));
|
||||
gl.active_texture(glow::TEXTURE0);
|
||||
gl.bind_texture(glow::TEXTURE_2D, nz(s.texture0).map(glow::NativeTexture));
|
||||
gl.active_texture(s.active_texture as u32);
|
||||
@@ -191,6 +280,8 @@ impl GlassRenderer {
|
||||
set(glow::DEPTH_TEST, s.depth);
|
||||
set(glow::STENCIL_TEST, s.stencil);
|
||||
set(glow::CULL_FACE, s.cull);
|
||||
gl.pixel_store_i32(glow::UNPACK_ALIGNMENT, s.unpack_alignment);
|
||||
gl.pixel_store_i32(glow::UNPACK_ROW_LENGTH, s.unpack_row_length);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -211,10 +302,7 @@ impl GlassRenderer {
|
||||
ty,
|
||||
glow::PixelUnpackData::Slice(None),
|
||||
);
|
||||
gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_MIN_FILTER, glow::LINEAR_MIPMAP_LINEAR as i32);
|
||||
gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_MAG_FILTER, glow::LINEAR as i32);
|
||||
gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_WRAP_S, glow::CLAMP_TO_EDGE as i32);
|
||||
gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_WRAP_T, glow::CLAMP_TO_EDGE as i32);
|
||||
set_filter(gl, true);
|
||||
gl.generate_mipmap(glow::TEXTURE_2D);
|
||||
gl.bind_framebuffer(glow::FRAMEBUFFER, Some(self.fbo));
|
||||
gl.framebuffer_texture_2d(glow::FRAMEBUFFER, glow::COLOR_ATTACHMENT0, glow::TEXTURE_2D, Some(self.tex), 0);
|
||||
@@ -238,6 +326,165 @@ impl GlassRenderer {
|
||||
self.tex_size = (w, h);
|
||||
}
|
||||
|
||||
/// Uploads a picture (RGBA8, top row first) for [`ImageDraw`].
|
||||
///
|
||||
/// # Safety
|
||||
/// Must be called with the context current (inside the rendering notifier).
|
||||
pub unsafe fn upload_image(&mut self, width: u32, height: u32, rgba: &[u8]) -> anyhow::Result<ImageId> {
|
||||
let (w, h) = (width as i32, height as i32);
|
||||
anyhow::ensure!(w > 0 && h > 0 && rgba.len() >= (width * height * 4) as usize, "bad image size");
|
||||
let gl = &self.gl;
|
||||
unsafe {
|
||||
let unpack = (gl.get_parameter_i32(glow::UNPACK_ALIGNMENT), gl.get_parameter_i32(glow::UNPACK_ROW_LENGTH));
|
||||
let bound = gl.get_parameter_i32(glow::TEXTURE_BINDING_2D);
|
||||
let tex = gl.create_texture().map_err(anyhow::Error::msg)?;
|
||||
gl.bind_texture(glow::TEXTURE_2D, Some(tex));
|
||||
gl.pixel_store_i32(glow::UNPACK_ALIGNMENT, 1);
|
||||
gl.pixel_store_i32(glow::UNPACK_ROW_LENGTH, 0);
|
||||
gl.tex_image_2d(
|
||||
glow::TEXTURE_2D,
|
||||
0,
|
||||
glow::RGBA8 as i32,
|
||||
w,
|
||||
h,
|
||||
0,
|
||||
glow::RGBA,
|
||||
glow::UNSIGNED_BYTE,
|
||||
glow::PixelUnpackData::Slice(Some(&rgba[..(width * height * 4) as usize])),
|
||||
);
|
||||
set_filter(gl, true);
|
||||
gl.generate_mipmap(glow::TEXTURE_2D);
|
||||
gl.pixel_store_i32(glow::UNPACK_ALIGNMENT, unpack.0);
|
||||
gl.pixel_store_i32(glow::UNPACK_ROW_LENGTH, unpack.1);
|
||||
gl.bind_texture(glow::TEXTURE_2D, std::num::NonZeroU32::new(bound as u32).map(glow::NativeTexture));
|
||||
let id = self.next_image;
|
||||
self.next_image += 1;
|
||||
self.images.insert(id, Image { tex, w, h });
|
||||
Ok(ImageId(id))
|
||||
}
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// Must be called with the context current.
|
||||
pub unsafe fn free_image(&mut self, id: ImageId) {
|
||||
if let Some(img) = self.images.remove(&id.0) {
|
||||
unsafe { self.gl.delete_texture(img.tex) };
|
||||
}
|
||||
}
|
||||
|
||||
/// Forgets the last video frame (the next one starts from black).
|
||||
pub fn clear_video(&mut self) {
|
||||
if let Some(v) = &mut self.video {
|
||||
v.ready = false;
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn upload_video(&mut self, frame: &dyn Nv12Frame) -> anyhow::Result<()> {
|
||||
let (w, h) = (frame.width() as i32, frame.height() as i32);
|
||||
anyhow::ensure!(w > 1 && h > 1, "empty video frame");
|
||||
let (cw, ch) = ((w + 1) / 2, (h + 1) / 2);
|
||||
let (y, y_stride) = frame.plane(0);
|
||||
let (uv, uv_stride) = frame.plane(1);
|
||||
anyhow::ensure!(y_stride >= w as usize && y.len() >= y_stride * (h as usize - 1) + w as usize, "short Y plane");
|
||||
anyhow::ensure!(
|
||||
uv_stride >= 2 * cw as usize && uv.len() >= uv_stride * (ch as usize - 1) + 2 * cw as usize,
|
||||
"short CbCr plane"
|
||||
);
|
||||
let gl = &self.gl;
|
||||
unsafe {
|
||||
if self.video.is_none() {
|
||||
let y = gl.create_texture().map_err(anyhow::Error::msg)?;
|
||||
let uv = gl.create_texture().map_err(anyhow::Error::msg)?;
|
||||
self.video =
|
||||
Some(Video { y, uv, size: (0, 0), aspect: 1.0, matrix: Matrix::Bt709, full: false, ready: false });
|
||||
}
|
||||
let v = self.video.as_mut().unwrap();
|
||||
let realloc = v.size != (w, h);
|
||||
gl.pixel_store_i32(glow::UNPACK_ALIGNMENT, 1);
|
||||
let planes = [
|
||||
(v.y, y, y_stride, w, h, glow::R8, glow::RED, 1usize),
|
||||
(v.uv, uv, uv_stride, cw, ch, glow::RG8, glow::RG, 2usize),
|
||||
];
|
||||
for (tex, data, stride, pw, ph, internal, format, bpp) in planes {
|
||||
gl.bind_texture(glow::TEXTURE_2D, Some(tex));
|
||||
gl.pixel_store_i32(glow::UNPACK_ROW_LENGTH, (stride / bpp) as i32);
|
||||
let len = stride * (ph as usize - 1) + pw as usize * bpp;
|
||||
let pixels = glow::PixelUnpackData::Slice(Some(&data[..len]));
|
||||
if realloc {
|
||||
gl.tex_image_2d(glow::TEXTURE_2D, 0, internal as i32, pw, ph, 0, format, glow::UNSIGNED_BYTE, pixels);
|
||||
set_filter(gl, true);
|
||||
} else {
|
||||
gl.tex_sub_image_2d(glow::TEXTURE_2D, 0, 0, 0, pw, ph, format, glow::UNSIGNED_BYTE, pixels);
|
||||
}
|
||||
// Mipmaps keep the small backdrop copy free of shimmer.
|
||||
gl.generate_mipmap(glow::TEXTURE_2D);
|
||||
}
|
||||
gl.pixel_store_i32(glow::UNPACK_ROW_LENGTH, 0);
|
||||
v.size = (w, h);
|
||||
v.aspect = frame.aspect();
|
||||
v.matrix = frame.matrix();
|
||||
v.full = frame.full_range();
|
||||
v.ready = true;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Pictures and video into the current framebuffer (viewport `w` x `h`).
|
||||
/// `all`: also the soft-only pictures (the small backdrop copy).
|
||||
unsafe fn draw_layers(&self, f: &Frame, w: i32, h: i32, all: bool, video_alpha: f32) {
|
||||
let gl = &self.gl;
|
||||
unsafe {
|
||||
gl.enable(glow::BLEND);
|
||||
gl.blend_equation_separate(glow::FUNC_ADD, glow::FUNC_ADD);
|
||||
gl.blend_func_separate(glow::SRC_ALPHA, glow::ONE_MINUS_SRC_ALPHA, glow::ZERO, glow::ONE);
|
||||
for d in f.images.iter().filter(|d| d.alpha > 0.002 && (all || d.sharp)) {
|
||||
let Some(img) = self.images.get(&d.image.0) else { continue };
|
||||
self.draw_image(img, d, w, h);
|
||||
}
|
||||
if let Some(v) = self.video.as_ref().filter(|v| v.ready && video_alpha > 0.002) {
|
||||
let l = &self.video_locs;
|
||||
gl.use_program(Some(self.video_prog));
|
||||
gl.active_texture(glow::TEXTURE1);
|
||||
gl.bind_texture(glow::TEXTURE_2D, Some(v.uv));
|
||||
gl.active_texture(glow::TEXTURE0);
|
||||
gl.bind_texture(glow::TEXTURE_2D, Some(v.y));
|
||||
gl.uniform_1_i32(l.y.as_ref(), 0);
|
||||
gl.uniform_1_i32(l.uv.as_ref(), 1);
|
||||
gl.uniform_2_f32(l.res.as_ref(), w as f32, h as f32);
|
||||
gl.uniform_1_f32(l.aspect.as_ref(), v.aspect);
|
||||
let m = match v.matrix {
|
||||
Matrix::Bt601 => 0,
|
||||
Matrix::Bt709 => 1,
|
||||
Matrix::Bt2020 => 2,
|
||||
};
|
||||
gl.uniform_1_i32(l.matrix.as_ref(), m);
|
||||
gl.uniform_1_i32(l.full.as_ref(), v.full as i32);
|
||||
gl.uniform_1_f32(l.alpha.as_ref(), video_alpha.clamp(0.0, 1.0));
|
||||
gl.draw_arrays(glow::TRIANGLES, 0, 3);
|
||||
}
|
||||
gl.disable(glow::BLEND);
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn draw_image(&self, img: &Image, d: &ImageDraw, w: i32, h: i32) {
|
||||
let gl = &self.gl;
|
||||
let l = &self.image_locs;
|
||||
unsafe {
|
||||
gl.use_program(Some(self.image_prog));
|
||||
gl.active_texture(glow::TEXTURE0);
|
||||
gl.bind_texture(glow::TEXTURE_2D, Some(img.tex));
|
||||
gl.uniform_1_i32(l.image.as_ref(), 0);
|
||||
gl.uniform_2_f32(l.img.as_ref(), img.w as f32, img.h as f32);
|
||||
gl.uniform_2_f32(l.res.as_ref(), w as f32, h as f32);
|
||||
gl.uniform_2_f32(l.align.as_ref(), d.align[0], d.align[1]);
|
||||
gl.uniform_1_f32(l.dim.as_ref(), d.dim);
|
||||
gl.uniform_1_f32(l.fade_left.as_ref(), d.fade_left);
|
||||
gl.uniform_1_f32(l.fade_bottom.as_ref(), d.fade_bottom);
|
||||
gl.uniform_1_f32(l.alpha.as_ref(), d.alpha.clamp(0.0, 1.0));
|
||||
gl.draw_arrays(glow::TRIANGLES, 0, 3);
|
||||
}
|
||||
}
|
||||
|
||||
/// # Safety
|
||||
/// Must be called from the Slint rendering notifier with the context current.
|
||||
pub unsafe fn render(&mut self, f: &Frame) {
|
||||
@@ -253,9 +500,20 @@ impl GlassRenderer {
|
||||
gl.disable(glow::DEPTH_TEST);
|
||||
gl.disable(glow::STENCIL_TEST);
|
||||
gl.disable(glow::CULL_FACE);
|
||||
|
||||
let mut video_alpha = 0.0;
|
||||
if let Some(v) = &f.video {
|
||||
video_alpha = v.alpha;
|
||||
if let Some(frame) = v.frame {
|
||||
if let Err(e) = self.upload_video(frame) {
|
||||
log::warn!("glass: video frame: {e:#}");
|
||||
}
|
||||
}
|
||||
}
|
||||
let gl = &self.gl;
|
||||
gl.bind_vertex_array(Some(self.vao));
|
||||
|
||||
// Pass 1: backdrop at low resolution (it is a smooth gradient).
|
||||
// Pass 1: backdrop at low resolution (blurred by the glass anyway).
|
||||
let sw = (w / 4).clamp(1, SCENE_MAX_W);
|
||||
let sh = ((sw as i64 * h as i64 / w as i64) as i32).max(1);
|
||||
self.ensure_target(sw, sh);
|
||||
@@ -268,13 +526,16 @@ impl GlassRenderer {
|
||||
gl.uniform_1_f32(l.time.as_ref(), f.time);
|
||||
gl.uniform_3_f32_slice(l.pal.as_ref(), &f.palette);
|
||||
gl.uniform_1_f32(l.zoom.as_ref(), f.zoom);
|
||||
gl.uniform_1_f32(l.shelf.as_ref(), f.shelf);
|
||||
gl.uniform_1_f32(l.bright.as_ref(), f.brightness);
|
||||
gl.draw_arrays(glow::TRIANGLES, 0, 3);
|
||||
self.draw_layers(f, sw, sh, true, video_alpha);
|
||||
|
||||
let gl = &self.gl;
|
||||
gl.active_texture(glow::TEXTURE0);
|
||||
gl.bind_texture(glow::TEXTURE_2D, Some(self.tex));
|
||||
gl.generate_mipmap(glow::TEXTURE_2D);
|
||||
|
||||
// Pass 2: upscale to the window framebuffer.
|
||||
// Pass 2: the window. Upscaled backdrop, then sharp pictures and video.
|
||||
gl.bind_framebuffer(
|
||||
glow::FRAMEBUFFER,
|
||||
std::num::NonZeroU32::new(saved.framebuffer as u32).map(glow::NativeFramebuffer),
|
||||
@@ -285,8 +546,12 @@ impl GlassRenderer {
|
||||
gl.uniform_1_i32(l.scene.as_ref(), 0);
|
||||
gl.uniform_1_f32(l.time.as_ref(), f.time);
|
||||
gl.draw_arrays(glow::TRIANGLES, 0, 3);
|
||||
self.draw_layers(f, w, h, false, video_alpha);
|
||||
|
||||
// Pass 3: glass, one quad per panel or merged group: dst * a + rgb.
|
||||
let gl = &self.gl;
|
||||
gl.active_texture(glow::TEXTURE0);
|
||||
gl.bind_texture(glow::TEXTURE_2D, Some(self.tex));
|
||||
gl.enable(glow::BLEND);
|
||||
gl.blend_equation_separate(glow::FUNC_ADD, glow::FUNC_ADD);
|
||||
gl.blend_func_separate(glow::ONE, glow::SRC_ALPHA, glow::ZERO, glow::ONE);
|
||||
@@ -297,6 +562,12 @@ impl GlassRenderer {
|
||||
gl.uniform_1_f32(l.scale.as_ref(), f.scale);
|
||||
gl.uniform_1_f32(l.time.as_ref(), f.time);
|
||||
gl.uniform_2_f32(l.light.as_ref(), f.light[0], f.light[1]);
|
||||
let mode = match f.quality {
|
||||
super::Quality::Full => 0,
|
||||
super::Quality::Light => 1,
|
||||
super::Quality::Flat => 2,
|
||||
};
|
||||
gl.uniform_1_i32(l.mode.as_ref(), mode);
|
||||
|
||||
let rects = &f.rects[..f.rects.len().min(MAX_RECTS)];
|
||||
let mut rect = [0f32; MAX_GROUP * 4];
|
||||
@@ -370,8 +641,17 @@ impl GlassRenderer {
|
||||
/// Must be called with the context current.
|
||||
pub unsafe fn destroy(&mut self) {
|
||||
unsafe {
|
||||
for (_, img) in self.images.drain() {
|
||||
self.gl.delete_texture(img.tex);
|
||||
}
|
||||
if let Some(v) = self.video.take() {
|
||||
self.gl.delete_texture(v.y);
|
||||
self.gl.delete_texture(v.uv);
|
||||
}
|
||||
self.gl.delete_program(self.scene_prog);
|
||||
self.gl.delete_program(self.blit_prog);
|
||||
self.gl.delete_program(self.image_prog);
|
||||
self.gl.delete_program(self.video_prog);
|
||||
self.gl.delete_program(self.glass_prog);
|
||||
self.gl.delete_vertex_array(self.vao);
|
||||
self.gl.delete_framebuffer(self.fbo);
|
||||
@@ -380,6 +660,17 @@ impl GlassRenderer {
|
||||
}
|
||||
}
|
||||
|
||||
/// Linear filtering on the bound texture, with mipmaps for minification.
|
||||
unsafe fn set_filter(gl: &glow::Context, mipmaps: bool) {
|
||||
let min = if mipmaps { glow::LINEAR_MIPMAP_LINEAR } else { glow::LINEAR };
|
||||
unsafe {
|
||||
gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_MIN_FILTER, min as i32);
|
||||
gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_MAG_FILTER, glow::LINEAR as i32);
|
||||
gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_WRAP_S, glow::CLAMP_TO_EDGE as i32);
|
||||
gl.tex_parameter_i32(glow::TEXTURE_2D, glow::TEXTURE_WRAP_T, glow::CLAMP_TO_EDGE as i32);
|
||||
}
|
||||
}
|
||||
|
||||
/// Splits the panels into draw runs: consecutive panels sharing a group
|
||||
/// (> 0) melt together and are drawn as one; the rest are drawn alone.
|
||||
fn runs(rects: &[Panel]) -> impl Iterator<Item = &[Panel]> {
|
||||
@@ -423,3 +714,22 @@ unsafe fn link(gl: &glow::Context, header: &str, vs: &str, fs: &str) -> anyhow::
|
||||
Ok(program)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
fn p(group: f32) -> Panel {
|
||||
Panel { group, alpha: 1.0, ..Panel::default() }
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn groups_merge_only_when_consecutive() {
|
||||
let rects = [p(0.0), p(1.0), p(1.0), p(2.0), p(1.0), p(0.0), p(0.0)];
|
||||
let sizes: Vec<usize> = runs(&rects).map(<[Panel]>::len).collect();
|
||||
assert_eq!(sizes, [1, 2, 1, 1, 1, 1]);
|
||||
let big = [p(3.0); 6];
|
||||
let sizes: Vec<usize> = runs(&big).map(<[Panel]>::len).collect();
|
||||
assert_eq!(sizes, [MAX_GROUP, 2]);
|
||||
}
|
||||
}
|
||||
@@ -35,7 +35,7 @@ uniform vec2 uRes;
|
||||
uniform float uTime;
|
||||
uniform vec3 uPal[3]; // highlight, mid, deep
|
||||
uniform float uZoom; // launch fly-in
|
||||
uniform float uShelf; // 1 = top shelf showing, 0 = scrolled into the grid
|
||||
uniform float uBright; // backdrop brightness: 1 = full, lower = calmer (launcher: shelf hidden)
|
||||
|
||||
float field(vec2 d, float r) {
|
||||
return exp(-dot(d, d) / (r * r));
|
||||
@@ -83,9 +83,9 @@ void main() {
|
||||
// Soft shoulder so bright palettes stay "dark mode".
|
||||
col = col / (1.0 + col * 1.2);
|
||||
|
||||
// Calmer at the bottom where the icons sit; dimmer when the shelf is gone.
|
||||
// Calmer at the bottom where the icons sit; dimmer when asked (uBright).
|
||||
col *= mix(1.0, 0.62, smoothstep(0.45, 1.0, uv.y));
|
||||
col *= mix(0.42, 1.0, uShelf);
|
||||
col *= mix(0.42, 1.0, uBright);
|
||||
vec2 v = uv - 0.5;
|
||||
col *= 1.0 - 0.30 * dot(v, v);
|
||||
|
||||
@@ -113,6 +113,90 @@ void main() {
|
||||
}
|
||||
"#;
|
||||
|
||||
/// A backdrop picture (artwork), cover-fitted to the viewport and toned for
|
||||
/// text on top: darkened overall (`uDim`) and towards the left and bottom
|
||||
/// edges, where titles usually sit. Blended with alpha (crossfades).
|
||||
pub const IMAGE: &str = r#"
|
||||
in vec2 vUv;
|
||||
out vec4 fragColor;
|
||||
uniform sampler2D uImage;
|
||||
uniform vec2 uImg; // image size, px
|
||||
uniform vec2 uRes; // viewport size, px
|
||||
uniform vec2 uAlign; // which part stays visible when cropping (0..1, 0.5 = centre)
|
||||
uniform float uDim;
|
||||
uniform float uFadeLeft;
|
||||
uniform float uFadeBottom;
|
||||
uniform float uAlpha;
|
||||
|
||||
void main() {
|
||||
vec2 uv = vec2(vUv.x, 1.0 - vUv.y); // top-left origin, like the image rows
|
||||
float va = uRes.x / uRes.y;
|
||||
float ia = uImg.x / max(uImg.y, 1.0);
|
||||
vec2 st = uv;
|
||||
if (ia > va) {
|
||||
float f = va / ia;
|
||||
st.x = uAlign.x * (1.0 - f) + uv.x * f;
|
||||
} else {
|
||||
float f = ia / va;
|
||||
st.y = uAlign.y * (1.0 - f) + uv.y * f;
|
||||
}
|
||||
vec3 col = texture(uImage, st).rgb;
|
||||
float kl = uFadeLeft * (1.0 - smoothstep(0.05, 0.85, uv.x));
|
||||
float kb = uFadeBottom * smoothstep(0.30, 0.95, uv.y);
|
||||
float k = 1.0 - (1.0 - kl) * (1.0 - kb);
|
||||
col = mix(col, vec3(0.018, 0.018, 0.022), k) * (1.0 - uDim);
|
||||
fragColor = vec4(col, uAlpha);
|
||||
}
|
||||
"#;
|
||||
|
||||
/// A video frame (NV12: full-size Y plane, half-size interleaved CbCr plane),
|
||||
/// contain-fitted with black bars, converted to RGB here.
|
||||
pub const VIDEO: &str = r#"
|
||||
in vec2 vUv;
|
||||
out vec4 fragColor;
|
||||
uniform sampler2D uY;
|
||||
uniform sampler2D uUV;
|
||||
uniform vec2 uRes; // viewport size, px
|
||||
uniform float uAspect; // display aspect of the video
|
||||
uniform int uMatrix; // 0 = BT.601, 1 = BT.709, 2 = BT.2020
|
||||
uniform int uFull; // 1 = full range (0..255), else limited (16..235)
|
||||
uniform float uAlpha;
|
||||
|
||||
void main() {
|
||||
vec2 uv = vec2(vUv.x, 1.0 - vUv.y);
|
||||
float va = uRes.x / uRes.y;
|
||||
vec2 st = uv;
|
||||
float inside = 1.0;
|
||||
if (uAspect > va) {
|
||||
float h = va / uAspect;
|
||||
st.y = (uv.y - 0.5) / h + 0.5;
|
||||
} else {
|
||||
float w = uAspect / va;
|
||||
st.x = (uv.x - 0.5) / w + 0.5;
|
||||
}
|
||||
if (st.x < 0.0 || st.x > 1.0 || st.y < 0.0 || st.y > 1.0) inside = 0.0;
|
||||
st = clamp(st, vec2(0.0), vec2(1.0));
|
||||
|
||||
float y = texture(uY, st).r;
|
||||
vec2 c = texture(uUV, st).rg;
|
||||
if (uFull == 1) {
|
||||
c -= 0.5;
|
||||
} else {
|
||||
y = (y - 16.0 / 255.0) * (255.0 / 219.0);
|
||||
c = (c - 128.0 / 255.0) * (255.0 / 224.0);
|
||||
}
|
||||
vec3 rgb;
|
||||
if (uMatrix == 0) {
|
||||
rgb = vec3(y + 1.402 * c.y, y - 0.344136 * c.x - 0.714136 * c.y, y + 1.772 * c.x);
|
||||
} else if (uMatrix == 2) {
|
||||
rgb = vec3(y + 1.4746 * c.y, y - 0.16455 * c.x - 0.57135 * c.y, y + 1.8814 * c.x);
|
||||
} else {
|
||||
rgb = vec3(y + 1.5748 * c.y, y - 0.1873 * c.x - 0.4681 * c.y, y + 1.8556 * c.x);
|
||||
}
|
||||
fragColor = vec4(clamp(rgb, 0.0, 1.0) * inside, uAlpha);
|
||||
}
|
||||
"#;
|
||||
|
||||
/// One Liquid Glass panel (or one merged group of panels), drawn as a quad
|
||||
/// over its bounds plus the shadow margin.
|
||||
///
|
||||
@@ -142,6 +226,7 @@ uniform vec4 uRect[MAX_GROUP]; // x, y, w, h (px, top-left origin)
|
||||
uniform vec4 uParam[MAX_GROUP]; // radius, focus, alpha, frost (mip lod; < 0 = nested on other glass)
|
||||
uniform vec4 uGlow[MAX_GROUP]; // accent rgb, unused
|
||||
uniform vec4 uTint[MAX_GROUP]; // tint rgb, tint amount
|
||||
uniform int uMode; // 0 = full, 1 = light (frost, no lensing), 2 = flat (no frost)
|
||||
|
||||
float sdRoundRect(vec2 p, vec2 b, float r) {
|
||||
vec2 q = abs(p) - b + r;
|
||||
@@ -298,9 +383,11 @@ void main() {
|
||||
// The glass colour is affine in what is underneath: g = dst * A + B.
|
||||
float A = 0.0;
|
||||
vec3 B;
|
||||
if (nested) {
|
||||
if (nested || uMode == 2) {
|
||||
A = 1.0;
|
||||
B = vec3(0.0);
|
||||
} else if (uMode == 1) {
|
||||
B = sceneAt(p / uRes, lod);
|
||||
} else if (slope > 0.02) {
|
||||
// Bevel: refract each channel with its own IOR (dispersion).
|
||||
B.r = sceneAt((p + refractOffset(N, height, 1.46) * lens + mag) / uRes, lod).r;
|
||||
@@ -344,7 +431,7 @@ void main() {
|
||||
// Fresnel: steep bevel reflects the (blurred, brightened) surroundings.
|
||||
float cosT = clamp(N.z, 0.0, 1.0);
|
||||
float F = 0.04 + 0.96 * pow(1.0 - cosT, 5.0);
|
||||
float Fm = clamp(F, 0.0, 1.0) * 0.35 * mat;
|
||||
float Fm = uMode == 0 ? clamp(F, 0.0, 1.0) * 0.35 * mat : 0.0;
|
||||
vec3 env = mix(sceneAt((p + n2 * 60.0 * s) / uRes, 5.0) * 1.6, vec3(0.92), 0.35);
|
||||
A *= 1.0 - Fm;
|
||||
B = mix(B, env, Fm);
|
||||
39
crates/sf-ui/src/text.rs
Normal file
39
crates/sf-ui/src/text.rs
Normal file
@@ -0,0 +1,39 @@
|
||||
//! String helpers Slint lacks (wired into the `SfText` global by `glue!`).
|
||||
|
||||
/// Without its last character.
|
||||
pub fn drop_last(s: &str) -> String {
|
||||
let mut s = s.to_string();
|
||||
s.pop();
|
||||
s
|
||||
}
|
||||
|
||||
/// `n` bullets (a masked password).
|
||||
pub fn dots(n: usize) -> String {
|
||||
"•".repeat(n)
|
||||
}
|
||||
|
||||
/// The characters of a key event's text that can be typed: no controls, no
|
||||
/// Slint special keys (arrows etc. arrive as private-use code points).
|
||||
pub fn typable(s: &str) -> String {
|
||||
s.chars().filter(|c| !c.is_control() && !('\u{E000}'..='\u{F8FF}').contains(c)).collect()
|
||||
}
|
||||
|
||||
/// At most `n` characters.
|
||||
pub fn truncate(s: &str, n: usize) -> String {
|
||||
s.chars().take(n).collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn edits() {
|
||||
assert_eq!(drop_last("abő"), "ab");
|
||||
assert_eq!(drop_last(""), "");
|
||||
assert_eq!(dots(3), "•••");
|
||||
assert_eq!(truncate("árvíz", 3), "árv");
|
||||
assert_eq!(typable("a\u{F700}\n"), "a");
|
||||
assert_eq!(typable("Ő"), "Ő");
|
||||
}
|
||||
}
|
||||
483
crates/sf-ui/src/video.rs
Normal file
483
crates/sf-ui/src/video.rs
Normal file
@@ -0,0 +1,483 @@
|
||||
//! Video playback with GStreamer, shown through the glass layer: the film is
|
||||
//! the backdrop, so glass controls on top refract it.
|
||||
//!
|
||||
//! - Hardware decoding (VA-API: H.264, HEVC incl. 10-bit, VP9, AV1) when the
|
||||
//! app has the `gpu` permission; FFmpeg software decoders otherwise.
|
||||
//! - `vapostproc` converts on the GPU and tone-maps HDR to SDR.
|
||||
//! - Every audio and subtitle track of the file (MKV, MP4, TS...), with
|
||||
//! embedded ASS/SRT subtitles rendered by GStreamer.
|
||||
//! - HTTP(S) streams with range seeking (a server streaming a file while it
|
||||
//! downloads works).
|
||||
//!
|
||||
//! ```ignore
|
||||
//! sf_ui::video::init()?;
|
||||
//! let player = Player::new("https://example.com/film.mkv", PlayerOptions { start: 754.0, ..Default::default() })?;
|
||||
//! glass.set_video(Some(player.video()));
|
||||
//! // every ~100 ms on the UI thread (slint::Timer):
|
||||
//! for event in player.poll() { /* Ready, Buffering, Eos, Error... */ }
|
||||
//! ```
|
||||
//!
|
||||
//! Needs GStreamer 1.22+ on the system (the SmartFox TV has it): base, good,
|
||||
//! bad (va, assrender), libav, and pipewire for sound. Apps need the `gpu`
|
||||
//! and `audio` permissions, and `network` for streams.
|
||||
|
||||
use std::rc::Rc;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use gstreamer as gst;
|
||||
use gstreamer::glib;
|
||||
use gstreamer::prelude::*;
|
||||
use gstreamer_app as gst_app;
|
||||
use gstreamer_video as gst_video;
|
||||
use gstreamer_video::prelude::*;
|
||||
|
||||
use crate::glass::VideoSource;
|
||||
use crate::render::{Matrix, Nv12Frame};
|
||||
|
||||
/// VA-API decoders, preferred over the software ones when present.
|
||||
const HW_DECODERS: [&str; 6] = ["vah264dec", "vah265dec", "vavp9dec", "vaav1dec", "vavp8dec", "vampeg2dec"];
|
||||
|
||||
/// Initialises GStreamer once and ranks the hardware decoders first.
|
||||
pub fn init() -> Result<()> {
|
||||
gst::init().context("initialising GStreamer")?;
|
||||
let registry = gst::Registry::get();
|
||||
for name in HW_DECODERS {
|
||||
if let Some(feature) = registry.lookup_feature(name) {
|
||||
feature.set_rank(gst::Rank::PRIMARY + 1);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Whether hardware video decoding is available (diagnostics).
|
||||
pub fn hardware_decoding() -> bool {
|
||||
let registry = gst::Registry::get();
|
||||
HW_DECODERS.iter().any(|n| registry.lookup_feature(n).is_some())
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct PlayerOptions {
|
||||
/// Start position in seconds.
|
||||
pub start: f64,
|
||||
/// Audio sync correction in milliseconds (positive: audio later).
|
||||
pub audio_offset_ms: i64,
|
||||
/// Show subtitles (the default track, see [`Player::set_text`]).
|
||||
pub subtitles: bool,
|
||||
/// HTTP user agent for streams.
|
||||
pub user_agent: Option<String>,
|
||||
/// Pango font for text subtitles (scaled with the video).
|
||||
pub subtitle_font: String,
|
||||
}
|
||||
|
||||
impl Default for PlayerOptions {
|
||||
fn default() -> Self {
|
||||
PlayerOptions {
|
||||
start: 0.0,
|
||||
audio_offset_ms: 0,
|
||||
subtitles: true,
|
||||
user_agent: None,
|
||||
subtitle_font: "Sans Bold 20".into(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What happened since the last [`Player::poll`].
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub enum Event {
|
||||
/// The stream is open (first frame ready): duration (s, if known) and
|
||||
/// the tracks can be read now. Playback starts right after.
|
||||
Ready { duration: Option<f64> },
|
||||
/// Network buffering, percent (100 = done; playback pauses meanwhile).
|
||||
Buffering(i32),
|
||||
/// Playing or paused (as asked, or because of buffering).
|
||||
Playing(bool),
|
||||
/// A seek finished.
|
||||
Seeked,
|
||||
/// The end of the stream.
|
||||
Eos,
|
||||
/// A fatal error; the player stops.
|
||||
Error(String),
|
||||
}
|
||||
|
||||
/// One audio or subtitle track of the stream.
|
||||
#[derive(Debug, Clone, Default, PartialEq)]
|
||||
pub struct Track {
|
||||
/// Index for [`Player::set_audio`] / [`Player::set_text`].
|
||||
pub index: i32,
|
||||
/// ISO 639 code ("hu", "en", "hun"...), if tagged.
|
||||
pub language: Option<String>,
|
||||
/// The track's title in the file ("Commentary", "Forced"...).
|
||||
pub title: Option<String>,
|
||||
pub codec: Option<String>,
|
||||
}
|
||||
|
||||
/// The newest decoded frame, shared with the appsink thread.
|
||||
#[derive(Default)]
|
||||
struct Feed {
|
||||
latest: Mutex<Option<gst::Sample>>,
|
||||
}
|
||||
|
||||
struct FeedSource(Arc<Feed>);
|
||||
|
||||
struct GstFrame {
|
||||
frame: gst_video::VideoFrame<gst_video::video_frame::Readable>,
|
||||
aspect: f32,
|
||||
matrix: Matrix,
|
||||
full: bool,
|
||||
}
|
||||
|
||||
impl Nv12Frame for GstFrame {
|
||||
fn width(&self) -> u32 {
|
||||
self.frame.width()
|
||||
}
|
||||
fn height(&self) -> u32 {
|
||||
self.frame.height()
|
||||
}
|
||||
fn aspect(&self) -> f32 {
|
||||
self.aspect
|
||||
}
|
||||
fn plane(&self, index: usize) -> (&[u8], usize) {
|
||||
let data = self.frame.plane_data(index as u32).unwrap_or(&[]);
|
||||
let stride = self.frame.plane_stride().get(index).copied().unwrap_or(0).max(0) as usize;
|
||||
(data, stride)
|
||||
}
|
||||
fn matrix(&self) -> Matrix {
|
||||
self.matrix
|
||||
}
|
||||
fn full_range(&self) -> bool {
|
||||
self.full
|
||||
}
|
||||
}
|
||||
|
||||
impl VideoSource for FeedSource {
|
||||
fn take_frame(&self) -> Option<Box<dyn Nv12Frame + '_>> {
|
||||
let sample = self.0.latest.lock().unwrap().take()?;
|
||||
let info = gst_video::VideoInfo::from_caps(sample.caps()?).ok()?;
|
||||
if info.format() != gst_video::VideoFormat::Nv12 {
|
||||
return None;
|
||||
}
|
||||
let par = info.par();
|
||||
let aspect = info.width() as f32 * par.numer() as f32 / (info.height().max(1) as f32 * par.denom().max(1) as f32);
|
||||
let colorimetry = info.colorimetry();
|
||||
let matrix = match colorimetry.matrix() {
|
||||
gst_video::VideoColorMatrix::Bt601 | gst_video::VideoColorMatrix::Smpte240m => Matrix::Bt601,
|
||||
gst_video::VideoColorMatrix::Bt2020 => Matrix::Bt2020,
|
||||
gst_video::VideoColorMatrix::Bt709 => Matrix::Bt709,
|
||||
_ if info.height() < 720 => Matrix::Bt601,
|
||||
_ => Matrix::Bt709,
|
||||
};
|
||||
let full = colorimetry.range() == gst_video::VideoColorRange::Range0_255;
|
||||
let buffer = sample.buffer_owned()?;
|
||||
let frame = gst_video::VideoFrame::from_buffer_readable(buffer, &info).ok()?;
|
||||
Some(Box::new(GstFrame { frame, aspect, matrix, full }))
|
||||
}
|
||||
}
|
||||
|
||||
/// A playing stream. Dropping it stops playback.
|
||||
pub struct Player {
|
||||
playbin: gst::Element,
|
||||
bus: gst::Bus,
|
||||
feed: Arc<Feed>,
|
||||
start: f64,
|
||||
/// Playing was asked for (buffering may hold it paused).
|
||||
want_playing: bool,
|
||||
buffering: bool,
|
||||
ready: bool,
|
||||
seeking: bool,
|
||||
failed: bool,
|
||||
}
|
||||
|
||||
impl Player {
|
||||
/// Opens `uri` (https://, http://, file://) and starts playing as soon
|
||||
/// as it can. Call [`init`] once before.
|
||||
pub fn new(uri: &str, opts: PlayerOptions) -> Result<Player> {
|
||||
let feed = Arc::new(Feed::default());
|
||||
|
||||
let caps = gst_video::VideoCapsBuilder::new().format(gst_video::VideoFormat::Nv12).build();
|
||||
let sink = gst_app::AppSink::builder().caps(&caps).sync(true).max_buffers(2).drop(true).build();
|
||||
sink.set_property("enable-last-sample", false);
|
||||
let shared = feed.clone();
|
||||
sink.set_callbacks(
|
||||
gst_app::AppSinkCallbacks::builder()
|
||||
.new_sample(move |s| {
|
||||
let sample = s.pull_sample().map_err(|_| gst::FlowError::Eos)?;
|
||||
*shared.latest.lock().unwrap() = Some(sample);
|
||||
Ok(gst::FlowSuccess::Ok)
|
||||
})
|
||||
.build(),
|
||||
);
|
||||
|
||||
let playbin = gst::ElementFactory::make("playbin")
|
||||
.property("uri", uri)
|
||||
.property("video-sink", &sink)
|
||||
.build()
|
||||
.context("GStreamer playbin is missing (gstreamer1.0-plugins-base)")?;
|
||||
|
||||
// GPU colour conversion and HDR tone mapping, before the subtitle
|
||||
// overlay (which needs system memory) and the sink.
|
||||
if gst::ElementFactory::find("vapostproc").is_some() {
|
||||
match gst::parse::bin_from_description("vapostproc name=pp ! video/x-raw,format=NV12", true) {
|
||||
Ok(bin) => {
|
||||
if let Some(pp) = bin.by_name("pp") {
|
||||
if pp.find_property("hdr-tone-mapping").is_some() {
|
||||
pp.set_property("hdr-tone-mapping", true);
|
||||
}
|
||||
}
|
||||
playbin.set_property("video-filter", &bin);
|
||||
}
|
||||
Err(e) => log::warn!("video: vapostproc: {e}"),
|
||||
}
|
||||
}
|
||||
if let Some(audio) = ["pulsesink", "pipewiresink"]
|
||||
.iter()
|
||||
.find_map(|n| gst::ElementFactory::make(n).build().ok())
|
||||
{
|
||||
playbin.set_property("audio-sink", &audio);
|
||||
}
|
||||
playbin.set_property("subtitle-font-desc", opts.subtitle_font.as_str());
|
||||
playbin.set_property("av-offset", opts.audio_offset_ms * 1_000_000);
|
||||
// A few seconds of network buffer: smooth over a torrent that delivers in bursts.
|
||||
playbin.set_property("buffer-duration", 8i64 * 1_000_000_000);
|
||||
if !opts.subtitles {
|
||||
set_flag(&playbin, "text", false);
|
||||
}
|
||||
if let Some(ua) = opts.user_agent.clone() {
|
||||
playbin.connect("source-setup", false, move |args| {
|
||||
if let Some(src) = args.get(1).and_then(|v| v.get::<gst::Element>().ok()) {
|
||||
if src.find_property("user-agent").is_some() {
|
||||
src.set_property("user-agent", ua.as_str());
|
||||
}
|
||||
}
|
||||
None
|
||||
});
|
||||
}
|
||||
|
||||
let bus = playbin.bus().context("playbin has no bus")?;
|
||||
playbin.set_state(gst::State::Paused).context("opening the stream")?;
|
||||
Ok(Player {
|
||||
playbin,
|
||||
bus,
|
||||
feed,
|
||||
start: opts.start.max(0.0),
|
||||
want_playing: true,
|
||||
buffering: false,
|
||||
ready: false,
|
||||
seeking: false,
|
||||
failed: false,
|
||||
})
|
||||
}
|
||||
|
||||
/// The frame source for [`crate::Glass::set_video`].
|
||||
pub fn video(&self) -> Rc<dyn VideoSource> {
|
||||
Rc::new(FeedSource(self.feed.clone()))
|
||||
}
|
||||
|
||||
/// Handles what GStreamer reported since the last call. Call it often
|
||||
/// (every 50–200 ms) on the UI thread; it also drives buffering and the
|
||||
/// start position.
|
||||
pub fn poll(&mut self) -> Vec<Event> {
|
||||
let mut out = Vec::new();
|
||||
while let Some(msg) = self.bus.pop() {
|
||||
use gst::MessageView;
|
||||
match msg.view() {
|
||||
MessageView::Eos(_) => out.push(Event::Eos),
|
||||
MessageView::Error(e) => {
|
||||
let text = match e.debug() {
|
||||
Some(d) => format!("{} ({d})", e.error()),
|
||||
None => e.error().to_string(),
|
||||
};
|
||||
log::warn!("video: {text}");
|
||||
self.failed = true;
|
||||
let _ = self.playbin.set_state(gst::State::Null);
|
||||
out.push(Event::Error(e.error().to_string()));
|
||||
}
|
||||
MessageView::Buffering(b) => {
|
||||
let pct = b.percent();
|
||||
out.push(Event::Buffering(pct));
|
||||
if pct < 100 && !self.buffering {
|
||||
self.buffering = true;
|
||||
if self.ready && self.want_playing {
|
||||
let _ = self.playbin.set_state(gst::State::Paused);
|
||||
}
|
||||
} else if pct >= 100 && self.buffering {
|
||||
self.buffering = false;
|
||||
if self.ready && self.want_playing {
|
||||
let _ = self.playbin.set_state(gst::State::Playing);
|
||||
}
|
||||
}
|
||||
}
|
||||
MessageView::AsyncDone(_) => {
|
||||
if !self.ready {
|
||||
if self.start > 0.5 {
|
||||
// First preroll: jump to the start position, then play.
|
||||
let at = gst::ClockTime::from_nseconds((self.start * 1e9) as u64);
|
||||
self.start = 0.0;
|
||||
if self.playbin.seek_simple(gst::SeekFlags::FLUSH | gst::SeekFlags::KEY_UNIT, at).is_ok() {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
self.ready = true;
|
||||
out.push(Event::Ready { duration: self.duration() });
|
||||
if self.want_playing && !self.buffering {
|
||||
let _ = self.playbin.set_state(gst::State::Playing);
|
||||
}
|
||||
} else if self.seeking {
|
||||
self.seeking = false;
|
||||
out.push(Event::Seeked);
|
||||
}
|
||||
}
|
||||
MessageView::StateChanged(s) => {
|
||||
if s.src().is_some_and(|src| src == &self.playbin) {
|
||||
match s.current() {
|
||||
gst::State::Playing => out.push(Event::Playing(true)),
|
||||
gst::State::Paused if s.old() == gst::State::Playing => out.push(Event::Playing(false)),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
pub fn play(&mut self) {
|
||||
self.want_playing = true;
|
||||
if self.ready && !self.buffering && !self.failed {
|
||||
let _ = self.playbin.set_state(gst::State::Playing);
|
||||
}
|
||||
}
|
||||
|
||||
pub fn pause(&mut self) {
|
||||
self.want_playing = false;
|
||||
if !self.failed {
|
||||
let _ = self.playbin.set_state(gst::State::Paused);
|
||||
}
|
||||
}
|
||||
|
||||
/// Play/pause; returns whether it plays now.
|
||||
pub fn toggle(&mut self) -> bool {
|
||||
if self.want_playing {
|
||||
self.pause();
|
||||
} else {
|
||||
self.play();
|
||||
}
|
||||
self.want_playing
|
||||
}
|
||||
|
||||
/// Playing was asked for (it may still wait for the network).
|
||||
pub fn is_playing(&self) -> bool {
|
||||
self.want_playing
|
||||
}
|
||||
|
||||
pub fn is_ready(&self) -> bool {
|
||||
self.ready
|
||||
}
|
||||
|
||||
pub fn is_buffering(&self) -> bool {
|
||||
self.buffering || self.seeking || !self.ready
|
||||
}
|
||||
|
||||
/// Current position in seconds.
|
||||
pub fn position(&self) -> Option<f64> {
|
||||
self.playbin.query_position::<gst::ClockTime>().map(|t| t.nseconds() as f64 / 1e9)
|
||||
}
|
||||
|
||||
/// Duration in seconds, when the stream knows it.
|
||||
pub fn duration(&self) -> Option<f64> {
|
||||
self.playbin.query_duration::<gst::ClockTime>().map(|t| t.nseconds() as f64 / 1e9).filter(|d| *d > 0.0)
|
||||
}
|
||||
|
||||
/// Jumps to `seconds`. `exact` decodes up to that very frame (slower);
|
||||
/// otherwise it lands on the nearest keyframe before it.
|
||||
pub fn seek(&mut self, seconds: f64, exact: bool) {
|
||||
if !self.ready {
|
||||
self.start = seconds.max(0.0);
|
||||
return;
|
||||
}
|
||||
let flags = gst::SeekFlags::FLUSH | if exact { gst::SeekFlags::ACCURATE } else { gst::SeekFlags::KEY_UNIT };
|
||||
let at = gst::ClockTime::from_nseconds((seconds.max(0.0) * 1e9) as u64);
|
||||
if self.playbin.seek_simple(flags, at).is_ok() {
|
||||
self.seeking = true;
|
||||
}
|
||||
}
|
||||
|
||||
pub fn audio_tracks(&self) -> Vec<Track> {
|
||||
self.tracks("n-audio", "get-audio-tags", gst::tags::AudioCodec::TAG_NAME)
|
||||
}
|
||||
|
||||
pub fn text_tracks(&self) -> Vec<Track> {
|
||||
self.tracks("n-text", "get-text-tags", gst::tags::SubtitleCodec::TAG_NAME)
|
||||
}
|
||||
|
||||
pub fn current_audio(&self) -> i32 {
|
||||
self.playbin.property::<i32>("current-audio")
|
||||
}
|
||||
|
||||
/// The subtitle track shown, or `None` when subtitles are off.
|
||||
pub fn current_text(&self) -> Option<i32> {
|
||||
get_flag(&self.playbin, "text").then(|| self.playbin.property::<i32>("current-text")).filter(|i| *i >= 0)
|
||||
}
|
||||
|
||||
pub fn set_audio(&self, index: i32) {
|
||||
self.playbin.set_property("current-audio", index);
|
||||
}
|
||||
|
||||
/// Shows subtitle track `index`, or hides subtitles (`None`).
|
||||
pub fn set_text(&self, index: Option<i32>) {
|
||||
match index {
|
||||
Some(i) => {
|
||||
set_flag(&self.playbin, "text", true);
|
||||
self.playbin.set_property("current-text", i);
|
||||
}
|
||||
None => set_flag(&self.playbin, "text", false),
|
||||
}
|
||||
}
|
||||
|
||||
/// Audio sync correction in milliseconds (positive: audio later).
|
||||
pub fn set_audio_offset_ms(&self, ms: i64) {
|
||||
self.playbin.set_property("av-offset", ms * 1_000_000);
|
||||
}
|
||||
|
||||
fn tracks(&self, count: &str, signal: &str, codec_tag: &str) -> Vec<Track> {
|
||||
let n = self.playbin.property::<i32>(count);
|
||||
(0..n)
|
||||
.map(|i| {
|
||||
let tags = self.playbin.emit_by_name::<Option<gst::TagList>>(signal, &[&i]);
|
||||
let mut t = Track { index: i, ..Track::default() };
|
||||
if let Some(tags) = tags {
|
||||
t.language = tags.get::<gst::tags::LanguageCode>().map(|v| v.get().to_string());
|
||||
t.title = tags.get::<gst::tags::Title>().map(|v| v.get().to_string());
|
||||
t.codec = tags
|
||||
.generic(codec_tag)
|
||||
.and_then(|v| v.get::<String>().ok())
|
||||
.or_else(|| tags.get::<gst::tags::Codec>().map(|v| v.get().to_string()));
|
||||
}
|
||||
t
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Player {
|
||||
fn drop(&mut self) {
|
||||
let _ = self.playbin.set_state(gst::State::Null);
|
||||
}
|
||||
}
|
||||
|
||||
fn get_flag(playbin: &gst::Element, nick: &str) -> bool {
|
||||
let value = playbin.property_value("flags");
|
||||
let Some(class) = glib::FlagsClass::with_type(value.type_()) else { return false };
|
||||
class.value_by_nick(nick).is_some_and(|f| class.is_set(&value, f.value()))
|
||||
}
|
||||
|
||||
fn set_flag(playbin: &gst::Element, nick: &str, on: bool) {
|
||||
let value = playbin.property_value("flags");
|
||||
let Some(class) = glib::FlagsClass::with_type(value.type_()) else { return };
|
||||
let Some(builder) = class.builder_with_value(value) else { return };
|
||||
let builder = if on { builder.set_by_nick(nick) } else { builder.unset_by_nick(nick) };
|
||||
if let Some(v) = builder.build() {
|
||||
playbin.set_property_from_value("flags", &v);
|
||||
}
|
||||
}
|
||||
BIN
crates/sf-ui/ui/fonts/Onest-Bold.ttf
Normal file
BIN
crates/sf-ui/ui/fonts/Onest-Bold.ttf
Normal file
Binary file not shown.
BIN
crates/sf-ui/ui/fonts/Onest-Medium.ttf
Normal file
BIN
crates/sf-ui/ui/fonts/Onest-Medium.ttf
Normal file
Binary file not shown.
@@ -1,8 +1,9 @@
|
||||
Copyright (c) 2016 The Inter Project Authors (https://github.com/rsms/inter)
|
||||
Copyright 2021 The Onest Project Authors (https://github.com/googlefonts/onest)
|
||||
|
||||
This Font Software is licensed under the SIL Open Font License, Version 1.1.
|
||||
This license is copied below, and is also available with a FAQ at:
|
||||
http://scripts.sil.org/OFL
|
||||
https://scripts.sil.org/OFL
|
||||
|
||||
|
||||
-----------------------------------------------------------
|
||||
SIL OPEN FONT LICENSE Version 1.1 - 26 February 2007
|
||||
@@ -43,7 +44,7 @@ new environment.
|
||||
"Author" refers to any designer, engineer, programmer, technical
|
||||
writer or other person who contributed to the Font Software.
|
||||
|
||||
PERMISSION AND CONDITIONS
|
||||
PERMISSION & CONDITIONS
|
||||
Permission is hereby granted, free of charge, to any person obtaining
|
||||
a copy of the Font Software, to use, study, copy, merge, embed, modify,
|
||||
redistribute, and sell modified and unmodified copies of the Font
|
||||
BIN
crates/sf-ui/ui/fonts/Onest-Regular.ttf
Normal file
BIN
crates/sf-ui/ui/fonts/Onest-Regular.ttf
Normal file
Binary file not shown.
BIN
crates/sf-ui/ui/fonts/Onest-SemiBold.ttf
Normal file
BIN
crates/sf-ui/ui/fonts/Onest-SemiBold.ttf
Normal file
Binary file not shown.
960
crates/sf-ui/ui/sf-ui.slint
Normal file
960
crates/sf-ui/ui/sf-ui.slint
Normal file
@@ -0,0 +1,960 @@
|
||||
// sf-ui: the SmartFox TV UI kit for Slint (guide: docs/sf-ui.md).
|
||||
//
|
||||
// import { TvWindow, Tv, SfText, GlassRect, GlassPane, GlassButton } from "@sf-ui/sf-ui.slint";
|
||||
//
|
||||
// Two layers make up the screen:
|
||||
// 1. the glass layer (Rust, OpenGL): the backdrop (gradient, picture or
|
||||
// video) and every glass pane, drawn first;
|
||||
// 2. Slint: text, icons and pictures, drawn on top.
|
||||
// So Slint never draws the glass itself. Each glass component here exposes
|
||||
// `out property <GlassRect> glass` (its window position, size and look);
|
||||
// your root component lists them in exported `[GlassRect]` arrays, and Rust
|
||||
// hands those to the glass layer every frame. Nothing Slint draws may sit
|
||||
// *under* a glass pane: the pane would cover it.
|
||||
//
|
||||
// Sizes are design pixels on a 1920x1080 grid times `Tv.u` (TvWindow keeps
|
||||
// `Tv.u` up to date), so the UI scales with the screen.
|
||||
|
||||
import "fonts/Onest-Regular.ttf";
|
||||
import "fonts/Onest-Medium.ttf";
|
||||
import "fonts/Onest-SemiBold.ttf";
|
||||
import "fonts/Onest-Bold.ttf";
|
||||
|
||||
// One glass panel, in window coordinates (logical px).
|
||||
export struct GlassRect {
|
||||
x: length,
|
||||
y: length,
|
||||
w: length,
|
||||
h: length,
|
||||
// Corner radius.
|
||||
r: length,
|
||||
// 0..1: light from within, brighter rim, accent glow.
|
||||
focus: float,
|
||||
// 0..1: fade in/out (the glass "materializes": lensing ramps with it).
|
||||
alpha: float,
|
||||
// Frost (blur of the backdrop seen through it): ~1.2 small controls,
|
||||
// 2-4 big panes. Negative: nested glass that sits on another pane.
|
||||
blur: float,
|
||||
// Accent light colour (a solid colour).
|
||||
glow: brush,
|
||||
// Tint colour (solid); its alpha is the amount (0 = clear glass).
|
||||
tint: brush,
|
||||
// Consecutive rects with the same group (> 0) melt together like liquid.
|
||||
group: int,
|
||||
}
|
||||
|
||||
// Design tokens. All lengths: design px * Tv.u.
|
||||
export global Tv {
|
||||
// One design pixel (1920x1080 grid) in logical px. Set by TvWindow.
|
||||
in-out property <length> u: 1px;
|
||||
|
||||
// Text and focus (DESIGN.md, Fennec OS).
|
||||
out property <color> text: #ffffff;
|
||||
out property <color> text-secondary: #ffffffb8;
|
||||
out property <color> text-tertiary: #ffffff8f;
|
||||
// Text and icons on a focused (white) platter.
|
||||
out property <color> ink: #121317;
|
||||
out property <color> platter: #ffffffe0;
|
||||
// Dark tint of grouping glass (use with alpha 0.30-0.48).
|
||||
out property <color> smoke: #0b0c12;
|
||||
out property <color> hairline: #ffffff1f;
|
||||
out property <color> night: #050506;
|
||||
// System accent (system actions only) and states: glass tone + ink tone.
|
||||
out property <color> orange: #ff7a35;
|
||||
out property <color> orange-ink: #ff9a5c;
|
||||
out property <color> ok: #34c759;
|
||||
out property <color> ok-ink: #5ee07a;
|
||||
out property <color> warn: #ff9f0a;
|
||||
out property <color> warn-ink: #ffb340;
|
||||
out property <color> danger: #ff453a;
|
||||
out property <color> danger-ink: #ff8278;
|
||||
|
||||
// Safe area: keep content this far from the screen edges.
|
||||
out property <length> safe-x: 96 * self.u;
|
||||
out property <length> safe-y: 64 * self.u;
|
||||
}
|
||||
|
||||
// String helpers Slint lacks; wired to Rust by `sf_ui::glue!(App)` and
|
||||
// `ui.sf_ui_setup()`. Export it from your main .slint file.
|
||||
export global SfText {
|
||||
// The text without its last character.
|
||||
pure callback drop-last(string) -> string;
|
||||
// n bullets (a masked password).
|
||||
pure callback dots(int) -> string;
|
||||
// The first n characters.
|
||||
pure callback truncate(string, int) -> string;
|
||||
// Only the typable characters of a key event's text (no arrows, Return...).
|
||||
pure callback typable(string) -> string;
|
||||
}
|
||||
|
||||
// Base window for TV apps: night background (under the glass layer), the
|
||||
// Onest font, and `Tv.u` kept in sync with the window size.
|
||||
export component TvWindow inherits Window {
|
||||
background: Tv.night;
|
||||
default-font-family: "Onest";
|
||||
default-font-size: 28 * Tv.u;
|
||||
title: "SmartFox";
|
||||
preferred-width: 1600px;
|
||||
preferred-height: 900px;
|
||||
init => {
|
||||
Tv.u = min(self.width / 1920, self.height / 1080);
|
||||
}
|
||||
changed width => {
|
||||
Tv.u = min(self.width / 1920, self.height / 1080);
|
||||
}
|
||||
changed height => {
|
||||
Tv.u = min(self.width / 1920, self.height / 1080);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- type styles (Onest; tracking tightens from 48 px up) ----------------
|
||||
|
||||
// The one big name on a screen (96/700).
|
||||
export component Display inherits Text {
|
||||
font-size: 96 * Tv.u;
|
||||
font-weight: 700;
|
||||
letter-spacing: -2 * Tv.u;
|
||||
color: Tv.text;
|
||||
overflow: elide;
|
||||
}
|
||||
|
||||
// Screen titles (56/700).
|
||||
export component Headline inherits Text {
|
||||
font-size: 56 * Tv.u;
|
||||
font-weight: 700;
|
||||
letter-spacing: -1 * Tv.u;
|
||||
color: Tv.text;
|
||||
overflow: elide;
|
||||
}
|
||||
|
||||
// Section and page titles (40/700).
|
||||
export component Title inherits Text {
|
||||
font-size: 40 * Tv.u;
|
||||
font-weight: 700;
|
||||
color: Tv.text;
|
||||
overflow: elide;
|
||||
}
|
||||
|
||||
// Row titles (36/600).
|
||||
export component SectionTitle inherits Text {
|
||||
font-size: 36 * Tv.u;
|
||||
font-weight: 600;
|
||||
color: Tv.text;
|
||||
overflow: elide;
|
||||
}
|
||||
|
||||
// Descriptions (28/400); wraps.
|
||||
export component Body inherits Text {
|
||||
font-size: 28 * Tv.u;
|
||||
font-weight: 400;
|
||||
color: Tv.text-secondary;
|
||||
wrap: word-wrap;
|
||||
overflow: elide;
|
||||
}
|
||||
|
||||
// List and menu items (26/600).
|
||||
export component Item inherits Text {
|
||||
font-size: 26 * Tv.u;
|
||||
font-weight: 600;
|
||||
color: Tv.text;
|
||||
overflow: elide;
|
||||
}
|
||||
|
||||
// Labels, facts (24/500): the smallest text the household must read.
|
||||
export component Label inherits Text {
|
||||
font-size: 24 * Tv.u;
|
||||
font-weight: 500;
|
||||
color: Tv.text-secondary;
|
||||
overflow: elide;
|
||||
}
|
||||
|
||||
// Hints and details (22/500).
|
||||
export component Caption inherits Text {
|
||||
font-size: 22 * Tv.u;
|
||||
font-weight: 500;
|
||||
color: Tv.text-tertiary;
|
||||
overflow: elide;
|
||||
}
|
||||
|
||||
// ---- icons ------------------------------------------------------------------
|
||||
|
||||
// Line icons on a 32-unit grid. Names: play, pause, back, forward, up, down,
|
||||
// plus, check, close, search, info, rewind, fast-forward, next, previous,
|
||||
// subtitles, audio, list, star, home, film, tv, user, settings, warning,
|
||||
// space, delete, refresh.
|
||||
export component Icon inherits Rectangle {
|
||||
in property <string> name;
|
||||
in property <color> ink: Tv.text;
|
||||
in property <length> size: 32 * Tv.u;
|
||||
width: self.size;
|
||||
height: self.size;
|
||||
property <bool> filled: self.name == "play" || self.name == "star";
|
||||
Path {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
viewbox-width: 32;
|
||||
viewbox-height: 32;
|
||||
stroke: root.filled ? transparent : root.ink;
|
||||
stroke-width: root.size * (root.name == "pause" ? 3.2 : 2.4) / 32;
|
||||
fill: root.filled ? root.ink : transparent;
|
||||
commands: root.name == "play" ? "M 10 6.5 L 25.5 16 L 10 25.5 Z"
|
||||
: root.name == "pause" ? "M 11 7 L 11 25 M 21 7 L 21 25"
|
||||
: root.name == "back" ? "M 20 6 L 10 16 L 20 26"
|
||||
: root.name == "forward" ? "M 12 6 L 22 16 L 12 26"
|
||||
: root.name == "up" ? "M 6 20 L 16 10 L 26 20"
|
||||
: root.name == "down" ? "M 6 12 L 16 22 L 26 12"
|
||||
: root.name == "plus" ? "M 16 6 L 16 26 M 6 16 L 26 16"
|
||||
: root.name == "check" ? "M 6.5 16.5 L 13 23 L 25.5 9.5"
|
||||
: root.name == "close" ? "M 8 8 L 24 24 M 24 8 L 8 24"
|
||||
: root.name == "search" ? "M 14 5 A 9 9 0 1 1 14 23 A 9 9 0 1 1 14 5 M 20.5 20.5 L 27 27"
|
||||
: root.name == "info" ? "M 16 4 A 12 12 0 1 1 16 28 A 12 12 0 1 1 16 4 M 16 14.5 L 16 22.5 M 16 9.5 L 16 10"
|
||||
: root.name == "rewind" ? "M 15 8 L 7 16 L 15 24 M 25 8 L 17 16 L 25 24"
|
||||
: root.name == "fast-forward" ? "M 7 8 L 15 16 L 7 24 M 17 8 L 25 16 L 17 24"
|
||||
: root.name == "next" ? "M 8 7.5 L 20 16 L 8 24.5 Z M 24.5 8 L 24.5 24"
|
||||
: root.name == "previous" ? "M 24 7.5 L 12 16 L 24 24.5 Z M 7.5 8 L 7.5 24"
|
||||
: root.name == "subtitles" ? "M 5 8 L 27 8 L 27 24 L 5 24 Z M 9 15 L 15 15 M 18 15 L 23 15 M 9 19.5 L 19 19.5"
|
||||
: root.name == "audio" ? "M 5 12.5 L 10 12.5 L 16 7 L 16 25 L 10 19.5 L 5 19.5 Z M 20.5 11.5 A 6 6 0 0 1 20.5 20.5 M 24 8 A 11 11 0 0 1 24 24"
|
||||
: root.name == "list" ? "M 6 9 L 26 9 M 6 16 L 26 16 M 6 23 L 26 23"
|
||||
: root.name == "star" ? "M 16 4 L 19.6 11.6 L 27.8 12.5 L 21.7 18.1 L 23.3 26.2 L 16 22.1 L 8.7 26.2 L 10.3 18.1 L 4.2 12.5 L 12.4 11.6 Z"
|
||||
: root.name == "home" ? "M 5 15 L 16 5.5 L 27 15 M 8.5 12.5 L 8.5 26 L 23.5 26 L 23.5 12.5"
|
||||
: root.name == "film" ? "M 6 6 L 26 6 L 26 26 L 6 26 Z M 11 6 L 11 26 M 21 6 L 21 26 M 6 16 L 11 16 M 21 16 L 26 16"
|
||||
: root.name == "tv" ? "M 4 8 L 28 8 L 28 23 L 4 23 Z M 11 27 L 21 27"
|
||||
: root.name == "user" ? "M 16 5 A 5.5 5.5 0 1 1 16 16 A 5.5 5.5 0 1 1 16 5 M 6 27 A 10 9 0 0 1 26 27"
|
||||
: root.name == "settings" ? "M 6 10 L 26 10 M 6 22 L 26 22 M 12 7 L 12 13 M 20 19 L 20 25"
|
||||
: root.name == "warning" ? "M 16 4.5 L 28.5 26.5 L 3.5 26.5 Z M 16 12.5 L 16 19 M 16 22.5 L 16 23"
|
||||
: root.name == "space" ? "M 6 15 L 6 21 L 26 21 L 26 15"
|
||||
: root.name == "delete" ? "M 11 7 L 28 7 L 28 25 L 11 25 L 3 16 Z M 15 12 L 23 20 M 23 12 L 15 20"
|
||||
: root.name == "refresh" ? "M 25 16 A 9 9 0 1 1 22.4 9.6 M 23 4.5 L 23 10 L 17.5 10"
|
||||
: "";
|
||||
}
|
||||
}
|
||||
|
||||
// ---- glass ------------------------------------------------------------------
|
||||
|
||||
// A glass pane; put content inside. List `pane.glass` in an exported
|
||||
// [GlassRect] so the glass layer draws it. Content fades by itself: set its
|
||||
// opacity together with `alpha`.
|
||||
export component GlassPane inherits Rectangle {
|
||||
in property <length> radius: 48 * Tv.u;
|
||||
// Big modal panes 3-4, grouping platters ~2.2, small controls ~1.2.
|
||||
in property <float> frost: 3.0;
|
||||
// Smoke at 30-48% for grouping and modal panes; a colour for accents.
|
||||
in property <color> tint: Tv.smoke.with-alpha(0.38);
|
||||
in property <color> glow: #ffffff;
|
||||
// 0..1: light from within and a brighter rim (a focused pane).
|
||||
in property <float> lit: 0;
|
||||
in property <float> alpha: 1;
|
||||
in property <int> group: 0;
|
||||
// Sits on another glass pane (lights what is beneath, no own frost).
|
||||
in property <bool> nested: false;
|
||||
out property <GlassRect> glass: {
|
||||
x: self.absolute-position.x,
|
||||
y: self.absolute-position.y,
|
||||
w: self.width,
|
||||
h: self.height,
|
||||
r: min(self.radius, min(self.width, self.height) / 2),
|
||||
focus: self.lit,
|
||||
alpha: self.alpha,
|
||||
blur: self.nested ? -1 : self.frost,
|
||||
glow: self.glow,
|
||||
tint: self.tint,
|
||||
group: self.group,
|
||||
};
|
||||
}
|
||||
|
||||
// A capsule button. Focus is state you own (`focused`), shown as a white
|
||||
// platter with dark ink and a small lift; `primary` buttons are accent glass.
|
||||
export component GlassButton inherits Rectangle {
|
||||
in property <string> text;
|
||||
in property <string> icon;
|
||||
in property <bool> focused;
|
||||
in property <bool> primary;
|
||||
in property <bool> enabled: true;
|
||||
in property <bool> nested;
|
||||
in property <color> accent: Tv.orange;
|
||||
in property <float> alpha: 1;
|
||||
// Height; width follows the content (icon-only buttons are round).
|
||||
in property <length> size: 72 * Tv.u;
|
||||
out property <float> f: self.focused && self.enabled ? 1 : 0;
|
||||
animate f { duration: 240ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
|
||||
property <float> s: 1 + 0.05 * self.f;
|
||||
property <color> ink: self.primary ? Tv.text : Tv.ink.mix(Tv.text, self.f);
|
||||
height: self.size;
|
||||
min-width: self.size;
|
||||
|
||||
inner := Rectangle {
|
||||
transform-scale: root.s;
|
||||
opacity: root.alpha * (root.enabled ? 1 : 0.45);
|
||||
HorizontalLayout {
|
||||
padding-left: root.text == "" ? (root.size - 32 * Tv.u) / 2 : (root.icon == "" ? 36 : 28) * Tv.u;
|
||||
padding-right: root.text == "" ? (root.size - 32 * Tv.u) / 2 : 36 * Tv.u;
|
||||
spacing: 12 * Tv.u;
|
||||
alignment: center;
|
||||
if root.icon != "": Icon {
|
||||
y: (parent.height - self.height) / 2;
|
||||
name: root.icon;
|
||||
ink: root.ink;
|
||||
}
|
||||
if root.text != "": Text {
|
||||
vertical-alignment: center;
|
||||
text: root.text;
|
||||
font-size: 26 * Tv.u;
|
||||
font-weight: 600;
|
||||
color: root.ink;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
out property <GlassRect> glass: {
|
||||
x: self.absolute-position.x - self.width * (self.s - 1) / 2,
|
||||
y: self.absolute-position.y - self.height * (self.s - 1) / 2,
|
||||
w: self.width * self.s,
|
||||
h: self.height * self.s,
|
||||
r: self.height * self.s / 2,
|
||||
focus: self.f,
|
||||
alpha: self.alpha * (self.enabled ? 1 : 0.6),
|
||||
blur: self.nested ? -1 : 1.4,
|
||||
glow: self.primary ? self.accent : #ffffff,
|
||||
tint: self.primary
|
||||
? self.accent.with-alpha(self.enabled ? 0.34 + 0.5 * self.f : 0.1)
|
||||
: #ffffff.with-alpha(0.06 + 0.82 * self.f),
|
||||
group: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// A track with a fill (playback position, download...). The track is glass,
|
||||
// the fill is drawn by Slint on top.
|
||||
export component ProgressBar inherits Rectangle {
|
||||
in property <float> value;
|
||||
in property <float> buffered;
|
||||
in property <color> fill: Tv.text;
|
||||
in property <float> alpha: 1;
|
||||
in property <bool> nested: true;
|
||||
height: 12 * Tv.u;
|
||||
Rectangle {
|
||||
x: 0;
|
||||
width: parent.width * clamp(root.buffered, 0, 1);
|
||||
border-radius: self.height / 2;
|
||||
background: #ffffff30;
|
||||
opacity: root.alpha;
|
||||
}
|
||||
Rectangle {
|
||||
x: 0;
|
||||
width: max(self.height, parent.width * clamp(root.value, 0, 1));
|
||||
border-radius: self.height / 2;
|
||||
background: root.fill;
|
||||
opacity: root.value > 0 ? root.alpha : 0;
|
||||
}
|
||||
out property <GlassRect> glass: {
|
||||
x: self.absolute-position.x,
|
||||
y: self.absolute-position.y,
|
||||
w: self.width,
|
||||
h: self.height,
|
||||
r: self.height / 2,
|
||||
focus: 0,
|
||||
alpha: self.alpha,
|
||||
blur: self.nested ? -1 : 1.2,
|
||||
glow: #ffffff,
|
||||
tint: #00000038,
|
||||
group: 0,
|
||||
};
|
||||
}
|
||||
|
||||
// A spinning arc (loading).
|
||||
export component Spinner inherits Rectangle {
|
||||
in property <length> size: 56 * Tv.u;
|
||||
in property <color> ink: Tv.text;
|
||||
width: self.size;
|
||||
height: self.size;
|
||||
Path {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
viewbox-width: 32;
|
||||
viewbox-height: 32;
|
||||
commands: "M 16 3 A 13 13 0 1 1 3 16";
|
||||
stroke: root.ink;
|
||||
stroke-width: root.size * 3 / 32;
|
||||
transform-rotation: mod(animation-tick() / 1ms, 1000) / 1000 * 360deg;
|
||||
}
|
||||
}
|
||||
|
||||
// Artwork (poster, still, logo) with rounded corners and a focus lift.
|
||||
// Plain Slint, no glass: shadows on imagery are Slint's job.
|
||||
export component ArtworkCard inherits Rectangle {
|
||||
in property <image> image;
|
||||
// Shown while there is no picture.
|
||||
in property <string> placeholder;
|
||||
in property <bool> focused;
|
||||
// 0..1 bar along the bottom; negative = none.
|
||||
in property <float> progress: -1;
|
||||
// Small text over the top-left corner ("Új rész").
|
||||
in property <string> badge;
|
||||
in property <length> radius: 24 * Tv.u;
|
||||
in property <float> lift: 0.08;
|
||||
in property <color> accent: Tv.text;
|
||||
out property <float> f: self.focused ? 1 : 0;
|
||||
animate f { duration: 260ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
|
||||
|
||||
Rectangle {
|
||||
transform-scale: 1 + root.lift * root.f;
|
||||
// Shadow and the empty-card tone.
|
||||
Rectangle {
|
||||
border-radius: root.radius;
|
||||
background: #1b1d24;
|
||||
drop-shadow-blur: (14 + 22 * root.f) * Tv.u;
|
||||
drop-shadow-offset-y: (8 + 12 * root.f) * Tv.u;
|
||||
drop-shadow-color: #00000090;
|
||||
}
|
||||
Rectangle {
|
||||
border-radius: root.radius;
|
||||
clip: true;
|
||||
if root.image.width == 0: Text {
|
||||
x: 24 * Tv.u;
|
||||
width: parent.width - 48 * Tv.u;
|
||||
horizontal-alignment: center;
|
||||
vertical-alignment: center;
|
||||
text: root.placeholder;
|
||||
font-size: 26 * Tv.u;
|
||||
font-weight: 600;
|
||||
color: Tv.text-tertiary;
|
||||
wrap: word-wrap;
|
||||
}
|
||||
Image {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
source: root.image;
|
||||
image-fit: cover;
|
||||
}
|
||||
// Resting cards sit back a little.
|
||||
Rectangle {
|
||||
background: #000000;
|
||||
opacity: 0.22 * (1 - root.f);
|
||||
}
|
||||
if root.progress >= 0: Rectangle {
|
||||
y: parent.height - 8 * Tv.u;
|
||||
height: 8 * Tv.u;
|
||||
background: #00000099;
|
||||
Rectangle {
|
||||
x: 0;
|
||||
width: parent.width * clamp(root.progress, 0, 1);
|
||||
background: root.accent;
|
||||
}
|
||||
}
|
||||
}
|
||||
if root.badge != "": Rectangle {
|
||||
x: 14 * Tv.u;
|
||||
y: 14 * Tv.u;
|
||||
width: badge-text.preferred-width + 24 * Tv.u;
|
||||
height: 36 * Tv.u;
|
||||
border-radius: self.height / 2;
|
||||
background: #000000b0;
|
||||
badge-text := Text {
|
||||
text: root.badge;
|
||||
font-size: 20 * Tv.u;
|
||||
font-weight: 600;
|
||||
color: Tv.text;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// One row of a GlassMenu.
|
||||
export struct MenuItem {
|
||||
text: string,
|
||||
detail: string,
|
||||
checked: bool,
|
||||
}
|
||||
|
||||
// A list on a smoke glass platter with a white focus pill: track pickers,
|
||||
// option lists. Focus and scrolling follow `focused-index`.
|
||||
// `glass` holds two rects (platter, pill): list both.
|
||||
export component GlassMenu inherits Rectangle {
|
||||
in property <[MenuItem]> items;
|
||||
// The focused row (also where the list scrolls to); -1 = none.
|
||||
in property <int> focused-index: 0;
|
||||
// False: the list keeps its scroll position but shows no focus pill
|
||||
// (another list on screen has the focus).
|
||||
in property <bool> active: true;
|
||||
in property <string> title;
|
||||
in property <float> alpha: 1;
|
||||
in property <length> row-h: 72 * Tv.u;
|
||||
in property <int> visible-rows: 7;
|
||||
in property <color> accent: Tv.orange;
|
||||
property <length> pad: 12 * Tv.u;
|
||||
property <length> head: self.title == "" ? 0 : 72 * Tv.u;
|
||||
property <int> shown-rows: min(self.items.length, self.visible-rows);
|
||||
out property <float> pos: self.focused-index;
|
||||
animate pos { duration: 220ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
|
||||
property <float> first: clamp(self.pos - (self.visible-rows - 1) / 2, 0, max(0, self.items.length - self.visible-rows));
|
||||
width: 560 * Tv.u;
|
||||
height: self.head + 2 * self.pad + self.shown-rows * self.row-h;
|
||||
|
||||
if root.title != "": Text {
|
||||
x: 32 * Tv.u;
|
||||
y: root.pad;
|
||||
height: root.head;
|
||||
vertical-alignment: center;
|
||||
text: root.title;
|
||||
font-size: 24 * Tv.u;
|
||||
font-weight: 600;
|
||||
color: Tv.text-secondary;
|
||||
opacity: root.alpha;
|
||||
}
|
||||
Rectangle {
|
||||
x: root.pad;
|
||||
y: root.pad + root.head;
|
||||
width: root.width - 2 * root.pad;
|
||||
height: root.shown-rows * root.row-h;
|
||||
clip: true;
|
||||
for item[i] in root.items: Rectangle {
|
||||
property <float> f: root.active ? max(0, 1 - abs(root.pos - i)) : 0;
|
||||
y: (i - root.first) * root.row-h;
|
||||
height: root.row-h;
|
||||
opacity: root.alpha;
|
||||
HorizontalLayout {
|
||||
padding-left: 24 * Tv.u;
|
||||
padding-right: 24 * Tv.u;
|
||||
spacing: 12 * Tv.u;
|
||||
Rectangle {
|
||||
width: 32 * Tv.u;
|
||||
if item.checked: Icon {
|
||||
y: (parent.height - self.height) / 2;
|
||||
name: "check";
|
||||
ink: f > 0.5 ? Tv.ink : root.accent.brighter(0.3);
|
||||
}
|
||||
}
|
||||
Text {
|
||||
horizontal-stretch: 1;
|
||||
vertical-alignment: center;
|
||||
text: item.text;
|
||||
font-size: 26 * Tv.u;
|
||||
font-weight: 600;
|
||||
color: Tv.ink.mix(Tv.text, f);
|
||||
overflow: elide;
|
||||
}
|
||||
if item.detail != "": Text {
|
||||
vertical-alignment: center;
|
||||
text: item.detail;
|
||||
font-size: 22 * Tv.u;
|
||||
color: f > 0.5 ? #121317a0 : Tv.text-tertiary;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out property <[GlassRect]> glass: [
|
||||
{
|
||||
x: self.absolute-position.x,
|
||||
y: self.absolute-position.y,
|
||||
w: self.width,
|
||||
h: self.height,
|
||||
r: 32 * Tv.u,
|
||||
focus: 0.1,
|
||||
alpha: self.alpha,
|
||||
blur: 3.0,
|
||||
glow: #ffffff,
|
||||
tint: Tv.smoke.with-alpha(0.46),
|
||||
group: 0,
|
||||
},
|
||||
{
|
||||
x: self.absolute-position.x + self.pad,
|
||||
y: self.absolute-position.y + self.pad + self.head + (self.pos - self.first) * self.row-h,
|
||||
w: self.width - 2 * self.pad,
|
||||
h: self.row-h,
|
||||
r: self.row-h / 2,
|
||||
focus: 0.6,
|
||||
alpha: self.items.length > 0 && self.focused-index >= 0 && self.active ? self.alpha : 0,
|
||||
blur: -1,
|
||||
glow: #ffffff,
|
||||
tint: #ffffff.with-alpha(0.86),
|
||||
group: 0,
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
// ---- on-screen keyboard -------------------------------------------------------
|
||||
|
||||
// tvOS-style keyboard: a text field, one row of keys with a gliding focus
|
||||
// lens, mode chips. Remote: left/right move, OK types, down = chips, up =
|
||||
// keys, Back = cancel. A real keyboard types directly.
|
||||
//
|
||||
// Pass key events to it while it is open: `kb.key(event)` from your
|
||||
// FocusScope. Its `glass` holds 9 rects: list them all. Needs SfText.
|
||||
// Size: 1920 x 572 design px (432 when `compact`); its width may be smaller.
|
||||
export component Keyboard inherits Rectangle {
|
||||
in property <string> title;
|
||||
in property <string> subtitle;
|
||||
in property <string> placeholder;
|
||||
// Shows dots (with a "Megjelenítés" chip).
|
||||
in property <bool> secret;
|
||||
in property <string> submit-label: "Kész";
|
||||
in property <int> min-length: 0;
|
||||
in property <int> max-length: 64;
|
||||
in property <float> alpha: 1;
|
||||
// False while the focus is elsewhere on the screen (no focus lens).
|
||||
in property <bool> active: true;
|
||||
// No title/subtitle: 1920 x 432 design px.
|
||||
in property <bool> compact: false;
|
||||
in-out property <string> text;
|
||||
// Shown in red under the field until the text changes ("Hibás jelszó").
|
||||
in-out property <string> error;
|
||||
callback submitted(string);
|
||||
callback cancelled();
|
||||
// Up on the key row / down on the chips: the focus wants to leave the
|
||||
// keyboard (e.g. to search results). Ignore them to keep it inside.
|
||||
callback exit-up();
|
||||
callback exit-down();
|
||||
|
||||
in-out property <int> mode: 0; // abc, ABC, 123, #+=
|
||||
in-out property <int> index: 1;
|
||||
in-out property <int> area: 0; // 0 = keys, 1 = chips
|
||||
in-out property <int> chip: 0;
|
||||
in-out property <bool> reveal: false;
|
||||
|
||||
out property <[string]> keys: self.mode == 1
|
||||
? ["A", "Á", "B", "C", "D", "E", "É", "F", "G", "H", "I", "Í", "J", "K", "L", "M", "N", "O", "Ó", "Ö", "Ő", "P", "Q", "R", "S", "T", "U", "Ú", "Ü", "Ű", "V", "W", "X", "Y", "Z"]
|
||||
: self.mode == 2
|
||||
? ["1", "2", "3", "4", "5", "6", "7", "8", "9", "0", ".", ",", "-", "_", "@", "!", "?", "#", "$", "%", "&", "*", ":", "/"]
|
||||
: self.mode == 3
|
||||
? ["+", "=", "\\", ";", "'", "\"", "(", ")", "[", "]", "{", "}", "<", ">", "^", "`", "|", "~"]
|
||||
: ["a", "á", "b", "c", "d", "e", "é", "f", "g", "h", "i", "í", "j", "k", "l", "m", "n", "o", "ó", "ö", "ő", "p", "q", "r", "s", "t", "u", "ú", "ü", "ű", "v", "w", "x", "y", "z"];
|
||||
property <int> n: self.keys.length + 2;
|
||||
out property <[string]> chips: [
|
||||
"abc", "ABC", ".?123", "#+=",
|
||||
self.secret ? (self.reveal ? "Elrejtés" : "Megjelenítés") : "Törlés",
|
||||
self.submit-label,
|
||||
];
|
||||
property <int> len: self.text.character-count;
|
||||
out property <bool> can-submit: self.len >= self.min-length;
|
||||
property <string> hint: self.error != "" ? self.error
|
||||
: !self.can-submit && self.len == 0 ? "Legalább \{self.min-length} karakter"
|
||||
: !self.can-submit ? "Még \{self.min-length - self.len} karakter kell"
|
||||
: self.len >= self.max-length ? "Legfeljebb \{self.max-length} karakter"
|
||||
: self.secret ? "\{self.len} karakter" : "";
|
||||
property <string> shown-text: self.secret && !self.reveal ? SfText.dots(self.len) : self.text;
|
||||
|
||||
out property <float> pos: self.index;
|
||||
animate pos { duration: 200ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
|
||||
out property <float> cpos: self.chip;
|
||||
animate cpos { duration: 300ms; easing: cubic-bezier(0.22, 1, 0.36, 1); }
|
||||
out property <float> keys-active: self.active && self.area == 0 ? 1 : 0;
|
||||
animate keys-active { duration: 260ms; easing: ease-out; }
|
||||
out property <float> chips-active: self.active && self.area == 1 ? 1 : 0;
|
||||
animate chips-active { duration: 260ms; easing: ease-out; }
|
||||
|
||||
// Geometry (local), design px * u.
|
||||
property <length> field-w: 1200 * Tv.u;
|
||||
property <length> field-h: 96 * Tv.u;
|
||||
property <length> field-x: (self.width - self.field-w) / 2;
|
||||
property <length> top: self.compact ? 0 : 140 * Tv.u;
|
||||
property <length> field-y: self.top;
|
||||
property <length> key-w: min(54 * Tv.u, 1640 * Tv.u / self.n);
|
||||
property <length> row-x: (self.width - self.n * self.key-w) / 2;
|
||||
property <length> row-y: self.top + 180 * Tv.u;
|
||||
property <length> row-h: 120 * Tv.u;
|
||||
property <length> chip-w: 200 * Tv.u;
|
||||
property <length> chip-h: 72 * Tv.u;
|
||||
property <length> chip-step: 216 * Tv.u;
|
||||
property <length> chip-x: (self.width - 6 * self.chip-step + 16 * Tv.u) / 2;
|
||||
property <length> chip-y: self.top + 360 * Tv.u;
|
||||
width: 1920 * Tv.u;
|
||||
height: self.top + 432 * Tv.u;
|
||||
|
||||
// Clears the text and puts the focus back on the first key.
|
||||
public function reset() {
|
||||
root.text = "";
|
||||
root.error = "";
|
||||
root.mode = 0;
|
||||
root.index = 1;
|
||||
root.area = 0;
|
||||
root.chip = 0;
|
||||
root.reveal = false;
|
||||
}
|
||||
|
||||
function type-text(s: string) {
|
||||
if s != "" && root.len < root.max-length {
|
||||
root.text = SfText.truncate(root.text + s, root.max-length);
|
||||
root.error = "";
|
||||
}
|
||||
}
|
||||
|
||||
function delete-char() {
|
||||
root.text = SfText.drop-last(root.text);
|
||||
root.error = "";
|
||||
}
|
||||
|
||||
function press-key() {
|
||||
if root.index == 0 {
|
||||
root.type-text(" ");
|
||||
} else if root.index >= root.n - 1 {
|
||||
root.delete-char();
|
||||
} else {
|
||||
root.type-text(root.keys[root.index - 1]);
|
||||
}
|
||||
}
|
||||
|
||||
function press-chip() {
|
||||
if root.chip < 4 {
|
||||
root.mode = root.chip;
|
||||
root.index = min(root.index, root.keys.length + 1);
|
||||
root.area = 0;
|
||||
} else if root.chip == 4 {
|
||||
if root.secret {
|
||||
root.reveal = !root.reveal;
|
||||
} else {
|
||||
root.text = "";
|
||||
root.error = "";
|
||||
}
|
||||
} else if root.can-submit {
|
||||
root.submitted(root.text);
|
||||
}
|
||||
}
|
||||
|
||||
// Handles one key press; call it from your FocusScope while open.
|
||||
public function key(event: KeyEvent) -> EventResult {
|
||||
if event.text == Key.Escape {
|
||||
root.cancelled();
|
||||
} else if event.text == Key.Backspace {
|
||||
root.delete-char();
|
||||
} else if event.text == Key.Return {
|
||||
if root.area == 0 {
|
||||
root.press-key();
|
||||
} else {
|
||||
root.press-chip();
|
||||
}
|
||||
} else if event.text == Key.LeftArrow {
|
||||
if root.area == 0 {
|
||||
root.index = root.index <= 0 ? root.n - 1 : root.index - 1;
|
||||
} else {
|
||||
root.chip = max(0, root.chip - 1);
|
||||
}
|
||||
} else if event.text == Key.RightArrow {
|
||||
if root.area == 0 {
|
||||
root.index = root.index >= root.n - 1 ? 0 : root.index + 1;
|
||||
} else {
|
||||
root.chip = min(5, root.chip + 1);
|
||||
}
|
||||
} else if event.text == Key.DownArrow {
|
||||
if root.area == 0 {
|
||||
root.area = 1;
|
||||
root.chip = root.can-submit ? 5 : root.mode;
|
||||
} else {
|
||||
root.exit-down();
|
||||
}
|
||||
} else if event.text == Key.UpArrow {
|
||||
if root.area == 1 {
|
||||
root.area = 0;
|
||||
} else {
|
||||
root.exit-up();
|
||||
}
|
||||
} else if !event.modifiers.control && !event.modifiers.alt && !event.modifiers.meta {
|
||||
root.type-text(SfText.typable(event.text));
|
||||
}
|
||||
accept
|
||||
}
|
||||
|
||||
// ---- heading ----
|
||||
Text {
|
||||
y: 0;
|
||||
width: root.width;
|
||||
height: 60 * Tv.u;
|
||||
horizontal-alignment: center;
|
||||
vertical-alignment: center;
|
||||
text: root.title;
|
||||
font-weight: 700;
|
||||
font-size: 48 * Tv.u;
|
||||
letter-spacing: -0.8 * Tv.u;
|
||||
color: Tv.text;
|
||||
opacity: root.compact ? 0 : root.alpha;
|
||||
overflow: elide;
|
||||
}
|
||||
Text {
|
||||
x: 160 * Tv.u;
|
||||
y: 72 * Tv.u;
|
||||
width: root.width - 320 * Tv.u;
|
||||
horizontal-alignment: center;
|
||||
text: root.subtitle;
|
||||
font-size: 24 * Tv.u;
|
||||
color: Tv.text-secondary;
|
||||
opacity: root.compact ? 0 : root.alpha;
|
||||
overflow: elide;
|
||||
}
|
||||
|
||||
// ---- text field ----
|
||||
Rectangle {
|
||||
x: root.field-x;
|
||||
y: root.field-y;
|
||||
width: root.field-w;
|
||||
height: root.field-h;
|
||||
clip: true;
|
||||
opacity: root.alpha;
|
||||
HorizontalLayout {
|
||||
padding-left: 36 * Tv.u;
|
||||
padding-right: 36 * Tv.u;
|
||||
alignment: start;
|
||||
spacing: 4 * Tv.u;
|
||||
if root.shown-text == "": Text {
|
||||
vertical-alignment: center;
|
||||
text: root.placeholder;
|
||||
font-size: 32 * Tv.u;
|
||||
color: #ffffff59;
|
||||
}
|
||||
if root.shown-text != "": Text {
|
||||
vertical-alignment: center;
|
||||
text: root.shown-text;
|
||||
font-size: 34 * Tv.u;
|
||||
font-weight: 500;
|
||||
letter-spacing: 1 * Tv.u;
|
||||
color: Tv.text;
|
||||
}
|
||||
Rectangle {
|
||||
width: 3 * Tv.u;
|
||||
Rectangle {
|
||||
y: (parent.height - self.height) / 2;
|
||||
width: 100%;
|
||||
height: 44 * Tv.u;
|
||||
border-radius: self.width / 2;
|
||||
background: Tv.orange-ink;
|
||||
opacity: mod(animation-tick() / 1ms, 1000) < 550 ? 1 : 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Text {
|
||||
x: root.field-x;
|
||||
y: root.field-y + root.field-h + 20 * Tv.u;
|
||||
width: root.field-w;
|
||||
horizontal-alignment: center;
|
||||
text: root.hint;
|
||||
font-size: 22 * Tv.u;
|
||||
color: root.error != "" ? Tv.danger-ink : #ffffff99;
|
||||
opacity: root.alpha;
|
||||
}
|
||||
|
||||
// ---- key row: keys grow as the lens passes them ----
|
||||
for key[i] in root.keys: Text {
|
||||
property <float> f: max(0, 1 - abs(root.pos - (i + 1))) * root.keys-active;
|
||||
x: root.row-x + (i + 1) * root.key-w - 20 * Tv.u;
|
||||
y: root.row-y;
|
||||
width: root.key-w + 40 * Tv.u;
|
||||
height: root.row-h;
|
||||
horizontal-alignment: center;
|
||||
vertical-alignment: center;
|
||||
text: key;
|
||||
font-size: (31 + 17 * self.f) * Tv.u;
|
||||
font-weight: self.f > 0.5 ? 700 : 500;
|
||||
color: self.f > 0.5 ? Tv.ink : #ffffffd8;
|
||||
opacity: root.alpha;
|
||||
}
|
||||
Icon {
|
||||
property <float> f: max(0, 1 - abs(root.pos)) * root.keys-active;
|
||||
size: (30 + 10 * self.f) * Tv.u;
|
||||
x: root.row-x + (root.key-w - self.size) / 2;
|
||||
y: root.row-y + (root.row-h - self.size) / 2;
|
||||
name: "space";
|
||||
ink: self.f > 0.5 ? Tv.ink : #ffffffd8;
|
||||
opacity: root.alpha;
|
||||
}
|
||||
Icon {
|
||||
property <float> f: max(0, 1 - abs(root.pos - (root.n - 1))) * root.keys-active;
|
||||
size: (32 + 10 * self.f) * Tv.u;
|
||||
x: root.row-x + (root.n - 1) * root.key-w + (root.key-w - self.size) / 2;
|
||||
y: root.row-y + (root.row-h - self.size) / 2;
|
||||
name: "delete";
|
||||
ink: self.f > 0.5 ? Tv.ink : #ffffffd8;
|
||||
opacity: root.alpha;
|
||||
}
|
||||
|
||||
// ---- chips ----
|
||||
for label[i] in root.chips: Text {
|
||||
property <float> f: max(0, 1 - abs(root.cpos - i)) * root.chips-active;
|
||||
property <bool> submit: i == root.chips.length - 1;
|
||||
property <bool> selected: i < 4 && i == root.mode;
|
||||
x: root.chip-x + i * root.chip-step;
|
||||
y: root.chip-y;
|
||||
width: root.chip-w;
|
||||
height: root.chip-h;
|
||||
horizontal-alignment: center;
|
||||
vertical-alignment: center;
|
||||
text: label;
|
||||
font-size: 24 * Tv.u;
|
||||
font-weight: self.submit || self.selected ? 700 : 500;
|
||||
color: self.submit ? (root.can-submit ? Tv.text : #ffffff66) : self.f > 0.5 ? Tv.ink : self.selected ? Tv.orange-ink : #ffffffc8;
|
||||
opacity: root.alpha;
|
||||
}
|
||||
|
||||
// ---- glass ----
|
||||
property <length> ax: self.absolute-position.x;
|
||||
property <length> ay: self.absolute-position.y;
|
||||
property <length> track-h: self.row-h - 28 * Tv.u;
|
||||
property <length> lens-w: 86 * Tv.u;
|
||||
property <length> lens-h: 112 * Tv.u;
|
||||
|
||||
pure function chip-rect(i: int) -> GlassRect {
|
||||
let f = max(0, 1 - abs(root.cpos - i)) * root.chips-active;
|
||||
let s = 1 + 0.05 * f;
|
||||
let sel = i < 4 && i == root.mode ? 0.16 : 0;
|
||||
{
|
||||
x: root.ax + root.chip-x + i * root.chip-step - root.chip-w * (s - 1) / 2,
|
||||
y: root.ay + root.chip-y - root.chip-h * (s - 1) / 2,
|
||||
w: root.chip-w * s,
|
||||
h: root.chip-h * s,
|
||||
r: root.chip-h * s / 2,
|
||||
focus: f,
|
||||
alpha: root.alpha,
|
||||
blur: -1,
|
||||
glow: i == 5 ? Tv.orange : #ffffff,
|
||||
tint: i == 5
|
||||
? Tv.orange.with-alpha(root.can-submit ? 0.34 + 0.56 * f : 0.08 + 0.2 * f)
|
||||
: #ffffff.with-alpha(0.04 + sel + 0.80 * f),
|
||||
group: 0,
|
||||
}
|
||||
}
|
||||
|
||||
out property <[GlassRect]> glass: [
|
||||
{
|
||||
x: root.ax + root.field-x,
|
||||
y: root.ay + root.field-y,
|
||||
w: root.field-w,
|
||||
h: root.field-h,
|
||||
r: 30 * Tv.u,
|
||||
focus: 0.25,
|
||||
alpha: root.alpha,
|
||||
blur: -1,
|
||||
glow: Tv.orange,
|
||||
tint: #ffffff12,
|
||||
group: 0,
|
||||
},
|
||||
{
|
||||
x: root.ax + root.row-x - 26 * Tv.u,
|
||||
y: root.ay + root.row-y + 14 * Tv.u,
|
||||
w: root.n * root.key-w + 52 * Tv.u,
|
||||
h: root.track-h,
|
||||
r: root.track-h / 2,
|
||||
focus: 0,
|
||||
alpha: root.alpha,
|
||||
blur: -1,
|
||||
glow: #ffffff,
|
||||
tint: #ffffff09,
|
||||
group: 0,
|
||||
},
|
||||
{
|
||||
x: root.ax + root.row-x + (root.pos + 0.5) * root.key-w - root.lens-w / 2,
|
||||
y: root.ay + root.row-y + (root.row-h - root.lens-h) / 2,
|
||||
w: root.lens-w,
|
||||
h: root.lens-h,
|
||||
r: 30 * Tv.u,
|
||||
focus: root.keys-active,
|
||||
alpha: root.alpha * root.keys-active,
|
||||
blur: -1,
|
||||
glow: #ffffff,
|
||||
tint: #ffffff.with-alpha(0.88 * root.keys-active),
|
||||
group: 0,
|
||||
},
|
||||
root.chip-rect(0),
|
||||
root.chip-rect(1),
|
||||
root.chip-rect(2),
|
||||
root.chip-rect(3),
|
||||
root.chip-rect(4),
|
||||
root.chip-rect(5),
|
||||
];
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "sf-update"
|
||||
description = "SmartFox package updater: signed shell and app packages from the Gitea package registry"
|
||||
description = "Fennec OS package updater: signed shell and app packages from the Gitea package registry"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
@@ -18,3 +18,6 @@ ed25519-dalek = "2"
|
||||
base64 = "0.22"
|
||||
tar = "0.4"
|
||||
ruzstd = "0.8"
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
272
crates/sf-update/src/appstore.rs
Normal file
272
crates/sf-update/src/appstore.rs
Normal file
@@ -0,0 +1,272 @@
|
||||
//! The app store side of sf-update (docs/store.md): reads what the user wants
|
||||
//! (store.toml, written by the launcher), asks the sources what they offer
|
||||
//! (catalog.json) and works out which store apps to install, update or
|
||||
//! remove. Downloading, checking and unpacking reuse the package store.
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::Path;
|
||||
use std::time::{SystemTime, UNIX_EPOCH};
|
||||
|
||||
use anyhow::{Context, Result};
|
||||
use sf_ipc::manifest::{AppManifest, version_cmp};
|
||||
use sf_ipc::store::{Catalog, CatalogApp, INDEX_FILE, Index, MAX_WANTED, PACKAGE_PREFIX, SourceInfo, Wanted, missing_permissions};
|
||||
|
||||
use crate::forge::{self, Repo};
|
||||
use crate::store::Store;
|
||||
|
||||
/// Apps one catalog may list.
|
||||
const MAX_CATALOG_APPS: usize = 200;
|
||||
|
||||
/// A store package to download.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct StoreDownload {
|
||||
pub id: String,
|
||||
pub package_url: String,
|
||||
pub approved: Vec<sf_ipc::Permission>,
|
||||
pub source: String,
|
||||
}
|
||||
|
||||
/// Reads store.toml. The launcher (user tv) writes it, so it is read
|
||||
/// carefully: no symlinks, a regular file, a size limit.
|
||||
pub fn read_wanted(path: &Path) -> Result<Wanted> {
|
||||
let mut opts = std::fs::OpenOptions::new();
|
||||
opts.read(true);
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
opts.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK);
|
||||
}
|
||||
let file = match opts.open(path) {
|
||||
Ok(f) => f,
|
||||
Err(e) if e.kind() == std::io::ErrorKind::NotFound => return Ok(Wanted::default()),
|
||||
Err(e) => return Err(e).with_context(|| format!("opening {}", path.display())),
|
||||
};
|
||||
let meta = file.metadata()?;
|
||||
anyhow::ensure!(meta.is_file(), "{} is not a regular file", path.display());
|
||||
anyhow::ensure!(meta.len() <= MAX_WANTED, "{} is too large", path.display());
|
||||
let mut text = String::new();
|
||||
use std::io::Read;
|
||||
file.take(MAX_WANTED).read_to_string(&mut text)?;
|
||||
Wanted::parse(&text)
|
||||
}
|
||||
|
||||
fn now() -> u64 {
|
||||
SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// The canonical address of a source, or the input if it doesn't parse.
|
||||
pub fn canonical(source: &str) -> String {
|
||||
Repo::parse(source).map(|r| r.url()).unwrap_or_else(|_| source.trim().to_string())
|
||||
}
|
||||
|
||||
/// Asks every source what it offers.
|
||||
pub fn refresh_catalog(wanted: &Wanted) -> Catalog {
|
||||
let agent = forge::agent();
|
||||
let mut sources: Vec<String> = Vec::new();
|
||||
for s in wanted.sources.iter().chain(wanted.apps.values().map(|a| &a.source)) {
|
||||
let c = canonical(s);
|
||||
if !sources.contains(&c) {
|
||||
sources.push(c);
|
||||
}
|
||||
}
|
||||
let mut catalog = Catalog { updated_at: now(), ..Default::default() };
|
||||
for url in sources {
|
||||
let mut info = SourceInfo { url: url.clone(), ..Default::default() };
|
||||
match Repo::parse(&url).and_then(|r| forge::detect(&agent, &r)) {
|
||||
Err(e) => info.error = Some(format!("{e:#}")),
|
||||
Ok(repo) => match forge::raw_file(&agent, &repo, INDEX_FILE) {
|
||||
Ok(Some(text)) => {
|
||||
info.kind = "catalog".into();
|
||||
match toml::from_str::<Index>(&text) {
|
||||
Err(e) => info.error = Some(format!("{INDEX_FILE}: {e}")),
|
||||
Ok(index) => {
|
||||
info.name = index.name.clone();
|
||||
let mut errors = Vec::new();
|
||||
for app_url in index.apps.iter().take(MAX_CATALOG_APPS) {
|
||||
match Repo::parse(app_url).and_then(|r| forge::detect(&agent, &r)).and_then(|r| app_entry(&agent, &r)) {
|
||||
Ok(Some(mut app)) => {
|
||||
app.catalog = Some(url.clone());
|
||||
catalog.apps.push(app);
|
||||
info.apps += 1;
|
||||
}
|
||||
Ok(None) => {}
|
||||
Err(e) => errors.push(format!("{app_url}: {e:#}")),
|
||||
}
|
||||
}
|
||||
for e in &errors {
|
||||
log::warn!("store: {e}");
|
||||
}
|
||||
if info.apps == 0 && !errors.is_empty() {
|
||||
info.error = errors.into_iter().next();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(None) | Err(_) => {
|
||||
info.kind = "app".into();
|
||||
match app_entry(&agent, &repo) {
|
||||
Ok(Some(app)) => {
|
||||
info.name = app.name.clone();
|
||||
info.apps = 1;
|
||||
catalog.apps.push(app);
|
||||
}
|
||||
Ok(None) => info.error = Some("no release with an app.toml yet".into()),
|
||||
Err(e) => info.error = Some(format!("{e:#}")),
|
||||
}
|
||||
}
|
||||
},
|
||||
}
|
||||
if let Some(e) = &info.error {
|
||||
log::warn!("store source {url}: {e}");
|
||||
}
|
||||
catalog.sources.push(info);
|
||||
}
|
||||
// One entry per id: the source the app is installed from wins, else the first.
|
||||
let mut seen: BTreeMap<String, usize> = BTreeMap::new();
|
||||
let mut apps: Vec<CatalogApp> = Vec::new();
|
||||
for app in catalog.apps.drain(..) {
|
||||
let pinned = wanted.apps.get(&app.id).map(|w| canonical(&w.source));
|
||||
match seen.get(&app.id) {
|
||||
Some(&i) => {
|
||||
if pinned.as_deref() == Some(app.source.as_str()) && apps[i].source != app.source {
|
||||
apps[i] = app;
|
||||
}
|
||||
}
|
||||
None => {
|
||||
seen.insert(app.id.clone(), apps.len());
|
||||
apps.push(app);
|
||||
}
|
||||
}
|
||||
}
|
||||
catalog.apps = apps;
|
||||
catalog
|
||||
}
|
||||
|
||||
/// The newest release of one app repo.
|
||||
fn app_entry(agent: &ureq::Agent, repo: &Repo) -> Result<Option<CatalogApp>> {
|
||||
let Some(release) = forge::latest_release(agent, repo)? else { return Ok(None) };
|
||||
let manifest_asset = release.asset("app.toml").context("app.toml")?;
|
||||
let app: AppManifest = toml::from_str(&forge::asset_text(agent, manifest_asset)?).context("app.toml")?;
|
||||
app.check_store_rules()?;
|
||||
anyhow::ensure!(crate::registry::is_release(&app.version), "version {} is not a release version (1.2.3)", app.version);
|
||||
let file = format!("{}-{}.tar.zst", app.id, app.version);
|
||||
let package = release.asset(&file).with_context(|| format!("release {} has no {file}", release.tag))?;
|
||||
Ok(Some(CatalogApp {
|
||||
id: app.id.clone(),
|
||||
name: app.name.clone(),
|
||||
version: app.version.clone(),
|
||||
kind: format!("{:?}", app.kind).to_lowercase(),
|
||||
category: app.category.clone(),
|
||||
description: app.description.clone(),
|
||||
author: app.author.clone().unwrap_or_default(),
|
||||
homepage: app.homepage.clone().unwrap_or_else(|| repo.url()),
|
||||
license: app.license.clone().unwrap_or_default(),
|
||||
accent: app.accent.clone(),
|
||||
permissions: app.permissions(),
|
||||
source: repo.url(),
|
||||
catalog: None,
|
||||
package_url: package.url.clone(),
|
||||
installed: None,
|
||||
blocked: None,
|
||||
}))
|
||||
}
|
||||
|
||||
/// Marks what's installed and what's held back, and returns the store
|
||||
/// packages to download (new installs and updates).
|
||||
pub fn plan(store: &Store, wanted: &Wanted, catalog: &mut Catalog) -> BTreeMap<String, (String, StoreDownload)> {
|
||||
let mut out = BTreeMap::new();
|
||||
for app in &mut catalog.apps {
|
||||
let name = format!("{PACKAGE_PREFIX}{}", app.id);
|
||||
app.installed = store.installed(&name);
|
||||
app.blocked = None;
|
||||
let Some(want) = wanted.apps.get(&app.id) else { continue };
|
||||
if canonical(&want.source) != app.source {
|
||||
continue;
|
||||
}
|
||||
if !missing_permissions(&app.permissions, &want.permissions).is_empty() {
|
||||
app.blocked = Some("permissions".into());
|
||||
continue;
|
||||
}
|
||||
let newer = app.installed.as_deref().is_none_or(|i| version_cmp(&app.version, i).is_gt());
|
||||
if newer && !store.bad(&name).contains(&app.version) {
|
||||
out.insert(
|
||||
name,
|
||||
(
|
||||
app.version.clone(),
|
||||
StoreDownload {
|
||||
id: app.id.clone(),
|
||||
package_url: app.package_url.clone(),
|
||||
approved: want.permissions.clone(),
|
||||
source: app.source.clone(),
|
||||
},
|
||||
),
|
||||
);
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Removes store apps the user no longer wants.
|
||||
pub fn remove_unwanted(store: &Store, wanted: &Wanted) -> bool {
|
||||
let mut changed = false;
|
||||
for id in store.store_apps() {
|
||||
if !wanted.apps.contains_key(&id) {
|
||||
match store.remove_store_app(&id) {
|
||||
Ok(()) => changed = true,
|
||||
Err(e) => log::error!("removing {id}: {e:#}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
changed
|
||||
}
|
||||
|
||||
pub fn write_catalog(path: &Path, catalog: &Catalog) {
|
||||
let ok = (|| -> Result<()> {
|
||||
if let Some(dir) = path.parent() {
|
||||
std::fs::create_dir_all(dir)?;
|
||||
}
|
||||
let tmp = path.with_extension("json.tmp");
|
||||
std::fs::write(&tmp, serde_json::to_vec_pretty(catalog)?)?;
|
||||
std::fs::rename(&tmp, path)?;
|
||||
Ok(())
|
||||
})();
|
||||
if let Err(e) = ok {
|
||||
log::warn!("writing {}: {e:#}", path.display());
|
||||
}
|
||||
}
|
||||
|
||||
/// Downloads a store package into `dir`.
|
||||
pub fn download(d: &StoreDownload, version: &str, dir: &Path) -> Result<std::path::PathBuf> {
|
||||
let agent = forge::agent();
|
||||
let file = dir.join(format!("{}-{version}.tar.zst", d.id));
|
||||
let n = forge::download(&agent, &d.package_url, &file, crate::registry::MAX_PACKAGE)?;
|
||||
log::info!("downloaded {} {version} ({n} bytes)", d.id);
|
||||
Ok(file)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn canonical_sources() {
|
||||
assert_eq!(canonical("github.com/Fox/App.git"), "https://github.com/Fox/App");
|
||||
assert_eq!(canonical(" not a url "), "not a url");
|
||||
}
|
||||
|
||||
#[cfg(unix)]
|
||||
#[test]
|
||||
fn wanted_file_is_read_carefully() {
|
||||
let dir = std::env::temp_dir().join(format!("sf-store-test-{}", std::process::id()));
|
||||
std::fs::create_dir_all(&dir).unwrap();
|
||||
let real = dir.join("real.toml");
|
||||
std::fs::write(&real, "sources = ['github.com/a/b']\n").unwrap();
|
||||
assert_eq!(read_wanted(&real).unwrap().sources, ["github.com/a/b"]);
|
||||
let link = dir.join("link.toml");
|
||||
let _ = std::fs::remove_file(&link);
|
||||
std::os::unix::fs::symlink(&real, &link).unwrap();
|
||||
assert!(read_wanted(&link).is_err());
|
||||
assert!(read_wanted(&dir.join("missing.toml")).unwrap().apps.is_empty());
|
||||
std::fs::remove_dir_all(&dir).unwrap();
|
||||
}
|
||||
}
|
||||
@@ -21,6 +21,7 @@ struct File {
|
||||
root: Option<PathBuf>,
|
||||
requests: Option<PathBuf>,
|
||||
factory: Option<PathBuf>,
|
||||
store_wanted: Option<PathBuf>,
|
||||
}
|
||||
|
||||
impl File {
|
||||
@@ -38,6 +39,7 @@ impl File {
|
||||
root: o.root.or(self.root),
|
||||
requests: o.requests.or(self.requests),
|
||||
factory: o.factory.or(self.factory),
|
||||
store_wanted: o.store_wanted.or(self.store_wanted),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -57,6 +59,10 @@ pub struct Config {
|
||||
pub requests: PathBuf,
|
||||
/// Versions of the copies built into the image.
|
||||
pub factory: PathBuf,
|
||||
/// What the user wants from the store (written by the launcher).
|
||||
pub store_wanted: PathBuf,
|
||||
/// What the store sources offer (written here).
|
||||
pub catalog: PathBuf,
|
||||
}
|
||||
|
||||
impl Config {
|
||||
@@ -84,12 +90,15 @@ impl Config {
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
let root = file.root.unwrap_or_else(|| "/var/lib/sf-pkg".into());
|
||||
Ok(Config {
|
||||
catalog: root.join("store").join("catalog.json"),
|
||||
store_wanted: file.store_wanted.unwrap_or_else(|| sf_ipc::store::WANTED_FILE.into()),
|
||||
server: server.trim_end_matches('/').to_string(),
|
||||
owner,
|
||||
auth,
|
||||
public_key,
|
||||
root: file.root.unwrap_or_else(|| "/var/lib/sf-pkg".into()),
|
||||
root,
|
||||
requests: file.requests.unwrap_or_else(|| "/var/lib/smartfox/update-requests".into()),
|
||||
factory: file.factory.unwrap_or_else(|| "/usr/share/smartfox/factory-versions.toml".into()),
|
||||
})
|
||||
|
||||
326
crates/sf-update/src/forge.rs
Normal file
326
crates/sf-update/src/forge.rs
Normal file
@@ -0,0 +1,326 @@
|
||||
//! Store sources: app repos on GitHub, Gitea/Forgejo (Codeberg too) and
|
||||
//! GitLab. An app is published as a release with two assets (docs/store.md):
|
||||
//!
|
||||
//! app.toml the manifest (name, permissions)
|
||||
//! <id>-<version>.tar.zst the package
|
||||
//!
|
||||
//! A catalog repo lists many app repos in `smartfox-store.toml` on its
|
||||
//! default branch.
|
||||
//!
|
||||
//! Requests go without our registry login (it must never reach third-party
|
||||
//! servers), HTTPS only, with size limits on everything.
|
||||
|
||||
use std::io::Read;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use serde::Deserialize;
|
||||
|
||||
const MAX_JSON: u64 = 4 * 1024 * 1024;
|
||||
const MAX_TEXT: u64 = 256 * 1024;
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum Forge {
|
||||
GitHub,
|
||||
Gitea,
|
||||
GitLab,
|
||||
}
|
||||
|
||||
/// A repository on a forge.
|
||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||
pub struct Repo {
|
||||
/// None: not known yet (self-hosted), found out by `detect`.
|
||||
pub forge: Option<Forge>,
|
||||
/// https://host
|
||||
pub base: String,
|
||||
/// owner/repo (GitLab: group/subgroup/project)
|
||||
pub path: String,
|
||||
}
|
||||
|
||||
impl Repo {
|
||||
/// What the user typed: `https://github.com/o/r(.git)`, `github.com/o/r`,
|
||||
/// or with an explicit forge: `gitea:git.example.org/o/r`,
|
||||
/// `gitlab:gitlab.example.org/group/project`, `github:o/r`.
|
||||
pub fn parse(input: &str) -> Result<Repo> {
|
||||
let input = input.trim();
|
||||
let (forge, rest) = match input.split_once(':') {
|
||||
Some(("github", r)) => (Some(Forge::GitHub), r),
|
||||
Some(("gitea" | "forgejo", r)) => (Some(Forge::Gitea), r),
|
||||
Some(("gitlab", r)) => (Some(Forge::GitLab), r),
|
||||
_ => (None, input),
|
||||
};
|
||||
let rest = rest.trim_start_matches('/');
|
||||
let rest = if let Some(r) = rest.strip_prefix("https://") {
|
||||
r
|
||||
} else if rest.starts_with("http://") {
|
||||
bail!("only https:// sources are allowed");
|
||||
} else {
|
||||
rest
|
||||
};
|
||||
let rest = rest.split(['?', '#']).next().unwrap_or("").trim_end_matches('/');
|
||||
let rest = rest.strip_suffix(".git").unwrap_or(rest);
|
||||
let (host, path) = match (forge, rest.split_once('/')) {
|
||||
(Some(Forge::GitHub), Some((h, p))) if !h.contains('.') => ("github.com", format!("{h}/{p}")),
|
||||
(_, Some((h, p))) => (h, p.to_string()),
|
||||
_ => bail!("not a repository address: {input}"),
|
||||
};
|
||||
let host = host.to_ascii_lowercase();
|
||||
let valid_host = !host.is_empty() && host.contains('.') && host.bytes().all(|b| b.is_ascii_alphanumeric() || b"-.:".contains(&b));
|
||||
if !valid_host {
|
||||
bail!("bad host in {input}");
|
||||
}
|
||||
let parts: Vec<&str> = path.split('/').collect();
|
||||
let valid_part = |p: &&str| !p.is_empty() && *p != "." && *p != ".." && p.bytes().all(|b| b.is_ascii_alphanumeric() || b"-._".contains(&b));
|
||||
if parts.len() < 2 || !parts.iter().all(valid_part) {
|
||||
bail!("expected owner/repository in {input}");
|
||||
}
|
||||
let forge = forge.or(match host.as_str() {
|
||||
"github.com" => Some(Forge::GitHub),
|
||||
"gitlab.com" | "framagit.org" => Some(Forge::GitLab),
|
||||
"codeberg.org" => Some(Forge::Gitea),
|
||||
_ => None,
|
||||
});
|
||||
if matches!(forge, Some(Forge::GitHub | Forge::Gitea)) && parts.len() != 2 {
|
||||
bail!("expected owner/repository in {input}");
|
||||
}
|
||||
Ok(Repo { forge, base: format!("https://{host}"), path })
|
||||
}
|
||||
|
||||
/// Canonical form, stored in store.toml and catalog.json.
|
||||
pub fn url(&self) -> String {
|
||||
format!("{}/{}", self.base, self.path)
|
||||
}
|
||||
|
||||
fn encoded_path(&self) -> String {
|
||||
self.path.replace('/', "%2F")
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Asset {
|
||||
pub name: String,
|
||||
pub url: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct Release {
|
||||
pub tag: String,
|
||||
pub assets: Vec<Asset>,
|
||||
}
|
||||
|
||||
impl Release {
|
||||
pub fn asset(&self, name: &str) -> Option<&Asset> {
|
||||
self.assets.iter().find(|a| a.name == name)
|
||||
}
|
||||
}
|
||||
|
||||
pub fn agent() -> ureq::Agent {
|
||||
ureq::Agent::config_builder()
|
||||
.timeout_connect(Some(Duration::from_secs(15)))
|
||||
.timeout_recv_response(Some(Duration::from_secs(60)))
|
||||
.timeout_recv_body(Some(Duration::from_secs(1800)))
|
||||
.https_only(true)
|
||||
.user_agent(concat!("FennecOS-store/", env!("CARGO_PKG_VERSION")))
|
||||
.build()
|
||||
.into()
|
||||
}
|
||||
|
||||
/// GET returning None on 404.
|
||||
fn get_text(agent: &ureq::Agent, url: &str, limit: u64) -> Result<Option<String>> {
|
||||
match agent.get(url).header("Accept", "application/json, text/plain, */*").call() {
|
||||
Ok(resp) => {
|
||||
let mut body = String::new();
|
||||
resp.into_body().into_reader().take(limit + 1).read_to_string(&mut body).with_context(|| format!("reading {url}"))?;
|
||||
if body.len() as u64 > limit {
|
||||
bail!("{url}: response is too large");
|
||||
}
|
||||
Ok(Some(body))
|
||||
}
|
||||
Err(ureq::Error::StatusCode(404)) => Ok(None),
|
||||
Err(ureq::Error::StatusCode(403 | 429)) if url.contains("api.github.com") => {
|
||||
bail!("GitHub rate limit reached, try again later")
|
||||
}
|
||||
Err(e) => Err(e).with_context(|| format!("GET {url}")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Works out the forge of a self-hosted repo.
|
||||
pub fn detect(agent: &ureq::Agent, repo: &Repo) -> Result<Repo> {
|
||||
if repo.forge.is_some() {
|
||||
return Ok(repo.clone());
|
||||
}
|
||||
let gitea = format!("{}/api/v1/repos/{}", repo.base, repo.path);
|
||||
if repo.path.matches('/').count() == 1 && get_text(agent, &gitea, MAX_JSON).ok().flatten().is_some() {
|
||||
return Ok(Repo { forge: Some(Forge::Gitea), ..repo.clone() });
|
||||
}
|
||||
let gitlab = format!("{}/api/v4/projects/{}", repo.base, repo.encoded_path());
|
||||
if get_text(agent, &gitlab, MAX_JSON).ok().flatten().is_some() {
|
||||
return Ok(Repo { forge: Some(Forge::GitLab), ..repo.clone() });
|
||||
}
|
||||
bail!("{}: no public GitHub, Gitea or GitLab repository found", repo.url())
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct GhRelease {
|
||||
tag_name: String,
|
||||
#[serde(default)]
|
||||
draft: bool,
|
||||
#[serde(default)]
|
||||
prerelease: bool,
|
||||
#[serde(default)]
|
||||
assets: Vec<GhAsset>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct GhAsset {
|
||||
name: String,
|
||||
browser_download_url: String,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct GlRelease {
|
||||
tag_name: String,
|
||||
#[serde(default)]
|
||||
upcoming_release: bool,
|
||||
#[serde(default)]
|
||||
assets: GlAssets,
|
||||
}
|
||||
|
||||
#[derive(Deserialize, Default)]
|
||||
struct GlAssets {
|
||||
#[serde(default)]
|
||||
links: Vec<GlLink>,
|
||||
}
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct GlLink {
|
||||
name: String,
|
||||
url: String,
|
||||
#[serde(default)]
|
||||
direct_asset_url: Option<String>,
|
||||
}
|
||||
|
||||
/// The newest published (not draft, not pre-release) release that carries
|
||||
/// an `app.toml`.
|
||||
pub fn latest_release(agent: &ureq::Agent, repo: &Repo) -> Result<Option<Release>> {
|
||||
let releases: Vec<Release> = match repo.forge.context("unknown forge")? {
|
||||
Forge::GitHub => {
|
||||
let url = format!("https://api.github.com/repos/{}/releases?per_page=20", repo.path);
|
||||
let Some(text) = get_text(agent, &url, MAX_JSON)? else { return Ok(None) };
|
||||
let list: Vec<GhRelease> = serde_json::from_str(&text).context("GitHub releases")?;
|
||||
list.into_iter().filter(|r| !r.draft && !r.prerelease).map(gh_release).collect()
|
||||
}
|
||||
Forge::Gitea => {
|
||||
let url = format!("{}/api/v1/repos/{}/releases?limit=20", repo.base, repo.path);
|
||||
let Some(text) = get_text(agent, &url, MAX_JSON)? else { return Ok(None) };
|
||||
let list: Vec<GhRelease> = serde_json::from_str(&text).context("Gitea releases")?;
|
||||
list.into_iter().filter(|r| !r.draft && !r.prerelease).map(gh_release).collect()
|
||||
}
|
||||
Forge::GitLab => {
|
||||
let url = format!("{}/api/v4/projects/{}/releases?per_page=20", repo.base, repo.encoded_path());
|
||||
let Some(text) = get_text(agent, &url, MAX_JSON)? else { return Ok(None) };
|
||||
let list: Vec<GlRelease> = serde_json::from_str(&text).context("GitLab releases")?;
|
||||
list.into_iter()
|
||||
.filter(|r| !r.upcoming_release)
|
||||
.map(|r| Release {
|
||||
tag: r.tag_name,
|
||||
assets: r.assets.links.into_iter().map(|l| Asset { url: l.direct_asset_url.unwrap_or(l.url), name: l.name }).collect(),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
};
|
||||
Ok(releases.into_iter().find(|r| r.asset("app.toml").is_some()))
|
||||
}
|
||||
|
||||
fn gh_release(r: GhRelease) -> Release {
|
||||
Release { tag: r.tag_name, assets: r.assets.into_iter().map(|a| Asset { name: a.name, url: a.browser_download_url }).collect() }
|
||||
}
|
||||
|
||||
/// A file from the default branch (catalogs: `smartfox-store.toml`).
|
||||
pub fn raw_file(agent: &ureq::Agent, repo: &Repo, file: &str) -> Result<Option<String>> {
|
||||
let url = match repo.forge.context("unknown forge")? {
|
||||
Forge::GitHub => format!("https://raw.githubusercontent.com/{}/HEAD/{file}", repo.path),
|
||||
Forge::Gitea => format!("{}/api/v1/repos/{}/raw/{file}", repo.base, repo.path),
|
||||
Forge::GitLab => format!("{}/api/v4/projects/{}/repository/files/{}/raw?ref=HEAD", repo.base, repo.encoded_path(), file.replace('/', "%2F")),
|
||||
};
|
||||
get_text(agent, &url, MAX_TEXT)
|
||||
}
|
||||
|
||||
/// A small text asset (the release's app.toml).
|
||||
pub fn asset_text(agent: &ureq::Agent, asset: &Asset) -> Result<String> {
|
||||
get_text(agent, &asset.url, MAX_TEXT)?.with_context(|| format!("{} is missing", asset.name))
|
||||
}
|
||||
|
||||
/// Downloads an asset into `path`, at most `limit` bytes.
|
||||
pub fn download(agent: &ureq::Agent, url: &str, path: &std::path::Path, limit: u64) -> Result<u64> {
|
||||
let resp = agent.get(url).call().with_context(|| format!("GET {url}"))?;
|
||||
let mut out = std::fs::File::create(path).with_context(|| format!("creating {}", path.display()))?;
|
||||
let mut body = resp.into_body().into_reader().take(limit + 1);
|
||||
let n = std::io::copy(&mut body, &mut out).with_context(|| format!("downloading {url}"))?;
|
||||
if n > limit {
|
||||
bail!("{url} is larger than {limit} bytes");
|
||||
}
|
||||
out.sync_all()?;
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn parses_repo_addresses() {
|
||||
let r = Repo::parse("https://github.com/Fox/hello-app.git").unwrap();
|
||||
assert_eq!((r.forge, r.url()), (Some(Forge::GitHub), "https://github.com/Fox/hello-app".to_string()));
|
||||
assert_eq!(Repo::parse("github.com/fox/x/").unwrap().url(), "https://github.com/fox/x");
|
||||
assert_eq!(Repo::parse("github:fox/x").unwrap().url(), "https://github.com/fox/x");
|
||||
let r = Repo::parse("gitlab.com/group/sub/proj").unwrap();
|
||||
assert_eq!((r.forge, r.path.as_str()), (Some(Forge::GitLab), "group/sub/proj"));
|
||||
let r = Repo::parse("gitea:git.example.org/o/r").unwrap();
|
||||
assert_eq!((r.forge, r.base.as_str()), (Some(Forge::Gitea), "https://git.example.org"));
|
||||
let r = Repo::parse("https://gitea.bluefox.support/bluefox/store").unwrap();
|
||||
assert_eq!(r.forge, None);
|
||||
assert!(Repo::parse("http://github.com/a/b").is_err());
|
||||
assert!(Repo::parse("github.com/a").is_err());
|
||||
assert!(Repo::parse("github.com/a/b/c").is_err());
|
||||
assert!(Repo::parse("github.com/../b").is_err());
|
||||
assert!(Repo::parse("exa mple.org/a/b").is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_releases() {
|
||||
let gh: Vec<GhRelease> = serde_json::from_str(
|
||||
r#"[{"tag_name":"v2","draft":true,"assets":[]},{"tag_name":"v1","prerelease":false,"assets":[{"name":"app.toml","browser_download_url":"https://x/app.toml","size":3}]}]"#,
|
||||
)
|
||||
.unwrap();
|
||||
let rel: Vec<Release> = gh.into_iter().filter(|r| !r.draft).map(gh_release).collect();
|
||||
assert_eq!(rel[0].tag, "v1");
|
||||
assert_eq!(rel[0].asset("app.toml").unwrap().url, "https://x/app.toml");
|
||||
let gl: Vec<GlRelease> = serde_json::from_str(r#"[{"tag_name":"1.0","assets":{"links":[{"name":"app.toml","url":"https://a","direct_asset_url":"https://b"}]}}]"#).unwrap();
|
||||
assert_eq!(gl[0].assets.links[0].direct_asset_url.as_deref(), Some("https://b"));
|
||||
}
|
||||
}
|
||||
|
||||
/// Talks to the real forges: `cargo test -p sf-update -- --ignored live`.
|
||||
#[cfg(test)]
|
||||
mod live {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
#[ignore]
|
||||
fn live_forges() {
|
||||
let agent = agent();
|
||||
for (url, file) in [
|
||||
("github.com/BurntSushi/ripgrep", "README.md"),
|
||||
("codeberg.org/forgejo/forgejo", "README.md"),
|
||||
("gitlab.com/gitlab-org/cli", "README.md"),
|
||||
("gitea:gitea.com/gitea/tea", "README.md"),
|
||||
] {
|
||||
let repo = detect(&agent, &Repo::parse(url).unwrap()).unwrap();
|
||||
let release = latest_release(&agent, &repo).unwrap();
|
||||
let readme = raw_file(&agent, &repo, file).unwrap();
|
||||
println!("{url}: {:?}, release with app.toml: {}, readme: {} bytes", repo.forge, release.is_some(), readme.map(|r| r.len()).unwrap_or(0));
|
||||
assert!(raw_file(&agent, &repo, "no-such-file.toml").unwrap().is_none());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,27 +1,32 @@
|
||||
//! sf-update: installs signed SmartFox packages (the shell and the apps) from
|
||||
//! the Gitea package registry onto the writable data partition. The root
|
||||
//! file system stays read-only and keeps the factory copies as a fallback.
|
||||
//! sf-update: installs signed Fennec OS packages (the shell and the apps) from
|
||||
//! the Gitea package registry, and store apps from their own GitHub, Gitea or
|
||||
//! GitLab repos, onto the writable data partition. The root file system stays
|
||||
//! read-only and keeps the factory copies as a fallback.
|
||||
//!
|
||||
//! Protocol and layout: docs/updates.md.
|
||||
//! Protocol and layout: docs/updates.md, docs/store.md.
|
||||
//!
|
||||
//! sf-update check ask the server what's new (status.json)
|
||||
//! sf-update check ask the servers what's new (status.json, catalog.json)
|
||||
//! sf-update auto check, then download and stage what's new (timer)
|
||||
//! sf-update apply switch staged packages live (at boot)
|
||||
//! sf-update install check, download, apply now and restart the UI
|
||||
//! sf-update store install / remove store apps as store.toml says, now
|
||||
//! sf-update requests handle the launcher's request files (path unit)
|
||||
//! sf-update status print status.json
|
||||
|
||||
mod appstore;
|
||||
mod config;
|
||||
mod forge;
|
||||
mod registry;
|
||||
mod store;
|
||||
|
||||
use std::collections::BTreeMap;
|
||||
use std::path::Path;
|
||||
use std::time::Duration;
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
|
||||
use crate::config::Config;
|
||||
use crate::store::Store;
|
||||
use crate::store::{Expect, Store};
|
||||
|
||||
fn main() {
|
||||
env_logger::Builder::from_env(env_logger::Env::default().default_filter_or("info")).init();
|
||||
@@ -34,14 +39,14 @@ fn main() {
|
||||
|
||||
fn run(cmd: &str) -> Result<()> {
|
||||
let cfg = Config::load()?;
|
||||
let store = Store::open(&cfg)?;
|
||||
let store = Store::open(&cfg.root, &cfg.factory)?;
|
||||
match cmd {
|
||||
"status" => {
|
||||
println!("{}", serde_json::to_string_pretty(&store.read_status())?);
|
||||
return Ok(());
|
||||
}
|
||||
"check" | "auto" | "apply" | "install" | "requests" => {}
|
||||
_ => bail!("usage: sf-update check|auto|apply|install|requests|status"),
|
||||
"check" | "auto" | "apply" | "install" | "store" | "requests" => {}
|
||||
_ => bail!("usage: sf-update check|auto|apply|install|store|requests|status"),
|
||||
}
|
||||
// One run at a time (timer, boot and launcher requests can overlap).
|
||||
let _lock = store.lock(Duration::from_secs(600))?;
|
||||
@@ -50,28 +55,78 @@ fn run(cmd: &str) -> Result<()> {
|
||||
"auto" => auto(&cfg, &store),
|
||||
"apply" => apply(&store).map(drop),
|
||||
"install" => install(&cfg, &store),
|
||||
"store" => store_sync(&cfg, &store),
|
||||
"requests" => requests(&cfg, &store),
|
||||
_ => unreachable!(),
|
||||
}
|
||||
}
|
||||
|
||||
/// Asks the registry for the newest version of every package and records
|
||||
/// which ones are newer than what's installed.
|
||||
fn check(cfg: &Config, store: &Store) -> Result<Vec<store::Pending>> {
|
||||
store.set_state("checking", "");
|
||||
let latest = match registry::latest_versions(cfg) {
|
||||
Ok(l) => l,
|
||||
/// The store's plan: newest versions of the wanted store apps that may be
|
||||
/// installed, with where to get them. None if store.toml can't be read
|
||||
/// (then nothing is installed or removed).
|
||||
fn store_plan(cfg: &Config, store: &Store) -> Option<(sf_ipc::store::Wanted, BTreeMap<String, (String, appstore::StoreDownload)>)> {
|
||||
let wanted = match appstore::read_wanted(&cfg.store_wanted) {
|
||||
Ok(w) => w,
|
||||
Err(e) => {
|
||||
store.set_state("error", &format!("{e:#}"));
|
||||
return Err(e);
|
||||
log::error!("store: {e:#}");
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let pending = store.refresh(&latest);
|
||||
if wanted.sources.is_empty() && wanted.apps.is_empty() {
|
||||
appstore::write_catalog(&cfg.catalog, &Default::default());
|
||||
return Some((wanted, BTreeMap::new()));
|
||||
}
|
||||
let mut catalog = appstore::refresh_catalog(&wanted);
|
||||
let plan = appstore::plan(store, &wanted, &mut catalog);
|
||||
appstore::write_catalog(&cfg.catalog, &catalog);
|
||||
Some((wanted, plan))
|
||||
}
|
||||
|
||||
/// Asks the registry and the store sources for the newest version of every
|
||||
/// package and records which ones are newer than what's installed.
|
||||
fn check(cfg: &Config, store: &Store) -> Result<Vec<store::Pending>> {
|
||||
store.set_state("checking", "");
|
||||
let official = registry::latest_versions(cfg);
|
||||
let mut latest = official.as_ref().cloned().unwrap_or_default();
|
||||
let mut downloads = BTreeMap::new();
|
||||
if let Some((_, plan)) = store_plan(cfg, store) {
|
||||
for (name, (version, d)) in plan {
|
||||
latest.insert(name.clone(), version);
|
||||
downloads.insert(name, d);
|
||||
}
|
||||
}
|
||||
let mut pending = store.refresh(&latest);
|
||||
for p in &mut pending {
|
||||
p.store = downloads.remove(&p.name);
|
||||
}
|
||||
// A store app without download info (shouldn't happen) is skipped.
|
||||
pending.retain(|p| registry::store_id(&p.name).is_none() || p.store.is_some());
|
||||
if let Err(e) = official {
|
||||
store.set_state("error", &format!("{e:#}"));
|
||||
return Err(e);
|
||||
}
|
||||
store.set_state("idle", "");
|
||||
log::info!("{} update(s) available", pending.len());
|
||||
Ok(pending)
|
||||
}
|
||||
|
||||
/// Downloads, checks and stages one package.
|
||||
fn fetch(cfg: &Config, store: &Store, p: &store::Pending) -> Result<()> {
|
||||
let dir = store.download_dir()?;
|
||||
match &p.store {
|
||||
None => {
|
||||
let (pkg, sig) = registry::download(cfg, &p.name, &p.version, &dir)?;
|
||||
store.verify_and_unpack(&cfg.public_key, &p.name, &p.version, &pkg, &sig, &Expect::Official)?;
|
||||
}
|
||||
Some(d) => {
|
||||
let pkg = appstore::download(d, &p.version, &dir)?;
|
||||
let expect = Expect::Store { id: &d.id, approved: &d.approved, source: &d.source };
|
||||
store.unpack_store(&p.name, &p.version, &pkg, &expect)?;
|
||||
}
|
||||
}
|
||||
store.stage(&p.name, &p.version)
|
||||
}
|
||||
|
||||
/// Downloads and stages each pending package. Failures of one package don't
|
||||
/// stop the others; the first error is reported.
|
||||
fn download(cfg: &Config, store: &Store, pending: &[store::Pending]) -> Result<usize> {
|
||||
@@ -83,12 +138,7 @@ fn download(cfg: &Config, store: &Store, pending: &[store::Pending]) -> Result<u
|
||||
continue;
|
||||
}
|
||||
store.set_state("downloading", &format!("{} {}", p.name, p.version));
|
||||
let result = (|| -> Result<()> {
|
||||
let dir = store.download_dir()?;
|
||||
let (pkg, sig) = registry::download(cfg, &p.name, &p.version, &dir)?;
|
||||
store.verify_and_unpack(cfg, &p.name, &p.version, &pkg, &sig)?;
|
||||
store.stage(&p.name, &p.version)
|
||||
})();
|
||||
let result = fetch(cfg, store, p);
|
||||
let _ = std::fs::remove_dir_all(store.download_dir_path());
|
||||
match result {
|
||||
Ok(()) => {
|
||||
@@ -123,7 +173,7 @@ fn auto(cfg: &Config, store: &Store) -> Result<()> {
|
||||
|
||||
/// Switches staged packages live. Returns which kinds changed.
|
||||
fn apply(store: &Store) -> Result<store::Applied> {
|
||||
let applied = store.apply_staged()?;
|
||||
let applied = store.apply_staged(|_| true)?;
|
||||
store.gc();
|
||||
store.write_status(|_| {});
|
||||
Ok(applied)
|
||||
@@ -139,13 +189,45 @@ fn install(cfg: &Config, store: &Store) -> Result<()> {
|
||||
result.map(drop)
|
||||
}
|
||||
|
||||
/// The store screen changed store.toml: install new apps and approved
|
||||
/// updates, remove the ones the user uninstalled, all right away. The
|
||||
/// launcher picks the new app list up by itself; nothing restarts.
|
||||
fn store_sync(cfg: &Config, store: &Store) -> Result<()> {
|
||||
store.set_state("checking", "");
|
||||
let Some((wanted, plan)) = store_plan(cfg, store) else {
|
||||
store.set_state("error", "store.toml can't be read");
|
||||
bail!("store.toml can't be read");
|
||||
};
|
||||
appstore::remove_unwanted(store, &wanted);
|
||||
let pending: Vec<store::Pending> = plan
|
||||
.into_iter()
|
||||
.map(|(name, (version, d))| store::Pending { name, version, store: Some(d) })
|
||||
.collect();
|
||||
let result = download(cfg, store, &pending);
|
||||
store.apply_staged(|name| registry::store_id(name).is_some())?;
|
||||
store.link_apps()?;
|
||||
store.gc();
|
||||
// The catalog's "installed" marks are now stale; refresh them from disk.
|
||||
if let Some(mut catalog) = sf_ipc::store::Catalog::load(&cfg.catalog) {
|
||||
for app in &mut catalog.apps {
|
||||
app.installed = store.installed(&format!("{}{}", sf_ipc::store::PACKAGE_PREFIX, app.id));
|
||||
}
|
||||
appstore::write_catalog(&cfg.catalog, &catalog);
|
||||
}
|
||||
store.write_status(|_| {});
|
||||
if result.is_ok() {
|
||||
store.set_state("idle", "");
|
||||
}
|
||||
result.map(drop)
|
||||
}
|
||||
|
||||
/// Restarts what an update touched: the remote driver for a new shell, the
|
||||
/// TV session (cage + launcher) for a new shell or new apps.
|
||||
fn restart(applied: &store::Applied) {
|
||||
if applied.shell {
|
||||
systemctl(&["restart", "sf-remote.service"]);
|
||||
}
|
||||
if applied.shell || applied.apps {
|
||||
if applied.shell || applied.apps || applied.store {
|
||||
restart_ui();
|
||||
}
|
||||
}
|
||||
@@ -164,9 +246,10 @@ fn systemctl(args: &[&str]) {
|
||||
|
||||
/// The launcher (user tv) can't run anything as root; it drops empty files
|
||||
/// named after a request into the requests folder, sf-update-requests.path
|
||||
/// starts this. Only the file names are used, never their contents.
|
||||
/// starts this. Only the file names are used, never their contents (the
|
||||
/// store request reads store.toml, carefully).
|
||||
fn requests(cfg: &Config, store: &Store) -> Result<()> {
|
||||
const ORDER: [&str; 4] = ["rollback", "confirm", "install", "check"];
|
||||
const ORDER: [&str; 5] = ["rollback", "confirm", "store", "install", "check"];
|
||||
let dir = &cfg.requests;
|
||||
let mut result = Ok(());
|
||||
for _ in 0..10 {
|
||||
@@ -178,6 +261,7 @@ fn requests(cfg: &Config, store: &Store) -> Result<()> {
|
||||
let r = match name {
|
||||
"rollback" => rollback(store),
|
||||
"confirm" => store.confirm_shell(),
|
||||
"store" => store_sync(cfg, store),
|
||||
"install" => install(cfg, store),
|
||||
_ => check(cfg, store).map(drop),
|
||||
};
|
||||
@@ -213,4 +297,3 @@ fn rollback(store: &Store) -> Result<()> {
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
|
||||
@@ -14,18 +14,29 @@ use serde::Deserialize;
|
||||
use sf_ipc::manifest::version_cmp;
|
||||
|
||||
/// Largest package we'll download.
|
||||
const MAX_PACKAGE: u64 = 1024 * 1024 * 1024;
|
||||
pub const MAX_PACKAGE: u64 = 1024 * 1024 * 1024;
|
||||
|
||||
use crate::config::Config;
|
||||
|
||||
/// Package names this updater handles.
|
||||
pub fn is_ours(name: &str) -> bool {
|
||||
/// Official package names (from our registry).
|
||||
pub fn is_official(name: &str) -> bool {
|
||||
name == "sf-shell" || name.strip_prefix("sf-app-").is_some_and(|id| !id.is_empty() && id.bytes().all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_'))
|
||||
}
|
||||
|
||||
/// Release versions only: digits and dots (prereleases like 1.2.0-rc1 are skipped).
|
||||
/// Store app id of a package name (`store-<id>`).
|
||||
pub fn store_id(name: &str) -> Option<&str> {
|
||||
name.strip_prefix(sf_ipc::store::PACKAGE_PREFIX).filter(|id| sf_ipc::manifest::is_store_id(id))
|
||||
}
|
||||
|
||||
/// Package names this updater handles: official ones and store apps.
|
||||
pub fn is_ours(name: &str) -> bool {
|
||||
is_official(name) || store_id(name).is_some()
|
||||
}
|
||||
|
||||
/// Release versions only: digits and dots, up to four parts (prereleases
|
||||
/// like 1.2.0-rc1 are skipped).
|
||||
pub fn is_release(version: &str) -> bool {
|
||||
!version.is_empty() && version.split('.').all(|p| !p.is_empty() && p.bytes().all(|b| b.is_ascii_digit())) && version.split('.').count() <= 3
|
||||
!version.is_empty() && version.split('.').all(|p| !p.is_empty() && p.len() <= 9 && p.bytes().all(|b| b.is_ascii_digit())) && version.split('.').count() <= 4
|
||||
}
|
||||
|
||||
fn agent() -> ureq::Agent {
|
||||
@@ -69,7 +80,7 @@ pub fn latest_versions(cfg: &Config) -> Result<BTreeMap<String, String>> {
|
||||
break;
|
||||
}
|
||||
for p in list {
|
||||
if !is_ours(&p.name) || !is_release(&p.version) {
|
||||
if !is_official(&p.name) || !is_release(&p.version) {
|
||||
continue;
|
||||
}
|
||||
match latest.get(&p.name) {
|
||||
@@ -90,7 +101,7 @@ pub fn file_name(name: &str, version: &str) -> String {
|
||||
|
||||
/// Downloads a package and its signature into `dir`.
|
||||
pub fn download(cfg: &Config, name: &str, version: &str, dir: &Path) -> Result<(PathBuf, Vec<u8>)> {
|
||||
if !is_ours(name) || !is_release(version) {
|
||||
if !is_official(name) || !is_release(version) {
|
||||
bail!("refusing package {name} {version}");
|
||||
}
|
||||
let agent = agent();
|
||||
@@ -124,7 +135,13 @@ mod tests {
|
||||
assert!(!is_ours("sf-app-"));
|
||||
assert!(!is_ours("sf-app-../x"));
|
||||
assert!(!is_ours("other"));
|
||||
assert!(is_ours("store-io.github.fox.hello"));
|
||||
assert!(!is_official("store-io.github.fox.hello"));
|
||||
assert!(!is_ours("store-youtube"));
|
||||
assert!(!is_ours("store-io.x/../y"));
|
||||
assert!(is_release("1.2.3"));
|
||||
assert!(is_release("1.0.0.87"));
|
||||
assert!(!is_release("1.0.0.0.1"));
|
||||
assert!(!is_release("1.2.3-rc1"));
|
||||
assert!(!is_release("1..2"));
|
||||
assert!(!is_release("../1"));
|
||||
|
||||
@@ -7,6 +7,9 @@
|
||||
//! <name>/bad versions that failed, never installed again
|
||||
//! sf-shell/trial a new shell that hasn't confirmed a good start yet
|
||||
//! apps/<id> -> ../sf-app-<id>/current (the launcher reads this folder)
|
||||
//! store-<id>/ a store app (docs/store.md), same layout plus:
|
||||
//! source the repo it was installed from
|
||||
//! store/apps/<id> -> ../../store-<id>/current
|
||||
//! status.json for the launcher's Updates row
|
||||
|
||||
use std::collections::{BTreeMap, BTreeSet};
|
||||
@@ -17,9 +20,9 @@ use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
|
||||
use anyhow::{Context, Result, bail};
|
||||
use ed25519_dalek::{Signature, VerifyingKey};
|
||||
use serde::{Deserialize, Serialize};
|
||||
use sf_ipc::manifest::version_cmp;
|
||||
use sf_ipc::Permission;
|
||||
use sf_ipc::manifest::{AppManifest, version_cmp};
|
||||
|
||||
use crate::config::Config;
|
||||
use crate::registry;
|
||||
|
||||
pub const SHELL: &str = "sf-shell";
|
||||
@@ -50,14 +53,30 @@ pub struct PackageStatus {
|
||||
pub struct Pending {
|
||||
pub name: String,
|
||||
pub version: String,
|
||||
/// Store apps: where to get it and what it must be.
|
||||
pub store: Option<crate::appstore::StoreDownload>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
pub struct Applied {
|
||||
pub shell: bool,
|
||||
pub apps: bool,
|
||||
pub store: bool,
|
||||
}
|
||||
|
||||
/// What a package must be to be installed.
|
||||
pub enum Expect<'a> {
|
||||
/// Ours: signed with the Fennec OS key.
|
||||
Official,
|
||||
/// A store app: its manifest must follow the store rules and stay within
|
||||
/// the approved permissions.
|
||||
Store { id: &'a str, approved: &'a [Permission], source: &'a str },
|
||||
}
|
||||
|
||||
/// Largest unpacked store package and file count.
|
||||
const MAX_STORE_UNPACKED: u64 = 8 * 1024 * 1024 * 1024;
|
||||
const MAX_STORE_FILES: usize = 200_000;
|
||||
|
||||
#[derive(Deserialize)]
|
||||
struct PkgInfo {
|
||||
name: String,
|
||||
@@ -83,13 +102,18 @@ pub struct Store {
|
||||
pub struct Lock(#[allow(dead_code)] fs::File);
|
||||
|
||||
impl Store {
|
||||
pub fn open(cfg: &Config) -> Result<Self> {
|
||||
fs::create_dir_all(&cfg.root).with_context(|| format!("creating {}", cfg.root.display()))?;
|
||||
let factory = match fs::read_to_string(&cfg.factory) {
|
||||
Ok(t) => toml::from_str(&t).with_context(|| format!("parsing {}", cfg.factory.display()))?,
|
||||
pub fn open(root: &Path, factory: &Path) -> Result<Self> {
|
||||
fs::create_dir_all(root).with_context(|| format!("creating {}", root.display()))?;
|
||||
let factory = match fs::read_to_string(factory) {
|
||||
Ok(t) => toml::from_str(&t).with_context(|| format!("parsing {}", factory.display()))?,
|
||||
Err(_) => BTreeMap::new(),
|
||||
};
|
||||
Ok(Store { root: cfg.root.clone(), factory })
|
||||
Ok(Store { root: root.to_path_buf(), factory })
|
||||
}
|
||||
|
||||
/// Store app folders: `store/` under the root.
|
||||
pub fn store_dir(&self) -> PathBuf {
|
||||
self.root.join("store")
|
||||
}
|
||||
|
||||
pub fn lock(&self, wait: Duration) -> Result<Lock> {
|
||||
@@ -134,7 +158,7 @@ impl Store {
|
||||
}
|
||||
|
||||
/// The version running now: installed package or factory copy, the newer one.
|
||||
fn installed(&self, name: &str) -> Option<String> {
|
||||
pub fn installed(&self, name: &str) -> Option<String> {
|
||||
let current = self.link(name, "current");
|
||||
let factory = self.factory.get(name).cloned();
|
||||
match (current, factory) {
|
||||
@@ -143,7 +167,7 @@ impl Store {
|
||||
}
|
||||
}
|
||||
|
||||
fn bad(&self, name: &str) -> BTreeSet<String> {
|
||||
pub fn bad(&self, name: &str) -> BTreeSet<String> {
|
||||
fs::read_to_string(self.dir(name).join("bad")).unwrap_or_default().lines().map(str::to_string).collect()
|
||||
}
|
||||
|
||||
@@ -164,7 +188,7 @@ impl Store {
|
||||
let Some(v) = latest.get(&name) else { continue };
|
||||
let newer = self.installed(&name).is_none_or(|i| version_cmp(v, &i).is_gt());
|
||||
if newer && !self.bad(&name).contains(v) {
|
||||
pending.push(Pending { name: name.clone(), version: v.clone() });
|
||||
pending.push(Pending { name: name.clone(), version: v.clone(), store: None });
|
||||
}
|
||||
}
|
||||
let now = SystemTime::now().duration_since(UNIX_EPOCH).map(|d| d.as_secs()).unwrap_or(0);
|
||||
@@ -190,13 +214,24 @@ impl Store {
|
||||
Ok(d)
|
||||
}
|
||||
|
||||
/// Checks the signature and unpacks into `<name>/<version>/`.
|
||||
pub fn verify_and_unpack(&self, cfg: &Config, name: &str, version: &str, pkg: &Path, sig: &[u8]) -> Result<()> {
|
||||
/// Checks the signature with `key` and unpacks into `<name>/<version>/`.
|
||||
pub fn verify_and_unpack(&self, key: &[u8; 32], name: &str, version: &str, pkg: &Path, sig: &[u8], expect: &Expect) -> Result<()> {
|
||||
anyhow::ensure!(matches!(expect, Expect::Official), "signed install is for official packages");
|
||||
let data = fs::read(pkg)?;
|
||||
let key = VerifyingKey::from_bytes(&cfg.public_key).context("public key")?;
|
||||
let key = VerifyingKey::from_bytes(key).context("public key")?;
|
||||
let sig = Signature::from_slice(sig).context("signature: not 64 bytes")?;
|
||||
key.verify_strict(&data, &sig).context("bad signature")?;
|
||||
self.unpack(name, version, &data, expect)
|
||||
}
|
||||
|
||||
/// Store packages come from the selected source and need no signature.
|
||||
pub fn unpack_store(&self, name: &str, version: &str, pkg: &Path, expect: &Expect) -> Result<()> {
|
||||
anyhow::ensure!(matches!(expect, Expect::Store { .. }), "unsigned install is for store apps");
|
||||
let data = fs::read(pkg)?;
|
||||
self.unpack(name, version, &data, expect)
|
||||
}
|
||||
|
||||
fn unpack(&self, name: &str, version: &str, data: &[u8], expect: &Expect) -> Result<()> {
|
||||
let dir = self.dir(name);
|
||||
fs::create_dir_all(&dir)?;
|
||||
let dest = dir.join(version);
|
||||
@@ -209,18 +244,60 @@ impl Store {
|
||||
let tmp = dir.join(format!(".tmp-{version}"));
|
||||
let _ = fs::remove_dir_all(&tmp);
|
||||
fs::create_dir_all(&tmp)?;
|
||||
let decoder = ruzstd::decoding::StreamingDecoder::new(&data[..]).map_err(|e| anyhow::anyhow!("zstd: {e}"))?;
|
||||
let mut archive = tar::Archive::new(decoder);
|
||||
archive.set_preserve_permissions(true);
|
||||
archive.set_preserve_ownerships(false);
|
||||
archive.unpack(&tmp).context("unpacking")?;
|
||||
|
||||
let info: PkgInfo = toml::from_str(&fs::read_to_string(tmp.join("pkg.toml")).context("pkg.toml missing")?).context("pkg.toml")?;
|
||||
if info.name != name || info.version != version {
|
||||
let result = (|| -> Result<()> {
|
||||
let decoder = ruzstd::decoding::StreamingDecoder::new(&data[..]).map_err(|e| anyhow::anyhow!("zstd: {e}"))?;
|
||||
let mut archive = tar::Archive::new(decoder);
|
||||
archive.set_preserve_ownerships(false);
|
||||
match expect {
|
||||
Expect::Official => {
|
||||
archive.set_preserve_permissions(true);
|
||||
archive.unpack(&tmp).context("unpacking")?;
|
||||
}
|
||||
Expect::Store { .. } => unpack_untrusted(&mut archive, &tmp)?,
|
||||
}
|
||||
let info: PkgInfo = toml::from_str(&fs::read_to_string(tmp.join("pkg.toml")).context("pkg.toml missing")?).context("pkg.toml")?;
|
||||
let expected_name = match expect {
|
||||
Expect::Official => name,
|
||||
Expect::Store { id, .. } => id,
|
||||
};
|
||||
if info.name != expected_name || info.version != version {
|
||||
bail!("package says it is {} {}, expected {expected_name} {version}", info.name, info.version);
|
||||
}
|
||||
if let Expect::Store { id, approved, .. } = expect {
|
||||
check_store_manifest(&tmp, id, version, approved)?;
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
if let Err(e) = result {
|
||||
let _ = fs::remove_dir_all(&tmp);
|
||||
bail!("package says it is {} {}, expected {name} {version}", info.name, info.version);
|
||||
return Err(e);
|
||||
}
|
||||
fs::rename(&tmp, &dest)?;
|
||||
if let Expect::Store { source, .. } = expect {
|
||||
fs::write(dir.join("source"), format!("{source}\n"))?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Ids of the store apps on disk.
|
||||
pub fn store_apps(&self) -> Vec<String> {
|
||||
let Ok(entries) = fs::read_dir(&self.root) else { return Vec::new() };
|
||||
entries
|
||||
.flatten()
|
||||
.filter_map(|e| e.file_name().into_string().ok())
|
||||
.filter_map(|n| registry::store_id(&n).map(str::to_string))
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Uninstalls a store app (its files; the user's data stays in their home).
|
||||
pub fn remove_store_app(&self, id: &str) -> Result<()> {
|
||||
let name = format!("{}{id}", sf_ipc::store::PACKAGE_PREFIX);
|
||||
anyhow::ensure!(registry::store_id(&name).is_some(), "bad store app id {id}");
|
||||
let _ = fs::remove_file(self.store_dir().join("apps").join(id));
|
||||
if self.dir(&name).exists() {
|
||||
fs::remove_dir_all(self.dir(&name)).with_context(|| format!("removing {name}"))?;
|
||||
log::info!("removed store app {id}");
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -228,12 +305,12 @@ impl Store {
|
||||
self.set_link(name, "staged", version)
|
||||
}
|
||||
|
||||
/// Makes every staged package live.
|
||||
pub fn apply_staged(&self) -> Result<Applied> {
|
||||
/// Makes every staged package live for which `which(name)` says so.
|
||||
pub fn apply_staged(&self, which: impl Fn(&str) -> bool) -> Result<Applied> {
|
||||
let mut applied = Applied::default();
|
||||
let Ok(entries) = fs::read_dir(&self.root) else { return Ok(applied) };
|
||||
for e in entries.flatten() {
|
||||
let Some(name) = e.file_name().into_string().ok().filter(|n| registry::is_ours(n)) else { continue };
|
||||
let Some(name) = e.file_name().into_string().ok().filter(|n| registry::is_ours(n) && which(n)) else { continue };
|
||||
let Some(v) = self.staged(&name) else { continue };
|
||||
if self.link(&name, "current").as_deref() != Some(v.as_str()) {
|
||||
if let Some(cur) = self.link(&name, "current") {
|
||||
@@ -244,6 +321,8 @@ impl Store {
|
||||
if name == SHELL {
|
||||
fs::write(self.dir(&name).join("trial"), &v)?;
|
||||
applied.shell = true;
|
||||
} else if registry::store_id(&name).is_some() {
|
||||
applied.store = true;
|
||||
} else {
|
||||
applied.apps = true;
|
||||
}
|
||||
@@ -254,17 +333,33 @@ impl Store {
|
||||
Ok(applied)
|
||||
}
|
||||
|
||||
/// apps/<id> -> ../sf-app-<id>/current for every installed app.
|
||||
fn link_apps(&self) -> Result<()> {
|
||||
/// apps/<id> -> ../sf-app-<id>/current for every installed app, and
|
||||
/// store/apps/<id> -> ../../store-<id>/current for store apps.
|
||||
pub fn link_apps(&self) -> Result<()> {
|
||||
let apps = self.root.join("apps");
|
||||
let store_apps = self.store_dir().join("apps");
|
||||
fs::create_dir_all(&apps)?;
|
||||
fs::create_dir_all(&store_apps)?;
|
||||
let Ok(entries) = fs::read_dir(&self.root) else { return Ok(()) };
|
||||
for e in entries.flatten() {
|
||||
let Some(name) = e.file_name().into_string().ok() else { continue };
|
||||
let Some(id) = name.strip_prefix("sf-app-").filter(|_| registry::is_ours(&name)) else { continue };
|
||||
let link = apps.join(id);
|
||||
let (link, target) = if let Some(id) = name.strip_prefix("sf-app-").filter(|_| registry::is_official(&name)) {
|
||||
(apps.join(id), format!("../{name}/current"))
|
||||
} else if let Some(id) = registry::store_id(&name) {
|
||||
(store_apps.join(id), format!("../../{name}/current"))
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
if self.link(&name, "current").is_some() && fs::symlink_metadata(&link).is_err() {
|
||||
symlink(format!("../{name}/current"), &link)?;
|
||||
symlink(target, &link)?;
|
||||
}
|
||||
}
|
||||
// Links of removed store apps.
|
||||
if let Ok(entries) = fs::read_dir(&store_apps) {
|
||||
for e in entries.flatten() {
|
||||
if !e.path().join("app.toml").exists() {
|
||||
let _ = fs::remove_file(e.path());
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
@@ -362,3 +457,213 @@ impl Store {
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// Unpacks a package from a third party: only plain files, folders and
|
||||
/// symlinks that stay inside, no setuid/setgid bits, nothing writable by
|
||||
/// others, within size limits.
|
||||
fn unpack_untrusted<R: std::io::Read>(archive: &mut tar::Archive<R>, dest: &Path) -> Result<()> {
|
||||
use std::path::Component;
|
||||
archive.set_preserve_permissions(false);
|
||||
let mut total = 0u64;
|
||||
let mut files = 0usize;
|
||||
for entry in archive.entries().context("reading the package")? {
|
||||
let mut entry = entry.context("reading the package")?;
|
||||
let path = entry.path().context("bad path")?.into_owned();
|
||||
if !path.components().all(|c| matches!(c, Component::Normal(_) | Component::CurDir)) {
|
||||
bail!("package path {} leaves the package", path.display());
|
||||
}
|
||||
match entry.header().entry_type() {
|
||||
tar::EntryType::Regular | tar::EntryType::Directory => {}
|
||||
tar::EntryType::Symlink => {
|
||||
let target = entry.link_name().ok().flatten().context("symlink without target")?;
|
||||
// Depth of the folder the link is in; ".." may not climb above the package.
|
||||
let mut level = path.components().filter(|c| matches!(c, Component::Normal(_))).count() as i64 - 1;
|
||||
for c in target.components() {
|
||||
match c {
|
||||
Component::Normal(_) => level += 1,
|
||||
Component::ParentDir => level -= 1,
|
||||
Component::CurDir => {}
|
||||
_ => bail!("symlink {} points outside the package", path.display()),
|
||||
}
|
||||
if level < 0 {
|
||||
bail!("symlink {} points outside the package", path.display());
|
||||
}
|
||||
}
|
||||
}
|
||||
other => bail!("{}: {other:?} entries are not allowed", path.display()),
|
||||
}
|
||||
total += entry.header().size().unwrap_or(0);
|
||||
files += 1;
|
||||
if total > MAX_STORE_UNPACKED || files > MAX_STORE_FILES {
|
||||
bail!("the package is too large");
|
||||
}
|
||||
if !entry.unpack_in(dest).with_context(|| format!("unpacking {}", path.display()))? {
|
||||
bail!("package path {} leaves the package", path.display());
|
||||
}
|
||||
}
|
||||
strip_modes(dest)
|
||||
}
|
||||
|
||||
/// No setuid/setgid/sticky and no group/other write anywhere in `dir`.
|
||||
#[cfg(unix)]
|
||||
fn strip_modes(dir: &Path) -> Result<()> {
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
for e in fs::read_dir(dir)?.flatten() {
|
||||
let meta = fs::symlink_metadata(e.path())?;
|
||||
if meta.file_type().is_symlink() {
|
||||
continue;
|
||||
}
|
||||
let mode = meta.permissions().mode() & 0o755;
|
||||
fs::set_permissions(e.path(), fs::Permissions::from_mode(mode))?;
|
||||
if meta.is_dir() {
|
||||
strip_modes(&e.path())?;
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(not(unix))]
|
||||
fn strip_modes(_dir: &Path) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The manifest inside a store package must match what was offered.
|
||||
fn check_store_manifest(dir: &Path, id: &str, version: &str, approved: &[Permission]) -> Result<()> {
|
||||
let text = fs::read_to_string(dir.join("app.toml")).context("app.toml missing")?;
|
||||
let app: AppManifest = toml::from_str(&text).context("app.toml")?;
|
||||
anyhow::ensure!(app.id == id, "app.toml says id {}, expected {id}", app.id);
|
||||
anyhow::ensure!(app.version == version, "app.toml says version {}, expected {version}", app.version);
|
||||
app.check_store_rules()?;
|
||||
let missing = sf_ipc::store::missing_permissions(&app.permissions(), approved);
|
||||
anyhow::ensure!(missing.is_empty(), "the package asks for permissions that were not approved: {missing:?}");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(all(test, unix))]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
const ID: &str = "io.github.fox.hello";
|
||||
|
||||
struct Pkg {
|
||||
tar: tar::Builder<Vec<u8>>,
|
||||
}
|
||||
|
||||
impl Pkg {
|
||||
fn new(version: &str, perms: &str) -> Pkg {
|
||||
let mut p = Pkg { tar: tar::Builder::new(Vec::new()) };
|
||||
p.file("pkg.toml", &format!("name = \"{ID}\"\nversion = \"{version}\"\n"), 0o644);
|
||||
p.file(
|
||||
"app.toml",
|
||||
&format!("id = \"{ID}\"\nname = \"Hello\"\nversion = \"{version}\"\nkind = \"exec\"\nexec = [\"bin/hello\"]\n[sandbox]\npermissions = [{perms}]\n"),
|
||||
0o644,
|
||||
);
|
||||
p.file("bin/hello", "#!/bin/sh\n", 0o755);
|
||||
p
|
||||
}
|
||||
|
||||
fn file(&mut self, path: &str, body: &str, mode: u32) {
|
||||
let mut h = tar::Header::new_gnu();
|
||||
h.set_size(body.len() as u64);
|
||||
h.set_mode(mode);
|
||||
self.tar.append_data(&mut h, path, body.as_bytes()).unwrap();
|
||||
}
|
||||
|
||||
fn link(&mut self, path: &str, target: &str) {
|
||||
let mut h = tar::Header::new_gnu();
|
||||
h.set_entry_type(tar::EntryType::Symlink);
|
||||
h.set_size(0);
|
||||
self.tar.append_link(&mut h, path, target).unwrap();
|
||||
}
|
||||
|
||||
fn write(self, dir: &Path) -> PathBuf {
|
||||
let tar = self.tar.into_inner().unwrap();
|
||||
let zst = ruzstd::encoding::compress_to_vec(&tar[..], ruzstd::encoding::CompressionLevel::Fastest);
|
||||
let path = dir.join("pkg.tar.zst");
|
||||
fs::write(&path, &zst).unwrap();
|
||||
path
|
||||
}
|
||||
}
|
||||
|
||||
fn setup(name: &str) -> (PathBuf, Store) {
|
||||
let root = std::env::temp_dir().join(format!("sf-update-{name}-{}", std::process::id()));
|
||||
let _ = fs::remove_dir_all(&root);
|
||||
let store = Store::open(&root, &root.join("none.toml")).unwrap();
|
||||
(root, store)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn installs_a_store_app_and_refuses_bad_ones() {
|
||||
let (root, store) = setup("store");
|
||||
let name = format!("store-{ID}");
|
||||
let approved = [Permission::Network];
|
||||
let expect = Expect::Store { id: ID, approved: &approved, source: "https://github.com/fox/hello" };
|
||||
|
||||
// A good package, with a setuid bit that must be stripped.
|
||||
let mut p = Pkg::new("1.0.0", "\"network\"");
|
||||
p.file("bin/suid", "x", 0o4777);
|
||||
p.link("bin/alias", "hello");
|
||||
let pkg = p.write(&root);
|
||||
store.unpack_store(&name, "1.0.0", &pkg, &expect).unwrap();
|
||||
store.stage(&name, "1.0.0").unwrap();
|
||||
let applied = store.apply_staged(|_| true).unwrap();
|
||||
assert!(applied.store && !applied.apps);
|
||||
assert!(root.join("store/apps").join(ID).join("app.toml").is_file());
|
||||
assert_eq!(store.installed(&name).as_deref(), Some("1.0.0"));
|
||||
assert_eq!(fs::read_to_string(root.join(&name).join("source")).unwrap().trim(), "https://github.com/fox/hello");
|
||||
use std::os::unix::fs::PermissionsExt;
|
||||
let mode = fs::metadata(root.join(&name).join("1.0.0/bin/suid")).unwrap().permissions().mode() & 0o7777;
|
||||
assert_eq!(mode, 0o755);
|
||||
|
||||
// An unsigned update installs from the selected source.
|
||||
let pkg = Pkg::new("1.1.0", "\"network\"").write(&root);
|
||||
store.unpack_store(&name, "1.1.0", &pkg, &expect).unwrap();
|
||||
// More permissions than approved.
|
||||
let pkg = Pkg::new("1.1.0", "\"network\", \"devices\"").write(&root);
|
||||
let err = store.unpack_store(&name, "1.1.0", &pkg, &expect).unwrap_err();
|
||||
assert!(format!("{err:#}").contains("not approved"), "{err:#}");
|
||||
// A symlink out of the package.
|
||||
let mut p = Pkg::new("1.1.0", "\"network\"");
|
||||
p.link("bin/evil", "../../../../etc/shadow");
|
||||
let pkg = p.write(&root);
|
||||
assert!(store.unpack_store(&name, "1.1.0", &pkg, &expect).is_err());
|
||||
let mut p = Pkg::new("1.1.0", "\"network\"");
|
||||
p.link("evil", "/etc/shadow");
|
||||
let pkg = p.write(&root);
|
||||
assert!(store.unpack_store(&name, "1.1.0", &pkg, &expect).is_err());
|
||||
// Nothing half-unpacked is left behind.
|
||||
assert!(!root.join(&name).join("1.1.0").exists());
|
||||
assert!(!root.join(&name).join(".tmp-1.1.0").exists());
|
||||
|
||||
// Uninstall.
|
||||
store.remove_store_app(ID).unwrap();
|
||||
assert!(!root.join(&name).exists());
|
||||
assert!(fs::symlink_metadata(root.join("store/apps").join(ID)).is_err());
|
||||
fs::remove_dir_all(&root).unwrap();
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn plan_holds_back_new_permissions() {
|
||||
use sf_ipc::store::{Catalog, CatalogApp, Wanted, WantedApp};
|
||||
let (root, store) = setup("plan");
|
||||
let app = |perms: Vec<Permission>| CatalogApp {
|
||||
id: ID.into(),
|
||||
name: "Hello".into(),
|
||||
version: "2.0.0".into(),
|
||||
permissions: perms,
|
||||
source: "https://github.com/fox/hello".into(),
|
||||
..Default::default()
|
||||
};
|
||||
let mut wanted = Wanted::default();
|
||||
wanted.apps.insert(ID.into(), WantedApp { source: "github.com/fox/hello".into(), permissions: vec![Permission::Network] });
|
||||
let mut cat = Catalog { apps: vec![app(vec![Permission::Network])], ..Default::default() };
|
||||
assert_eq!(crate::appstore::plan(&store, &wanted, &mut cat).len(), 1);
|
||||
let mut cat = Catalog { apps: vec![app(vec![Permission::Network, Permission::Gpu])], ..Default::default() };
|
||||
assert!(crate::appstore::plan(&store, &wanted, &mut cat).is_empty());
|
||||
assert_eq!(cat.apps[0].blocked.as_deref(), Some("permissions"));
|
||||
// Not wanted: nothing to do.
|
||||
let mut cat = Catalog { apps: vec![app(vec![])], ..Default::default() };
|
||||
assert!(crate::appstore::plan(&store, &Wanted::default(), &mut cat).is_empty());
|
||||
fs::remove_dir_all(&root).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user