diff --git a/ASSETS.md b/ASSETS.md index 4391e2c..3566d1c 100644 --- a/ASSETS.md +++ b/ASSETS.md @@ -12,3 +12,7 @@ Generated-in-code art is original and has no file to list (default colour scheme |---|---|---|---|---| | `assets/app-icon/icon.png` | Daniel Diekert | concept generated with Gemini (Google), finished by Daniel Diekert in Photoshop (2026-10-15) | MIT OR Apache-2.0 | App icon master, 720 x 720 RGBA with rounded corners baked in; a square crop of the banner scene. `apps/lutra-desktop/build.rs` downscales it to the Tauri icons. Photoshop source kept outside git. | | `docs/images/banner.png` | Daniel Diekert | concept generated with Gemini (Google), finished by Daniel Diekert in Photoshop (2026-10-15) | MIT OR Apache-2.0 | README banner, 1456 x 720. Wordmark font: tbd. Photoshop source kept outside git. | +| `assets/installer/nsis-sidebar.bmp` | Daniel Diekert (banner); layout by Amy (Lutra designer) | derived from `docs/images/banner.png` by `cargo xtask installer-images` (crops, solid fills, an arrow; no new art), 2026-10-31 | MIT OR Apache-2.0 | NSIS sidebar of the Windows setup (welcome and finish pages), 164 x 314, 24-bit BMP: the otter on its tower. Regenerate with `cargo xtask installer-images`. | +| `assets/installer/nsis-header.bmp` | Daniel Diekert (banner); layout by Amy (Lutra designer) | derived from `docs/images/banner.png` by `cargo xtask installer-images` (crops, solid fills, an arrow; no new art), 2026-10-31 | MIT OR Apache-2.0 | NSIS header of the Windows setup pages, 150 x 57, 24-bit BMP: the wordmark on magenta. Regenerate with `cargo xtask installer-images`. | +| `assets/installer/dmg-background.png` | Daniel Diekert (banner); layout by Amy (Lutra designer) | derived from `docs/images/banner.png` by `cargo xtask installer-images` (crops, solid fills, an arrow; no new art), 2026-10-31 | MIT OR Apache-2.0 | macOS DMG window background, 720 x 400: wordmark, otter column, skyline, a lighter label shelf and a cream arrow. Regenerate with `cargo xtask installer-images`. | +| `assets/installer/dmg-background@2x.png` | Daniel Diekert (banner); layout by Amy (Lutra designer) | derived from `docs/images/banner.png` by `cargo xtask installer-images` (crops, solid fills, an arrow; no new art), 2026-10-31 | MIT OR Apache-2.0 | The DMG background at 2x (1440 x 800), joined with the 1x image into a HiDPI TIFF by `cargo xtask bundle` on macOS. Regenerate with `cargo xtask installer-images`. | diff --git a/Cargo.lock b/Cargo.lock index db349b4..95ec43f 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -6550,6 +6550,7 @@ name = "xtask" version = "0.0.0" dependencies = [ "lutra-proc", + "png 0.18.1", "serde_json", "tempfile", "toml 1.1.8+spec-1.1.0", diff --git a/README.md b/README.md index 31d3ad0..8e1d333 100644 --- a/README.md +++ b/README.md @@ -30,6 +30,10 @@ - **Agent-native.** Every action is a command that a JSON control channel and an MCP server expose, so Claude and other agents can work in the IDE the way a person does. - **PHP-first.** Symfony, Laravel, Shopware and WordPress support are on the roadmap from the start. +## Install + +The alpha comes as an unsigned installer: a per-user setup (`.exe`, English and German) for Windows and a `.dmg` for macOS on Apple Silicon. Build it with `cargo xtask bundle` on that platform. Windows SmartScreen and macOS Gatekeeper warn on the first start because it is not signed yet; [`docs/install.md`](docs/install.md) shows how to start it anyway, how to uninstall and where your data lives. On Linux, build from source as below. + ## Quick start > The foundation (M0) is built: `cargo xtask dev` opens an empty themed window and `cargo xtask ci` runs the quality gate. The `lutra` command below is the target of milestone M3. diff --git a/apps/lutra-desktop/build.rs b/apps/lutra-desktop/build.rs index 74f4505..06e7ac6 100644 --- a/apps/lutra-desktop/build.rs +++ b/apps/lutra-desktop/build.rs @@ -3,7 +3,8 @@ //! Produces the app icons Tauri needs into the gitignored `icons/` directory, //! then runs the Tauri build step, which needs those files. The source is the //! owner's master icon `assets/app-icon/icon.png` (listed in ASSETS.md), -//! downscaled to the window icon `icon.png` and to a multi-size `icon.ico`. +//! downscaled to the window icon `icon.png`, to `512x512.png` (the macOS +//! bundler builds the `.icns` from the PNGs) and to a multi-size `icon.ico`. //! If the master is missing or unreadable, the build prints a warning and //! falls back to a placeholder generated in code (an otter-brown rounded //! square holding a pale stone), so the build never fails over the icon. @@ -16,6 +17,9 @@ use std::path::{Path, PathBuf}; /// Edge length of the placeholder and of the window icon `icon.png`. const SIZE: u32 = 256; +/// Edge length of the large PNG for the macOS app icon. +const LARGE: u32 = 512; + /// Edge lengths of the images in `icon.ico`. const ICO_SIZES: [u32; 6] = [16, 32, 48, 64, 128, 256]; @@ -60,6 +64,10 @@ fn main() -> Result<(), Box> { let dir = manifest.join("icons"); fs::create_dir_all(&dir)?; write_if_changed(&dir.join("icon.png"), &encode_png(&resize(&master, SIZE))?)?; + write_if_changed( + &dir.join("512x512.png"), + &encode_png(&resize(&master, LARGE))?, + )?; let mut entries = Vec::with_capacity(ICO_SIZES.len()); for size in ICO_SIZES { entries.push((size, encode_png(&resize(&master, size))?)); diff --git a/apps/lutra-desktop/src/main.rs b/apps/lutra-desktop/src/main.rs index bf54809..1f67ea7 100644 --- a/apps/lutra-desktop/src/main.rs +++ b/apps/lutra-desktop/src/main.rs @@ -10,7 +10,9 @@ //! `LUTRA_DATA_DIR` or `--control` keeps its files away from the user's //! (see [`datadir`]). With `--control` the window opens without taking the //! foreground, so an agent starting Lutra does not catch the user's typing; -//! `app.focus` brings it to the front on request. +//! `app.focus` brings it to the front on request. The first normal start +//! under the current app identifier copies the user's files from the +//! placeholder identifier's directories (see [`migrate`]). #![cfg_attr(not(debug_assertions), windows_subsystem = "windows")] @@ -19,13 +21,14 @@ mod datadir; mod host; mod instance; mod menu; +mod migrate; mod screenshot; use std::process::ExitCode; use std::sync::{Arc, OnceLock}; -use lutra_engine::{CommandInfo, Engine, EngineConfig, ErrorPayload, theme}; -use serde_json::Value; +use lutra_engine::{CommandInfo, Engine, EngineConfig, ErrorPayload, NotificationLevel, theme}; +use serde_json::{Map, Value, json}; use tauri::window::Color; use tauri::{Manager, WebviewUrl, WebviewWindowBuilder}; @@ -59,7 +62,9 @@ fn main() -> ExitCode { } /// Forwards to a running instance if there is one; otherwise builds the -/// Tauri app, starts the engine with the app's config and data directories +/// Tauri app, copies the user's files from the placeholder identifier once +/// (normal starts only, see [`migrate`]), starts the engine with the app's +/// config and data directories /// (or the isolated data directory, sharing the user's managed tools), /// the host, the control channel and the single-instance listener, and runs /// the event loop. The window is created in the setup hook, which runs once @@ -129,6 +134,11 @@ fn run(args: &args::Args) -> Result<(), String> { .build(tauri::generate_context!()) .map_err(|e| e.to_string())?; let user = engine_config(&app)?; + let migration = if isolated.is_none() { + migrate_legacy(&user) + } else { + None + }; let config = match &isolated { Some(dir) => datadir::engine_config(dir), None => user.clone(), @@ -138,7 +148,10 @@ fn run(args: &args::Args) -> Result<(), String> { engine.share_tools_from(user.data_dir); } engine.allow_downloads().map_err(|e| e.to_string())?; - let startup = engine.take_events(); + let mut startup = engine.take_events(); + if let Some((level, key, message, params)) = migration { + startup.extend(engine.notify(level, Some(key), Some(message), Some(params))); + } let host = Host::new(engine); host.publish_startup(&startup); app.manage(host.clone()); @@ -189,6 +202,51 @@ fn engine_config(app: &tauri::App) -> Result { }) } +/// A notification about the one-time copy from the placeholder +/// identifier's directories: what [`migrate::migrate`] did, logged to +/// standard error and returned as (level, catalog key, English text, +/// params) for the window. `None` if there was nothing to copy or the old +/// directories cannot be derived. +fn migrate_legacy( + user: &EngineConfig, +) -> Option<(NotificationLevel, &'static str, String, Map)> { + let old = migrate::legacy_dirs(user)?; + match migrate::migrate(&old, user) { + Ok(None) => None, + Ok(Some(migrated)) => { + let summary = migrated.summary(); + eprintln!("lutra: {summary}"); + let mut params = Map::new(); + params.insert("from".into(), json!(migrated.from.display().to_string())); + params.insert("to".into(), json!(migrated.to.display().to_string())); + Some(( + NotificationLevel::Info, + "notification.app.dataMigrated", + format!("Lutra {summary}."), + params, + )) + } + Err(e) => { + eprintln!( + "lutra: cannot copy the data from {}: {e}", + old.data_dir.display() + ); + let mut params = Map::new(); + params.insert("from".into(), json!(old.data_dir.display().to_string())); + params.insert("error".into(), json!(e.to_string())); + Some(( + NotificationLevel::Warning, + "notification.app.dataMigrationFailed", + format!( + "Cannot copy your settings and tools from {}: {e}. Lutra starts with the defaults and tries again next time.", + old.data_dir.display() + ), + params, + )) + } + } +} + /// The stored `appearance.theme` value, `system` if it cannot be read. fn stored_theme(host: &Host) -> String { host.run( diff --git a/apps/lutra-desktop/src/migrate.rs b/apps/lutra-desktop/src/migrate.rs new file mode 100644 index 0000000..e2f74d9 --- /dev/null +++ b/apps/lutra-desktop/src/migrate.rs @@ -0,0 +1,309 @@ +//! The one-time move from the placeholder app identifier. +//! +//! Until the alpha installers, the app identifier was +//! [`rendezvous::LEGACY_APP_IDENTIFIER`] (`dev.lutra.desktop`); it is now +//! [`rendezvous::APP_IDENTIFIER`] (`com.tyrveil.lutra`). Tauri derives the +//! config and data directories from the identifier, so a normal start would +//! begin with empty directories. On the first normal start under the new +//! identifier, when the new data directory does not exist and an old +//! directory does, [`migrate`] copies the user's files over once: +//! `settings.json` from the config directory, the recovery journal +//! (`recovery/`) and the managed tools (`tools/`, the Phpactor PHAR) from +//! the data directory. The old directories stay as they are, so an older +//! build still finds its files. The rendezvous file is not copied; it +//! belongs to a running instance. +//! +//! The data directory is assembled in a sibling staging directory and +//! renamed into place at the end, so a start that fails half-way leaves no +//! new data directory and the next start tries again. On Windows and macOS +//! the config and data directories are the same folder; on Linux +//! `settings.json` goes straight into the new config directory, never +//! replacing one that is already there. +//! +//! The webview's own data (recent projects, window layout) lives in a +//! folder the webview manages and is not copied. + +use std::fs; +use std::io; +use std::path::{Path, PathBuf}; + +use lutra_control::rendezvous; +use lutra_engine::EngineConfig; + +/// Name of the settings file inside the config directory. +const SETTINGS_FILE: &str = "settings.json"; + +/// Folders copied from the old data directory: the recovery journal and +/// the managed tools. +const DATA_DIRS: [&str; 2] = ["recovery", "tools"]; + +/// Suffix of the staging directory next to the new data directory. +const STAGING_SUFFIX: &str = ".migrating"; + +/// What [`migrate`] copied. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Migrated { + /// The old data directory the files came from. + pub from: PathBuf, + /// The new data directory. + pub to: PathBuf, + /// The copied entries, `settings.json`, `recovery` and `tools`, in + /// that order, each only if it existed. + pub entries: Vec<&'static str>, +} + +impl Migrated { + /// A one-line English summary for the log and the notification. + pub fn summary(&self) -> String { + format!( + "copied {} from {} to {}", + self.entries.join(", "), + self.from.display(), + self.to.display() + ) + } +} + +/// The directories the placeholder identifier used, next to `current`'s: +/// each one's last component replaced by +/// [`rendezvous::LEGACY_APP_IDENTIFIER`]. `None` if a directory has no +/// parent. +pub fn legacy_dirs(current: &EngineConfig) -> Option { + let legacy = |dir: &Path| Some(dir.parent()?.join(rendezvous::LEGACY_APP_IDENTIFIER)); + Some(EngineConfig { + config_dir: legacy(¤t.config_dir)?, + data_dir: legacy(¤t.data_dir)?, + }) +} + +/// Copies the user's files from `old` to `new` once; see the module docs. +/// +/// # Returns +/// `None` if there was nothing to do: the new data directory exists, or +/// neither old directory does. Otherwise what was copied. +/// +/// # Errors +/// If a file cannot be read, copied or the staging directory renamed. The +/// new data directory is then not created, so the next start tries again. +pub fn migrate(old: &EngineConfig, new: &EngineConfig) -> io::Result> { + if new.data_dir.exists() || !(old.data_dir.is_dir() || old.config_dir.is_dir()) { + return Ok(None); + } + let staging = staging_dir(&new.data_dir)?; + if staging.exists() { + fs::remove_dir_all(&staging)?; + } + fs::create_dir_all(&staging)?; + let mut entries = Vec::new(); + let settings = old.config_dir.join(SETTINGS_FILE); + if settings.is_file() { + let target_dir = if new.config_dir == new.data_dir { + staging.clone() + } else { + new.config_dir.clone() + }; + let target = target_dir.join(SETTINGS_FILE); + if !target.exists() { + fs::create_dir_all(&target_dir)?; + fs::copy(&settings, &target)?; + entries.push(SETTINGS_FILE); + } + } + for name in DATA_DIRS { + let source = old.data_dir.join(name); + if fs::symlink_metadata(&source).is_ok_and(|m| m.is_dir()) { + copy_dir(&source, &staging.join(name))?; + entries.push(name); + } + } + fs::rename(&staging, &new.data_dir)?; + Ok(Some(Migrated { + from: old.data_dir.clone(), + to: new.data_dir.clone(), + entries, + })) +} + +/// The staging directory next to `data_dir`: its name plus +/// [`STAGING_SUFFIX`]. +/// +/// # Errors +/// If `data_dir` has no file name. +fn staging_dir(data_dir: &Path) -> io::Result { + let name = data_dir + .file_name() + .ok_or_else(|| io::Error::other("the data directory has no name"))?; + let mut staged = name.to_os_string(); + staged.push(STAGING_SUFFIX); + Ok(data_dir.with_file_name(staged)) +} + +/// Copies the directory `from` to `to` with its files and subdirectories. +/// Symbolic links are skipped, so the copy never leaves the old directory. +/// +/// # Errors +/// If a directory cannot be listed or created, or a file copied. +fn copy_dir(from: &Path, to: &Path) -> io::Result<()> { + fs::create_dir_all(to)?; + for entry in fs::read_dir(from)? { + let entry = entry?; + let kind = entry.file_type()?; + let target = to.join(entry.file_name()); + if kind.is_dir() { + copy_dir(&entry.path(), &target)?; + } else if kind.is_file() { + fs::copy(entry.path(), &target)?; + } + } + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Directories as on Windows and macOS: config and data are one folder. + fn shared(base: &Path, id: &str) -> EngineConfig { + EngineConfig { + config_dir: base.join(id), + data_dir: base.join(id), + } + } + + /// Fills `dir` like a user's data directory of the old identifier. + fn fill(dir: &EngineConfig) { + fs::create_dir_all(&dir.config_dir).unwrap(); + fs::write( + dir.config_dir.join("settings.json"), + "{\"appearance.theme\":\"lutra-light\"}", + ) + .unwrap(); + let journal = dir.data_dir.join("recovery").join("p1"); + fs::create_dir_all(&journal).unwrap(); + fs::write(journal.join("e1.json"), "{}").unwrap(); + let tools = dir.data_dir.join("tools").join("phpactor").join("2025.1"); + fs::create_dir_all(&tools).unwrap(); + fs::write(tools.join("phpactor.phar"), "phar").unwrap(); + fs::write(dir.data_dir.join("instance.json"), "{}").unwrap(); + } + + #[test] + fn the_legacy_dirs_sit_next_to_the_current_ones() { + let base = Path::new("/home/u"); + let current = EngineConfig { + config_dir: base.join(".config").join(rendezvous::APP_IDENTIFIER), + data_dir: base.join(".local/share").join(rendezvous::APP_IDENTIFIER), + }; + let legacy = legacy_dirs(¤t).unwrap(); + assert_eq!(legacy.config_dir, base.join(".config/dev.lutra.desktop")); + assert_eq!(legacy.data_dir, base.join(".local/share/dev.lutra.desktop")); + } + + #[test] + fn copies_settings_journal_and_tools_once() { + let tmp = tempfile::tempdir().unwrap(); + let old = shared(tmp.path(), rendezvous::LEGACY_APP_IDENTIFIER); + let new = shared(tmp.path(), rendezvous::APP_IDENTIFIER); + fill(&old); + + let migrated = migrate(&old, &new).unwrap().unwrap(); + assert_eq!(migrated.entries, ["settings.json", "recovery", "tools"]); + assert_eq!(migrated.to, new.data_dir); + assert!( + migrated + .summary() + .contains("settings.json, recovery, tools") + ); + assert_eq!( + fs::read_to_string(new.config_dir.join("settings.json")).unwrap(), + "{\"appearance.theme\":\"lutra-light\"}" + ); + assert!(new.data_dir.join("recovery/p1/e1.json").is_file()); + assert_eq!( + fs::read(new.data_dir.join("tools/phpactor/2025.1/phpactor.phar")).unwrap(), + b"phar" + ); + assert!(!new.data_dir.join("instance.json").exists()); + assert!(old.data_dir.join("settings.json").is_file(), "old dir kept"); + assert!(!staging_dir(&new.data_dir).unwrap().exists()); + + fs::write(new.config_dir.join("settings.json"), "{}").unwrap(); + assert_eq!(migrate(&old, &new).unwrap(), None); + assert_eq!( + fs::read_to_string(new.config_dir.join("settings.json")).unwrap(), + "{}" + ); + } + + #[test] + fn does_nothing_without_an_old_dir_or_with_a_new_one() { + let tmp = tempfile::tempdir().unwrap(); + let old = shared(tmp.path(), rendezvous::LEGACY_APP_IDENTIFIER); + let new = shared(tmp.path(), rendezvous::APP_IDENTIFIER); + assert_eq!(migrate(&old, &new).unwrap(), None); + assert!(!new.data_dir.exists()); + + fill(&old); + fs::create_dir_all(&new.data_dir).unwrap(); + assert_eq!(migrate(&old, &new).unwrap(), None); + assert!(!new.data_dir.join("settings.json").exists()); + } + + #[test] + fn copies_only_what_exists() { + let tmp = tempfile::tempdir().unwrap(); + let old = shared(tmp.path(), rendezvous::LEGACY_APP_IDENTIFIER); + let new = shared(tmp.path(), rendezvous::APP_IDENTIFIER); + fs::create_dir_all(&old.config_dir).unwrap(); + fs::write(old.config_dir.join("settings.json"), "{}").unwrap(); + let migrated = migrate(&old, &new).unwrap().unwrap(); + assert_eq!(migrated.entries, ["settings.json"]); + assert!(new.data_dir.join("settings.json").is_file()); + } + + #[test] + fn separate_config_dirs_keep_existing_settings() { + let tmp = tempfile::tempdir().unwrap(); + let dirs = |id: &str| EngineConfig { + config_dir: tmp.path().join("config").join(id), + data_dir: tmp.path().join("data").join(id), + }; + let old = dirs(rendezvous::LEGACY_APP_IDENTIFIER); + let new = dirs(rendezvous::APP_IDENTIFIER); + fill(&old); + fs::create_dir_all(&new.config_dir).unwrap(); + fs::write(new.config_dir.join("settings.json"), "{\"mine\":1}").unwrap(); + + let migrated = migrate(&old, &new).unwrap().unwrap(); + assert_eq!(migrated.entries, ["recovery", "tools"]); + assert_eq!( + fs::read_to_string(new.config_dir.join("settings.json")).unwrap(), + "{\"mine\":1}" + ); + assert!(!new.data_dir.join("settings.json").exists()); + assert!(new.data_dir.join("recovery/p1/e1.json").is_file()); + } + + #[test] + fn a_leftover_staging_dir_is_replaced() { + let tmp = tempfile::tempdir().unwrap(); + let old = shared(tmp.path(), rendezvous::LEGACY_APP_IDENTIFIER); + let new = shared(tmp.path(), rendezvous::APP_IDENTIFIER); + fill(&old); + let staging = staging_dir(&new.data_dir).unwrap(); + fs::create_dir_all(staging.join("recovery")).unwrap(); + fs::write(staging.join("half-copied"), "x").unwrap(); + + migrate(&old, &new).unwrap().unwrap(); + assert!(!new.data_dir.join("half-copied").exists()); + assert!(!staging.exists()); + assert!(new.data_dir.join("recovery/p1/e1.json").is_file()); + } + + #[test] + fn the_tauri_config_uses_the_app_identifier() { + let conf: serde_json::Value = + serde_json::from_str(include_str!("../tauri.conf.json")).unwrap(); + assert_eq!(conf["identifier"], rendezvous::APP_IDENTIFIER); + } +} diff --git a/apps/lutra-desktop/tauri.conf.json b/apps/lutra-desktop/tauri.conf.json index abbf72b..3225ff2 100644 --- a/apps/lutra-desktop/tauri.conf.json +++ b/apps/lutra-desktop/tauri.conf.json @@ -2,7 +2,7 @@ "$schema": "https://schema.tauri.app/config/2", "productName": "Lutra", "version": "0.0.0", - "identifier": "dev.lutra.desktop", + "identifier": "com.tyrveil.lutra", "build": { "devUrl": "http://localhost:5173", "frontendDist": "../../ui/dist", @@ -17,7 +17,34 @@ } }, "bundle": { - "active": false, - "icon": ["icons/icon.png", "icons/icon.ico"] + "active": true, + "targets": ["nsis", "dmg"], + "publisher": "Lutra", + "copyright": "Copyright (c) 2026 Daniel Diekert and the Lutra contributors", + "license": "MIT OR Apache-2.0", + "category": "DeveloperTool", + "shortDescription": "An otterly perfect IDE for PHP", + "longDescription": "Lutra is an open-source PHP IDE with a Rust core.", + "icon": ["icons/icon.png", "icons/512x512.png", "icons/icon.ico"], + "windows": { + "nsis": { + "installMode": "currentUser", + "languages": ["English", "German"], + "displayLanguageSelector": false, + "installerIcon": "icons/icon.ico", + "headerImage": "../../assets/installer/nsis-header.bmp", + "sidebarImage": "../../assets/installer/nsis-sidebar.bmp", + "compression": "lzma" + } + }, + "macOS": { + "minimumSystemVersion": "11.0", + "dmg": { + "background": "../../assets/installer/dmg-background.png", + "windowSize": { "width": 720, "height": 400 }, + "appPosition": { "x": 100, "y": 184 }, + "applicationFolderPosition": { "x": 326, "y": 184 } + } + } } } diff --git a/assets/installer/dmg-background.png b/assets/installer/dmg-background.png new file mode 100644 index 0000000..f3e437f Binary files /dev/null and b/assets/installer/dmg-background.png differ diff --git a/assets/installer/dmg-background@2x.png b/assets/installer/dmg-background@2x.png new file mode 100644 index 0000000..8934f18 Binary files /dev/null and b/assets/installer/dmg-background@2x.png differ diff --git a/assets/installer/nsis-header.bmp b/assets/installer/nsis-header.bmp new file mode 100644 index 0000000..9c04818 Binary files /dev/null and b/assets/installer/nsis-header.bmp differ diff --git a/assets/installer/nsis-sidebar.bmp b/assets/installer/nsis-sidebar.bmp new file mode 100644 index 0000000..3111852 Binary files /dev/null and b/assets/installer/nsis-sidebar.bmp differ diff --git a/crates/control/src/rendezvous.rs b/crates/control/src/rendezvous.rs index d980be4..7d02e79 100644 --- a/crates/control/src/rendezvous.rs +++ b/crates/control/src/rendezvous.rs @@ -40,8 +40,14 @@ pub const DIR_ENV: &str = "LUTRA_RENDEZVOUS_DIR"; /// main instance. The CLI looks for the rendezvous file there too. pub const DATA_DIR_ENV: &str = "LUTRA_DATA_DIR"; -/// The Tauri app identifier, the last part of the data directory. -pub const APP_IDENTIFIER: &str = "dev.lutra.desktop"; +/// The Tauri app identifier, the last part of the data directory. It must +/// match `identifier` in `apps/lutra-desktop/tauri.conf.json`. +pub const APP_IDENTIFIER: &str = "com.tyrveil.lutra"; + +/// The placeholder identifier used before the alpha installers. The desktop +/// copies the user's files from its directories once (see the desktop's +/// `migrate` module). +pub const LEGACY_APP_IDENTIFIER: &str = "dev.lutra.desktop"; /// Random bytes in a token; the token is their lowercase hex form. pub const TOKEN_BYTES: usize = 32; diff --git a/docs/architecture.md b/docs/architecture.md index 42c070d..4c01dbf 100644 --- a/docs/architecture.md +++ b/docs/architecture.md @@ -69,7 +69,7 @@ As built in M0: ### CLI and single instance (M3.7) - **Rendezvous file:** a desktop that owns the single instance serves a second, token-protected control listener on a free port of `127.0.0.1` (`lutra_control::start_with_token`) and writes `/instance.json` = `{port, token, pid, version}` (`lutra_control::rendezvous`). The token is 32 bytes from the OS generator (`getrandom`), hex. The file is written to a temporary file and renamed, so readers never see half a file; on exit the app removes it if it still holds its own token. -- **Directory:** `LUTRA_RENDEZVOUS_DIR` if set, else `rendezvous::default_data_dir()`, which computes Tauri's `app_data_dir()` for the identifier `dev.lutra.desktop` without Tauri (`%APPDATA%\dev.lutra.desktop` on Windows, `~/Library/Application Support/dev.lutra.desktop` on macOS, `$XDG_DATA_HOME` or `~/.local/share` + the identifier elsewhere), so the CLI and the desktop agree without sharing a runtime. +- **Directory:** `LUTRA_RENDEZVOUS_DIR` if set, else `rendezvous::default_data_dir()`, which computes Tauri's `app_data_dir()` for the identifier `com.tyrveil.lutra` (`rendezvous::APP_IDENTIFIER`) without Tauri (`%APPDATA%\com.tyrveil.lutra` on Windows, `~/Library/Application Support/com.tyrveil.lutra` on macOS, `$XDG_DATA_HOME` or `~/.local/share` + the identifier elsewhere), so the CLI and the desktop agree without sharing a runtime. - **Security:** only the user may read the token. Unix: the file is created with mode `0600`. Windows: it lives in the user's roaming AppData folder, whose inherited ACL grants the user, `SYSTEM` and Administrators only (checked with `icacls` in the M3.7 live check); Lutra sets no ACL of its own. Both listeners bind `127.0.0.1` only. On the token listener the first request must be `app.auth {token}` within 10 s (`AUTH_TIMEOUT`); a wrong token, another method or garbage gets `unauthorized` and the connection is closed. Tokens are compared in constant time. The `--control PORT` listener stays open (no token) for development and agents; it is opt-in and documented as such. - **Second start:** `lutra-desktop [PATH]` without `--control` reads the rendezvous file first. If the listener answers, accepts the token and pings, the start forwards `PATH` (folder → `project.open`, file → `file.open`), calls `app.focus` and exits 0. If the file is missing, unreadable, invalid, or its port refuses or rejects the token, it is stale: this start becomes the instance and replaces the file. Two starts in the same instant can both become instances; the later file wins (accepted, rare). - **Development instances:** a start with `--control PORT` skips the single instance (no forwarding, no rendezvous file) so parallel agents' instances never forward to each other, unless `LUTRA_RENDEZVOUS_DIR` is set, which opts it into the single instance in that directory (used for isolated live checks). @@ -750,13 +750,15 @@ Watched directories: the VFS watcher is non-recursive, so `project.children` wat | Text buffer | `ropey` (MIT) in `crates/text`. | Mature rope with line and UTF-16 helpers. | | Clippy panic lints | `unwrap_used`, `expect_used`, `panic`, `unreachable`, `todo`, `unimplemented`, `indexing_slicing`, `string_slice` are denied workspace-wide; `clippy.toml` allows them in `#[test]`/`#[cfg(test)]`; integration tests in `tests/` and `testkit` allow them at crate level. `missing_docs` is denied too, to back the doc-comment code style. `unsafe_code` is denied; a crate that needs it allows it locally with a doc comment saying why. | AGENTS.md › Never crash. | | Desktop dev mode | Plain `cargo build`/`cargo run -p lutra-desktop` is a Tauri dev build that loads the Vite dev server. `cargo xtask dev [-- ARGS]` starts both. A self-contained build embeds `ui/dist` through the `bundled-ui` feature. | Keeps `cargo build --workspace` independent of the frontend build. | -| App identifier | `dev.lutra.desktop` is a placeholder. The final reverse-DNS identifier depends on the project's domain and hosting, which are the owner's decision (execution plan §4); bundling stays off until then. | Tauri requires an identifier to build. | +| App identifier | `com.tyrveil.lutra` (owner, D26, 2026-10-31), in `tauri.conf.json` and `rendezvous::APP_IDENTIFIER` (a test keeps them equal). It replaced the placeholder `dev.lutra.desktop`: the first normal start under the new identifier, when its data directory does not exist and an old directory does, copies `settings.json`, `recovery/` and `tools/` from the old directories into a staging folder next to the new data directory, renames it into place, logs the copy to stderr and shows an info notification (`apps/lutra-desktop/src/migrate.rs`). The old directories stay; the rendezvous file and the webview data are not copied. Isolated starts never migrate. | Tauri derives the data directories from the identifier; without the copy, alpha testers would lose their settings, journal and Phpactor download. Staging plus rename makes a half-done copy retry on the next start instead of counting as done. | +| Installers | `bundle.active` with `targets` NSIS and DMG; `cargo xtask bundle` runs `cargo tauri build --bundles nsis\|dmg --features bundled-ui` for the current platform and prints the installer and its size. NSIS: `installMode: currentUser` (no admin, `%LOCALAPPDATA%\Lutra`), English and German following the OS, Start menu shortcut, desktop shortcut as a finish-page option, uninstaller with the opt-in "delete app data" box; header and sidebar BMPs from `assets/installer/`. DMG: 720 × 400 window with the app at (100, 184) and Applications at (326, 184) over `dmg-background.png`; on macOS `xtask bundle` joins the 1x and 2x PNGs into a HiDPI TIFF with `tiffutil` and passes it through `--config`. `build.rs` also writes `icons/512x512.png`, from which the macOS bundler makes the `.icns`. Unsigned (owner, D26). Install, unsigned-start and data-location steps: [`install.md`](install.md). Live check (Windows 11, 2026-10-31, measured): `cargo xtask bundle` 3 min 42 s release build with 4 jobs, setup 4.95 MiB; `/S /D=` installed in about 1 s, 18.8 MiB on disk (`lutra-desktop.exe` 18.6 MiB, `uninstall.exe` 0.2 MiB), Start menu and desktop shortcuts and the HKCU uninstall entry present; the installed app started with `--control --data-dir` and showed a project in its screenshot; `uninstall.exe /S` removed the files, both shortcuts and the entry. | Tauri's bundler covers both formats without extra tools on Windows (it fetches NSIS) or macOS (`hdiutil`). A per-user install needs no UAC prompt, which suits an alpha. The installer images are generated by `cargo xtask installer-images` from the banner, so they can be regenerated. | | App icon | `apps/lutra-desktop/build.rs` downscales the owner's master `assets/app-icon/icon.png` (720 px, see ASSETS.md) with an area-averaging box filter into the gitignored `apps/lutra-desktop/icons/`: `icon.png` (256 px window icon) and a multi-size `icon.ico` (16, 32, 48, 64, 128, 256 px, PNG entries). If the master is missing or unreadable, the build prints a cargo warning and uses the placeholder generated in code (rounded otter-brown square with a pale stone). | The icon is the owner's (M1.14); decoding uses the `png` build dependency already present, so no new dependency. The fallback keeps a checkout without the asset buildable and never fails the build over an icon. | ## Revision history | Date | Change | Summary | |---|---|---| +| 2026-10-31 | minor | C7 B1: app identifier `com.tyrveil.lutra` with the one-time copy from `dev.lutra.desktop`, NSIS and DMG installers, `cargo xtask bundle` | | 2026-10-31 | minor | C7 A3: `git.mergeMessage` and the merge message prefill, `git.ignore` and the Changes context menu, gutter markers kept on their line, per-module `COMMAND_IDS` for the command listing test | | 2026-10-30 | minor | M4.7: blame (`git.blame` with `--contents` from the buffer, the annotation gutter by age, hover with the commit message, `vcs.toggleBlame`, `vcs.showCommit`) | | 2026-10-28 | minor | M4.6: history backend (`git.log`, `git.showCommit`, `git.showAt`), the shared hook for new git commands, the Log tab, diffs at a commit | diff --git a/docs/development.md b/docs/development.md index a1de624..00266f0 100644 --- a/docs/development.md +++ b/docs/development.md @@ -19,6 +19,8 @@ cargo xtask ci # the full quality gate, run before every commit cargo xtask fixtures # create Symfony and Laravel reference projects in target/fixtures/ cargo xtask mac-report # gate, build and an app self-check, written to target/mac-report/report.md cargo xtask demo-project ../lutra-demo # offline demo project for docs/alpha-checklist.md +cargo xtask bundle # this platform's installer (NSIS setup on Windows, DMG on macOS), see install.md +cargo xtask installer-images # regenerate assets/installer/ from docs/images/banner.png ``` `mac-report` is made for checking a machine the developers cannot reach (the Mac, see [`macos.md`](macos.md)) but runs everywhere. Every step has a timeout; `--skip-gate` leaves out the gate, `--port` picks the control port (default 7971). @@ -61,6 +63,7 @@ No inline comments. Doc comment blocks above modules, functions, types and field | Date | Change | Summary | |---|---|---| +| 2026-10-31 | minor | B1: `cargo xtask bundle`, `cargo xtask installer-images` | | 2026-10-31 | minor | A2: `cargo xtask demo-project` | | 2026-10-31 | minor | A1: `cargo xtask mac-report`, link to the macOS setup | | 2026-10-27 | minor | F3: data directories, build directories inside the repository, parallel builds, deleting `ui/node_modules` | diff --git a/docs/install.md b/docs/install.md new file mode 100644 index 0000000..ea26395 --- /dev/null +++ b/docs/install.md @@ -0,0 +1,72 @@ +# Installing Lutra + +> **Status:** draft, alpha installers · **Last updated:** 2026-10-31 + +Lutra's alpha comes as an installer for Windows (a setup `.exe`) and macOS (a `.dmg`). Both are **not signed yet**, so Windows and macOS warn before the first start; the steps below get past that once. Linux has no installer yet: build it from source ([`development.md`](development.md)). + +The installers contain the desktop app only. The `lutra` command-line tool (`lutra .`, `lutra mcp`) is not in them yet; build it with `cargo build --release -p lutra-cli` if you need it. + +## Building an installer + +On the platform you want the installer for: + +```sh +cargo xtask bundle +``` + +It builds the release app with the bundled UI and prints the installer's path and size: `target/release/bundle/nsis/Lutra__x64-setup.exe` on Windows, `target/release/bundle/dmg/Lutra__aarch64.dmg` on macOS. It needs the Tauri CLI (`cargo install tauri-cli --locked`) and, on macOS, the Xcode Command Line Tools ([`macos.md`](macos.md)). + +## Windows + +Lutra installs for your user only: no administrator rights, no UAC prompt. It needs Microsoft Edge WebView2, which Windows 10 and 11 already have; if it is missing, the setup downloads it. + +1. Start `Lutra__x64-setup.exe`. +2. Windows SmartScreen says "Windows protected your PC", because the setup is not signed. Click **More info**, check that the app is `Lutra__x64-setup.exe` and the publisher is "Unknown publisher", then click **Run anyway**. If you downloaded the file with a browser, the browser may ask first whether to keep it. +3. The setup runs in English or German, following Windows. Click **Next**, keep or change the folder (default `%LOCALAPPDATA%\Lutra`), click **Install**. +4. On the last page, tick **Create desktop shortcut** if you want one, and click **Finish**. + +Lutra is now in the Start menu as **Lutra**. Installing a newer setup over it updates it in place and keeps your settings. + +For scripts: `Lutra__x64-setup.exe /S` installs silently with both shortcuts, `/D=C:\path` (last argument) picks the folder, `/NS` skips the shortcuts. + +### Uninstalling on Windows + +Settings → Apps → Installed apps → **Lutra** → … → **Uninstall**, or run `uninstall.exe` in the install folder. The uninstaller removes the app and its shortcuts. Your settings, recovery journal and Phpactor stay unless you tick **Delete the application data**. + +## macOS + +The DMG holds the app for Apple Silicon (M1 or newer), macOS 11 or newer. + +1. Open `Lutra__aarch64.dmg` and drag **Lutra** onto **Applications**. Eject the DMG. +2. The first start is blocked because the app is not signed or notarised. In **Applications**, **right-click** (or Control-click) Lutra → **Open**, and click **Open** in the dialog. On macOS 15 Sequoia and newer that dialog has no Open button: click **Done**, then open **System Settings → Privacy & Security**, scroll to "Lutra was blocked", click **Open Anyway** and confirm with your password. +3. Alternatively, remove the quarantine flag once in Terminal and start Lutra normally: + +```sh +xattr -dr com.apple.quarantine /Applications/Lutra.app +``` + +You need to do this once per installed version. + +### Uninstalling on macOS + +Quit Lutra and drag **Lutra** from **Applications** to the Trash. Your data stays; delete the folders below to remove it. + +## Where your data lives + +| What | Windows | macOS | +|---|---|---| +| The app | `%LOCALAPPDATA%\Lutra\` | `/Applications/Lutra.app` | +| Settings (`settings.json`), recovery journal (`recovery\`), downloaded Phpactor (`tools\`) | `%APPDATA%\com.tyrveil.lutra\` | `~/Library/Application Support/com.tyrveil.lutra/` | +| Window data of the web view (recent projects, layout) | `%LOCALAPPDATA%\com.tyrveil.lutra\` | `~/Library/WebKit/com.tyrveil.lutra/`, `~/Library/Caches/com.tyrveil.lutra/` | + +On Linux, when built from source: settings in `~/.config/com.tyrveil.lutra/`, journal and tools in `~/.local/share/com.tyrveil.lutra/`. + +**From a build before the installers.** Earlier builds used the identifier `dev.lutra.desktop`. The first start of a new build copies `settings.json`, the recovery journal and the downloaded Phpactor from the old `dev.lutra.desktop` folders once and shows a notification; the old folders stay untouched and can be deleted afterwards. Recent projects and the window layout are not copied. + +An instance started with `--control PORT` or `--data-dir DIR` keeps its files in its own folder (see [`development.md`](development.md#data-directories)). + +## Revision history + +| Date | Change | Summary | +|---|---|---| +| 2026-10-31 | major | B1: initial version, NSIS setup and DMG, unsigned | diff --git a/docs/macos.md b/docs/macos.md index ebbdf0b..49a5cc6 100644 --- a/docs/macos.md +++ b/docs/macos.md @@ -4,7 +4,7 @@ How to set up a fresh Apple Silicon Mac (M1 or newer, macOS 14 Sonoma or newer) to build, test and run Lutra from source, and how to send a machine report back to the developers. Follow the steps in order and type the commands exactly as shown; each one is a single line for the Terminal. -Lutra is not signed or notarised yet, and there is no installer (DMG). You build it yourself, which is fine for the alpha: a program you build on your own Mac is not quarantined, so Gatekeeper does not block it (see [Gatekeeper](#gatekeeper-and-code-signing)). +Lutra is not signed or notarised yet. This guide builds it from source, which is fine for the alpha: a program you build on your own Mac is not quarantined, so Gatekeeper does not block it (see [Gatekeeper](#gatekeeper-and-code-signing)). ## 1. Open Terminal @@ -177,6 +177,14 @@ The first time this asks for the Tauri CLI; install it with `cargo install tauri target/debug/lutra-desktop ~/Projekte/some-php-project ``` +## 9. Building the DMG + +```sh +cargo xtask bundle +``` + +It builds the release app and packs it into `target/release/bundle/dmg/Lutra__aarch64.dmg` (the app itself is next to it in `target/release/bundle/macos/Lutra.app`). The DMG background comes in two sizes, joined with `tiffutil` so a Retina display shows the sharp one. A DMG you built yourself is not quarantined; one you copy to another Mac is, see [`install.md`](install.md#macos). + ## Gatekeeper and code signing - **Built on this Mac:** files you compile yourself (with `cargo`) carry no quarantine attribute, and the Apple Silicon linker signs them ad hoc automatically, so they run without any Gatekeeper prompt. That covers everything in this guide. @@ -188,7 +196,7 @@ target/debug/lutra-desktop ~/Projekte/some-php-project Or open it once with a right click ▸ Open (on macOS 15 and later: try to open it, then System Settings ▸ Privacy & Security ▸ Open Anyway). - **Phpactor:** Lutra downloads the Phpactor PHAR itself and checks its SHA-256; files that Lutra writes are not quarantined, and PHP runs the PHAR, so Gatekeeper is not involved. -- Real signing and notarisation need an Apple Developer ID and the final app identifier (open owner decision O2); they come with the installers, after the alpha. +- Real signing and notarisation need an Apple Developer ID; the alpha DMG is unsigned (owner decision D26), so the first start needs right-click ▸ Open or `xattr` (see [`install.md`](install.md#macos)). ## What is different on macOS @@ -196,7 +204,7 @@ target/debug/lutra-desktop ~/Projekte/some-php-project - **Shortcuts.** `Mod` in Lutra's keymap is ⌘ on macOS and Ctrl elsewhere. - **Terminal.** The integrated terminal starts your login shell (`$SHELL`, normally zsh) with `-l`, as Terminal.app does, so `~/.zprofile` runs and Homebrew's PHP and Composer are on the `PATH` even when Lutra was started from the Finder or Dock. Without a locale in the environment it sets `LANG=en_US.UTF-8`. - **PHP.** Lutra finds PHP on the `PATH` and, after it, in `/opt/homebrew/bin`, `/usr/local/bin` and `/opt/local/bin`, because an app started from the Finder only gets the system `PATH`. The setting `php.executable` overrides both. -- **Data.** Settings, the recovery journal and the downloaded Phpactor live in `~/Library/Application Support/dev.lutra.desktop/`. An instance started with `--control` or `--data-dir` (as the report does) uses its own folder and shares only the Phpactor download. +- **Data.** Settings, the recovery journal and the downloaded Phpactor live in `~/Library/Application Support/com.tyrveil.lutra/` (builds before the alpha installers used `dev.lutra.desktop/`; the first start copies its files over). An instance started with `--control` or `--data-dir` (as the report does) uses its own folder and shares only the Phpactor download. - **File names.** The default APFS volume ignores case, like Windows, so paths the language server reports are matched to project files without regard to case. ## What was checked without a Mac @@ -218,4 +226,5 @@ These can only be checked on the Mac itself, which is what the report does: | Date | Change | Summary | |---|---|---| +| 2026-10-31 | minor | B1: new identifier `com.tyrveil.lutra`, building the DMG with `cargo xtask bundle` | | 2026-10-31 | major | A1: initial guide (setup, `cargo xtask mac-report`, Gatekeeper, macOS differences, what Windows cannot check) | diff --git a/ui/src/i18n/en.json b/ui/src/i18n/en.json index fa8fa3b..b431263 100644 --- a/ui/src/i18n/en.json +++ b/ui/src/i18n/en.json @@ -152,6 +152,8 @@ "nav.rename.label": "New name for {name}", "nav.rename.notHere": "There is nothing to rename at the cursor", "nav.rename.preview": "Changes {uses} uses in {files} files. Enter to rename, Escape to cancel", + "notification.app.dataMigrated": "Lutra copied your settings, recovery journal and tools from {from} to {to}.", + "notification.app.dataMigrationFailed": "Cannot copy your settings and tools from {from}: {error}. Lutra starts with the defaults and tries again next time.", "notification.close": "Close notification", "notification.command.failed": "{command} failed: {message}", "notification.lsp.failed": "The PHP language server stopped: {reason}. Run Restart PHP Language Server to try again.", diff --git a/xtask/Cargo.toml b/xtask/Cargo.toml index 97be44a..070d91c 100644 --- a/xtask/Cargo.toml +++ b/xtask/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "xtask" -description = "Project automation: ci, layers, assets, cleanroom, dev, fixtures, demo-project, mac-report" +description = "Project automation: ci, layers, assets, cleanroom, dev, bundle, fixtures, demo-project, mac-report" version.workspace = true edition.workspace = true rust-version.workspace = true @@ -13,6 +13,7 @@ layer = "tool" [dependencies] lutra-proc.workspace = true +png = "0.18.1" serde_json = "1.0.154" toml = "1.1.8" diff --git a/xtask/src/bundle.rs b/xtask/src/bundle.rs new file mode 100644 index 0000000..eb91a85 --- /dev/null +++ b/xtask/src/bundle.rs @@ -0,0 +1,127 @@ +//! `cargo xtask bundle`: the platform's installer. +//! +//! Builds the desktop app in release mode with the bundled UI through the +//! Tauri CLI and packs it: an NSIS setup (`.exe`, per-user install) on +//! Windows, a DMG on macOS. The settings live in +//! `apps/lutra-desktop/tauri.conf.json`; the installer images in +//! `assets/installer/`. On macOS the 1x and 2x DMG backgrounds are joined +//! into one HiDPI TIFF with `tiffutil` first, so Finder picks the sharp one +//! on a Retina display; without `tiffutil` the 1x PNG from the config is +//! used. Other platforms have no installer yet. + +use std::path::{Path, PathBuf}; + +use crate::util::{TaskResult, repo_root, run}; + +/// The Tauri bundle target and the output folder under `bundle/` for this +/// platform, or `None` without an installer. +fn target() -> Option<(&'static str, &'static str)> { + if cfg!(windows) { + Some(("nsis", "nsis")) + } else if cfg!(target_os = "macos") { + Some(("dmg", "dmg")) + } else { + None + } +} + +/// Builds the platform's installer and prints where it is. +/// +/// # Errors +/// Fails on a platform without an installer, if the frontend dependencies +/// cannot be installed, or if the Tauri CLI is missing or fails. +pub fn bundle() -> TaskResult { + let Some((bundles, folder)) = target() else { + return Err("no installer for this platform yet (Windows: NSIS, macOS: DMG)".into()); + }; + let root = repo_root()?; + let cargo = std::env::var("CARGO").unwrap_or_else(|_| "cargo".into()); + if !root.join("ui").join("node_modules").is_dir() { + run(&root.join("ui"), "pnpm", &["install", "--frozen-lockfile"])?; + } + let mut args = vec![ + "tauri".to_string(), + "build".into(), + "--bundles".into(), + bundles.into(), + "--features".into(), + "bundled-ui".into(), + ]; + let target_dir = target_dir(&root); + if cfg!(target_os = "macos") + && let Some(tiff) = hidpi_background(&root, &target_dir) + { + args.push("--config".into()); + args.push(dmg_background_override(&tiff)); + } + let args: Vec<&str> = args.iter().map(String::as_str).collect(); + run(&root.join("apps").join("lutra-desktop"), &cargo, &args).map_err(|e| { + format!("{e}\n(install the Tauri CLI with `cargo install tauri-cli --locked`)") + })?; + let out = target_dir.join("release").join("bundle").join(folder); + let listing = std::fs::read_dir(&out) + .map_err(|e| format!("no installer folder {}: {e}", out.display()))?; + for entry in listing.flatten() { + let path = entry.path(); + let size = entry.metadata().map(|m| m.len()).unwrap_or(0); + println!( + "bundle: {} ({:.1} MB)", + path.display(), + size as f64 / 1_000_000.0 + ); + } + Ok(()) +} + +/// The Cargo target directory: `CARGO_TARGET_DIR` (relative to the +/// repository root) or `/target`. +fn target_dir(root: &Path) -> PathBuf { + match std::env::var_os("CARGO_TARGET_DIR").filter(|v| !v.is_empty()) { + Some(dir) => root.join(dir), + None => root.join("target"), + } +} + +/// Joins `dmg-background.png` and `dmg-background@2x.png` into +/// `/dmg-background.tiff` with `tiffutil -cathidpicheck`. `None` +/// (and a note) if that fails; the bundle then uses the 1x PNG. +fn hidpi_background(root: &Path, target_dir: &Path) -> Option { + let dir = root.join("assets").join("installer"); + let out = target_dir.join("dmg-background.tiff"); + std::fs::create_dir_all(target_dir).ok()?; + let status = std::process::Command::new("tiffutil") + .arg("-cathidpicheck") + .arg(dir.join("dmg-background.png")) + .arg(dir.join("dmg-background@2x.png")) + .arg("-out") + .arg(&out) + .status(); + match status { + Ok(s) if s.success() => Some(out), + _ => { + println!("bundle: tiffutil failed; the DMG uses the 1x background"); + None + } + } +} + +/// The `--config` JSON for the Tauri CLI that sets the DMG background to +/// `tiff`. +fn dmg_background_override(tiff: &Path) -> String { + serde_json::json!({ + "bundle": { "macOS": { "dmg": { "background": tiff } } } + }) + .to_string() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn the_override_names_the_tiff() { + let json: serde_json::Value = + serde_json::from_str(&dmg_background_override(Path::new("/t/bg.tiff"))).unwrap(); + assert_eq!(json["bundle"]["macOS"]["dmg"]["background"], "/t/bg.tiff"); + } +} diff --git a/xtask/src/images.rs b/xtask/src/images.rs new file mode 100644 index 0000000..ebcc00d --- /dev/null +++ b/xtask/src/images.rs @@ -0,0 +1,212 @@ +//! `cargo xtask installer-images`: the installer images, generated from +//! the README banner `docs/images/banner.png` into `assets/installer/`. +//! +//! Amy's design (B1): crops of the banner on its magenta, no new art. +//! - `nsis-sidebar.bmp` (164 × 314): the otter on its tower. +//! - `nsis-header.bmp` (150 × 57): the "Lutra" wordmark, centred. +//! - `dmg-background.png` (720 × 400) and `dmg-background@2x.png` +//! (1440 × 800): wordmark top left, the otter column on the right, the +//! skyline along the bottom, a lighter magenta shelf behind the app and +//! Applications icons (centred at (100, 184) and (326, 184)) so Finder's +//! black or white labels stay readable, and a cream arrow between them. +//! +//! Every crop is resampled straight from the banner to its final size; +//! the 2x background is drawn with every target coordinate doubled. The +//! output is deterministic, so running the task again gives the same +//! files. + +use std::path::Path; + +use crate::raster::{Raster, Rect, color}; +use crate::util::{TaskResult, repo_root}; + +/// The banner's flat background. +const MAGENTA: &str = "#bb3b78"; + +/// The wordmark and otter colour, used for the arrow. +const CREAM: &str = "#f2ebd9"; + +/// The label shelf: black and white text both reach WCAG AA on it. +const SHELF: &str = "#c54883"; + +/// Width of the feathered edges of the DMG wordmark, in 1x pixels. +const FEATHER: u32 = 16; + +/// Shorthand for a [`Rect`]. +const fn rect(x: u32, y: u32, w: u32, h: u32) -> Rect { + Rect { x, y, w, h } +} + +/// Writes all installer images from the banner. +/// +/// # Errors +/// If the banner cannot be read or decoded, a crop lies outside it, or a +/// file cannot be written. +pub fn generate() -> TaskResult { + let root = repo_root()?; + let banner_path = root.join("docs").join("images").join("banner.png"); + let bytes = std::fs::read(&banner_path) + .map_err(|e| format!("cannot read {}: {e}", banner_path.display()))?; + let banner = Raster::decode_png(&bytes)?; + let out = root.join("assets").join("installer"); + std::fs::create_dir_all(&out).map_err(|e| e.to_string())?; + write(&out, "nsis-sidebar.bmp", &sidebar(&banner)?.encode_bmp())?; + write(&out, "nsis-header.bmp", &header(&banner)?.encode_bmp())?; + write(&out, "dmg-background.png", &dmg(&banner, 1)?.encode_png()?)?; + write( + &out, + "dmg-background@2x.png", + &dmg(&banner, 2)?.encode_png()?, + )?; + Ok(()) +} + +/// Writes `bytes` to `dir/name` and prints it. +/// +/// # Errors +/// If the file cannot be written. +fn write(dir: &Path, name: &str, bytes: &[u8]) -> TaskResult { + let path = dir.join(name); + std::fs::write(&path, bytes).map_err(|e| format!("cannot write {}: {e}", path.display()))?; + println!( + "installer-images: {} ({} bytes)", + path.display(), + bytes.len() + ); + Ok(()) +} + +/// The NSIS sidebar: the otter, head in the upper third, on magenta. +/// +/// # Errors +/// If the crop lies outside the banner. +pub fn sidebar(banner: &Raster) -> TaskResult { + let mut img = Raster::new(164, 314, color(MAGENTA)?); + let otter = banner.crop(rect(980, 60, 345, 660))?.resize(164, 314); + img.draw(&otter, 0, 0, 1.0); + Ok(img) +} + +/// The NSIS header: the wordmark, 9 px of magenta above and below. +/// +/// # Errors +/// If the crop lies outside the banner. +pub fn header(banner: &Raster) -> TaskResult { + let mut img = Raster::new(150, 57, color(MAGENTA)?); + let mark = banner.crop(rect(14, 28, 820, 214))?.resize(150, 39); + img.draw(&mark, 0, 9, 1.0); + Ok(img) +} + +/// The DMG background at `scale` (1 or 2) times 720 × 400; layers in +/// Amy's order: magenta, feathered wordmark, skyline, otter column, label +/// shelf, arrow. +/// +/// # Errors +/// If a crop lies outside the banner. +pub fn dmg(banner: &Raster, scale: u32) -> TaskResult { + let s = |v: u32| v * scale; + let mut img = Raster::new(s(720), s(400), color(MAGENTA)?); + let mut mark = banner.crop(rect(0, 0, 860, 330))?.resize(s(310), s(119)); + feather(&mut mark, s(FEATHER)); + img.draw(&mark, 0, 0, 1.0); + let skyline = banner.crop(rect(0, 520, 766, 200))?.resize(s(426), s(111)); + img.draw(&skyline, 0, i64::from(s(289)), 1.0); + let otter = banner.crop(rect(870, 0, 527, 720))?.resize(s(294), s(400)); + img.draw(&otter, i64::from(s(426)), 0, 1.0); + img.fill_rect(rect(s(10), s(116), s(406), s(172)), color(SHELF)?); + let cream = color(CREAM)?; + img.fill_rect(rect(s(178), s(180), s(54), s(8)), cream); + let p = |x: u32, y: u32| (f64::from(s(x)), f64::from(s(y))); + img.fill_triangle([p(232, 172), p(248, 184), p(232, 196)], cream); + Ok(img) +} + +/// Fades the right and bottom `width` pixels of `img` to transparent with +/// a linear ramp (the factors multiply in the corner), so the crop melts +/// into the background. +fn feather(img: &mut Raster, width: u32) { + let (w, h) = (img.width, img.height); + let ramp = |pos: u32, size: u32| { + if pos + width >= size { + f64::from(size - pos) / f64::from(width + 1) + } else { + 1.0 + } + }; + for y in 0..h { + for x in 0..w { + let factor = ramp(x, w) * ramp(y, h); + if factor < 1.0 { + let [r, g, b, a] = img.pixel(x, y); + img.put(x, y, [r, g, b, (f64::from(a) * factor).round() as u8]); + } + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A flat stand-in banner of the real size. + fn banner() -> Raster { + Raster::new(1456, 720, color(MAGENTA).unwrap()) + } + + #[test] + fn images_have_the_installer_sizes_and_are_opaque() { + let b = banner(); + for (img, w, h) in [ + (sidebar(&b).unwrap(), 164, 314), + (header(&b).unwrap(), 150, 57), + (dmg(&b, 1).unwrap(), 720, 400), + (dmg(&b, 2).unwrap(), 1440, 800), + ] { + assert_eq!((img.width, img.height), (w, h)); + assert!(img.rgba.as_chunks::<4>().0.iter().all(|p| p[3] == 255)); + } + } + + #[test] + fn the_dmg_has_the_shelf_and_the_arrow() { + let b = banner(); + let one = dmg(&b, 1).unwrap(); + assert_eq!(one.pixel(100, 260), color(SHELF).unwrap()); + assert_eq!(one.pixel(200, 184), color(CREAM).unwrap()); + assert_eq!(one.pixel(236, 184), color(CREAM).unwrap()); + let two = dmg(&b, 2).unwrap(); + assert_eq!(two.pixel(400, 368), color(CREAM).unwrap()); + } + + #[test] + fn feathering_fades_only_the_right_and_bottom_edges() { + let mut img = Raster::new(40, 40, [0, 0, 0, 255]); + feather(&mut img, 16); + assert_eq!(img.pixel(0, 0)[3], 255); + assert_eq!(img.pixel(23, 23)[3], 255); + assert_eq!(img.pixel(39, 0)[3], 15); + assert!(img.pixel(39, 39)[3] < 2); + } + + #[test] + fn the_real_banner_gives_the_committed_images() { + let root = repo_root().unwrap(); + let bytes = std::fs::read(root.join("docs/images/banner.png")).unwrap(); + let banner = Raster::decode_png(&bytes).unwrap(); + let dir = root.join("assets/installer"); + let committed = |name: &str| std::fs::read(dir.join(name)).unwrap(); + assert_eq!( + sidebar(&banner).unwrap().encode_bmp(), + committed("nsis-sidebar.bmp") + ); + assert_eq!( + header(&banner).unwrap().encode_bmp(), + committed("nsis-header.bmp") + ); + assert_eq!( + dmg(&banner, 1).unwrap().encode_png().unwrap(), + committed("dmg-background.png") + ); + } +} diff --git a/xtask/src/main.rs b/xtask/src/main.rs index ad7db3f..b8196bd 100644 --- a/xtask/src/main.rs +++ b/xtask/src/main.rs @@ -4,12 +4,15 @@ //! message when the check fails. mod assets; +mod bundle; mod cleanroom; mod demo; +mod images; mod layers; mod licences; mod lints; mod macreport; +mod raster; mod tasks; mod util; @@ -27,6 +30,8 @@ commands: ui-licences check the licences of the frontend's production dependencies lints-selftest prove that shipped unwrap() fails clippy and test unwrap() passes dev [-- ARGS] run the desktop app in development mode, ARGS go to the app + bundle build this platform's installer (Windows: NSIS setup, macOS: DMG) + installer-images regenerate assets/installer/ from docs/images/banner.png fixtures create Symfony and Laravel reference projects in target/fixtures/ demo-project DIR create the offline demo for docs/alpha-checklist.md in DIR ", @@ -58,6 +63,8 @@ fn main() -> ExitCode { .collect(); tasks::dev(&app_args) } + "bundle" => bundle::bundle(), + "installer-images" => images::generate(), "fixtures" => tasks::fixtures(), "demo-project" => demo::run(rest), "mac-report" => macreport::parse(rest).and_then(|o| macreport::mac_report(&o)), diff --git a/xtask/src/raster.rs b/xtask/src/raster.rs new file mode 100644 index 0000000..fce61f0 --- /dev/null +++ b/xtask/src/raster.rs @@ -0,0 +1,498 @@ +//! A small RGBA raster for the generated installer images: PNG decoding, +//! cropping, resampling, solid fills, simple shapes, +//! alpha compositing, and PNG and 24-bit BMP encoding. +//! +//! Pixels are 8-bit RGBA, not premultiplied, row by row from the top. +//! Resampling works on premultiplied alpha with a tent filter whose width +//! grows with the shrink factor, so it averages areas when shrinking and +//! interpolates linearly when enlarging. + +use std::io::Cursor; + +use crate::util::TaskResult; + +/// Largest accepted edge length of a decoded image. +const MAX_EDGE: u32 = 8192; + +/// An RGBA colour, 8 bits per channel, not premultiplied. +pub type Rgba = [u8; 4]; + +/// A rectangle in pixels. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Rect { + /// Left edge. + pub x: u32, + /// Top edge. + pub y: u32, + /// Width. + pub w: u32, + /// Height. + pub h: u32, +} + +/// An RGBA image. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct Raster { + /// Width in pixels. + pub width: u32, + /// Height in pixels. + pub height: u32, + /// Pixels, four bytes each, row by row from the top. + pub rgba: Vec, +} + +/// Parses `#rrggbb` (opaque) or `#rrggbbaa`. +/// +/// # Errors +/// If `hex` is not in one of those forms. +pub fn color(hex: &str) -> TaskResult { + let digits = hex + .strip_prefix('#') + .ok_or_else(|| format!("colour `{hex}` lacks `#`"))?; + let byte = |at: usize| { + digits + .get(at..at + 2) + .and_then(|s| u8::from_str_radix(s, 16).ok()) + .ok_or_else(|| format!("bad colour `{hex}`")) + }; + match digits.len() { + 6 => Ok([byte(0)?, byte(2)?, byte(4)?, 255]), + 8 => Ok([byte(0)?, byte(2)?, byte(4)?, byte(6)?]), + _ => Err(format!("bad colour `{hex}`")), + } +} + +impl Raster { + /// A `width`×`height` image filled with `fill`. + pub fn new(width: u32, height: u32, fill: Rgba) -> Self { + let count = width as usize * height as usize; + Self { + width, + height, + rgba: fill.repeat(count), + } + } + + /// Decodes a PNG of any 8-bit colour type into RGBA. + /// + /// # Errors + /// If the bytes are not a PNG, use 16 bits per channel, or exceed + /// [`MAX_EDGE`]. + pub fn decode_png(bytes: &[u8]) -> TaskResult { + let mut decoder = png::Decoder::new(Cursor::new(bytes)); + decoder.set_transformations(png::Transformations::normalize_to_color8()); + let mut reader = decoder.read_info().map_err(|e| e.to_string())?; + let (width, height) = (reader.info().width, reader.info().height); + if width == 0 || height == 0 || width > MAX_EDGE || height > MAX_EDGE { + return Err(format!("image size {width}x{height} not supported")); + } + let size = reader + .output_buffer_size() + .ok_or("image too large to decode")?; + let mut buf = vec![0; size]; + let frame = reader.next_frame(&mut buf).map_err(|e| e.to_string())?; + if frame.bit_depth != png::BitDepth::Eight { + return Err("only 8-bit PNGs are supported".into()); + } + let data = buf.get(..frame.buffer_size()).ok_or("short PNG frame")?; + let rgba: Vec = match frame.color_type { + png::ColorType::Rgba => data.to_vec(), + png::ColorType::Rgb => data + .as_chunks::<3>() + .0 + .iter() + .flat_map(|&[r, g, b]| [r, g, b, 255]) + .collect(), + png::ColorType::GrayscaleAlpha => data + .as_chunks::<2>() + .0 + .iter() + .flat_map(|&[v, a]| [v, v, v, a]) + .collect(), + png::ColorType::Grayscale => data.iter().flat_map(|&v| [v, v, v, 255]).collect(), + png::ColorType::Indexed => return Err("PNG palette was not expanded".into()), + }; + Ok(Self { + width, + height, + rgba, + }) + } + + /// The pixel at (`x`, `y`), transparent outside the image. + pub fn pixel(&self, x: u32, y: u32) -> Rgba { + if x >= self.width || y >= self.height { + return [0; 4]; + } + let at = (y as usize * self.width as usize + x as usize) * 4; + match self.rgba.get(at..at + 4) { + Some(&[r, g, b, a]) => [r, g, b, a], + _ => [0; 4], + } + } + + /// Sets the pixel at (`x`, `y`); ignored outside the image. + pub fn put(&mut self, x: u32, y: u32, value: Rgba) { + if x >= self.width || y >= self.height { + return; + } + let at = (y as usize * self.width as usize + x as usize) * 4; + if let Some(cell) = self.rgba.get_mut(at..at + 4) { + cell.copy_from_slice(&value); + } + } + + /// Blends `value` over the pixel at (`x`, `y`) with extra coverage + /// `cover` (0–1); ignored outside the image. + fn blend(&mut self, x: u32, y: u32, value: Rgba, cover: f64) { + let under = self.pixel(x, y); + self.put(x, y, over(value, under, cover)); + } + + /// The part of the image inside `rect`. + /// + /// # Errors + /// If `rect` is empty or reaches outside the image. + pub fn crop(&self, rect: Rect) -> TaskResult { + if rect.w == 0 + || rect.h == 0 + || rect.x + rect.w > self.width + || rect.y + rect.h > self.height + { + return Err(format!( + "crop {rect:?} outside the {}x{} image", + self.width, self.height + )); + } + let mut out = Self::new(rect.w, rect.h, [0; 4]); + for y in 0..rect.h { + for x in 0..rect.w { + out.put(x, y, self.pixel(rect.x + x, rect.y + y)); + } + } + Ok(out) + } + + /// The image resampled to `width`×`height`. + pub fn resize(&self, width: u32, height: u32) -> Self { + if width == self.width && height == self.height { + return self.clone(); + } + let premul: Vec<[f64; 4]> = self + .rgba + .as_chunks::<4>() + .0 + .iter() + .map(|&[r, g, b, a]| { + let a = f64::from(a) / 255.0; + [f64::from(r) * a, f64::from(g) * a, f64::from(b) * a, a] + }) + .collect(); + let (sw, sh) = (self.width as usize, self.height as usize); + let dw = width as usize; + let xtaps = taps(self.width, width); + let ytaps = taps(self.height, height); + let mut rows = vec![[0.0f64; 4]; dw * sh]; + for y in 0..sh { + for (x, row_taps) in xtaps.iter().enumerate() { + let mut acc = [0.0f64; 4]; + for &(i, w) in row_taps { + if let Some(p) = premul.get(y * sw + i) { + add(&mut acc, p, w); + } + } + if let Some(cell) = rows.get_mut(y * dw + x) { + *cell = acc; + } + } + } + let mut out = Self::new(width, height, [0; 4]); + for (y, col_taps) in ytaps.iter().enumerate() { + for x in 0..dw { + let mut acc = [0.0f64; 4]; + for &(j, w) in col_taps { + if let Some(p) = rows.get(j * dw + x) { + add(&mut acc, p, w); + } + } + out.put(x as u32, y as u32, unpremultiply(acc)); + } + } + out + } + + /// Blends `value` over every pixel of `rect` (clipped to the image). + pub fn fill_rect(&mut self, rect: Rect, value: Rgba) { + for y in rect.y..(rect.y + rect.h).min(self.height) { + for x in rect.x..(rect.x + rect.w).min(self.width) { + self.blend(x, y, value, 1.0); + } + } + } + + /// Blends `value` over the triangle `points` (in pixel coordinates, + /// pixel centres at +0.5), anti-aliased with 4×4 samples per pixel. + pub fn fill_triangle(&mut self, points: [(f64, f64); 3], value: Rgba) { + let xs = points.map(|p| p.0); + let ys = points.map(|p| p.1); + let lo = |v: [f64; 3]| { + v.iter() + .copied() + .fold(f64::INFINITY, f64::min) + .floor() + .max(0.0) + }; + let hi = |v: [f64; 3]| v.iter().copied().fold(f64::NEG_INFINITY, f64::max).ceil(); + let (x0, y0) = (lo(xs) as u32, lo(ys) as u32); + let x1 = (hi(xs) as u32).min(self.width); + let y1 = (hi(ys) as u32).min(self.height); + for y in y0..y1 { + for x in x0..x1 { + let mut inside = 0u32; + for sy in 0..4 { + for sx in 0..4 { + let px = f64::from(x) + (f64::from(sx) + 0.5) / 4.0; + let py = f64::from(y) + (f64::from(sy) + 0.5) / 4.0; + if in_triangle((px, py), points) { + inside += 1; + } + } + } + if inside > 0 { + self.blend(x, y, value, f64::from(inside) / 16.0); + } + } + } + } + + /// Blends `layer` over this image with its top-left corner at + /// (`x`, `y`), scaling its alpha by `opacity` (0–1). + pub fn draw(&mut self, layer: &Self, x: i64, y: i64, opacity: f64) { + for ly in 0..layer.height { + for lx in 0..layer.width { + let (tx, ty) = (x + i64::from(lx), y + i64::from(ly)); + let (Ok(tx), Ok(ty)) = (u32::try_from(tx), u32::try_from(ty)) else { + continue; + }; + self.blend(tx, ty, layer.pixel(lx, ly), opacity); + } + } + } + + /// Encodes the image as an RGBA PNG. + /// + /// # Errors + /// If the encoder fails. + pub fn encode_png(&self) -> TaskResult> { + let mut out = Vec::new(); + { + let mut encoder = png::Encoder::new(&mut out, self.width, self.height); + encoder.set_color(png::ColorType::Rgba); + encoder.set_depth(png::BitDepth::Eight); + let mut writer = encoder.write_header().map_err(|e| e.to_string())?; + writer + .write_image_data(&self.rgba) + .map_err(|e| e.to_string())?; + } + Ok(out) + } + + /// Encodes the image as an uncompressed 24-bit BMP (bottom-up rows + /// padded to four bytes), the format NSIS shows. Alpha is dropped, so + /// the image should be opaque. + pub fn encode_bmp(&self) -> Vec { + let row = (self.width as usize * 3).div_ceil(4) * 4; + let data = row * self.height as usize; + let size = 54 + data; + let mut out = Vec::with_capacity(size); + out.extend_from_slice(b"BM"); + out.extend_from_slice(&(size as u32).to_le_bytes()); + out.extend_from_slice(&0u32.to_le_bytes()); + out.extend_from_slice(&54u32.to_le_bytes()); + out.extend_from_slice(&40u32.to_le_bytes()); + out.extend_from_slice(&(self.width as i32).to_le_bytes()); + out.extend_from_slice(&(self.height as i32).to_le_bytes()); + out.extend_from_slice(&1u16.to_le_bytes()); + out.extend_from_slice(&24u16.to_le_bytes()); + out.extend_from_slice(&0u32.to_le_bytes()); + out.extend_from_slice(&(data as u32).to_le_bytes()); + out.extend_from_slice(&2835i32.to_le_bytes()); + out.extend_from_slice(&2835i32.to_le_bytes()); + out.extend_from_slice(&0u32.to_le_bytes()); + out.extend_from_slice(&0u32.to_le_bytes()); + for y in (0..self.height).rev() { + let start = out.len(); + for x in 0..self.width { + let [r, g, b, _] = self.pixel(x, y); + out.extend_from_slice(&[b, g, r]); + } + out.resize(start + row, 0); + } + out + } +} + +/// `value` blended over `under` with extra coverage `cover` (Porter-Duff +/// "over" on straight alpha). +fn over(value: Rgba, under: Rgba, cover: f64) -> Rgba { + let sa = f64::from(value[3]) / 255.0 * cover.clamp(0.0, 1.0); + let da = f64::from(under[3]) / 255.0; + let oa = sa + da * (1.0 - sa); + if oa <= 0.0 { + return [0; 4]; + } + let channel = |s: u8, d: u8| { + ((f64::from(s) * sa + f64::from(d) * da * (1.0 - sa)) / oa) + .round() + .clamp(0.0, 255.0) as u8 + }; + [ + channel(value[0], under[0]), + channel(value[1], under[1]), + channel(value[2], under[2]), + (oa * 255.0).round() as u8, + ] +} + +/// Adds `p` weighted by `w` to `acc`. +fn add(acc: &mut [f64; 4], p: &[f64; 4], w: f64) { + for (a, v) in acc.iter_mut().zip(p) { + *a += v * w; + } +} + +/// Straight 8-bit RGBA from a premultiplied accumulator. +fn unpremultiply(acc: [f64; 4]) -> Rgba { + let a = acc[3].clamp(0.0, 1.0); + if a <= 0.0 { + return [0; 4]; + } + let channel = |v: f64| (v / a).round().clamp(0.0, 255.0) as u8; + [ + channel(acc[0]), + channel(acc[1]), + channel(acc[2]), + (a * 255.0).round() as u8, + ] +} + +/// Whether `p` lies inside the triangle `t` (either winding). +fn in_triangle(p: (f64, f64), t: [(f64, f64); 3]) -> bool { + let side = |a: (f64, f64), b: (f64, f64)| (b.0 - a.0) * (p.1 - a.1) - (b.1 - a.1) * (p.0 - a.0); + let d = [side(t[0], t[1]), side(t[1], t[2]), side(t[2], t[0])]; + d.iter().all(|&v| v >= 0.0) || d.iter().all(|&v| v <= 0.0) +} + +/// Source taps (index, weight) for each output position when resampling +/// `src` samples to `dst` with a tent filter; weights sum to 1. +fn taps(src: u32, dst: u32) -> Vec> { + let scale = f64::from(src) / f64::from(dst); + let support = scale.max(1.0); + (0..dst) + .map(|o| { + let centre = (f64::from(o) + 0.5) * scale - 0.5; + let first = (centre - support).floor().max(0.0) as u32; + let last = ((centre + support).ceil() as u32).min(src.saturating_sub(1)); + let mut list: Vec<(usize, f64)> = (first..=last) + .filter_map(|i| { + let w = 1.0 - (f64::from(i) - centre).abs() / support; + (w > 0.0).then_some((i as usize, w)) + }) + .collect(); + if list.is_empty() { + let nearest = centre.round().clamp(0.0, f64::from(src.saturating_sub(1))); + list.push((nearest as usize, 1.0)); + } + let total: f64 = list.iter().map(|t| t.1).sum(); + for t in &mut list { + t.1 /= total; + } + list + }) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_colours() { + assert_eq!(color("#c03a7c").unwrap(), [0xc0, 0x3a, 0x7c, 255]); + assert_eq!(color("#00000080").unwrap(), [0, 0, 0, 0x80]); + assert!(color("c03a7c").is_err()); + assert!(color("#c03").is_err()); + } + + #[test] + fn resizing_keeps_a_flat_colour() { + let flat = Raster::new(30, 20, [10, 200, 30, 255]); + for (w, h) in [(7, 5), (60, 40), (30, 20)] { + let out = flat.resize(w, h); + assert_eq!((out.width, out.height), (w, h)); + assert!( + out.rgba + .as_chunks::<4>() + .0 + .iter() + .all(|p| *p == [10, 200, 30, 255]) + ); + } + } + + #[test] + fn crops_and_rejects_outside_rects() { + let mut img = Raster::new(4, 4, [0, 0, 0, 255]); + img.put(2, 1, [255, 0, 0, 255]); + let part = img + .crop(Rect { + x: 2, + y: 1, + w: 2, + h: 2, + }) + .unwrap(); + assert_eq!(part.pixel(0, 0), [255, 0, 0, 255]); + assert!( + img.crop(Rect { + x: 3, + y: 0, + w: 2, + h: 1 + }) + .is_err() + ); + } + + #[test] + fn blends_and_draws_shapes() { + let mut img = Raster::new(10, 10, [0, 0, 0, 255]); + img.fill_rect( + Rect { + x: 0, + y: 0, + w: 5, + h: 10, + }, + [255, 255, 255, 128], + ); + assert_eq!(img.pixel(1, 1), [128, 128, 128, 255]); + assert_eq!(img.pixel(7, 1), [0, 0, 0, 255]); + img.fill_triangle([(0.0, 0.0), (10.0, 0.0), (0.0, 10.0)], [255, 0, 0, 255]); + assert_eq!(img.pixel(1, 1), [255, 0, 0, 255]); + assert_eq!(img.pixel(9, 9), [0, 0, 0, 255]); + } + + #[test] + fn encodes_a_padded_bmp_and_a_png_that_decodes() { + let mut img = Raster::new(3, 2, [1, 2, 3, 255]); + img.put(0, 1, [9, 8, 7, 255]); + let bmp = img.encode_bmp(); + assert_eq!(&bmp[..2], b"BM"); + assert_eq!(bmp.len(), 54 + 12 * 2); + assert_eq!(&bmp[54..57], &[7, 8, 9]); + assert_eq!(&bmp[63..66], &[0, 0, 0]); + let back = Raster::decode_png(&img.encode_png().unwrap()).unwrap(); + assert_eq!(back, img); + } +}