//! 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, status: Option, notice: String, actions: Vec, /// Ids of installed store apps last time we looked; a change reloads the /// launcher's app list once the store is closed. installed: Vec, reload_pending: bool, } pub struct Screen { ui: slint::Weak, state: RefCell, on_apps_changed: RefCell>>, timer: slint::Timer, } thread_local! { static SCREEN: RefCell>> = const { RefCell::new(None) }; /// Demo (Windows / SMARTFOX_DEMO_SYSTEM): store.toml and catalog in memory. static DEMO: RefCell> = const { RefCell::new(None) }; } pub fn current() -> Option> { SCREEN.with(|s| s.borrow().clone()) } fn row(title: impl Into, value: impl Into, detail: impl Into, 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::()) } 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::>().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| 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 { 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 { 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 { 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) { 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) { 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, Vec) { 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 { 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 = 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")); } }