//! App manifests: one `app.toml` per folder under the apps directory. use std::path::{Path, PathBuf}; use anyhow::{Context, Result}; use serde::{Deserialize, Serialize}; use crate::settings::Settings; #[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] #[serde(rename_all = "lowercase")] pub enum AppKind { /// Runs in the shared Chromium web runtime. Web, /// Any executable: AppImage, Rust binary, script. Exec, /// Built into the launcher (e.g. settings screen). Builtin, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct AppManifest { pub id: String, pub name: String, pub kind: AppKind, /// Package version (semver). Published as `sf-app-` when it changes; /// the newer of a factory and an installed copy wins. #[serde(default = "default_version")] pub version: String, /// Short label above the title in the hero ("Saját app", "Castolás"...). #[serde(default)] pub category: String, #[serde(default)] pub description: String, /// Web apps: start URL. May contain `${settings.}` placeholders. #[serde(default)] pub url: Option, /// Exec apps: command line. #[serde(default)] pub exec: Option>, /// Built-in icon name used by the launcher. #[serde(default)] pub icon: String, /// Accent color (hex), used for focus glow and buttons. #[serde(default = "default_accent")] pub accent: String, /// Three colors for the animated hero backdrop: highlight, mid, deep. #[serde(default)] pub palette: Vec, /// Sort order on the home row. #[serde(default)] pub order: i32, #[serde(default)] pub web: WebOptions, #[serde(default)] pub dial: Option, /// Background receiver (AirPlay, Miracast): sf-core keeps it running all /// the time and it shows its own window when something connects. The /// launcher tile only opens the details sheet. #[serde(default)] pub service: bool, /// Folder the manifest was loaded from (not serialized). #[serde(skip)] pub dir: PathBuf, } #[derive(Debug, Clone, Default, Serialize, Deserialize)] pub struct WebOptions { /// Full user agent override. #[serde(default)] pub user_agent: Option, /// Appended to the default user agent. #[serde(default)] pub user_agent_suffix: Option, /// Unpacked extensions to load (paths relative to the app folder). #[serde(default)] pub extensions: Vec, } #[derive(Debug, Clone, Serialize, Deserialize)] pub struct DialOptions { /// DIAL application name, e.g. "YouTube". pub name: String, } fn default_version() -> String { "0.0.0".into() } fn default_accent() -> String { "#ffffff".into() } impl AppManifest { /// Start URL with `${settings.key}` placeholders filled in. pub fn resolved_url(&self, settings: &Settings) -> Option { self.url.as_ref().map(|u| settings.expand(u)) } } /// Loads every `*/app.toml` under `dir`, sorted by `order` then name. pub fn load_apps(dir: &Path) -> Result> { let mut apps = Vec::new(); let entries = std::fs::read_dir(dir).with_context(|| format!("reading {}", dir.display()))?; for entry in entries.flatten() { let path = entry.path().join("app.toml"); if !path.is_file() { continue; } match load_one(&path) { Ok(app) => apps.push(app), Err(e) => log::warn!("skipping {}: {e:#}", path.display()), } } sort_apps(&mut apps); Ok(apps) } /// Loads apps from several folders (factory apps, then installed packages). /// Missing folders are skipped; of two apps with the same id the higher /// `version` wins, on a tie the later folder. pub fn load_apps_from(dirs: &[PathBuf]) -> Result> { let mut apps: Vec = Vec::new(); let mut found = false; for dir in dirs { if !dir.is_dir() { continue; } found = true; for app in load_apps(dir)? { match apps.iter_mut().find(|a| a.id == app.id) { Some(old) if version_cmp(&app.version, &old.version).is_ge() => *old = app, Some(_) => {} None => apps.push(app), } } } anyhow::ensure!(found, "none of the app folders exist: {dirs:?}"); 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. pub fn version_cmp(a: &str, b: &str) -> std::cmp::Ordering { let parts = |v: &str| -> Vec { v.split(['.', '-', '+']).take(3).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) } fn load_one(path: &Path) -> Result { let text = std::fs::read_to_string(path)?; let mut app: AppManifest = toml::from_str(&text)?; app.dir = path.parent().unwrap_or(Path::new(".")).to_path_buf(); Ok(app) } #[cfg(test)] mod tests { use super::*; #[test] fn parses_web_manifest() { let app: AppManifest = toml::from_str( r##" id = "netflex" name = "Netflex" kind = "web" url = "${settings.netflex_server}/" accent = "#E50914" palette = ["#ff3b3b", "#7a0a10", "#0c0203"] [web] user_agent_suffix = "SMART-TV SmartFox/0.1" "##, ) .unwrap(); assert_eq!(app.kind, AppKind::Web); let mut s = Settings::default(); s.values.insert("netflex_server".into(), "http://10.0.0.5:7880".into()); assert_eq!(app.resolved_url(&s).unwrap(), "http://10.0.0.5:7880/"); assert_eq!(app.version, "0.0.0"); } #[test] fn compares_versions() { use std::cmp::Ordering::*; 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); } }