From 1f34346f6db95fd5a3706bed321bd0e25e8db488 Mon Sep 17 00:00:00 2001 From: Jeremy Date: Fri, 16 Oct 2026 11:36:12 +0100 Subject: [PATCH] feat(extensions): Extensions page with Themes and Installed tabs over the shared store Adds crates/ui-egui/src/features/extensions (trait, click plan, screen, theme card, in-memory sample store) and a desktop store over craft-ext-store. Apps | Extensions switch only where the host has a store. Strings in all ten catalogs. craft-ext-* are path dependencies for now. --- Cargo.lock | 138 ++++++- Cargo.toml | 4 + apps/artcraft-launcher/Cargo.toml | 9 + apps/artcraft-launcher/src/extensions.rs | 96 +++++ .../artcraft-launcher/src/extensions/tests.rs | 178 +++++++++ apps/artcraft-launcher/src/main.rs | 18 +- crates/ui-egui/Cargo.toml | 1 + crates/ui-egui/src/app.rs | 16 + .../ui-egui/src/features/extensions/card.rs | 42 +++ crates/ui-egui/src/features/extensions/mod.rs | 56 +++ .../ui-egui/src/features/extensions/plan.rs | 104 ++++++ .../src/features/extensions/plan_tests.rs | 155 ++++++++ .../ui-egui/src/features/extensions/sample.rs | 152 ++++++++ .../ui-egui/src/features/extensions/screen.rs | 345 ++++++++++++++++++ .../ui-egui/src/features/extensions/source.rs | 49 +++ .../ui-egui/src/features/extensions/tests.rs | 73 ++++ crates/ui-egui/src/features/mod.rs | 3 + crates/ui-egui/src/i18n/cs.tsv | 35 ++ crates/ui-egui/src/i18n/de.tsv | 35 ++ crates/ui-egui/src/i18n/es.tsv | 35 ++ crates/ui-egui/src/i18n/fr.tsv | 35 ++ crates/ui-egui/src/i18n/hu.tsv | 35 ++ crates/ui-egui/src/i18n/ja.tsv | 35 ++ crates/ui-egui/src/i18n/pl.tsv | 35 ++ crates/ui-egui/src/i18n/pt-BR.tsv | 35 ++ crates/ui-egui/src/i18n/ru.tsv | 35 ++ crates/ui-egui/src/i18n/tests.rs | 4 + crates/ui-egui/src/i18n/zh-CN.tsv | 35 ++ crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/tests/extensions.rs | 207 +++++++++++ 30 files changed, 1994 insertions(+), 7 deletions(-) create mode 100644 apps/artcraft-launcher/src/extensions.rs create mode 100644 apps/artcraft-launcher/src/extensions/tests.rs create mode 100644 crates/ui-egui/src/features/extensions/card.rs create mode 100644 crates/ui-egui/src/features/extensions/mod.rs create mode 100644 crates/ui-egui/src/features/extensions/plan.rs create mode 100644 crates/ui-egui/src/features/extensions/plan_tests.rs create mode 100644 crates/ui-egui/src/features/extensions/sample.rs create mode 100644 crates/ui-egui/src/features/extensions/screen.rs create mode 100644 crates/ui-egui/src/features/extensions/source.rs create mode 100644 crates/ui-egui/src/features/extensions/tests.rs create mode 100644 crates/ui-egui/src/features/mod.rs create mode 100644 crates/ui-egui/tests/extensions.rs diff --git a/Cargo.lock b/Cargo.lock index 6da3e935..d5d3911c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -281,6 +281,8 @@ dependencies = [ "artcraft-launcher-core", "artcraft-launcher-native", "artcraft-launcher-ui-egui", + "craft-ext-core", + "craft-ext-store", "eframe", "egui", "env_logger", @@ -293,10 +295,14 @@ dependencies = [ "rfd", "ron", "serde", + "serde_json", + "sha2 0.11.1", + "tempfile", "tray-icon", "winreg", "winresource", "zbus", + "zip 9.0.4", ] [[package]] @@ -319,12 +325,12 @@ dependencies = [ "plist", "serde", "serde_json", - "sha2", + "sha2 0.10.9", "tar", "tempfile", "ureq", "winreg", - "zip", + "zip 8.6.0", ] [[package]] @@ -332,6 +338,7 @@ name = "artcraft-launcher-ui-egui" version = "0.4.1" dependencies = [ "artcraft-launcher-core", + "craft-ext-core", "egui", "egui_extras", "egui_kittest", @@ -627,6 +634,15 @@ dependencies = [ "generic-array", ] +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + [[package]] name = "block2" version = "0.5.1" @@ -878,6 +894,12 @@ dependencies = [ "crossbeam-utils", ] +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + [[package]] name = "core-foundation" version = "0.9.4" @@ -937,6 +959,43 @@ dependencies = [ "libc", ] +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "craft-atomic" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=8f5a2831614e632f91ad367f7af2a6e5b61b9529#8f5a2831614e632f91ad367f7af2a6e5b61b9529" +dependencies = [ + "rustix 1.1.5", +] + +[[package]] +name = "craft-ext-core" +version = "0.1.0" +dependencies = [ + "serde", + "serde_json", +] + +[[package]] +name = "craft-ext-store" +version = "0.1.0" +dependencies = [ + "craft-atomic", + "craft-ext-core", + "serde", + "serde_json", + "sha2 0.11.1", + "zip 9.0.4", +] + [[package]] name = "crc32fast" version = "1.5.2" @@ -996,6 +1055,15 @@ dependencies = [ "typenum", ] +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + [[package]] name = "cursor-icon" version = "1.2.0" @@ -1064,8 +1132,19 @@ version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ - "block-buffer", - "crypto-common", + "block-buffer 0.10.4", + "crypto-common 0.1.7", +] + +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid", + "crypto-common 0.2.2", ] [[package]] @@ -2173,6 +2252,15 @@ version = "1.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + [[package]] name = "icu_collections" version = "2.3.0" @@ -2838,6 +2926,18 @@ dependencies = [ "jni-sys 0.3.1", ] +[[package]] +name = "nix" +version = "0.31.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf20d2fde8ff38632c426f1165ed7436270b44f199fc55284c38276f9db47c3d" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "cfg_aliases", + "libc", +] + [[package]] name = "nohash-hasher" version = "0.2.0" @@ -4163,8 +4263,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" dependencies = [ "cfg-if", - "cpufeatures", - "digest", + "cpufeatures 0.2.17", + "digest 0.10.7", +] + +[[package]] +name = "sha2" +version = "0.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d7069beb7d6ac7b9acd1039986e73443f24234f41074da099d6f994ac9ad19" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "digest 0.11.3", ] [[package]] @@ -6072,6 +6183,21 @@ dependencies = [ "zopfli", ] +[[package]] +name = "zip" +version = "9.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a954114b47a54df49f83d2722814e86b23d4bb1b54a1b90fb7d92b41619ddc22" +dependencies = [ + "crc32fast", + "flate2", + "indexmap", + "memchr", + "nix", + "typed-path", + "zopfli", +] + [[package]] name = "zlib-rs" version = "0.6.8" diff --git a/Cargo.toml b/Cargo.toml index 99be343b..20f073c7 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -20,6 +20,10 @@ todo = "warn" artcraft-launcher-core = { path = "crates/core" } artcraft-launcher-ui-egui = { path = "crates/ui-egui" } artcraft-launcher-native = { path = "crates/native" } +# Local path while the extension crates are built beside the launcher. Replace with a pinned git revision of +# https://github.com/Jeremy8776/craft-extensions before any pull request. +craft-ext-core = { path = "../craft-extensions/crates/ext-core" } +craft-ext-store = { path = "../craft-extensions/crates/ext-store" } egui = "0.36" eframe = { version = "0.36", default-features = false } egui_extras = { version = "0.36", default-features = false } diff --git a/apps/artcraft-launcher/Cargo.toml b/apps/artcraft-launcher/Cargo.toml index dd275092..378068c2 100644 --- a/apps/artcraft-launcher/Cargo.toml +++ b/apps/artcraft-launcher/Cargo.toml @@ -20,6 +20,8 @@ local-mirror = ["artcraft-launcher-native/local-mirror"] artcraft-launcher-core = { workspace = true } artcraft-launcher-ui-egui = { workspace = true } artcraft-launcher-native = { workspace = true } +craft-ext-core = { workspace = true } +craft-ext-store = { workspace = true } eframe = { workspace = true, features = ["default_fonts", "wgpu", "accesskit", "wayland", "x11", "persistence", "links"] } egui = { workspace = true } log = { workspace = true } @@ -63,6 +65,13 @@ tray-icon = { version = "0.25", default-features = false, features = ["ksni"] } [target.'cfg(not(target_arch = "wasm32"))'.dependencies] rfd = { version = "=0.17.2", default-features = false, features = ["xdg-portal", "wayland"] } +[dev-dependencies] +# The extensions tests build small packages by hand, with the versions the store itself uses. +serde_json = { workspace = true } +sha2 = "0.11.1" +tempfile = "3.27.0" +zip = { version = "9.0.4", default-features = false, features = ["deflate"] } + [build-dependencies] # Icon + VERSIONINFO for artcraft-launcher.exe; build.rs only uses it when targeting Windows. winresource = "0.1" diff --git a/apps/artcraft-launcher/src/extensions.rs b/apps/artcraft-launcher/src/extensions.rs new file mode 100644 index 00000000..313b0db9 --- /dev/null +++ b/apps/artcraft-launcher/src/extensions.rs @@ -0,0 +1,96 @@ +//! The shared extensions store as the Extensions page sees it: a thin layer over `craft-ext-store`. +//! +//! Invariants: nothing here opens a network connection; every failure comes back as a short +//! sentence a person can read (the store's own wording, which is plain by its own tests); a theme +//! whose file no longer reads or passes the colour checks simply has no preview, it never panics. + +use std::collections::HashMap; +use std::fs::File; +use std::io::Read; +use std::path::{Path, PathBuf}; + +use artcraft_launcher_ui_egui::features::extensions::{ExtensionSource, Row}; +use craft_ext_core::id::{AppId, ExtensionId}; +use craft_ext_core::manifest::{Kind, THEME_FILE}; +use craft_ext_core::palette::{MAX_THEME_BYTES, Palette, ThemeFile}; +use craft_ext_core::tier::Tier; +use craft_ext_core::version::Version; +use craft_ext_store::location; +use craft_ext_store::reader::Reader; +use craft_ext_store::store::Store; + +pub struct DesktopStore { + store: Store, + reader: Reader, + /// Palettes already read, by extension and version. A package folder is never edited after install. + palettes: HashMap<(ExtensionId, Version), Palette>, +} + +impl DesktopStore { + /// The store in its usual place (`CRAFT_EXT_DIR` overrides it), shared with every Craft app. + pub fn open() -> Result { + location::default_root().map(Self::at).map_err(|e| e.to_string()) + } + + pub fn at(root: PathBuf) -> Self { + Self { store: Store::at(&root), reader: Reader::open(root), palettes: HashMap::new() } + } + + fn palette(&mut self, id: &ExtensionId, version: Version) -> Option { + if let Some(found) = self.palettes.get(&(id.clone(), version)) { + return Some(found.clone()); + } + let path = self.store.package_dir(id, version).join(THEME_FILE); + let mut bytes = Vec::new(); + File::open(path).ok()?.take(MAX_THEME_BYTES as u64 + 1).read_to_end(&mut bytes).ok()?; + let palette = ThemeFile::parse(&bytes).ok()?.palette; + self.palettes.insert((id.clone(), version), palette.clone()); + Some(palette) + } +} + +impl ExtensionSource for DesktopStore { + fn generation(&mut self) -> u64 { + self.reader.generation() + } + + fn rows(&mut self) -> Result, String> { + let state = self.store.state().map_err(|e| e.to_string())?; + let mut rows = Vec::with_capacity(state.installed.len()); + for i in &state.installed { + let palette = if i.kind == Kind::Theme { self.palette(&i.id, i.version) } else { None }; + rows.push(Row { + id: i.id.clone(), + version: i.version, + kind: i.kind, + name: i.name.clone(), + tier: i.tier, + apps: i.apps.clone(), + enabled: i.apps.iter().filter(|a| state.is_enabled(a, &i.id)).cloned().collect(), + worn: state.active_theme.iter().filter(|(_, chosen)| **chosen == i.id).map(|(app, _)| app.clone()).collect(), + palette, + }); + } + self.palettes.retain(|(id, version), _| state.installed.iter().any(|i| &i.id == id && i.version == *version)); + Ok(rows) + } + + fn add_file(&mut self, path: &Path) -> Result { + self.store.install_file(path, Tier::FromFile).map(|installed| installed.name).map_err(|e| e.to_string()) + } + + fn remove(&mut self, id: &ExtensionId) -> Result<(), String> { + self.store.uninstall(id).map_err(|e| e.to_string()) + } + + fn set_enabled(&mut self, app: &AppId, id: &ExtensionId, on: bool) -> Result<(), String> { + self.store.set_enabled(app, id, on).map_err(|e| e.to_string()) + } + + fn wear(&mut self, app: &AppId, id: Option<&ExtensionId>) -> Result<(), String> { + self.store.set_active_theme(app, id).map_err(|e| e.to_string()) + } +} + +#[cfg(test)] +mod tests; diff --git a/apps/artcraft-launcher/src/extensions/tests.rs b/apps/artcraft-launcher/src/extensions/tests.rs new file mode 100644 index 00000000..5f662b4d --- /dev/null +++ b/apps/artcraft-launcher/src/extensions/tests.rs @@ -0,0 +1,178 @@ +//! The desktop store against a real folder: install a file, choose it, and see an app's `Reader` +//! (the code every Craft app uses) agree. The packages are built here from test colours. + +use std::io::{Cursor, Write}; + +use sha2::{Digest, Sha256}; +use zip::write::SimpleFileOptions; +use zip::{CompressionMethod, ZipWriter}; + +use super::*; + +fn app(s: &str) -> AppId { + AppId::new(s).unwrap() +} + +fn theme_json() -> Vec { + serde_json::json!({ + "schema": 1, + "palette": { + "dark": true, "background": "#0f1720", "surface": "#18222e", "text": "#e8eef4", "muted_text": "#a9b7c6", + "line": "#2b3a4a", "accent": "#4da3ff", "good": "#4cc38a", "warn": "#e0b04a", "bad": "#ff6b6b" + } + }) + .to_string() + .into_bytes() +} + +fn package(id: &str, name: &str, apps: &[&str], theme: &[u8]) -> Vec { + let hex: String = Sha256::digest(theme).iter().map(|b| format!("{b:02x}")).collect(); + let compat: serde_json::Map = apps.iter().map(|a| (a.to_string(), serde_json::json!({}))).collect(); + let manifest = serde_json::json!({ + "schema": 1, "id": id, "name": name, "version": "1.0.0", "kind": "theme", "publisher": {"name": "Example"}, + "compat": compat, "files": [{"path": "theme.json", "sha256": hex, "size": theme.len()}] + }) + .to_string(); + let mut zip = ZipWriter::new(Cursor::new(Vec::new())); + let options = SimpleFileOptions::default().compression_method(CompressionMethod::Deflated); + zip.start_file("craft-extension.json", options).unwrap(); + zip.write_all(manifest.as_bytes()).unwrap(); + zip.start_file("theme.json", options).unwrap(); + zip.write_all(theme).unwrap(); + zip.finish().unwrap().into_inner() +} + +fn write_package(dir: &Path, file: &str, bytes: &[u8]) -> PathBuf { + let path = dir.join(file); + std::fs::write(&path, bytes).unwrap(); + path +} + +#[test] +fn a_file_added_in_the_launcher_is_listed_chosen_and_seen_by_an_app() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().join("ext"); + let mut launcher = DesktopStore::at(root.clone()); + let file = write_package(dir.path(), "ocean.zip", &package("org.example.ocean", "Ocean", &["photocraft", "lightcraft"], &theme_json())); + + assert_eq!(launcher.rows().unwrap(), Vec::new(), "an empty store lists nothing"); + assert_eq!(launcher.add_file(&file).unwrap(), "Ocean"); + let rows = launcher.rows().unwrap(); + assert_eq!(rows.len(), 1); + let row = &rows[0]; + assert_eq!(row.tier, Tier::FromFile, "a file the person picked is recorded as such"); + assert_eq!(row.enabled.len(), 2, "installing switches it on for the apps it is made for"); + assert!(row.worn.is_empty(), "installing changes nobody's look"); + assert!(row.palette.as_ref().is_some_and(|p| p.dark)); + + // An app, with no launcher, reads the same folder. + let photocraft = Reader::open(&root); + let before = photocraft.generation(); + assert!(photocraft.active_theme(&app("photocraft")).is_none()); + launcher.wear(&app("photocraft"), Some(&row.id)).unwrap(); + assert!(photocraft.generation() > before, "the running app can tell something changed"); + assert_eq!(photocraft.active_theme(&app("photocraft")).unwrap().name, "Ocean"); + assert!(photocraft.active_theme(&app("lightcraft")).is_none(), "another app keeps its own look until it chooses"); + assert_eq!(launcher.rows().unwrap()[0].worn.iter().map(|a| a.as_str()).collect::>(), ["photocraft"]); + + launcher.set_enabled(&app("photocraft"), &row.id, false).unwrap(); + assert!(photocraft.active_theme(&app("photocraft")).is_none(), "switching it off gives the app its look back"); + assert!(launcher.rows().unwrap()[0].worn.is_empty()); + + launcher.remove(&row.id).unwrap(); + assert!(launcher.rows().unwrap().is_empty()); +} + +#[test] +fn a_hostile_or_broken_file_is_refused_with_a_sentence_and_adds_nothing() { + let dir = tempfile::tempdir().unwrap(); + let mut launcher = DesktopStore::at(dir.path().join("ext")); + let not_a_package = write_package(dir.path(), "nope.zip", b"this is not a zip file"); + let low_contrast = serde_json::json!({ + "schema": 1, + "palette": { + "dark": true, "background": "#0f1720", "surface": "#18222e", "text": "#101820", "muted_text": "#a9b7c6", + "line": "#2b3a4a", "accent": "#4da3ff", "good": "#4cc38a", "warn": "#e0b04a", "bad": "#ff6b6b" + } + }) + .to_string() + .into_bytes(); + let unreadable = write_package(dir.path(), "dim.zip", &package("org.example.dim", "Dim", &["photocraft"], &low_contrast)); + let claims_first_party = write_package(dir.path(), "fake.zip", &package("org.storytold.fake", "Fake", &["photocraft"], &theme_json())); + for file in [not_a_package, unreadable, claims_first_party, dir.path().join("missing.zip")] { + let reason = launcher.add_file(&file).unwrap_err(); + assert!(!reason.is_empty() && reason.chars().next().is_some_and(char::is_lowercase), "{reason:?}"); + for word in ["zip", "manifest", "sha", "namespace", "unwrap", "panic"] { + assert!(!reason.to_lowercase().contains(word), "{reason:?} mentions {word:?}"); + } + } + assert!(launcher.rows().unwrap().is_empty()); +} + +#[test] +fn a_theme_whose_file_goes_bad_after_install_loses_its_preview_without_failing_the_list() { + let dir = tempfile::tempdir().unwrap(); + let root = dir.path().join("ext"); + let mut launcher = DesktopStore::at(root.clone()); + let file = write_package(dir.path(), "ocean.zip", &package("org.example.ocean", "Ocean", &["photocraft"], &theme_json())); + launcher.add_file(&file).unwrap(); + let id = launcher.rows().unwrap()[0].id.clone(); + // A second, fresh view of the same folder (no cached colours) after the file is damaged. + std::fs::write(root.join("packages").join(id.as_str()).join("1.0.0").join("theme.json"), b"garbage").unwrap(); + let mut fresh = DesktopStore::at(root); + let rows = fresh.rows().unwrap(); + assert_eq!(rows.len(), 1); + assert!(rows[0].palette.is_none()); +} + +/// Writes three sample theme packages for hand testing, and proves each installs. Ignored by +/// default; run with `CRAFT_EXT_SAMPLES_OUT= cargo test -p artcraft-launcher --bin +/// artcraft-launcher -- --ignored write_sample_packages`. +#[test] +#[ignore = "writes files for hand testing"] +fn write_sample_packages() { + let Some(out) = std::env::var_os("CRAFT_EXT_SAMPLES_OUT").map(PathBuf::from) else { return }; + std::fs::create_dir_all(&out).unwrap(); + let theme = |dark: bool, c: [&str; 9]| { + serde_json::json!({ + "schema": 1, + "palette": { + "dark": dark, "background": c[0], "surface": c[1], "text": c[2], "muted_text": c[3], "line": c[4], + "accent": c[5], "good": c[6], "warn": c[7], "bad": c[8] + } + }) + .to_string() + .into_bytes() + }; + let apps = ["photocraft", "lightcraft", "pdfcraft"]; + let samples = [ + ( + "sample-midnight.zip", + "org.example.midnight", + "Midnight", + &apps[..], + theme(true, ["#101820", "#18222d", "#e8eef4", "#a9b6c2", "#35424f", "#4aa3ff", "#3fd6b8", "#ffc14d", "#ff6259"]), + ), + ( + "sample-paper.zip", + "org.example.paper", + "Paper", + &apps[..], + theme(false, ["#f5f1e8", "#ece6d8", "#1d1b16", "#55504a", "#cdc5b3", "#1a5fb4", "#0a7563", "#8a5800", "#b3261e"]), + ), + ( + "sample-ocean.zip", + "org.example.ocean", + "Ocean", + &apps[..1], + theme(true, ["#0b2530", "#12384a", "#e6f4f7", "#a6c8d2", "#2c5b6e", "#3fd6b8", "#4cc38a", "#e0b04a", "#ff6b6b"]), + ), + ]; + let scratch = tempfile::tempdir().unwrap(); + let mut proof = DesktopStore::at(scratch.path().join("ext")); + for (file, id, name, apps, colours) in samples { + let path = write_package(&out, file, &package(id, name, apps, &colours)); + assert_eq!(proof.add_file(&path).unwrap(), name, "{file} must install"); + } + assert_eq!(proof.rows().unwrap().iter().filter(|r| r.palette.is_some()).count(), 3); +} diff --git a/apps/artcraft-launcher/src/main.rs b/apps/artcraft-launcher/src/main.rs index d7f78743..94058e57 100644 --- a/apps/artcraft-launcher/src/main.rs +++ b/apps/artcraft-launcher/src/main.rs @@ -5,6 +5,7 @@ #![cfg_attr(windows, windows_subsystem = "windows")] #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +mod extensions; mod logging; mod motion; mod settings_file; @@ -391,6 +392,8 @@ fn claim_notification_identity() -> &'static Result<(), String> { struct DesktopHost { tray: bool, quit: bool, + /// The shared extensions store; `None` when this computer has no place to keep one. + extensions: Option, } impl Host for DesktopHost { @@ -440,6 +443,14 @@ impl Host for DesktopHost { dialog.pick_folder().and_then(|p| p.to_str().map(str::to_string)) } + fn pick_file(&mut self, title: &str, extensions: &[&str]) -> Option { + rfd::FileDialog::new().set_title(title).add_filter(title, extensions).pick_file() + } + + fn extensions(&mut self) -> Option<&mut dyn artcraft_launcher_ui_egui::features::extensions::ExtensionSource> { + self.extensions.as_mut().map(|store| store as &mut dyn artcraft_launcher_ui_egui::features::extensions::ExtensionSource) + } + fn reduce_motion(&self) -> bool { motion::reduced() } @@ -449,6 +460,11 @@ impl Host for DesktopHost { } } +/// The shared extensions store, or `None` (with a note in the log) where there is no place for one. +fn open_extensions() -> Option { + extensions::DesktopStore::open().inspect_err(|e| log::warn!("extensions are unavailable: {e}")).ok() +} + /// Everything that outlives a window: the UI state and its backend, the tray icon, and the work /// that goes on with or without a window. struct Launcher { @@ -485,7 +501,7 @@ impl Launcher { system_theme: system_theme::Monitor::default(), ui: LauncherUi::new(&windowless, backend, Settings::default()), tray: None, - host: DesktopHost { tray: false, quit: false }, + host: DesktopHost { tray: false, quit: false, extensions: open_extensions() }, starts, windowless, run_again, diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 151967fc..89f7d011 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -12,6 +12,7 @@ workspace = true [dependencies] artcraft-launcher-core = { workspace = true } +craft-ext-core = { workspace = true } egui = { workspace = true } egui_extras = { workspace = true, features = ["image", "svg"] } image = { version = "0.25", default-features = false, features = ["png", "jpeg"] } diff --git a/crates/ui-egui/src/app.rs b/crates/ui-egui/src/app.rs index 0f21221a..292d25a3 100644 --- a/crates/ui-egui/src/app.rs +++ b/crates/ui-egui/src/app.rs @@ -61,6 +61,14 @@ pub trait Host { fn pick_folder(&mut self, _initial: Option<&str>) -> Option { None } + /// Asks the person for a file; `extensions` are the file endings on offer, without the dot. + fn pick_file(&mut self, _title: &str, _extensions: &[&str]) -> Option { + None + } + /// The shared extensions store, where this build has one (not the web build). + fn extensions(&mut self) -> Option<&mut dyn crate::features::extensions::ExtensionSource> { + None + } /// Quit the launcher for real (not just hide to the tray). fn quit(&mut self) {} } @@ -128,6 +136,8 @@ pub struct LauncherUi { /// The details pictures the backend has sent (or been asked for), by app and picture key. pub(crate) pictures: std::collections::HashMap<(String, String), crate::details::Picture>, started: bool, + /// The Extensions page: what it shows and has read from the shared store. + pub(crate) extensions: crate::features::extensions::State, applied_theme: Option, /// The OS asks for fewer animations: what the host last said, and the context's time to ask /// it again at. @@ -196,6 +206,7 @@ impl LauncherUi { detail_zoom: false, pictures: std::collections::HashMap::new(), started: false, + extensions: Default::default(), applied_theme: None, reduce_motion: false, motion_recheck: 0.0, @@ -572,6 +583,11 @@ impl LauncherUi { egui::CentralPanel::default() .frame(egui::Frame::new().fill(tokens.bg).inner_margin(egui::Margin { left: 20, right: 20, top: 18, bottom: 0 })) .show(ui, |ui| { + self.page_switch(ui, host); + if self.extensions.open { + self.extensions_page(ui, host); + return; + } self.toolbar(ui); ui.add_space(18.0); let ids = self.visible_ids(); diff --git a/crates/ui-egui/src/features/extensions/card.rs b/crates/ui-egui/src/features/extensions/card.rs new file mode 100644 index 00000000..607cd984 --- /dev/null +++ b/crates/ui-egui/src/features/extensions/card.rs @@ -0,0 +1,42 @@ +//! A theme card's picture: a small mock window painted from the theme's own colours, so no +//! screenshots are needed and the preview can never disagree with the theme. + +use craft_ext_core::palette::{Palette, Rgb}; +use egui::{Color32, CornerRadius, Rect, Stroke, Ui, pos2, vec2}; + +pub fn color(c: Rgb) -> Color32 { + Color32::from_rgb(c.0, c.1, c.2) +} + +/// Paints the preview into `rect`, clipped to it. +pub fn paint_preview(ui: &Ui, rect: Rect, p: &Palette) { + let paint = ui.painter_at(rect); + let square = CornerRadius::ZERO; + let bar = |origin: egui::Pos2, width: f32, height: f32, c: Rgb| { + paint.rect_filled(Rect::from_min_size(origin, vec2(width, height)), square, color(c)); + }; + paint.rect_filled(rect, square, color(p.background)); + + // A side panel with three entries. + let side = Rect::from_min_max(rect.min, pos2(rect.left() + rect.width() * 0.28, rect.bottom())); + paint.rect_filled(side, square, color(p.surface)); + paint.vline(side.right() - 0.5, side.y_range(), Stroke::new(1.0, color(p.line))); + for i in 0..3 { + bar(side.min + vec2(12.0, 16.0 + 16.0 * i as f32), side.width() * 0.5, 5.0, p.muted_text); + } + + // The page: a heading, two lines of text, a button. + let page = rect.min + vec2(rect.width() * 0.28 + 16.0, 16.0); + bar(page, rect.width() * 0.3, 8.0, p.text); + bar(page + vec2(0.0, 20.0), rect.width() * 0.4, 5.0, p.muted_text); + bar(page + vec2(0.0, 32.0), rect.width() * 0.32, 5.0, p.muted_text); + bar(page + vec2(0.0, 52.0), 52.0, 16.0, p.accent); + + // A panel on the page, and the three status colours. + let panel = Rect::from_min_size(page + vec2(0.0, 80.0), vec2(rect.width() * 0.4, 28.0)); + paint.rect_filled(panel, square, color(p.surface)); + paint.rect_stroke(panel, square, Stroke::new(1.0, color(p.line)), egui::StrokeKind::Inside); + for (i, c) in [p.good, p.warn, p.bad].into_iter().enumerate() { + bar(pos2(rect.right() - 22.0 - 14.0 * i as f32, rect.top() + 16.0), 8.0, 8.0, c); + } +} diff --git a/crates/ui-egui/src/features/extensions/mod.rs b/crates/ui-egui/src/features/extensions/mod.rs new file mode 100644 index 00000000..c55ee8e6 --- /dev/null +++ b/crates/ui-egui/src/features/extensions/mod.rs @@ -0,0 +1,56 @@ +//! The Extensions screen: themes (and later plug-ins and resources) shared by every Craft app. +//! +//! Invariants: +//! - The screen reads and changes the shared store only through [`ExtensionSource`], which the +//! desktop shell implements. With no source (the web build) the screen does not exist. +//! - Installing never changes anyone's look: a theme is worn only after the person chooses it. +//! - Every sentence a person reads goes through `tl!` and is free of developer words +//! (`tests::plain_words`). Extension names come from the package and are shown as written. +//! - Drawing is in `screen.rs` and `card.rs`, what a click means is in `plan.rs`, and `sample.rs` +//! is an in-memory store for tests. + +pub mod card; +pub mod plan; +pub mod sample; +mod screen; +pub mod source; +#[cfg(test)] +mod tests; + +use craft_ext_core::id::ExtensionId; + +pub use source::{ExtensionSource, Row}; + +/// Which list the screen shows. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +pub(crate) enum Tab { + #[default] + Themes, + Installed, +} + +/// The launcher's two pages. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum Page { + Apps, + Extensions, +} + +/// What the screen remembers between frames. +#[derive(Default)] +pub(crate) struct State { + /// The Extensions page is showing instead of the apps. + pub open: bool, + pub tab: Tab, + pub rows: Vec, + /// The store's generation when `rows` was read. + pub generation: u64, + /// `rows` has been read at least once since the page opened. + pub loaded: bool, + /// The context time at which to look at the generation again. + pub next_poll: f64, + /// The extension whose removal is waiting for a yes. + pub confirm_remove: Option, + /// Why the list could not be read, in words. + pub error: Option, +} diff --git a/crates/ui-egui/src/features/extensions/plan.rs b/crates/ui-egui/src/features/extensions/plan.rs new file mode 100644 index 00000000..4637f1c6 --- /dev/null +++ b/crates/ui-egui/src/features/extensions/plan.rs @@ -0,0 +1,104 @@ +//! What the screen shows and what a click means, as plain data with no drawing. +//! +//! Invariants: nothing here touches the store or egui; every click is turned into a list of +//! [`Step`]s the screen then runs in order, so what a click does can be tested without a window. + +use craft_ext_core::id::{AppId, ExtensionId}; +use craft_ext_core::manifest::Kind; +use craft_ext_core::tier::Tier; + +use super::source::Row; + +/// One change to the store. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum Step { + SetEnabled { app: AppId, id: ExtensionId, on: bool }, + Wear { app: AppId, id: Option }, + Remove { id: ExtensionId }, +} + +/// What a click on `app` in a theme's "Use in" menu does: take the theme off if the app wears it, +/// otherwise switch it on for the app where needed and have the app wear it. +pub fn wear_steps(row: &Row, app: &AppId) -> Vec { + if !row.apps.contains(app) { + return Vec::new(); + } + if row.worn.contains(app) { + return vec![Step::Wear { app: app.clone(), id: None }]; + } + let mut steps = Vec::new(); + if !row.enabled.contains(app) { + steps.push(Step::SetEnabled { app: app.clone(), id: row.id.clone(), on: true }); + } + steps.push(Step::Wear { app: app.clone(), id: Some(row.id.clone()) }); + steps +} + +/// What "Use in all apps" does: every app that does not yet wear the theme, in app id order. +pub fn everywhere_steps(row: &Row) -> Vec { + let mut apps: Vec<&AppId> = row.apps.iter().filter(|a| !row.worn.contains(*a)).collect(); + apps.sort(); + apps.dedup(); + apps.into_iter().flat_map(|app| wear_steps(row, app)).collect() +} + +/// What switching an extension on or off for one app does. +pub fn enable_steps(row: &Row, app: &AppId) -> Vec { + if !row.apps.contains(app) { + return Vec::new(); + } + vec![Step::SetEnabled { app: app.clone(), id: row.id.clone(), on: !row.enabled.contains(app) }] +} + +fn by_name(a: &&Row, b: &&Row) -> std::cmp::Ordering { + a.name.to_lowercase().cmp(&b.name.to_lowercase()).then_with(|| a.id.cmp(&b.id)) +} + +/// Themes the Themes tab can draw (their colours could be read), in a stable order. +pub fn themes(rows: &[Row]) -> Vec<&Row> { + let mut out: Vec<&Row> = rows.iter().filter(|r| r.kind == Kind::Theme && r.palette.is_some()).collect(); + out.sort_by(by_name); + out +} + +/// All rows, in a stable order. +pub fn ordered(rows: &[Row]) -> Vec<&Row> { + let mut out: Vec<&Row> = rows.iter().collect(); + out.sort_by(by_name); + out +} + +/// The name of an app for a person: its catalogue name, or the id itself for an app this launcher +/// does not know. +pub fn app_name(id: &AppId) -> String { + artcraft_launcher_core::CraftApp::by_id(id.as_str()).map_or_else(|| id.as_str().to_string(), |a| a.name.to_string()) +} + +/// The apps wearing a theme, by name and in a stable order, or `None` when no app does. +pub fn in_use_line(row: &Row) -> Option { + let mut names: Vec = row.worn.iter().map(app_name).collect(); + names.sort(); + if names.is_empty() { None } else { Some(names.join(", ")) } +} + +/// The words that say where an extension came from, in the current language. +pub fn trust_label(tier: Tier) -> &'static str { + match tier { + Tier::FirstParty => tl!("Made by ArtCraft"), + Tier::FromFile => tl!("Added from a file"), + Tier::ReviewedThirdParty => tl!("From an outside publisher"), + } +} + +/// The word for what an extension is, in the current language. +pub fn kind_label(kind: Kind) -> &'static str { + match kind { + Kind::Theme => tl!("Theme"), + Kind::Plugin => tl!("Plug-in"), + Kind::Resource => tl!("Resource"), + } +} + +#[cfg(test)] +#[path = "plan_tests.rs"] +mod tests; diff --git a/crates/ui-egui/src/features/extensions/plan_tests.rs b/crates/ui-egui/src/features/extensions/plan_tests.rs new file mode 100644 index 00000000..8a75df16 --- /dev/null +++ b/crates/ui-egui/src/features/extensions/plan_tests.rs @@ -0,0 +1,155 @@ +use super::*; +use craft_ext_core::palette::{Palette, Rgb}; +use craft_ext_core::version::Version; +use std::collections::BTreeSet; + +fn app(s: &str) -> AppId { + AppId::new(s).unwrap() +} + +fn ext(s: &str) -> ExtensionId { + ExtensionId::new(s).unwrap() +} + +fn palette() -> Palette { + Palette { + dark: true, + background: Rgb(0x12, 0x13, 0x16), + surface: Rgb(0x1c, 0x1e, 0x24), + text: Rgb(0xf2, 0xf1, 0xee), + muted_text: Rgb(0xb0, 0xb2, 0xb8), + line: Rgb(0x44, 0x46, 0x4c), + accent: Rgb(0x2d, 0x81, 0xff), + good: Rgb(0x3f, 0xd6, 0xb8), + warn: Rgb(0xff, 0xc1, 0x4d), + bad: Rgb(0xff, 0x62, 0x59), + } +} + +fn row(id: &str, name: &str, apps: &[&str], enabled: &[&str], worn: &[&str]) -> Row { + let set = |names: &[&str]| names.iter().map(|n| app(n)).collect::>(); + Row { + id: ext(id), + version: Version::new(1, 0, 0), + kind: Kind::Theme, + name: name.to_string(), + tier: Tier::FromFile, + apps: apps.iter().map(|n| app(n)).collect(), + enabled: set(enabled), + worn: set(worn), + palette: Some(palette()), + } +} + +#[test] +fn choosing_a_theme_in_an_app_it_is_not_switched_on_for_switches_it_on_first() { + let r = row("org.example.ocean", "Ocean", &["photocraft", "lightcraft"], &[], &[]); + assert_eq!( + wear_steps(&r, &app("photocraft")), + vec![ + Step::SetEnabled { app: app("photocraft"), id: ext("org.example.ocean"), on: true }, + Step::Wear { app: app("photocraft"), id: Some(ext("org.example.ocean")) }, + ] + ); +} + +#[test] +fn choosing_a_theme_that_is_already_switched_on_only_chooses_it() { + let r = row("org.example.ocean", "Ocean", &["photocraft"], &["photocraft"], &[]); + assert_eq!(wear_steps(&r, &app("photocraft")), vec![Step::Wear { app: app("photocraft"), id: Some(ext("org.example.ocean")) }]); +} + +#[test] +fn choosing_a_theme_the_app_already_wears_gives_the_app_its_own_look_back() { + let r = row("org.example.ocean", "Ocean", &["photocraft"], &["photocraft"], &["photocraft"]); + assert_eq!(wear_steps(&r, &app("photocraft")), vec![Step::Wear { app: app("photocraft"), id: None }]); +} + +#[test] +fn an_app_the_theme_is_not_made_for_gets_no_steps() { + let r = row("org.example.ocean", "Ocean", &["photocraft"], &["photocraft"], &[]); + assert_eq!(wear_steps(&r, &app("filmcraft")), Vec::new()); + assert_eq!(enable_steps(&r, &app("filmcraft")), Vec::new()); +} + +#[test] +fn use_in_all_apps_skips_the_apps_already_wearing_it_and_keeps_a_stable_order() { + let r = row("org.example.ocean", "Ocean", &["photocraft", "lightcraft", "pdfcraft"], &["photocraft"], &["pdfcraft"]); + let id = ext("org.example.ocean"); + assert_eq!( + everywhere_steps(&r), + vec![ + Step::SetEnabled { app: app("lightcraft"), id: id.clone(), on: true }, + Step::Wear { app: app("lightcraft"), id: Some(id.clone()) }, + Step::Wear { app: app("photocraft"), id: Some(id) }, + ] + ); +} + +#[test] +fn switching_an_extension_flips_its_state_for_that_app() { + let on = row("org.example.ocean", "Ocean", &["photocraft"], &["photocraft"], &[]); + let off = row("org.example.ocean", "Ocean", &["photocraft"], &[], &[]); + assert_eq!(enable_steps(&on, &app("photocraft")), vec![Step::SetEnabled { app: app("photocraft"), id: ext("org.example.ocean"), on: false }]); + assert_eq!(enable_steps(&off, &app("photocraft")), vec![Step::SetEnabled { app: app("photocraft"), id: ext("org.example.ocean"), on: true }]); +} + +#[test] +fn the_themes_tab_lists_only_themes_it_can_draw_sorted_by_name_ignoring_case() { + let mut plugin = row("org.example.tone", "Aardvark tone", &["photocraft"], &[], &[]); + plugin.kind = Kind::Plugin; + // Even a plug-in that carries colours is not a theme. + let mut unreadable = row("org.example.broken", "Broken", &["photocraft"], &[], &[]); + unreadable.palette = None; + let rows = vec![ + row("org.example.ember", "ember", &["photocraft"], &[], &[]), + plugin, + row("org.example.amber", "Amber", &["photocraft"], &[], &[]), + unreadable, + row("org.example.mist", "Mist", &["photocraft"], &[], &[]), + ]; + let names: Vec<&str> = themes(&rows).iter().map(|r| r.name.as_str()).collect(); + assert_eq!(names, ["Amber", "ember", "Mist"], "sorted ignoring case"); +} + +#[test] +fn the_installed_list_keeps_every_kind_and_orders_equal_names_by_id() { + let mut plugin = row("org.example.tone", "Tone", &["photocraft"], &[], &[]); + plugin.kind = Kind::Plugin; + let rows = vec![row("org.example.b", "Same", &["photocraft"], &[], &[]), plugin, row("org.example.a", "Same", &["photocraft"], &[], &[])]; + let ids: Vec<&str> = ordered(&rows).iter().map(|r| r.id.as_str()).collect(); + assert_eq!(ids, ["org.example.a", "org.example.b", "org.example.tone"]); +} + +#[test] +fn known_apps_use_their_catalogue_name_and_unknown_ones_their_id() { + assert_eq!(app_name(&app("photocraft")), "PhotoCraft"); + assert_eq!(app_name(&app("somenewcraft")), "somenewcraft"); +} + +#[test] +fn the_in_use_line_names_the_apps_in_a_stable_order_or_is_absent() { + let none = row("org.example.ocean", "Ocean", &["photocraft"], &["photocraft"], &[]); + assert_eq!(in_use_line(&none), None); + let two = row("org.example.ocean", "Ocean", &["photocraft", "lightcraft"], &["photocraft", "lightcraft"], &["photocraft", "lightcraft"]); + assert_eq!(in_use_line(&two).as_deref(), Some("LightCraft, PhotoCraft")); + // Ordered by the words a person reads, not by id: an unknown app shows its lowercase id. + let mixed = row("org.example.ocean", "Ocean", &["photocraft", "aaacraft"], &["photocraft", "aaacraft"], &["photocraft", "aaacraft"]); + assert_eq!(in_use_line(&mixed).as_deref(), Some("PhotoCraft, aaacraft")); +} + +#[test] +fn every_origin_and_kind_has_its_own_words_with_no_developer_terms() { + let tiers = [Tier::FirstParty, Tier::FromFile, Tier::ReviewedThirdParty]; + let labels: BTreeSet<&str> = tiers.iter().map(|t| trust_label(*t)).collect(); + assert_eq!(labels.len(), 3, "each origin reads differently"); + let kinds: BTreeSet<&str> = [Kind::Theme, Kind::Plugin, Kind::Resource].iter().map(|k| kind_label(*k)).collect(); + assert_eq!(kinds.len(), 3); + for text in labels.into_iter().chain(kinds) { + assert!(!text.is_empty()); + let lower = text.to_lowercase(); + for banned in ["tier", "sha", "hash", "wasm", "abi", "sandbox", "manifest", "namespace", "adapter"] { + assert!(!lower.contains(banned), "{text:?} contains {banned:?}"); + } + } +} diff --git a/crates/ui-egui/src/features/extensions/sample.rs b/crates/ui-egui/src/features/extensions/sample.rs new file mode 100644 index 00000000..2c2dca4e --- /dev/null +++ b/crates/ui-egui/src/features/extensions/sample.rs @@ -0,0 +1,152 @@ +//! An in-memory [`ExtensionSource`] with a few sample themes, for tests and headless runs. It +//! follows the same rules as the real store: switching a theme off for an app also stops that app +//! wearing it, and an app wears a theme only if the theme is switched on for it. + +use std::collections::BTreeSet; +use std::path::Path; + +use craft_ext_core::id::{AppId, ExtensionId}; +use craft_ext_core::manifest::Kind; +use craft_ext_core::palette::{Palette, Rgb}; +use craft_ext_core::tier::Tier; +use craft_ext_core::version::Version; + +use super::source::{ExtensionSource, Row}; + +#[derive(Clone, Debug)] +pub struct SampleSource { + rows: Vec, + generation: u64, +} + +fn rgb(hex: u32) -> Rgb { + let [_, r, g, b] = hex.to_be_bytes(); + Rgb(r, g, b) +} + +fn palette(dark: bool, [background, surface, text, muted, line, accent]: [u32; 6]) -> Palette { + Palette { + dark, + background: rgb(background), + surface: rgb(surface), + text: rgb(text), + muted_text: rgb(muted), + line: rgb(line), + accent: rgb(accent), + good: rgb(if dark { 0x3fd6b8 } else { 0x0a7563 }), + warn: rgb(if dark { 0xffc14d } else { 0x8a5800 }), + bad: rgb(if dark { 0xff6259 } else { 0xb3261e }), + } +} + +fn row(id: &str, name: &str, tier: Tier, apps: &[&str], palette: Palette) -> Option { + let apps: Vec = apps.iter().filter_map(|a| AppId::new(a).ok()).collect(); + Some(Row { + id: ExtensionId::new(id).ok()?, + version: Version::new(1, 0, 0), + kind: Kind::Theme, + name: name.to_string(), + tier, + enabled: apps.iter().cloned().collect(), + apps, + worn: BTreeSet::new(), + palette: Some(palette), + }) +} + +impl Default for SampleSource { + fn default() -> Self { + let suite = ["photocraft", "lightcraft", "pdfcraft"]; + let rows = [ + row( + "org.storytold.midnight", + "Midnight", + Tier::FirstParty, + &suite, + palette(true, [0x101820, 0x18222d, 0xe8eef4, 0xa9b6c2, 0x35424f, 0x4aa3ff]), + ), + row( + "org.storytold.paper", + "Paper", + Tier::FirstParty, + &suite, + palette(false, [0xf5f1e8, 0xece6d8, 0x1d1b16, 0x55504a, 0xcdc5b3, 0x1a5fb4]), + ), + row( + "org.example.ocean", + "Ocean", + Tier::FromFile, + &["photocraft"], + palette(true, [0x0b2530, 0x12384a, 0xe6f4f7, 0xa6c8d2, 0x2c5b6e, 0x3fd6b8]), + ), + ]; + Self { rows: rows.into_iter().flatten().collect(), generation: 1 } + } +} + +impl SampleSource { + fn change(&mut self, f: impl FnOnce(&mut Vec) -> Result) -> Result { + let out = f(&mut self.rows)?; + self.generation += 1; + Ok(out) + } +} + +impl ExtensionSource for SampleSource { + fn generation(&mut self) -> u64 { + self.generation + } + + fn rows(&mut self) -> Result, String> { + Ok(self.rows.clone()) + } + + fn add_file(&mut self, _path: &Path) -> Result { + Err("this sample list cannot add files".to_string()) + } + + fn remove(&mut self, id: &ExtensionId) -> Result<(), String> { + self.change(|rows| { + let before = rows.len(); + rows.retain(|r| &r.id != id); + if rows.len() == before { Err("that extension is not installed".to_string()) } else { Ok(()) } + }) + } + + fn set_enabled(&mut self, app: &AppId, id: &ExtensionId, on: bool) -> Result<(), String> { + self.change(|rows| { + let r = rows.iter_mut().find(|r| &r.id == id).ok_or("that extension is not installed")?; + if !r.apps.contains(app) { + return Err("that extension is not made for this app".to_string()); + } + if on { + r.enabled.insert(app.clone()); + } else { + r.enabled.remove(app); + r.worn.remove(app); + } + Ok(()) + }) + } + + fn wear(&mut self, app: &AppId, id: Option<&ExtensionId>) -> Result<(), String> { + self.change(|rows| { + if let Some(id) = id { + let r = rows.iter().find(|r| &r.id == id).ok_or("that extension is not installed")?; + if !r.apps.contains(app) { + return Err("that extension is not made for this app".to_string()); + } + if !r.enabled.contains(app) { + return Err("turn the theme on for this app before choosing it".to_string()); + } + } + for r in rows.iter_mut() { + r.worn.remove(app); + } + if let Some(r) = id.and_then(|id| rows.iter_mut().find(|r| &r.id == id)) { + r.worn.insert(app.clone()); + } + Ok(()) + }) + } +} diff --git a/crates/ui-egui/src/features/extensions/screen.rs b/crates/ui-egui/src/features/extensions/screen.rs new file mode 100644 index 00000000..1086510f --- /dev/null +++ b/crates/ui-egui/src/features/extensions/screen.rs @@ -0,0 +1,345 @@ +//! Drawing the Extensions page and running what the person clicks. +//! +//! Drawing only collects [`Action`]s; they run afterwards against the source, so no drawing code +//! holds the store and the store is read again after every change. + +use std::time::Duration; + +use craft_ext_core::id::{AppId, ExtensionId}; +use egui::{Align, Layout, Rect, RichText, Sense, Ui, pos2, vec2}; + +use super::card; +use super::plan::{self, Step}; +use super::source::{ExtensionSource, Row}; +use super::{Page, State, Tab}; +use crate::app::{Host, LauncherUi}; +use crate::i18n::{current, fmt, tr_ctx}; +use crate::theme::{self, Tokens}; +use crate::widgets::{self, Cell, Kind}; + +const CARD_MIN_W: f32 = 290.0; +const CARD_H: f32 = 268.0; +const PREVIEW_H: f32 = 124.0; +const CARD_PAD: f32 = 18.0; + +/// Something the person asked for while the page was drawn. +enum Action { + Tab(Tab), + AddFile, + AskRemove(ExtensionId), + CancelRemove, + Run(Vec), +} + +impl LauncherUi { + /// The Apps | Extensions switch at the top of the page. Nothing is drawn, and the apps stay + /// in view, where this build has no extensions store. + pub(crate) fn page_switch(&mut self, ui: &mut Ui, host: &mut dyn Host) { + if host.extensions().is_none() { + self.extensions.open = false; + return; + } + let mut page = if self.extensions.open { Page::Extensions } else { Page::Apps }; + let options = [ + (Page::Apps, Cell { label: tl!("Apps"), tip: tl!("Install and update Craft apps"), count: None }), + (Page::Extensions, Cell { label: tl!("Extensions"), tip: tl!("Themes for your Craft apps"), count: None }), + ]; + if widgets::cells(ui, &mut page, &options) { + self.extensions.open = page == Page::Extensions; + self.extensions.loaded = false; + self.extensions.confirm_remove = None; + } + ui.add_space(14.0); + } + + /// The Extensions page. + pub(crate) fn extensions_page(&mut self, ui: &mut Ui, host: &mut dyn Host) { + let ctx = ui.ctx().clone(); + self.sync_extensions(&ctx, host); + let t = Tokens::get(&ctx); + let mut actions = Vec::new(); + let state = &self.extensions; + ui.horizontal(|ui| { + ui.label(widgets::heading(tl!("Extensions"), 24.0, t.ink_strong)); + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + if widgets::button(ui, tl!("Add from file"), Kind::Primary, 0.0).clicked() { + actions.push(Action::AddFile); + } + }); + }); + ui.add_space(4.0); + ui.add( + egui::Label::new(RichText::new(tl!("Themes change how your Craft apps look. Only add files from people you trust.")).color(t.muted)) + .wrap(), + ); + ui.add_space(14.0); + let mut tab = state.tab; + let tabs = [ + ( + Tab::Themes, + Cell { label: tl!("Themes"), tip: tl!("Colour themes for your Craft apps"), count: Some((plan::themes(&state.rows).len(), None)) }, + ), + ( + Tab::Installed, + Cell { + label: tr_ctx(current(), "filter", "Installed"), + tip: tl!("Everything you have added"), + count: Some((state.rows.len(), None)), + }, + ), + ]; + if widgets::cells(ui, &mut tab, &tabs) { + actions.push(Action::Tab(tab)); + } + ui.add_space(18.0); + if let Some(reason) = &state.error { + let text = fmt(tl!("Couldn't read the installed extensions: {reason}"), &[("reason", reason)]); + ui.add(egui::Label::new(RichText::new(text).color(t.bad)).wrap()); + ui.add_space(10.0); + } + egui::ScrollArea::vertical().auto_shrink(false).show(ui, |ui| { + match state.tab { + Tab::Themes => themes_grid(ui, state, &mut actions), + Tab::Installed => installed_list(ui, state, &mut actions), + } + ui.add_space(16.0); + }); + self.run_extension_actions(&ctx, host, actions); + } + + /// Reads the store when the page opens and whenever something changed, in any app. + fn sync_extensions(&mut self, ctx: &egui::Context, host: &mut dyn Host) { + let now = ctx.input(|i| i.time); + ctx.request_repaint_after(Duration::from_secs(1)); + if self.extensions.loaded && now < self.extensions.next_poll { + return; + } + self.extensions.next_poll = now + 1.0; + let Some(source) = host.extensions() else { return }; + if !self.extensions.loaded || source.generation() != self.extensions.generation { + self.extensions.reload(source); + } + } + + fn run_extension_actions(&mut self, ctx: &egui::Context, host: &mut dyn Host, actions: Vec) { + for action in actions { + match action { + Action::Tab(tab) => self.extensions.tab = tab, + Action::AskRemove(id) => self.extensions.confirm_remove = Some(id), + Action::CancelRemove => self.extensions.confirm_remove = None, + Action::AddFile => self.add_extension_file(ctx, host), + Action::Run(steps) => self.run_extension_steps(ctx, host, &steps), + } + } + } + + fn add_extension_file(&mut self, ctx: &egui::Context, host: &mut dyn Host) { + let Some(path) = host.pick_file(tl!("Add an extension"), &["zip"]) else { return }; + let Some(source) = host.extensions() else { return }; + let outcome = source.add_file(&path); + self.extensions.reload(source); + match outcome { + Ok(name) => self.toast(ctx, fmt(tl!("Added {name}"), &[("name", &name)]), false), + Err(reason) => self.toast(ctx, fmt(tl!("Couldn't add that file: {reason}"), &[("reason", &reason)]), true), + } + } + + fn run_extension_steps(&mut self, ctx: &egui::Context, host: &mut dyn Host, steps: &[Step]) { + let removed: Vec = steps + .iter() + .filter_map(|s| match s { + Step::Remove { id } => self.extensions.rows.iter().find(|r| &r.id == id).map(|r| r.name.clone()), + _ => None, + }) + .collect(); + let Some(source) = host.extensions() else { return }; + let mut failure = None; + for step in steps { + let done = match step { + Step::SetEnabled { app, id, on } => source.set_enabled(app, id, *on), + Step::Wear { app, id } => source.wear(app, id.as_ref()), + Step::Remove { id } => source.remove(id), + }; + if let Err(reason) = done { + failure = Some(reason); + break; + } + } + self.extensions.reload(source); + self.extensions.confirm_remove = None; + match failure { + Some(reason) => self.toast(ctx, fmt(tl!("Couldn't change that: {reason}"), &[("reason", &reason)]), true), + None => { + for name in removed { + self.toast(ctx, fmt(tl!("Removed {name}"), &[("name", &name)]), false); + } + } + } + } +} + +impl State { + /// Reads the generation and then the rows, so a change made in between is noticed next time. + pub(super) fn reload(&mut self, source: &mut dyn ExtensionSource) { + self.generation = source.generation(); + match source.rows() { + Ok(rows) => { + self.rows = rows; + self.error = None; + } + Err(reason) => self.error = Some(reason), + } + self.loaded = true; + } +} + +/// A button that opens a menu, drawn like the other square controls. +fn menu_button(ui: &mut Ui, label: &str, add_contents: impl FnOnce(&mut Ui)) { + let t = Tokens::get(ui.ctx()); + let text = RichText::new(label.to_uppercase()).family(theme::mono_bold()).size(theme::HUD_SIZE).color(t.ink); + let button = egui::Button::new(text).min_size(vec2(0.0, theme::CONTROL_H)); + egui::containers::menu::MenuButton::from_button(button).ui(ui, |ui| { + ui.set_min_width(200.0); + add_contents(ui); + }); +} + +fn sorted_apps(row: &Row) -> Vec<&AppId> { + let mut apps: Vec<&AppId> = row.apps.iter().collect(); + apps.sort_by_key(|a| plan::app_name(a).to_lowercase()); + apps +} + +fn themes_grid(ui: &mut Ui, state: &State, actions: &mut Vec) { + let t = Tokens::get(ui.ctx()); + let themes = plan::themes(&state.rows); + if themes.is_empty() { + ui.add_space(40.0); + ui.vertical_centered(|ui| { + widgets::hud(ui, tl!("No themes yet"), t.muted); + ui.add_space(6.0); + ui.label(RichText::new(tl!("Add a theme from a file and it appears here.")).color(t.faint)); + }); + return; + } + let width = ui.available_width(); + // Neighbouring cards share their hairline, like the apps grid. + let cols = ((width / CARD_MIN_W).floor() as usize).max(1); + let card_w = (width + (cols as f32 - 1.0)) / cols as f32; + let rows = themes.len().div_ceil(cols); + let (area, _) = ui.allocate_exact_size(vec2(width, rows as f32 * (CARD_H - 1.0) + 1.0), Sense::hover()); + for (i, row) in themes.into_iter().enumerate() { + let (r, c) = (i / cols, i % cols); + let min = area.min + vec2(c as f32 * (card_w - 1.0), r as f32 * (CARD_H - 1.0)); + theme_card(ui, row, Rect::from_min_size(min, vec2(card_w, CARD_H)), actions); + } +} + +fn theme_card(ui: &mut Ui, row: &Row, rect: Rect, actions: &mut Vec) { + let Some(palette) = &row.palette else { return }; + let t = Tokens::get(ui.ctx()); + ui.painter_at(rect.expand(1.0)).rect(rect, egui::CornerRadius::ZERO, t.bg, t.hairline(), egui::StrokeKind::Inside); + let picture = Rect::from_min_size(rect.min + vec2(1.0, 1.0), vec2(rect.width() - 2.0, PREVIEW_H)); + card::paint_preview(ui, picture, palette); + ui.painter().hline(picture.x_range(), picture.bottom(), t.hairline()); + ui.interact(picture, ui.id().with(("theme-preview", row.id.as_str())), Sense::hover()) + .widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Image, true, fmt(tl!("Preview of {name}"), &[("name", &row.name)]))); + + let inner = Rect::from_min_max(pos2(rect.left() + CARD_PAD, picture.bottom() + 14.0), rect.max - vec2(CARD_PAD, CARD_PAD)); + let mut child = ui.new_child(egui::UiBuilder::new().max_rect(inner).layout(Layout::top_down(Align::Min))); + child.set_clip_rect(rect.intersect(ui.clip_rect())); + let ui = &mut child; + ui.add(egui::Label::new(RichText::new(&row.name).size(16.0).family(theme::semibold()).color(t.ink_strong)).truncate()); + ui.horizontal(|ui| { + widgets::badge(ui, if palette.dark { tl!("Dark") } else { tl!("Light") }, t.muted); + ui.add(egui::Label::new(RichText::new(plan::trust_label(row.tier)).size(12.0).color(t.muted)).truncate()); + }); + ui.add_space(2.0); + match plan::in_use_line(row) { + Some(apps) => { + let text = fmt(tl!("In use: {apps}"), &[("apps", &apps)]); + ui.add(egui::Label::new(RichText::new(text).size(12.5).color(t.accent_ink)).truncate()); + } + None => { + ui.add(egui::Label::new(RichText::new(tl!("Not used yet")).size(12.5).color(t.faint)).truncate()); + } + } + ui.with_layout(Layout::bottom_up(Align::Min), |ui| { + ui.horizontal(|ui| { + menu_button(ui, tl!("Use in…"), |ui| { + for app in sorted_apps(row) { + let mut on = row.worn.contains(app); + if ui.checkbox(&mut on, plan::app_name(app)).changed() { + actions.push(Action::Run(plan::wear_steps(row, app))); + ui.close(); + } + } + }); + if row.apps.len() > 1 + && row.worn.len() < row.apps.len() + && widgets::button(ui, tl!("All apps"), Kind::Secondary, 0.0) + .on_hover_text(tl!("Use this theme in every app it is made for")) + .clicked() + { + actions.push(Action::Run(plan::everywhere_steps(row))); + } + }); + }); +} + +fn installed_list(ui: &mut Ui, state: &State, actions: &mut Vec) { + let t = Tokens::get(ui.ctx()); + if state.rows.is_empty() { + ui.add_space(40.0); + ui.vertical_centered(|ui| { + widgets::hud(ui, tl!("Nothing added yet"), t.muted); + }); + return; + } + egui::Frame::new().stroke(t.hairline()).show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.spacing_mut().item_spacing.y = 0.0; + for row in plan::ordered(&state.rows) { + let confirming = state.confirm_remove.as_ref() == Some(&row.id); + let line = egui::Frame::new().inner_margin(egui::Margin::symmetric(16, 12)).show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.horizontal(|ui| installed_row(ui, row, confirming, actions)); + }); + ui.painter().hline(line.response.rect.x_range(), line.response.rect.bottom(), t.hairline()); + } + }); +} + +fn installed_row(ui: &mut Ui, row: &Row, confirming: bool, actions: &mut Vec) { + let t = Tokens::get(ui.ctx()); + ui.vertical(|ui| { + ui.spacing_mut().item_spacing.y = 2.0; + ui.add(egui::Label::new(RichText::new(&row.name).size(15.0).family(theme::semibold()).color(t.ink_strong)).truncate()); + let details = format!("{} · v{} · {}", plan::kind_label(row.kind), row.version, plan::trust_label(row.tier)); + ui.add(egui::Label::new(RichText::new(details).size(12.5).color(t.muted)).truncate()); + }); + ui.with_layout(Layout::right_to_left(Align::Center), |ui| { + if confirming { + if widgets::button(ui, tl!("Remove"), Kind::Danger, 0.0).clicked() { + actions.push(Action::Run(vec![Step::Remove { id: row.id.clone() }])); + } + if widgets::button(ui, tl!("Keep"), Kind::Secondary, 0.0).clicked() { + actions.push(Action::CancelRemove); + } + ui.label(RichText::new(tl!("Remove from every Craft app?")).color(t.muted)); + return; + } + if widgets::button(ui, tl!("Remove"), Kind::Secondary, 0.0).clicked() { + actions.push(Action::AskRemove(row.id.clone())); + } + menu_button(ui, tl!("Switched on in…"), |ui| { + for app in sorted_apps(row) { + let mut on = row.enabled.contains(app); + if ui.checkbox(&mut on, plan::app_name(app)).changed() { + actions.push(Action::Run(plan::enable_steps(row, app))); + ui.close(); + } + } + }); + }); +} diff --git a/crates/ui-egui/src/features/extensions/source.rs b/crates/ui-egui/src/features/extensions/source.rs new file mode 100644 index 00000000..0269fdf2 --- /dev/null +++ b/crates/ui-egui/src/features/extensions/source.rs @@ -0,0 +1,49 @@ +//! What the Extensions screen needs from the shared store, as a trait the desktop shell implements. +//! +//! The store itself (`craft-ext-store`) is desktop only, so the shared UI sees it only through +//! [`ExtensionSource`] and plain [`Row`]s built from the wasm-safe contract types. A source never +//! panics and reports every failure as a sentence a person can read. + +use std::collections::BTreeSet; +use std::path::Path; + +use craft_ext_core::id::{AppId, ExtensionId}; +use craft_ext_core::manifest::Kind; +use craft_ext_core::palette::Palette; +use craft_ext_core::tier::Tier; +use craft_ext_core::version::Version; + +/// One installed extension with everything the screen draws. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct Row { + pub id: ExtensionId, + pub version: Version, + pub kind: Kind, + pub name: String, + /// Where it came from, as the launcher recorded it (never read from the package). + pub tier: Tier, + /// Apps the package says it works with. + pub apps: Vec, + /// Apps it is switched on for. + pub enabled: BTreeSet, + /// Apps wearing it as their look (themes only). + pub worn: BTreeSet, + /// The colours of a theme, when its file could be read and passed the checks. + pub palette: Option, +} + +/// The shared store as the screen sees it. +pub trait ExtensionSource { + /// Changes whenever anything is installed, removed, switched or chosen, in any app. + fn generation(&mut self) -> u64; + /// Everything installed. + fn rows(&mut self) -> Result, String>; + /// Installs a package the person picked. Returns the name of what was added. + fn add_file(&mut self, path: &Path) -> Result; + /// Removes an extension from every app. + fn remove(&mut self, id: &ExtensionId) -> Result<(), String>; + /// Switches an extension on or off for one app. + fn set_enabled(&mut self, app: &AppId, id: &ExtensionId, on: bool) -> Result<(), String>; + /// Chooses the theme an app wears, or none to give it back its own look. + fn wear(&mut self, app: &AppId, id: Option<&ExtensionId>) -> Result<(), String>; +} diff --git a/crates/ui-egui/src/features/extensions/tests.rs b/crates/ui-egui/src/features/extensions/tests.rs new file mode 100644 index 00000000..e6e94fbb --- /dev/null +++ b/crates/ui-egui/src/features/extensions/tests.rs @@ -0,0 +1,73 @@ +//! Words people read on the Extensions page: they are plain, and every one has a row in the +//! catalogs (the shared coverage test in `i18n::tests` reads this directory's sources too). + +use std::collections::BTreeSet; + +/// The files whose literals a person reads. +const SOURCES: [&str; 4] = [include_str!("screen.rs"), include_str!("plan.rs"), include_str!("card.rs"), include_str!("mod.rs")]; + +/// Words that mean something to a developer and nothing to a person using the page. +const DEVELOPER_WORDS: &[&str] = &[ + "abi", + "wasm", + "webassembly", + "sandbox", + "manifest", + "namespace", + "schema", + "sha256", + "sha-256", + "hash", + "tier", + "adapter", + "payload", + "json", + "zip", + "archive", + "unpack", + "generation", + "signature", + "revocation", + "provenance", + "palette", + "token", +]; + +fn literals() -> BTreeSet { + let mut out = BTreeSet::new(); + for source in SOURCES { + for (i, _) in source.match_indices("tl!(\"") { + let start = i + 5; + if let Some(len) = source[start..].find('"') { + out.insert(source[start..start + len].to_string()); + } + } + } + out +} + +fn words(text: &str) -> impl Iterator + '_ { + text.split(|c: char| !c.is_alphanumeric() && c != '-').filter(|w| !w.is_empty()).map(str::to_lowercase) +} + +#[test] +fn the_page_has_words_to_check() { + assert!(literals().len() >= 25, "found only {:?}", literals()); +} + +#[test] +fn plain_words() { + for text in literals() { + // The one place a file ending is shown to the person is the file picker, which is not a literal here. + for word in words(&text) { + assert!(!DEVELOPER_WORDS.contains(&word.as_str()), "{text:?} uses the developer word {word:?}"); + } + } +} + +#[test] +fn words_the_page_shows_never_name_the_inside_of_a_package() { + let all = literals(); + assert!(all.contains("Made by ArtCraft") && all.contains("Added from a file")); + assert!(all.iter().all(|t| !t.is_empty() && !t.starts_with(' ') && !t.ends_with(' '))); +} diff --git a/crates/ui-egui/src/features/mod.rs b/crates/ui-egui/src/features/mod.rs new file mode 100644 index 00000000..d99feb50 --- /dev/null +++ b/crates/ui-egui/src/features/mod.rs @@ -0,0 +1,3 @@ +//! Features that live in their own module tree rather than in `views.rs`. + +pub mod extensions; diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 869cc51d..493444fa 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -330,3 +330,38 @@ filter Installed Nainstalováno Replace what's there? Nahradit, co tam je? {path} already exists. Installing {name} will overwrite it. {path} už existuje. Instalace aplikace {name} ho přepíše. Replace Nahradit +# Extensions screen + Apps Aplikace + Install and update Craft apps Instalace a aktualizace aplikací Craft + Extensions Rozšíření + Themes for your Craft apps Motivy pro vaše aplikace Craft + Add from file Přidat ze souboru + Themes change how your Craft apps look. Only add files from people you trust. Motivy mění vzhled vašich aplikací Craft. Přidávejte jen soubory od lidí, kterým důvěřujete. + Themes Motivy + Colour themes for your Craft apps Barevné motivy pro aplikace Craft + Everything you have added Vše, co jste přidali + Couldn't read the installed extensions: {reason} Nainstalovaná rozšíření se nepodařilo načíst: {reason} + Add an extension Přidat rozšíření + Added {name} Přidáno: {name} + Couldn't add that file: {reason} Tento soubor se nepodařilo přidat: {reason} + Couldn't change that: {reason} Tuto změnu se nepodařilo provést: {reason} + Removed {name} Odebráno: {name} + No themes yet Zatím žádné motivy + Add a theme from a file and it appears here. Přidejte motiv ze souboru a objeví se tady. + Preview of {name} Náhled: {name} + In use: {apps} Používá se v: {apps} + Not used yet Zatím nepoužíváno + Use in… Použít v… + All apps Všechny aplikace + Use this theme in every app it is made for Použít tento motiv ve všech aplikacích, pro které je určen + Nothing added yet Zatím nic nepřidáno + Remove Odebrat + Keep Ponechat + Remove from every Craft app? Odebrat ze všech aplikací Craft? + Switched on in… Zapnuto v… + Made by ArtCraft Od ArtCraft + Added from a file Přidáno ze souboru + From an outside publisher Od externího vydavatele + Theme Motiv + Plug-in Zásuvný modul + Resource Prostředek diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 08e325d7..6b12fc64 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -362,3 +362,38 @@ filter Installed Installiert Replace what's there? Vorhandenes ersetzen? {path} already exists. Installing {name} will overwrite it. {path} existiert bereits. Die Installation von {name} überschreibt es. Replace Ersetzen +# Extensions screen + Apps Apps + Install and update Craft apps Craft-Apps installieren und aktualisieren + Extensions Erweiterungen + Themes for your Craft apps Designs für deine Craft-Apps + Add from file Aus Datei hinzufügen + Themes change how your Craft apps look. Only add files from people you trust. Designs ändern das Aussehen deiner Craft-Apps. Füge nur Dateien von Personen hinzu, denen du vertraust. + Themes Designs + Colour themes for your Craft apps Farbdesigns für deine Craft-Apps + Everything you have added Alles, was du hinzugefügt hast + Couldn't read the installed extensions: {reason} Die installierten Erweiterungen konnten nicht gelesen werden: {reason} + Add an extension Erweiterung hinzufügen + Added {name} {name} hinzugefügt + Couldn't add that file: {reason} Die Datei konnte nicht hinzugefügt werden: {reason} + Couldn't change that: {reason} Das konnte nicht geändert werden: {reason} + Removed {name} {name} entfernt + No themes yet Noch keine Designs + Add a theme from a file and it appears here. Füge ein Design aus einer Datei hinzu, dann erscheint es hier. + Preview of {name} Vorschau von {name} + In use: {apps} In Verwendung: {apps} + Not used yet Noch nicht verwendet + Use in… Verwenden in… + All apps Alle Apps + Use this theme in every app it is made for Dieses Design in jeder App verwenden, für die es gemacht ist + Nothing added yet Noch nichts hinzugefügt + Remove Entfernen + Keep Behalten + Remove from every Craft app? Aus allen Craft-Apps entfernen? + Switched on in… Eingeschaltet in… + Made by ArtCraft Von ArtCraft + Added from a file Aus einer Datei hinzugefügt + From an outside publisher Von einem externen Herausgeber + Theme Design + Plug-in Plug-in + Resource Ressource diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 93e21926..6e7500cf 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -343,3 +343,38 @@ filter Installed Instaladas Replace what's there? ¿Reemplazar lo que hay? {path} already exists. Installing {name} will overwrite it. {path} ya existe. Instalar {name} lo sobrescribirá. Replace Reemplazar +# Extensions screen + Apps Aplicaciones + Install and update Craft apps Instala y actualiza las aplicaciones de Craft + Extensions Extensiones + Themes for your Craft apps Temas para tus aplicaciones de Craft + Add from file Añadir desde un archivo + Themes change how your Craft apps look. Only add files from people you trust. Los temas cambian el aspecto de tus aplicaciones de Craft. Añade solo archivos de personas de confianza. + Themes Temas + Colour themes for your Craft apps Temas de color para tus aplicaciones de Craft + Everything you have added Todo lo que has añadido + Couldn't read the installed extensions: {reason} No se pudieron leer las extensiones instaladas: {reason} + Add an extension Añadir una extensión + Added {name} Se añadió {name} + Couldn't add that file: {reason} No se pudo añadir ese archivo: {reason} + Couldn't change that: {reason} No se pudo hacer ese cambio: {reason} + Removed {name} Se quitó {name} + No themes yet Aún no hay temas + Add a theme from a file and it appears here. Añade un tema desde un archivo y aparecerá aquí. + Preview of {name} Vista previa de {name} + In use: {apps} En uso: {apps} + Not used yet Aún sin usar + Use in… Usar en… + All apps Todas las aplicaciones + Use this theme in every app it is made for Usar este tema en todas las aplicaciones para las que está hecho + Nothing added yet Aún no has añadido nada + Remove Quitar + Keep Conservar + Remove from every Craft app? ¿Quitar de todas las aplicaciones de Craft? + Switched on in… Activado en… + Made by ArtCraft Creado por ArtCraft + Added from a file Añadido desde un archivo + From an outside publisher De un editor externo + Theme Tema + Plug-in Complemento + Resource Recurso diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index d15ab44e..42f35929 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -360,3 +360,38 @@ filter Installed Installées Replace what's there? Remplacer l’existant ? {path} already exists. Installing {name} will overwrite it. {path} existe déjà. L’installation de {name} l’écrasera. Replace Remplacer +# Extensions screen + Apps Applications + Install and update Craft apps Installer et mettre à jour les applications Craft + Extensions Extensions + Themes for your Craft apps Des thèmes pour vos applications Craft + Add from file Ajouter depuis un fichier + Themes change how your Craft apps look. Only add files from people you trust. Les thèmes changent l'apparence de vos applications Craft. N'ajoutez que des fichiers de personnes de confiance. + Themes Thèmes + Colour themes for your Craft apps Thèmes de couleurs pour vos applications Craft + Everything you have added Tout ce que vous avez ajouté + Couldn't read the installed extensions: {reason} Impossible de lire les extensions installées : {reason} + Add an extension Ajouter une extension + Added {name} {name} ajouté + Couldn't add that file: {reason} Impossible d'ajouter ce fichier : {reason} + Couldn't change that: {reason} Impossible d'effectuer ce changement : {reason} + Removed {name} {name} supprimé + No themes yet Aucun thème pour le moment + Add a theme from a file and it appears here. Ajoutez un thème depuis un fichier et il apparaîtra ici. + Preview of {name} Aperçu de {name} + In use: {apps} Utilisé dans : {apps} + Not used yet Pas encore utilisé + Use in… Utiliser dans… + All apps Toutes les applications + Use this theme in every app it is made for Utiliser ce thème dans chaque application pour laquelle il est conçu + Nothing added yet Rien n'a encore été ajouté + Remove Supprimer + Keep Conserver + Remove from every Craft app? Supprimer de toutes les applications Craft ? + Switched on in… Activé dans… + Made by ArtCraft Créé par ArtCraft + Added from a file Ajouté depuis un fichier + From an outside publisher D'un éditeur externe + Theme Thème + Plug-in Plug-in + Resource Ressource diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 9aeaac86..67766c76 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -363,3 +363,38 @@ filter Installed Telepítve Replace what's there? Lecseréli, ami ott van? {path} already exists. Installing {name} will overwrite it. {path} már létezik. A(z) {name} telepítése felülírja. Replace Csere +# Extensions screen + Apps Alkalmazások + Install and update Craft apps Craft-alkalmazások telepítése és frissítése + Extensions Bővítmények + Themes for your Craft apps Témák a Craft-alkalmazásaidhoz + Add from file Hozzáadás fájlból + Themes change how your Craft apps look. Only add files from people you trust. A témák megváltoztatják a Craft-alkalmazásaid kinézetét. Csak olyan emberektől adj hozzá fájlokat, akikben megbízol. + Themes Témák + Colour themes for your Craft apps Színtémák a Craft-alkalmazásokhoz + Everything you have added Minden, amit hozzáadtál + Couldn't read the installed extensions: {reason} A telepített bővítményeket nem sikerült beolvasni: {reason} + Add an extension Bővítmény hozzáadása + Added {name} Hozzáadva: {name} + Couldn't add that file: {reason} Ezt a fájlt nem sikerült hozzáadni: {reason} + Couldn't change that: {reason} A módosítás nem sikerült: {reason} + Removed {name} Eltávolítva: {name} + No themes yet Még nincs téma + Add a theme from a file and it appears here. Adj hozzá egy témát fájlból, és itt fog megjelenni. + Preview of {name} {name} előnézete + In use: {apps} Használatban: {apps} + Not used yet Még nincs használatban + Use in… Használat itt… + All apps Minden alkalmazás + Use this theme in every app it is made for A téma használata minden olyan alkalmazásban, amelyhez készült + Nothing added yet Még nincs hozzáadva semmi + Remove Eltávolítás + Keep Megtartás + Remove from every Craft app? Eltávolítod az összes Craft-alkalmazásból? + Switched on in… Bekapcsolva itt… + Made by ArtCraft Az ArtCrafttól + Added from a file Fájlból hozzáadva + From an outside publisher Külső kiadótól + Theme Téma + Plug-in Beépülő modul + Resource Erőforrás diff --git a/crates/ui-egui/src/i18n/ja.tsv b/crates/ui-egui/src/i18n/ja.tsv index 84a74f7d..08bfcf84 100644 --- a/crates/ui-egui/src/i18n/ja.tsv +++ b/crates/ui-egui/src/i18n/ja.tsv @@ -365,3 +365,38 @@ filter Installed インストール済み Replace what's there? 既存の項目を置き換えますか? {path} already exists. Installing {name} will overwrite it. {path} は既に存在します。{name} をインストールすると上書きされます。 Replace 置き換える +# Extensions screen + Apps アプリ + Install and update Craft apps Craftアプリのインストールと更新 + Extensions 拡張機能 + Themes for your Craft apps Craftアプリ用のテーマ + Add from file ファイルから追加 + Themes change how your Craft apps look. Only add files from people you trust. テーマはCraftアプリの見た目を変えます。信頼できる人のファイルだけを追加してください。 + Themes テーマ + Colour themes for your Craft apps Craftアプリ用のカラーテーマ + Everything you have added 追加したものすべて + Couldn't read the installed extensions: {reason} インストール済みの拡張機能を読み込めませんでした: {reason} + Add an extension 拡張機能を追加 + Added {name} {name} を追加しました + Couldn't add that file: {reason} このファイルを追加できませんでした: {reason} + Couldn't change that: {reason} 変更できませんでした: {reason} + Removed {name} {name} を削除しました + No themes yet テーマはまだありません + Add a theme from a file and it appears here. ファイルからテーマを追加すると、ここに表示されます。 + Preview of {name} {name} のプレビュー + In use: {apps} 使用中: {apps} + Not used yet 未使用 + Use in… 使用するアプリ… + All apps すべてのアプリ + Use this theme in every app it is made for このテーマを、対応するすべてのアプリで使用します + Nothing added yet まだ何も追加されていません + Remove 削除 + Keep 残す + Remove from every Craft app? すべてのCraftアプリから削除しますか? + Switched on in… 有効にするアプリ… + Made by ArtCraft ArtCraft製 + Added from a file ファイル経由で追加 + From an outside publisher 外部の提供元 + Theme テーマ + Plug-in プラグイン + Resource リソース diff --git a/crates/ui-egui/src/i18n/pl.tsv b/crates/ui-egui/src/i18n/pl.tsv index 25d64838..90108483 100644 --- a/crates/ui-egui/src/i18n/pl.tsv +++ b/crates/ui-egui/src/i18n/pl.tsv @@ -364,3 +364,38 @@ filter Installed Zainstalowane Replace what's there? Zastąpić to, co tam jest? {path} already exists. Installing {name} will overwrite it. {path} już istnieje. Instalacja {name} go nadpisze. Replace Zastąp +# Extensions screen + Apps Aplikacje + Install and update Craft apps Instaluj i aktualizuj aplikacje Craft + Extensions Rozszerzenia + Themes for your Craft apps Motywy dla twoich aplikacji Craft + Add from file Dodaj z pliku + Themes change how your Craft apps look. Only add files from people you trust. Motywy zmieniają wygląd twoich aplikacji Craft. Dodawaj tylko pliki od osób, którym ufasz. + Themes Motywy + Colour themes for your Craft apps Motywy kolorystyczne dla twoich aplikacji Craft + Everything you have added Wszystko, co zostało dodane + Couldn't read the installed extensions: {reason} Nie udało się odczytać zainstalowanych rozszerzeń: {reason} + Add an extension Dodaj rozszerzenie + Added {name} Dodano: {name} + Couldn't add that file: {reason} Nie udało się dodać tego pliku: {reason} + Couldn't change that: {reason} Nie udało się wprowadzić tej zmiany: {reason} + Removed {name} Usunięto: {name} + No themes yet Brak motywów + Add a theme from a file and it appears here. Dodaj motyw z pliku, a pojawi się tutaj. + Preview of {name} Podgląd: {name} + In use: {apps} Używany w: {apps} + Not used yet Jeszcze nieużywany + Use in… Użyj w… + All apps Wszystkie aplikacje + Use this theme in every app it is made for Użyj tego motywu w każdej aplikacji, dla której jest przeznaczony + Nothing added yet Nic jeszcze nie dodano + Remove Usuń + Keep Zachowaj + Remove from every Craft app? Usunąć ze wszystkich aplikacji Craft? + Switched on in… Włączone w… + Made by ArtCraft Od ArtCraft + Added from a file Dodane z pliku + From an outside publisher Od zewnętrznego wydawcy + Theme Motyw + Plug-in Wtyczka + Resource Zasób diff --git a/crates/ui-egui/src/i18n/pt-BR.tsv b/crates/ui-egui/src/i18n/pt-BR.tsv index 7857dd3d..a81c3dc9 100644 --- a/crates/ui-egui/src/i18n/pt-BR.tsv +++ b/crates/ui-egui/src/i18n/pt-BR.tsv @@ -350,3 +350,38 @@ filter Installed Instalados Replace what's there? Substituir o que já existe? {path} already exists. Installing {name} will overwrite it. {path} já existe. Instalar o {name} vai substituí-lo. Replace Substituir +# Extensions screen + Apps Aplicativos + Install and update Craft apps Instale e atualize os aplicativos Craft + Extensions Extensões + Themes for your Craft apps Temas para seus aplicativos Craft + Add from file Adicionar de um arquivo + Themes change how your Craft apps look. Only add files from people you trust. Os temas mudam a aparência dos seus aplicativos Craft. Adicione apenas arquivos de pessoas em quem você confia. + Themes Temas + Colour themes for your Craft apps Temas de cores para seus aplicativos Craft + Everything you have added Tudo o que você adicionou + Couldn't read the installed extensions: {reason} Não foi possível ler as extensões instaladas: {reason} + Add an extension Adicionar uma extensão + Added {name} {name} adicionado + Couldn't add that file: {reason} Não foi possível adicionar esse arquivo: {reason} + Couldn't change that: {reason} Não foi possível fazer essa alteração: {reason} + Removed {name} {name} removido + No themes yet Nenhum tema ainda + Add a theme from a file and it appears here. Adicione um tema de um arquivo e ele aparecerá aqui. + Preview of {name} Prévia de {name} + In use: {apps} Em uso: {apps} + Not used yet Ainda não usado + Use in… Usar em… + All apps Todos os aplicativos + Use this theme in every app it is made for Usar este tema em todos os aplicativos para os quais ele foi feito + Nothing added yet Nada adicionado ainda + Remove Remover + Keep Manter + Remove from every Craft app? Remover de todos os aplicativos Craft? + Switched on in… Ativado em… + Made by ArtCraft Feito pela ArtCraft + Added from a file Adicionado de um arquivo + From an outside publisher De um editor externo + Theme Tema + Plug-in Plug-in + Resource Recurso diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index 27b751b9..b2a69b02 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -358,3 +358,38 @@ filter Installed Установлены Replace what's there? Заменить существующее? {path} already exists. Installing {name} will overwrite it. {path} уже существует. Установка {name} перезапишет его. Replace Заменить +# Extensions screen + Apps Приложения + Install and update Craft apps Установка и обновление приложений Craft + Extensions Расширения + Themes for your Craft apps Темы для ваших приложений Craft + Add from file Добавить из файла + Themes change how your Craft apps look. Only add files from people you trust. Темы меняют внешний вид приложений Craft. Добавляйте только файлы от людей, которым вы доверяете. + Themes Темы + Colour themes for your Craft apps Цветовые темы для приложений Craft + Everything you have added Всё, что вы добавили + Couldn't read the installed extensions: {reason} Не удалось прочитать установленные расширения: {reason} + Add an extension Добавить расширение + Added {name} Добавлено: {name} + Couldn't add that file: {reason} Не удалось добавить этот файл: {reason} + Couldn't change that: {reason} Не удалось внести это изменение: {reason} + Removed {name} Удалено: {name} + No themes yet Тем пока нет + Add a theme from a file and it appears here. Добавьте тему из файла, и она появится здесь. + Preview of {name} Предпросмотр: {name} + In use: {apps} Используется в: {apps} + Not used yet Пока не используется + Use in… Использовать в… + All apps Все приложения + Use this theme in every app it is made for Использовать эту тему во всех приложениях, для которых она сделана + Nothing added yet Пока ничего не добавлено + Remove Удалить + Keep Оставить + Remove from every Craft app? Удалить из всех приложений Craft? + Switched on in… Включено в… + Made by ArtCraft Создано ArtCraft + Added from a file Добавлено из файла + From an outside publisher От стороннего издателя + Theme Тема + Plug-in Плагин + Resource Ресурс diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index 524b69a4..561180d6 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -131,6 +131,10 @@ fn complete_catalogs_cover_every_ui_literal() { include_str!("../settings.rs"), include_str!("../views.rs"), include_str!("../widgets.rs"), + // The Extensions page. + include_str!("../features/extensions/screen.rs"), + include_str!("../features/extensions/plan.rs"), + include_str!("../features/extensions/card.rs"), // The desktop shell's tray menu and tooltip. include_str!("../../../../apps/artcraft-launcher/src/tray.rs"), ]; diff --git a/crates/ui-egui/src/i18n/zh-CN.tsv b/crates/ui-egui/src/i18n/zh-CN.tsv index 4e1ef143..9131678d 100644 --- a/crates/ui-egui/src/i18n/zh-CN.tsv +++ b/crates/ui-egui/src/i18n/zh-CN.tsv @@ -330,3 +330,38 @@ figcraft Interface design and prototyping 界面设计与原型制作 Replace what's there? 替换现有内容? {path} already exists. Installing {name} will overwrite it. {path} 已存在。安装 {name} 将覆盖它。 Replace 替换 +# Extensions screen + Apps 应用 + Install and update Craft apps 安装和更新 Craft 应用 + Extensions 扩展 + Themes for your Craft apps 适用于你的 Craft 应用的主题 + Add from file 从文件添加 + Themes change how your Craft apps look. Only add files from people you trust. 主题会改变 Craft 应用的外观。只添加来自你信任的人的文件。 + Themes 主题 + Colour themes for your Craft apps Craft 应用的配色主题 + Everything you have added 你添加的所有内容 + Couldn't read the installed extensions: {reason} 无法读取已安装的扩展:{reason} + Add an extension 添加扩展 + Added {name} 已添加 {name} + Couldn't add that file: {reason} 无法添加该文件:{reason} + Couldn't change that: {reason} 无法完成此更改:{reason} + Removed {name} 已移除 {name} + No themes yet 还没有主题 + Add a theme from a file and it appears here. 从文件添加主题后,它会显示在这里。 + Preview of {name} {name} 预览 + In use: {apps} 使用中:{apps} + Not used yet 尚未使用 + Use in… 用于… + All apps 所有应用 + Use this theme in every app it is made for 在其适用的每个应用中使用此主题 + Nothing added yet 还没有添加任何内容 + Remove 移除 + Keep 保留 + Remove from every Craft app? 从所有 Craft 应用中移除? + Switched on in… 在这些应用中启用… + Made by ArtCraft 由 ArtCraft 制作 + Added from a file 通过文件添加 + From an outside publisher 来自外部发布者 + Theme 主题 + Plug-in 插件 + Resource 资源 diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 3198378f..dcf9f420 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -21,6 +21,7 @@ mod app; mod cjk_font; mod details; mod dialogs; +pub mod features; pub mod i18n; pub mod icons; pub mod model; diff --git a/crates/ui-egui/tests/extensions.rs b/crates/ui-egui/tests/extensions.rs new file mode 100644 index 00000000..08429bd8 --- /dev/null +++ b/crates/ui-egui/tests/extensions.rs @@ -0,0 +1,207 @@ +//! Drives the Extensions page against the in-memory sample store: what shows, and what each click +//! changes. No files and no network. + +use std::cell::RefCell; +use std::path::{Path, PathBuf}; +use std::rc::Rc; + +use artcraft_launcher_core::protocol::{Backend, Capabilities, Command, Event}; +use artcraft_launcher_core::{Arch, Os, Platform}; +use artcraft_launcher_ui_egui::features::extensions::sample::SampleSource; +use artcraft_launcher_ui_egui::features::extensions::{ExtensionSource, Row}; +use artcraft_launcher_ui_egui::{Host, LauncherUi, Settings}; +use craft_ext_core::id::{AppId, ExtensionId}; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; + +struct Quiet; + +impl Backend for Quiet { + fn send(&mut self, _command: Command) {} + fn poll(&mut self) -> Vec { + Vec::new() + } + fn capabilities(&self) -> Capabilities { + Capabilities { manage_apps: true, reveal_label: "Show in Finder", self_update: false } + } + fn platform(&self) -> Option { + Some(Platform { os: Os::MacOs, arch: Arch::Arm64 }) + } + fn now(&self) -> i64 { + 1_791_500_000 + } +} + +/// The sample store, shared with the test so it can look at it and change it behind the screen's back. +#[derive(Clone, Default)] +struct Shared(Rc>); + +impl ExtensionSource for Shared { + fn generation(&mut self) -> u64 { + self.0.borrow_mut().generation() + } + fn rows(&mut self) -> Result, String> { + self.0.borrow_mut().rows() + } + fn add_file(&mut self, path: &Path) -> Result { + self.0.borrow_mut().add_file(path) + } + fn remove(&mut self, id: &ExtensionId) -> Result<(), String> { + self.0.borrow_mut().remove(id) + } + fn set_enabled(&mut self, app: &AppId, id: &ExtensionId, on: bool) -> Result<(), String> { + self.0.borrow_mut().set_enabled(app, id, on) + } + fn wear(&mut self, app: &AppId, id: Option<&ExtensionId>) -> Result<(), String> { + self.0.borrow_mut().wear(app, id) + } +} + +struct WithStore { + store: Shared, + picked: Option, +} + +impl Host for WithStore { + fn pick_file(&mut self, _title: &str, _extensions: &[&str]) -> Option { + self.picked.take() + } + fn extensions(&mut self) -> Option<&mut dyn ExtensionSource> { + Some(&mut self.store) + } +} + +struct NoStore; +impl Host for NoStore {} + +fn harness(mut host: H) -> Harness<'static, Option> { + artcraft_launcher_ui_egui::i18n::set_test_lang(artcraft_launcher_ui_egui::i18n::Lang::EN); + let mut backend: Option> = Some(Box::new(Quiet)); + Harness::builder().with_size(egui::vec2(1180.0, 900.0)).build_ui_state( + move |ui, state: &mut Option| { + if let Some(b) = backend.take() { + *state = Some(LauncherUi::new(ui.ctx(), b, Settings { notify: false, ..Settings::default() })); + } + if let Some(launcher) = state { + launcher.logic(&ui.ctx().clone(), &mut host); + launcher.ui(ui, &mut host); + } + }, + None, + ) +} + +fn open(store: &Shared, picked: Option) -> Harness<'static, Option> { + let mut h = harness(WithStore { store: store.clone(), picked }); + h.run(); + h.get_by_label("Extensions").click(); + h.run(); + h +} + +fn app(s: &str) -> AppId { + AppId::new(s).unwrap() +} + +fn worn_by(store: &Shared, app_id: &str) -> Vec { + let rows = store.0.borrow_mut().rows().unwrap(); + rows.iter().filter(|r| r.worn.contains(&app(app_id))).map(|r| r.name.clone()).collect() +} + +#[test] +fn a_build_with_no_store_has_no_extensions_page() { + let mut h = harness(NoStore); + h.run(); + assert!(h.query_by_label("Extensions").is_none()); + assert!(h.query_by_label("Apps").is_none()); +} + +#[test] +fn the_page_lists_every_theme_and_changes_nobodys_look_by_itself() { + let store = Shared::default(); + let h = open(&store, None); + for name in ["Midnight", "Ocean", "Paper"] { + h.get_by_label(name); + } + assert_eq!(h.get_all_by_label("Made by ArtCraft").count(), 2); + h.get_by_label("Added from a file"); + assert!(worn_by(&store, "photocraft").is_empty(), "opening the page chose nothing"); +} + +#[test] +fn choosing_a_theme_from_the_use_in_menu_makes_that_app_wear_it_and_clicking_again_gives_the_look_back() { + let store = Shared::default(); + let mut h = open(&store, None); + // Themes are listed by name: Midnight, Ocean, Paper. + h.get_all_by_label("USE IN…").nth(1).unwrap().click(); + h.run(); + h.get_by_label("PhotoCraft").click(); + h.run(); + assert_eq!(worn_by(&store, "photocraft"), ["Ocean"]); + h.get_by_label("In use: PhotoCraft"); + + h.get_all_by_label("USE IN…").nth(1).unwrap().click(); + h.run(); + h.get_by_label("PhotoCraft").click(); + h.run(); + assert!(worn_by(&store, "photocraft").is_empty()); +} + +#[test] +fn use_in_all_apps_makes_every_app_the_theme_is_made_for_wear_it() { + let store = Shared::default(); + let mut h = open(&store, None); + // Midnight is made for three apps; Ocean for one, so only two cards offer "All apps". + assert_eq!(h.get_all_by_label("All apps").count(), 2); + h.get_all_by_label("All apps").next().unwrap().click(); + h.run(); + for id in ["photocraft", "lightcraft", "pdfcraft"] { + assert_eq!(worn_by(&store, id), ["Midnight"], "{id}"); + } +} + +#[test] +fn removing_asks_first_and_then_removes_the_extension_from_the_list() { + let store = Shared::default(); + let mut h = open(&store, None); + h.get_by_label("Installed 3").click(); + h.run(); + h.get_all_by_label("Remove").nth(1).unwrap().click(); + h.run(); + h.get_by_label("Remove from every Craft app?"); + assert_eq!(store.0.borrow_mut().rows().unwrap().len(), 3, "asking removes nothing"); + h.get_by_label("Keep").click(); + h.run(); + assert!(h.query_by_label("Remove from every Craft app?").is_none()); + assert_eq!(store.0.borrow_mut().rows().unwrap().len(), 3); + + h.get_all_by_label("Remove").nth(1).unwrap().click(); + h.run(); + // The row asking for a yes now has the red Remove button, still second in the list. + h.get_all_by_label("Remove").nth(1).unwrap().click(); + h.run_steps(3); + let names: Vec = store.0.borrow_mut().rows().unwrap().into_iter().map(|r| r.name).collect(); + assert_eq!(names, ["Midnight", "Paper"], "Ocean is the second row and went"); + h.get_by_label("Removed Ocean"); +} + +#[test] +fn a_file_that_cannot_be_added_says_why_in_words() { + let store = Shared::default(); + let mut h = open(&store, Some(PathBuf::from("not-an-extension.zip"))); + h.get_by_label("Add from file").click(); + h.run_steps(3); + h.get_by_label("Couldn't add that file: this sample list cannot add files"); +} + +#[test] +fn a_change_made_elsewhere_shows_up_within_a_few_seconds() { + let store = Shared::default(); + let mut h = open(&store, None); + h.get_by_label("Ocean"); + store.0.borrow_mut().remove(&ExtensionId::new("org.example.ocean").unwrap()).unwrap(); + for _ in 0..12 { + h.step(); + } + assert!(h.query_by_label("Ocean").is_none()); +}