diff --git a/Cargo.lock b/Cargo.lock index 3881ba174b..27b9e695a6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -487,7 +487,7 @@ dependencies = [ "futures-lite", "parking", "polling", - "rustix 1.1.5", + "rustix 1.1.6", "slab", "windows-sys 0.61.2", ] @@ -518,7 +518,7 @@ dependencies = [ "cfg-if", "event-listener", "futures-lite", - "rustix 1.1.5", + "rustix 1.1.6", ] [[package]] @@ -544,7 +544,7 @@ dependencies = [ "cfg-if", "futures-core", "futures-io", - "rustix 1.1.5", + "rustix 1.1.6", "signal-hook-registry", "slab", "windows-sys 0.61.2", @@ -1193,7 +1193,7 @@ dependencies = [ "io-lifetimes 3.0.1", "ipnet", "maybe-owned", - "rustix 1.1.5", + "rustix 1.1.6", "rustix-linux-procfs", "windows-sys 0.61.2", "winx", @@ -1208,7 +1208,7 @@ dependencies = [ "cap-primitives", "io-extras", "io-lifetimes 3.0.1", - "rustix 1.1.5", + "rustix 1.1.6", ] [[package]] @@ -2053,7 +2053,7 @@ dependencies = [ name = "craft-atomic" version = "0.1.0" dependencies = [ - "rustix 1.1.5", + "rustix 1.1.6", ] [[package]] @@ -2080,7 +2080,7 @@ version = "0.1.0" name = "craft-automation" version = "0.1.0" dependencies = [ - "base64 0.22.1", + "base64 0.23.1", "craft-behavior", "craft-control", "craft-host", @@ -3485,6 +3485,7 @@ dependencies = [ "egui", "kurbo", "serde", + "serde_json", ] [[package]] @@ -3654,6 +3655,7 @@ dependencies = [ "craft-atomic", "craft-docpath", "craft-host", + "craft-i18n", "craft-theme", "fmv-macos-events", "futures-lite", @@ -3767,6 +3769,7 @@ version = "0.1.0" dependencies = [ "craft-behavior", "craft-host", + "craft-theme", "craft-ui", "craft-winprint-gdi", "egui", @@ -3846,6 +3849,8 @@ dependencies = [ "egui", "objc2 0.6.5", "objc2-app-kit 0.3.2", + "wasm-bindgen", + "web-sys", ] [[package]] @@ -3891,6 +3896,7 @@ dependencies = [ name = "craft-review" version = "0.1.0" dependencies = [ + "base64 0.23.1", "craft-behavior", "craft-host", "craft-i18n", @@ -4393,6 +4399,7 @@ dependencies = [ "syn 2.0.119", "toml", "typeid", + "wasm-bindgen-futures", "web-time", ] @@ -4528,12 +4535,14 @@ dependencies = [ "craft-host", "craft-i18n", "craft-keymap", + "craft-svg", "craft-theme", "craft-ui-contract", "craft-ui-macros", "craft-ui-test-kit", "craft-ui-widgets", "egui", + "log", "serde", "smallvec", ] @@ -4552,7 +4561,7 @@ dependencies = [ "image", "log", "plist", - "rustix 1.1.5", + "rustix 1.1.6", "semver", "serde", "serde_json", @@ -4651,7 +4660,10 @@ dependencies = [ name = "craft-web-host" version = "0.1.0" dependencies = [ + "craft-host", + "craft-platform", "wasm-bindgen", + "wasm-bindgen-futures", "wasm-bindgen-test", "web-sys", ] @@ -5398,7 +5410,7 @@ dependencies = [ "drm-ffi", "drm-fourcc", "libc", - "rustix 1.1.5", + "rustix 1.1.6", ] [[package]] @@ -5408,7 +5420,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "51a91c9b32ac4e8105dec255e849e0d66e27d7c34d184364fb93e469db08f690" dependencies = [ "drm-sys", - "rustix 1.1.5", + "rustix 1.1.6", ] [[package]] @@ -6323,7 +6335,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "94e7099f6313ecacbe1256e8ff9d617b75d1bcb16a6fddef94866d225a01a14a" dependencies = [ "io-lifetimes 2.0.4", - "rustix 1.1.5", + "rustix 1.1.6", "windows-sys 0.59.0", ] @@ -6573,7 +6585,7 @@ version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" dependencies = [ - "rustix 1.1.5", + "rustix 1.1.6", "windows-link", ] @@ -8272,7 +8284,7 @@ dependencies = [ "libc", "libspa-sys", "nom 8.0.0", - "rustix 1.1.5", + "rustix 1.1.6", "system-deps", ] @@ -8311,7 +8323,7 @@ dependencies = [ "image", "khronos-egl", "memmap2", - "rustix 1.1.5", + "rustix 1.1.6", "thiserror 2.0.21", "tracing", "wayland-backend", @@ -9986,7 +9998,7 @@ dependencies = [ "libspa", "libspa-sys", "pipewire-sys", - "rustix 1.1.5", + "rustix 1.1.6", ] [[package]] @@ -10117,7 +10129,7 @@ dependencies = [ "concurrent-queue", "hermit-abi", "pin-project-lite", - "rustix 1.1.5", + "rustix 1.1.6", "windows-sys 0.61.2", ] @@ -11194,9 +11206,9 @@ dependencies = [ [[package]] name = "rustix" -version = "1.1.5" +version = "1.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "891efababe418670775f199f0d233d84843c227a0949a883ce15b37c78d6629d" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" dependencies = [ "bitflags 2.13.2", "errno", @@ -11212,7 +11224,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2fc84bf7e9aa16c4f2c758f27412dc9841341e16aa682d9c7ac308fe3ee12056" dependencies = [ "once_cell", - "rustix 1.1.5", + "rustix 1.1.6", ] [[package]] @@ -12576,7 +12588,7 @@ dependencies = [ "fastrand", "getrandom 0.4.3", "once_cell", - "rustix 1.1.5", + "rustix 1.1.6", "windows-sys 0.61.2", ] @@ -13855,7 +13867,7 @@ checksum = "38a91b4eaddff87b1cd1074985e3713da4af2c49742d1b356b2c01670a67a078" dependencies = [ "cc", "downcast-rs", - "rustix 1.1.5", + "rustix 1.1.6", "scoped-tls", "smallvec", "wayland-sys", @@ -13868,7 +13880,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e3c36a0f861ad76d0901f2800b46321410d9f73f2ea88aac0650d86c32688073" dependencies = [ "bitflags 2.13.2", - "rustix 1.1.5", + "rustix 1.1.6", "wayland-backend", "wayland-scanner", ] @@ -13917,7 +13929,7 @@ checksum = "0dde9c29be0f723a573977de51ee455bf3dfa03652730a74f9dd3b337e374d75" dependencies = [ "bitflags 2.13.2", "downcast-rs", - "rustix 1.1.5", + "rustix 1.1.6", "wayland-backend", "wayland-scanner", ] @@ -14546,7 +14558,7 @@ dependencies = [ "libc", "log", "os_pipe", - "rustix 1.1.5", + "rustix 1.1.6", "thiserror 2.0.21", "tree_magic_mini", "wayland-backend", @@ -14663,7 +14675,7 @@ dependencies = [ "libc", "libloading", "once_cell", - "rustix 1.1.5", + "rustix 1.1.6", "x11rb-protocol", ] @@ -14746,7 +14758,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32e45ad4206f6d2479085147f02bc2ef834ac85886624a23575ae137c8aa8156" dependencies = [ "libc", - "rustix 1.1.5", + "rustix 1.1.6", ] [[package]] @@ -14906,7 +14918,7 @@ dependencies = [ "hex", "libc", "ordered-stream", - "rustix 1.1.5", + "rustix 1.1.6", "serde", "serde_repr", "tracing", diff --git a/crates/atomic/Cargo.toml b/crates/atomic/Cargo.toml index c19c64359e..2b0b43a475 100644 --- a/crates/atomic/Cargo.toml +++ b/crates/atomic/Cargo.toml @@ -11,5 +11,8 @@ description = "Crash-safe atomic file writing and replacement for the Craft suit [lints] workspace = true +# Plain fsync where F_FULLFSYNC is refused, and the replaced file's extended attributes (`fs`), with +# explicit size queries (`fgetxattr_query`). + [target.'cfg(target_vendor = "apple")'.dependencies] -rustix = { version = "1.1", default-features = false, features = ["std", "fs"] } +rustix = { version = "1.1.6", default-features = false, features = ["std", "fs"] } diff --git a/crates/atomic/src/lib.rs b/crates/atomic/src/lib.rs index a87a8734d8..c0bbcf5553 100644 --- a/crates/atomic/src/lib.rs +++ b/crates/atomic/src/lib.rs @@ -34,6 +34,13 @@ //! Existing destinations always stage privately and retain their original Unix mode. Restoring //! an already-matching mode needs no chmod, including on fixed-mode network filesystems. //! +//! ### Attributes +//! A replaced file is the same document: its stage gets the file's extended attributes (macOS), +//! its hidden and system attributes (Windows, at creation) and its creation date (macOS, +//! Windows) before it is flushed. An extended attribute that cannot be read or copied whole, or +//! passes a bound, refuses the save and leaves the original as it was. Saving through a symbolic +//! link keeps the link and replaces the file it names, so the attributes kept are that file's. +//! //! ### Platform Characteristics //! - **Windows**: Antivirus scanners, search indexers, and backup utilities briefly hold files //! open with sharing violations. The rename is retried with exponential backoff (`RenameRetry`). @@ -59,6 +66,15 @@ pub trait AtomicFs { /// request mode `0600` for `Private` or `0666` for `PlatformDefault`; the OS applies its /// umask/default ACL. Other platforms keep their native creation behavior. fn create_new(&self, path: &Path, permissions: NewFilePermissions) -> io::Result; + /// Create the stage like [`AtomicFs::create_new`], carrying over the attributes of the file it + /// replaces that can only be given at creation (Windows: hidden and system). `keep` is the + /// `metadata` of the regular file being replaced: a save through a symbolic link keeps the + /// link and replaces the file it names, so `keep` describes that file, never the link. `None` + /// for a new file. The default ignores `keep` and calls `create_new`. + fn create_new_keeping(&self, path: &Path, permissions: NewFilePermissions, keep: Option<&std::fs::Metadata>) -> io::Result { + let _ = keep; + self.create_new(path, permissions) + } /// Flush a written file to durable storage. fn sync(&self, file: &File) -> io::Result<()>; /// Rename `from` over `to`, replacing it atomically. @@ -99,6 +115,21 @@ impl AtomicFs for RealFs { options.open(path) } + fn create_new_keeping(&self, path: &Path, permissions: NewFilePermissions, keep: Option<&std::fs::Metadata>) -> io::Result { + // Given as the file is created, so a hidden file's stage is never visible: Windows has no + // safe call that sets them on an open file afterwards. + #[cfg(windows)] + if let Some(keep) = keep { + use std::os::windows::fs::{MetadataExt, OpenOptionsExt}; + let mut options = OpenOptions::new(); + options.write(true).create_new(true).attributes(keep.file_attributes() & KEPT_ATTRIBUTES); + return options.open(path); + } + #[cfg(not(windows))] + let _ = keep; + self.create_new(path, permissions) + } + fn sync(&self, file: &File) -> io::Result<()> { sync_file(file) } @@ -315,12 +346,16 @@ fn replace_with_options( check_writable(&target).map_err(|e| read_only_error(e, path))?; } - let tmp = stage(fs, &dir, &name, path, existing.as_ref(), new_permissions, fill)?; + let tmp = stage(fs, &dir, &name, path, existing.as_ref().map(|m| (target.as_path(), m)), new_permissions, fill)?; if let Err(e) = retry_rename(retry, || fs.rename(&tmp, &target)) { let _ = fs.remove(&tmp); return Err(rename_error(e, path, existed)); } + #[cfg(windows)] + if let Some(replaced) = existing.as_ref().filter(|m| m.is_file()) { + restore_kept_attributes(&target, replaced); + } // The new bytes are in place; a failed directory fsync can't be undone and must not report // the save as failed, so it is best effort. @@ -369,31 +404,35 @@ fn adopt_group(fs: &dyn AtomicFs, file: &File, stage_gid: u32, replaced_gid: u32 } /// Create a temporary file in `dir`, fill it with `fill`, give it the permissions and group of -/// the file it replaces (`replaced`, Unix) and flush it. Permission restoration is skipped when +/// the file it replaces (`replaced`: its resolved path and `metadata`, Unix), keep that file's +/// other attributes ([`keep_attributes`]) and flush it. Permission restoration is skipped when /// the mode already matches after `fill`; the group bits are dropped when the file cannot be put /// in the replaced file's group, so they never open the file to a group that was not granted -/// them. A leftover file with the same name is skipped. When any step fails, the temporary file -/// is removed. +/// them. A name something already has (a leftover file, a link, a folder) is skipped, never +/// opened, so nothing planted there receives or redirects the write. When any step fails, the +/// temporary file is removed. fn stage( fs: &dyn AtomicFs, dir: &Path, name: &str, path: &Path, - replaced: Option<&std::fs::Metadata>, + replaced: Option<(&Path, &std::fs::Metadata)>, new_permissions: NewFilePermissions, fill: impl FnOnce(&mut File) -> io::Result<()>, ) -> io::Result { let existed = replaced.is_some(); // Windows files carry only a read-only flag, and a read-only file can't be replaced. - let perms = replaced.filter(|_| cfg!(unix)).map(|m| m.permissions()); + let perms = replaced.filter(|_| cfg!(unix)).map(|(_, m)| m.permissions()); + // A folder or other non-file at the target has no attributes a stage could carry. + let keep = replaced.map(|(_, m)| m).filter(|m| m.is_file()); // New documents inherit the directory's policy directly: no probe or chmod is needed. // Existing destinations still stage privately, including when their final mode is shared. let creation = if existed { NewFilePermissions::Private } else { new_permissions }; for _ in 0..8 { let tmp = dir.join(temp_name(name)); - let mut file = match fs.create_new(&tmp, creation) { + let mut file = match fs.create_new_keeping(&tmp, creation, keep) { Ok(f) => f, - Err(e) if e.kind() == io::ErrorKind::AlreadyExists => continue, + Err(e) if name_taken(&e, &tmp) => continue, Err(e) => return Err(write_error(e, path, dir, existed)), }; let written = fill(&mut file) @@ -413,7 +452,7 @@ fn stage( } // The group bits belong to the replaced file's group, which a new // inode need not be in (setgid directory, another primary group). - if let Some(replaced) = replaced { + if let Some((_, replaced)) = replaced { let stage_gid = std::os::unix::fs::MetadataExt::gid(&file.metadata()?); let replaced_gid = std::os::unix::fs::MetadataExt::gid(replaced); let perms = adopt_group(fs, &file, stage_gid, replaced_gid, p)?; @@ -424,6 +463,7 @@ fn stage( }) .map_err(|e| permissions_error(e, path)) }) + .and_then(|()| keep_attributes(&file, replaced.filter(|(_, m)| m.is_file())).map_err(|e| attributes_error(e, path))) .and_then(|()| fs.sync(&file).map_err(|e| write_error(e, path, dir, existed))); #[allow( clippy::drop_non_drop, @@ -438,6 +478,143 @@ fn stage( Err(io::Error::new(io::ErrorKind::AlreadyExists, format!("{}: could not create a temporary file", dir.display()))) } +/// Whether creating the stage failed because something already has its name: a file, a link +/// (even a dangling one) or a folder. Windows reports a folder there as access denied. +fn name_taken(e: &io::Error, tmp: &Path) -> bool { + match e.kind() { + io::ErrorKind::AlreadyExists => true, + io::ErrorKind::PermissionDenied => cfg!(windows) && std::fs::symlink_metadata(tmp).is_ok(), + _ => false, + } +} + +/// The Windows attributes a replaced file passes on to its stage: hidden and system, the two that +/// say who should see the file. A read-only file is never replaced, the archive bit is the +/// system's to set on a changed file, and the others describe how the volume stores it. + +#[cfg(windows)] +const KEPT_ATTRIBUTES: u32 = 0x2 | 0x4; + +/// A server that hides dot-named files (Samba, NAS) marks the stage hidden and keeps the mark +/// through the rename: the saved file then gets the replaced file's attributes back. Only when the +/// kept bits differ, since restoring the whole attribute word on a local disk would clear the +/// archive bit backup tools read. Best effort: the new bytes are already in place. +#[cfg(windows)] +fn restore_kept_attributes(target: &Path, replaced: &std::fs::Metadata) { + use std::os::windows::fs::MetadataExt; + let saved = std::fs::symlink_metadata(target).map(|m| m.file_attributes() & KEPT_ATTRIBUTES); + if saved.is_ok_and(|bits| bits != replaced.file_attributes() & KEPT_ATTRIBUTES) { + let _ = std::fs::set_permissions(target, replaced.permissions()); + } +} + +/// Give the stage what the replaced regular file (`replaced`: its resolved path and `metadata`) +/// carries besides its bytes and mode, before the stage is flushed: on macOS its extended +/// attributes (`copy_xattrs`; an attribute that cannot be kept refuses the save), on macOS and +/// Windows its creation date (best effort: a volume that stores none keeps the stage's own). A +/// saved document is the same document. A new file has nothing to keep. +fn keep_attributes(stage: &File, replaced: Option<(&Path, &std::fs::Metadata)>) -> io::Result<()> { + let Some((target, meta)) = replaced else { return Ok(()) }; + #[cfg(target_os = "macos")] + copy_xattrs(target, stage)?; + #[cfg(not(target_os = "macos"))] + let _ = target; + #[cfg(any(target_os = "macos", windows))] + if let Ok(created) = meta.created() { + #[cfg(target_os = "macos")] + use std::os::macos::fs::FileTimesExt; + #[cfg(windows)] + use std::os::windows::fs::FileTimesExt; + let _ = stage.set_times(std::fs::FileTimes::new().set_created(created)); + } + #[cfg(not(any(target_os = "macos", windows)))] + let _ = (stage, meta); + Ok(()) +} + +/// The longest list of extended attribute names read from a replaced file. +#[cfg(target_os = "macos")] +const MAX_XATTR_NAMES_BYTES: usize = 64 * 1024; +/// The most extended attributes copied from a replaced file. +#[cfg(target_os = "macos")] +const MAX_XATTRS: usize = 1024; +/// The largest extended attribute value copied (a resource fork can be larger than ordinary ones). +#[cfg(target_os = "macos")] +const MAX_XATTR_VALUE_BYTES: usize = 16 * 1024 * 1024; +/// The most extended attribute bytes copied from one file in all. +#[cfg(target_os = "macos")] +const MAX_XATTR_TOTAL_BYTES: usize = 64 * 1024 * 1024; + +/// Copy the extended attributes of the regular file at `target` (Finder tags, the "Open with" +/// binding, quarantine, resource forks) to the stage. The attributes are as untrusted as the +/// bytes, so the reads are bounded; one that cannot be read or written whole, or passes a bound, +/// refuses the save rather than dropping the user's metadata unnoticed. Only a volume without +/// extended attributes (`ENOTSUP`) is skipped. `com.apple.provenance` belongs to macOS, which +/// gives the new file its own. Compression bookkeeping stays hidden (no `XATTR_SHOWCOMPRESSION`). +#[cfg(target_os = "macos")] +fn copy_xattrs(target: &Path, stage: &File) -> io::Result<()> { + use rustix::fs::{Mode, OFlags, XattrFlags, fgetxattr, fgetxattr_query, flistxattr, fsetxattr, open}; + use rustix::io::Errno; + + // Never read through a link: the target is already resolved, and a link swapped in since + // names another file. NONBLOCK keeps a FIFO put at the name from hanging the open. + let source = match open(target, OFlags::RDONLY | OFlags::CLOEXEC | OFlags::NOFOLLOW | OFlags::NONBLOCK, Mode::empty()) { + Ok(fd) => File::from(fd), + Err(Errno::NOENT | Errno::LOOP) => return Ok(()), + Err(e) => return Err(e.into()), + }; + if !source.metadata()?.is_file() { + return Ok(()); + } + let names_too_long = || io::Error::other("the extended attribute names exceed 64 KiB"); + let mut names = vec![0u8; MAX_XATTR_NAMES_BYTES]; + let len = match flistxattr(&source, names.as_mut_slice()) { + Ok(len) => len, + Err(Errno::NOTSUP) => return Ok(()), + Err(Errno::RANGE) => return Err(names_too_long()), + Err(e) => return Err(e.into()), + }; + let names = names.get(..len).ok_or_else(names_too_long)?; + let mut total = 0usize; + for (index, name) in names.split(|b| *b == 0).filter(|name| !name.is_empty()).enumerate() { + if index >= MAX_XATTRS { + return Err(io::Error::other("more than 1024 extended attributes")); + } + if name == b"com.apple.provenance" { + continue; + } + let name = std::ffi::CString::new(name).map_err(|_| io::Error::other("an extended attribute name is not valid"))?; + // An empty read buffer reads zero bytes in rustix, not the size: query it explicitly. + let size = fgetxattr_query(&source, &name)?; + if size > MAX_XATTR_VALUE_BYTES || size > MAX_XATTR_TOTAL_BYTES.saturating_sub(total) { + return Err(io::Error::other("the extended attributes exceed 16 MiB per value or 64 MiB in total")); + } + let value = read_xattr_value(size, |buffer| Ok(fgetxattr(&source, &name, buffer)?), || Ok(fgetxattr_query(&source, &name)?))?; + fsetxattr(stage, &name, &value, XattrFlags::empty())?; + total = total.saturating_add(value.len()); + } + Ok(()) +} + +/// Read one attribute value of `size` bytes (already within the bounds) with `read`, then ask +/// its size again with `query_size`. A read that does not fill `size`, or a size that changed, +/// is refused: a growing resource fork returns the prefix that fits instead of an error. +#[cfg(target_os = "macos")] +fn read_xattr_value( + size: usize, + read: impl FnOnce(&mut [u8]) -> io::Result, + query_size: impl FnOnce() -> io::Result, +) -> io::Result> { + let mut value = vec![0u8; size.max(1)]; + let len = read(value.as_mut_slice())?; + let after = query_size()?; + if len != size || after != size { + return Err(io::Error::other("an extended attribute changed size while saving")); + } + value.truncate(len); + Ok(value) +} + /// Exclusively creates and writes `path` with normal OS permissions, without replacing existing files. /// Use [`WriteOptions`] for private data. pub fn write_new(path: &Path, bytes: &[u8]) -> io::Result<()> { @@ -597,11 +774,18 @@ fn resolve_links(path: &Path) -> io::Result { Err(io::Error::new(io::ErrorKind::InvalidInput, format!("cannot save {}: too many levels of symbolic links", path.display()))) } -/// Generates a unique, hidden temporary file name beside `file`. +/// The most bytes of the target's name a temporary name keeps: with the leading `.`, the pid, the +/// counter and `.craft_tmp` the name stays within the 255-byte (Linux, macOS) and 255-unit +/// (Windows) limits however long the target's name is. +const TEMP_STEM_BYTES: usize = 128; + +/// Generates a unique, hidden temporary file name beside `file`: `.{file}.{pid}-{n}.craft_tmp`, +/// with `file` cut to its first 128 bytes between characters. pub fn temp_name(file: &str) -> String { static COUNTER: AtomicU64 = AtomicU64::new(0); let n = COUNTER.fetch_add(1, Ordering::Relaxed); - let stem: String = file.chars().take(64).collect(); + let end = file.char_indices().map(|(i, c)| i + c.len_utf8()).take_while(|&end| end <= TEMP_STEM_BYTES).last().unwrap_or(0); + let stem = file.get(..end).unwrap_or_default(); #[cfg(not(target_arch = "wasm32"))] let pid = std::process::id(); #[cfg(target_arch = "wasm32")] @@ -633,6 +817,11 @@ fn permissions_error(e: io::Error, path: &Path) -> io::Error { io::Error::new(e.kind(), msg) } +fn attributes_error(e: io::Error, path: &Path) -> io::Error { + let msg = format!("cannot save {}: the original's extended attributes cannot be kept ({e}){}", path.display(), unchanged(true)); + io::Error::new(e.kind(), msg) +} + fn read_only_error(e: io::Error, path: &Path) -> io::Error { let kept = unchanged(true); let msg = match e.kind() { diff --git a/crates/atomic/src/tests.rs b/crates/atomic/src/tests.rs index 6edcc5430f..78cc37ae16 100644 --- a/crates/atomic/src/tests.rs +++ b/crates/atomic/src/tests.rs @@ -241,6 +241,341 @@ fn temp_name_format_is_valid() { assert!(name.ends_with(".craft_tmp")); } +/// What a [`Planting`] filesystem puts at a stage name just before the stage is created there. +#[derive(Clone, Copy, Debug)] +enum Obstacle { + File, + Folder, + /// A link to the file `outside` beside the stage. + #[cfg(unix)] + Link, + /// A link to `missing` beside the stage, which does not exist. + #[cfg(unix)] + DanglingLink, +} + +/// The real filesystem, except that the first `obstacles.len()` stage names get an obstacle +/// planted at them first, as someone racing the save would. +struct Planting { + obstacles: Vec, + planted: std::cell::RefCell>, +} + +impl Planting { + fn new(obstacles: Vec) -> Self { + Self { obstacles, planted: Default::default() } + } + + fn plant(&self, at: &Path) -> io::Result<()> { + let next = self.planted.borrow().len(); + let Some(&obstacle) = self.obstacles.get(next) else { return Ok(()) }; + match obstacle { + Obstacle::File => std::fs::write(at, b"PLANTED")?, + Obstacle::Folder => std::fs::create_dir(at)?, + #[cfg(unix)] + Obstacle::Link => std::os::unix::fs::symlink(at.with_file_name("outside"), at)?, + #[cfg(unix)] + Obstacle::DanglingLink => std::os::unix::fs::symlink(at.with_file_name("missing"), at)?, + } + self.planted.borrow_mut().push(at.to_path_buf()); + Ok(()) + } +} + +impl AtomicFs for Planting { + fn create_new(&self, path: &Path, permissions: NewFilePermissions) -> io::Result { + self.plant(path)?; + RealFs.create_new(path, permissions) + } + fn sync(&self, file: &File) -> io::Result<()> { + RealFs.sync(file) + } + fn rename(&self, from: &Path, to: &Path) -> io::Result<()> { + RealFs.rename(from, to) + } + fn hard_link(&self, from: &Path, to: &Path) -> io::Result<()> { + RealFs.hard_link(from, to) + } + fn remove(&self, path: &Path) -> io::Result<()> { + RealFs.remove(path) + } + fn sync_dir(&self, dir: &Path) -> io::Result<()> { + RealFs.sync_dir(dir) + } + fn set_permissions(&self, file: &File, perms: std::fs::Permissions) -> io::Result<()> { + RealFs.set_permissions(file, perms) + } + #[cfg(unix)] + fn set_group(&self, file: &File, gid: u32) -> io::Result<()> { + RealFs.set_group(file, gid) + } +} + +/// A stage name something already has (a file, a folder, a link, a dangling link) is skipped, +/// never opened: writing through it would put the user's document where the planter chose. With +/// every name taken the save fails and the original is kept. +#[test] +fn a_name_taken_at_the_stage_is_skipped_and_never_written_through() { + let d = TempDir::new("planted"); + let p = d.0.join("doc.craft"); + let outside = d.0.join("outside"); + std::fs::write(&p, ORIGINAL).unwrap(); + std::fs::write(&outside, b"OUTSIDE").unwrap(); + + #[cfg(unix)] + let obstacles = vec![Obstacle::File, Obstacle::Folder, Obstacle::Link, Obstacle::DanglingLink]; + #[cfg(not(unix))] + let obstacles = vec![Obstacle::File, Obstacle::Folder]; + let fs = Planting::new(obstacles.clone()); + atomic_write_custom(&fs, NO_RETRY, &p, b"new").unwrap(); + assert_eq!(std::fs::read(&p).unwrap(), b"new"); + let planted = fs.planted.into_inner(); + assert_eq!(planted.len(), obstacles.len(), "every obstacle was met"); + for (at, obstacle) in planted.iter().zip(&obstacles) { + let meta = std::fs::symlink_metadata(at).unwrap(); + match obstacle { + Obstacle::File => assert_eq!(std::fs::read(at).unwrap(), b"PLANTED", "the planted file is not written"), + Obstacle::Folder => assert!(meta.is_dir() && std::fs::read_dir(at).unwrap().next().is_none(), "the folder is left empty"), + #[cfg(unix)] + Obstacle::Link | Obstacle::DanglingLink => assert!(meta.file_type().is_symlink(), "the link is left as a link"), + } + } + assert_eq!(std::fs::read(&outside).unwrap(), b"OUTSIDE", "nothing was written through a link"); + assert!(!outside.with_file_name("missing").exists(), "a dangling link's file was not created"); + for at in &planted { + let _ = std::fs::remove_file(at).or_else(|_| std::fs::remove_dir(at)); + } + assert_no_temp(&d.0); + + // Every name taken: the save is refused and the original kept. + let fs = Planting::new(vec![Obstacle::File; 64]); + let e = atomic_write_custom(&fs, NO_RETRY, &p, b"newer").unwrap_err(); + assert_eq!(e.kind(), io::ErrorKind::AlreadyExists, "{e}"); + assert_eq!(std::fs::read(&p).unwrap(), b"new"); + for at in fs.planted.into_inner() { + assert_eq!(std::fs::read(&at).unwrap(), b"PLANTED"); + let _ = std::fs::remove_file(at); + } + assert_no_temp(&d.0); +} + +/// A name near the 255-byte limit, in four-byte characters, still stages: the temporary name +/// keeps at most 128 bytes of it, cut between characters, and only the target is left. +#[test] +fn a_long_name_stages_and_leaves_only_the_target() { + let d = TempDir::new("long-name"); + // 2 + 61 × 4 + 4 = 250 bytes, 67 characters: the first 64 characters alone are 247 bytes. + let name = format!("ab{}.pdf", "\u{1F600}".repeat(61)); + assert_eq!(name.len(), 250); + let p = d.0.join(&name); + atomic_write(&p, b"first").unwrap(); + atomic_write(&p, b"second").unwrap(); + assert_eq!(std::fs::read(&p).unwrap(), b"second"); + let left: Vec<_> = std::fs::read_dir(&d.0).unwrap().map(|e| e.unwrap().file_name()).collect(); + assert_eq!(left, [std::ffi::OsString::from(&name)], "only the target is left"); + + let staged = temp_name(&name); + assert!(staged.len() <= 255, "{} bytes", staged.len()); + assert!(staged.starts_with(&format!(".ab{}.", "\u{1F600}".repeat(31))), "128 bytes of the name, cut between characters: {staged}"); +} + +/// Reads the extended attribute `name` of `path`, following no further than the path itself. +#[cfg(target_os = "macos")] +fn xattr(path: &Path, name: &str) -> Option> { + let size = rustix::fs::getxattr_query(path, name).ok()?; + let mut value = vec![0u8; size.max(1)]; + let len = rustix::fs::getxattr(path, name, &mut value[..]).ok()?; + value.truncate(len); + Some(value) +} + +/// A save keeps the replaced file's extended attributes (Finder tags, the "Open with" binding, +/// quarantine, binary, empty and resource-fork values), save after save, including one another +/// process sets while the stage is written. Through a symbolic link the link stays and the file it +/// names keeps them. A link swapped in at the target while staging is never read through: its +/// file's attributes stay its own. (`com.apple.provenance` cannot be set by a test; a file that +/// has it saves only because the copy skips it, as macOS refuses writing it.) +#[cfg(target_os = "macos")] +#[test] +fn attributes_set_while_staging_are_kept() { + use rustix::fs::{XattrFlags, setxattr}; + let d = TempDir::new("xattrs"); + let target = d.0.join("doc.pdf"); + std::fs::write(&target, ORIGINAL).unwrap(); + let attributes: &[(&str, &[u8])] = &[ + ("com.apple.metadata:_kMDItemUserTags", b"Craft\n6"), + ("com.apple.LaunchServices.OpenWith", b"bplist00\xd1\x01\x02Wversion\x10\x00"), + ("com.apple.quarantine", b"0081;5e0d1d05;Craft;"), + ("com.craft.test.binary", b"\0\xff\x80original\0"), + ("com.craft.test.empty", b""), + ("com.apple.ResourceFork", b"\0\xfffork"), + ]; + for (name, value) in attributes { + setxattr(&target, *name, value, XattrFlags::empty()).unwrap(); + } + // What the system stored (quarantine may be normalised): the saved file must hold the same. + let stored: Vec<_> = attributes.iter().map(|(name, _)| (*name, xattr(&target, name).unwrap())).collect(); + + for save in 0..2 { + atomic_write_with(&target, |f| { + // Another process tags the original while the new bytes are written. + setxattr(&target, "com.craft.test.late", format!("late {save}").as_bytes(), XattrFlags::empty())?; + f.write_all(b"new") + }) + .unwrap(); + assert_eq!(std::fs::read(&target).unwrap(), b"new"); + for (name, value) in &stored { + assert_eq!(xattr(&target, name).as_ref(), Some(value), "save {save} keeps {name}"); + } + assert_eq!(xattr(&target, "com.craft.test.late"), Some(format!("late {save}").into_bytes()), "set while staging"); + assert_no_temp(&d.0); + } + + // Through a link: the link stays, the file it names is replaced and keeps its attributes. + let link = d.0.join("link.pdf"); + std::os::unix::fs::symlink(&target, &link).unwrap(); + atomic_write(&link, b"through the link").unwrap(); + assert!(std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink(), "the link stays a link"); + assert_eq!(std::fs::read(&target).unwrap(), b"through the link"); + for (name, value) in &stored { + assert_eq!(xattr(&target, name).as_ref(), Some(value), "the linked file keeps {name}"); + } + + // A link put at the target while staging names another file: nothing is read through it. + let outside = d.0.join("outside.pdf"); + std::fs::write(&outside, b"OUTSIDE").unwrap(); + setxattr(&outside, "com.craft.test.private", b"private", XattrFlags::empty()).unwrap(); + atomic_write_with(&target, |f| { + std::fs::remove_file(&target)?; + std::os::unix::fs::symlink(&outside, &target)?; + f.write_all(b"swapped") + }) + .unwrap(); + assert_eq!(std::fs::read(&outside).unwrap(), b"OUTSIDE"); + assert_eq!(xattr(&outside, "com.craft.test.private"), Some(b"private".to_vec())); + assert!(!std::fs::symlink_metadata(&target).unwrap().file_type().is_symlink()); + assert_eq!(xattr(&target, "com.craft.test.private"), None, "the swapped-in link's file lent nothing"); + assert_no_temp(&d.0); +} + +/// An attribute past the 16 MiB value bound refuses the save instead of dropping it: the target +/// keeps its bytes and its attribute, and no stage is left. +#[cfg(target_os = "macos")] +#[test] +fn oversized_attributes_refuse_the_save_and_keep_the_target() { + use rustix::fs::{XattrFlags, getxattr_query, setxattr}; + let d = TempDir::new("xattrs-bound"); + let target = d.0.join("doc.pdf"); + std::fs::write(&target, ORIGINAL).unwrap(); + // Only a resource fork may be this large; the bytes exist only in this temporary file. + let fork = vec![42u8; 16 * 1024 * 1024 + 1]; + setxattr(&target, "com.apple.ResourceFork", &fork, XattrFlags::empty()).unwrap(); + let e = atomic_write(&target, b"new").unwrap_err(); + assert!(e.to_string().contains("extended attributes"), "{e}"); + assert_eq!(std::fs::read(&target).unwrap(), ORIGINAL); + assert_eq!(getxattr_query(&target, "com.apple.ResourceFork").unwrap(), fork.len()); + assert_no_temp(&d.0); +} + +/// A value read must fill the size first queried and keep it in a second query: a growing +/// resource fork returns the prefix that fits instead of an error. Complete values, empty and +/// binary, are kept as read. +#[cfg(target_os = "macos")] +#[test] +fn an_attribute_read_must_fill_its_size_and_keep_it() { + for bytes in [&b""[..], &b"\0\xffB"[..]] { + let value = read_xattr_value( + bytes.len(), + |buffer| { + buffer[..bytes.len()].copy_from_slice(bytes); + Ok(bytes.len()) + }, + || Ok(bytes.len()), + ) + .unwrap(); + assert_eq!(value, bytes); + } + // A short read, a size that grew after the read, a prefix of a grown value. + for (before, read_len, after) in [(3, 2, 3), (3, 3, 4), (0, 1, 1), (3, 2, 2)] { + let e = read_xattr_value(before, |_| Ok(read_len), || Ok(after)).unwrap_err(); + assert!(e.to_string().contains("changed size"), "{before} {read_len} {after}: {e}"); + } + let e = read_xattr_value(3, |_| Ok(3), || Err(io::Error::new(io::ErrorKind::PermissionDenied, "recheck refused"))).unwrap_err(); + assert_eq!(e.kind(), io::ErrorKind::PermissionDenied); +} + +/// A saved document is the same document: it keeps its creation date. A new file gets its own. +#[cfg(any(target_os = "macos", windows))] +#[test] +fn a_replaced_files_creation_date_is_kept() { + #[cfg(target_os = "macos")] + use std::os::macos::fs::FileTimesExt; + #[cfg(windows)] + use std::os::windows::fs::FileTimesExt; + let d = TempDir::new("created"); + let target = d.0.join("doc.pdf"); + std::fs::write(&target, ORIGINAL).unwrap(); + // 2020-01-02 03:04:05 UTC. + let then = std::time::SystemTime::UNIX_EPOCH + std::time::Duration::from_secs(1_577_934_245); + let file = OpenOptions::new().write(true).open(&target).unwrap(); + file.set_times(std::fs::FileTimes::new().set_created(then)).unwrap(); + drop(file); + assert_eq!(std::fs::metadata(&target).unwrap().created().unwrap(), then, "the fixture's date is set"); + atomic_write(&target, b"new").unwrap(); + assert_eq!(std::fs::read(&target).unwrap(), b"new"); + assert_eq!(std::fs::metadata(&target).unwrap().created().unwrap(), then, "the saved file keeps its creation date"); + let fresh = d.0.join("new.pdf"); + atomic_write(&fresh, b"new").unwrap(); + assert!(std::fs::metadata(&fresh).unwrap().created().unwrap() > then, "a new file has a date of its own"); +} + +/// A hidden or system file stays hidden or system, and its stage already is while written; a +/// plain file stays plain though the stage's name starts with a dot; a new file gets neither. +/// Through a symbolic link the file it names is the replaced file and keeps its attributes. +#[cfg(windows)] +#[test] +fn hidden_and_system_attributes_are_kept() { + use std::os::windows::fs::{MetadataExt, OpenOptionsExt}; + const HIDDEN: u32 = 0x2; + const SYSTEM: u32 = 0x4; + let d = TempDir::new("attributes"); + let kept = |p: &Path| std::fs::metadata(p).unwrap().file_attributes() & (HIDDEN | SYSTEM); + let plant = |p: &Path, attributes: u32| { + let mut fixture = OpenOptions::new().write(true).create_new(true).attributes(attributes).open(p).unwrap(); + fixture.write_all(ORIGINAL).unwrap(); + }; + for (i, keep) in [0, HIDDEN, SYSTEM, HIDDEN | SYSTEM].into_iter().enumerate() { + let target = d.0.join(format!("doc{i}.pdf")); + plant(&target, keep); + assert_eq!(kept(&target), keep, "the fixture has attributes {keep:#x}"); + let mut staged = u32::MAX; + atomic_write_with(&target, |f| { + staged = f.metadata()?.file_attributes() & (HIDDEN | SYSTEM); + f.write_all(b"new") + }) + .unwrap(); + assert_eq!(staged, keep, "the stage has the target's attributes before it is flushed"); + assert_eq!(kept(&target), keep, "the saved file keeps attributes {keep:#x}"); + assert_eq!(std::fs::read(&target).unwrap(), b"new"); + } + let fresh = d.0.join("new.pdf"); + atomic_write(&fresh, b"new").unwrap(); + assert_eq!(kept(&fresh), 0, "a new file is neither hidden nor system"); + + let referent = d.0.join("referent.pdf"); + plant(&referent, HIDDEN); + let link = d.0.join("link.pdf"); + if let Err(e) = std::os::windows::fs::symlink_file(&referent, &link) { + eprintln!("skipped the link case: creating a symbolic link needs Developer Mode or administrator rights ({e})"); + return; + } + atomic_write(&link, b"through the link").unwrap(); + assert!(std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink(), "the link stays a link"); + assert_eq!(std::fs::read(&referent).unwrap(), b"through the link"); + assert_eq!(kept(&referent), HIDDEN, "the file the link names stays hidden"); + assert_no_temp(&d.0); +} + #[cfg(target_arch = "wasm32")] #[test] fn wasm_atomic_write_returns_unsupported() { diff --git a/crates/automation/Cargo.toml b/crates/automation/Cargo.toml index e374c4c20d..7fd0ce225b 100644 --- a/crates/automation/Cargo.toml +++ b/crates/automation/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "craft-automation" -description = "Drive a running Craft app from tests, agents and the CLI (control channel, screenshot queue, frame profiler and frame trace; native only), and recorded actions with the Actions panel (every target)." +description = "Drive a running Craft app from tests, agents and the CLI (control channel, screenshot queue and synthetic input on every target; server, client, frame profiler and frame trace native only), and recorded actions with the Actions panel (every target)." version.workspace = true edition.workspace = true license.workspace = true @@ -22,7 +22,7 @@ default = [] # The egui parts: the Actions panel, the control channel's server side (screenshots, synthetic # input) and `ui` stories. Without it the crate has no egui: `ControlOptions`, `ControlClient`, # `Params` and the recorded actions' model and files. -ui = ["dep:craft-behavior", "dep:craft-keymap", "dep:craft-ui", "dep:egui"] +ui = ["dep:craft-behavior", "dep:craft-keymap", "dep:craft-ui", "dep:egui", "dep:craft-host"] # The Actions panel's and the Agents page's stories and mock, and the integration binary `tests/it`. screen-testing = ["ui", "agents", "craft-ui/testing"] # Agents in the open window (desktop): the ArtCraft Launcher's switch, the connection file an @@ -31,25 +31,27 @@ screen-testing = ["ui", "agents", "craft-ui/testing"] agents = ["craft-control/agents", "dep:craft-host"] [dependencies] +# The screenshot reply's PNG and its inline base64 (the control channel builds on every target with `ui`). +base64 = "0.23" craft-behavior = { workspace = true, optional = true } # The agents code without a UI toolkit (settings, the launcher's switch, the connection file, the # CLI's live client), re-exported by `agents` so every app shares one copy. craft-control = { workspace = true } +# The recorded actions' file picks (`ui`) go through the host on every target. +craft-host = { workspace = true, optional = true } craft-keymap = { workspace = true, optional = true } craft-theme = { workspace = true } craft-ui = { workspace = true, optional = true } egui = { workspace = true, optional = true } +png = "0.17" serde = { workspace = true } serde_json = { workspace = true } -# The screenshot queue encodes and inlines PNGs on every target the control channel builds for. -base64 = "0.22" -craft-host = { workspace = true, optional = true } craft-platform = { workspace = true } log = "0.4" -png = "0.17" +# `std::time::Instant` panics on wasm; this is the same type on native. web-time = "1.1" -# The server, client, profiler and trace. +# The server, client, token files, profiler and trace. [target.'cfg(not(target_arch = "wasm32"))'.dependencies] getrandom = "0.3" hmac = "0.12" diff --git a/crates/automation/src/access.rs b/crates/automation/src/access.rs index f37f24c866..d25f93d112 100644 --- a/crates/automation/src/access.rs +++ b/crates/automation/src/access.rs @@ -1,11 +1,15 @@ -//! Named controls over the window's access tree: the controls a client finds by name and role, describes, and places -//! a pointer on. Built with the in-process channel, under the `ui` feature. +//! Named controls over the window's access tree (`ui.find`, `control` targets) and `ui.inspect` (the reported +//! widgets of a window's access tree, and the lookup of the one node a click or a focus names). +//! +//! Both read the tree the window host keeps from the last presented frame ([`WindowHost::keep_access_tree`], which +//! the control server turns on) and walk only the nodes assistive technology reports ([`AccessTree::keys`]): a hidden node, +//! one below it and one behind an open modal are neither listed nor reachable. use std::collections::HashSet; use craft_behavior::Mixed; use craft_ui::runtime::access::Role; -use craft_ui::runtime::egui::access::{AccessTree, NodeKey, name}; +use craft_ui::runtime::egui::access::{AccessTree, Declared, NodeKey, name}; use craft_ui::runtime::windows::WindowHost; use egui::{Rect, ViewportId}; use serde_json::{Map, Value, json}; @@ -27,6 +31,9 @@ pub const NO_PLACE: &str = "the control has no place on the screen"; /// The largest `index` a target takes. pub const MAX_INDEX: usize = 1024; +/// The widgets `ui.inspect` lists when the request names no `limit`. +pub const DEFAULT_LIMIT: u64 = 500; + /// The place of a control a target names: its rect in screen points, or the error why it has none. pub type ControlMap<'a> = &'a dyn Fn(&Target) -> Result; @@ -54,7 +61,110 @@ fn plain(text: &str) -> &str { text.strip_suffix(':').unwrap_or(text).trim() } -/// The AccessKit role name of a node, as `role` fields spell it. +/// The node a method names: its id or its label. +#[derive(Clone, Debug, PartialEq, Eq)] +pub enum NodeTarget { + /// The node's id. + Id(u64), + /// The node's label, matched case-insensitively. + Label(String), +} + +impl NodeTarget { + /// The node `params` name (`id` or `label`), or none when they name none. `id` is the id `ui.inspect` lists, a + /// decimal string or a number; `label` is a string; naming both is an error. Other fields are the caller's to + /// check; a `null` field is absent. + pub fn from_params(params: &Value) -> Result, String> { + let field = |key: &str| params.get(key).filter(|value| !value.is_null()); + match (field("id"), field("label")) { + (Some(_), Some(_)) => Err("`id` and `label` exclude each other".into()), + (Some(id), None) => { + let raw = id.as_u64().or_else(|| id.as_str().and_then(|text| text.parse().ok())); + raw.map(|raw| Some(NodeTarget::Id(raw))).ok_or_else(|| "id must be a widget id from ui.inspect".into()) + } + (None, Some(Value::String(label))) => Ok(Some(NodeTarget::Label(label.clone()))), + (None, Some(_)) => Err("label must be a string".into()), + (None, None) => Ok(None), + } + } +} + +/// What a node that takes `action` is, for the refusal of one that does not. +fn able(action: Declared) -> &'static str { + match action { + Declared::Click => "clickable", + Declared::Focus => "focusable", + Declared::ContextMenu => "a widget with a context menu", + _ => "a widget that takes this action", + } +} + +/// Queues `action` on the node `target` names in `viewport`'s kept access tree. +fn inject_node(host: &WindowHost, viewport: ViewportId, target: &NodeTarget, action: Declared) -> Result<(), String> { + let tree = host.access_tree_view(viewport).ok_or_else(|| NO_TREE.to_owned())?; + let node = resolve(&tree, target, action)?; + host.inject_access(viewport, node, action); + Ok(()) +} + +/// Queues a click of the node `target` names in `viewport`, once the kept tree has it as one reported, enabled, +/// clickable node ([`resolve`]). +pub fn inject_click(host: &WindowHost, viewport: ViewportId, target: &NodeTarget) -> Result<(), String> { + inject_node(host, viewport, target, Declared::Click) +} + +/// Queues the context menu of the node `target` names in `viewport`, once the kept tree has it as one reported, +/// enabled node with a context menu ([`resolve`]). +pub fn inject_context_menu(host: &WindowHost, viewport: ViewportId, target: &NodeTarget) -> Result<(), String> { + inject_node(host, viewport, target, Declared::ContextMenu) +} + +/// Queues the focus request for the node `target` names in `viewport`, once the kept tree has it as one reported, +/// enabled, focusable node ([`resolve`]). +pub fn inject_focus(host: &WindowHost, viewport: ViewportId, target: &NodeTarget) -> Result<(), String> { + inject_node(host, viewport, target, Declared::Focus) +} + +/// The one reported, enabled node of `tree` that declares `action` and that `target` names; an error names none, +/// several, disabled or undeclared. An id must be a reported node; a label matches the reported, enabled nodes that +/// declare `action` and whose label equals it, ignoring case, and exactly one must match. +pub fn resolve(tree: &AccessTree, target: &NodeTarget, action: Declared) -> Result { + let reported = tree.keys(); + let label_of = |key: NodeKey| tree.name_of(key).unwrap_or("unlabelled").to_owned(); + let key = match target { + NodeTarget::Id(raw) => { + let key = NodeKey::from_raw(*raw); + if !reported.contains(&key) { + return Err(format!("no widget with id {raw} on screen (run ui.inspect again)")); + } + key + } + NodeTarget::Label(label) => { + let wanted = label.to_lowercase(); + let named: Vec = + reported.iter().copied().filter(|key| tree.name_of(*key).is_some_and(|name| name.to_lowercase() == wanted)).collect(); + let usable: Vec = named.iter().copied().filter(|key| !tree.is_disabled_key(*key) && tree.declares_key(*key, action)).collect(); + match usable.as_slice() { + [one] => *one, + [] if named.is_empty() => return Err(format!("no widget labelled {label:?} on screen (try ui.inspect with query)")), + [] if named.iter().any(|key| tree.declares_key(*key, action)) => { + return Err(format!("the widget labelled {label:?} is disabled")); + } + [] => return Err(format!("the widget labelled {label:?} is not {}", able(action))), + many => return Err(format!("{} widgets are labelled {label:?}; name one by id", many.len())), + } + } + }; + if tree.is_disabled_key(key) { + return Err(format!("widget {} ({}) is disabled", key.raw(), label_of(key))); + } + if !tree.declares_key(key, action) { + return Err(format!("widget {} ({}) is not {}", key.raw(), label_of(key), able(action))); + } + Ok(key) +} + +/// The accesskit role's name as agents' scripts read it (`Button`, `CheckBox`). fn role_name(tree: &AccessTree, key: NodeKey) -> Option { match tree.role_of(key)? { Role::Node(role) => Some(format!("{role:?}")), @@ -191,3 +301,90 @@ fn find(params: &Value, host: &WindowHost, viewport: ViewportId) -> Result Value { + let mut w = Map::new(); + w.insert("id".into(), json!(key.raw().to_string())); + w.insert("role".into(), json!(role_name(tree, key))); + w.insert("depth".into(), json!(depth)); + w.insert("enabled".into(), json!(!tree.is_disabled_key(key))); + w.insert("clickable".into(), json!(tree.declares_key(key, Declared::Click))); + w.insert("focusable".into(), json!(tree.declares_key(key, Declared::Focus))); + if let Some(label) = tree.name_of(key) { + w.insert("label".into(), json!(label)); + } + if let Some(value) = tree.value_of(key) { + w.insert("value".into(), json!(value)); + } + if let Some(description) = tree.description_of(key) { + w.insert("description".into(), json!(description)); + } + if let Some(rect) = tree.bounds_of(key) { + w.insert("rect".into(), json!([rect.min.x, rect.min.y, rect.max.x, rect.max.y])); + } + if let Some(toggled) = tree.toggled_of(key) { + let toggled = match toggled { + Mixed::Same(true) => "true", + Mixed::Same(false) => "false", + Mixed::Mixed => "mixed", + }; + w.insert("toggled".into(), json!(toggled)); + } + if let Some(selected) = tree.selected_of(key) { + w.insert("selected".into(), json!(selected)); + } + if focused { + w.insert("focused".into(), json!(true)); + } + Value::Object(w) +} + +/// `inspect {query?, role?, focused?, limit?=500}`: the reply `{widgets, count, truncated}` over the reported nodes +/// of `viewport`'s access tree, in tree order (depth first from the root, which is not listed, children in their +/// order). `query` matches a widget whose label, value or description contains it, ignoring case; `role` its role's +/// name, ignoring case; `focused` whether it is the focused node. `count` is every widget the filters keep, `widgets` +/// the first `limit` of them. No other fields; [`NO_TREE`] before the window presented a frame. +pub fn inspect(host: &WindowHost, viewport: ViewportId, params: &Value) -> Result { + let p = Params(params).only(None, &["query", "role", "focused", "limit"])?; + let p = Params(&p); + let query = p.str_field("query")?.map(str::to_lowercase); + let role = p.str_field("role")?.map(str::to_lowercase); + let focused = p.bool_field("focused")?; + let limit = usize::try_from(p.uint_field("limit")?.unwrap_or(DEFAULT_LIMIT)).unwrap_or(usize::MAX); + let tree = host.access_tree_view(viewport).ok_or_else(|| NO_TREE.to_owned())?; + + let reported: HashSet = tree.keys().into_iter().collect(); + let root = tree.root_key(); + let focus = tree.focused_key(); + let (mut widgets, mut count) = (Vec::new(), 0usize); + // A stack, not recursion: the tree comes from the app and may be deep. `walked` keeps a malformed tree that lists + // a node twice from listing it twice or looping. + let mut walked = HashSet::new(); + let mut pending: Vec<(NodeKey, usize)> = root.into_iter().map(|key| (key, 0)).collect(); + while let Some((key, depth)) = pending.pop() { + if !reported.contains(&key) || !walked.insert(key) { + continue; + } + pending.extend(tree.children_of(key).into_iter().rev().map(|child| (child, depth + 1))); + if Some(key) == root { + continue; + } + let text = + [tree.name_of(key), tree.value_of(key), tree.description_of(key)].into_iter().flatten().collect::>().join(" ").to_lowercase(); + let keep = query.as_ref().is_none_or(|query| text.contains(query.as_str())) + && role.as_ref().is_none_or(|role| role_name(&tree, key).is_some_and(|name| name.to_lowercase() == *role)) + && focused.is_none_or(|wanted| (key == focus) == wanted); + if !keep { + continue; + } + count += 1; + if widgets.len() < limit { + widgets.push(widget(&tree, key, depth, key == focus)); + } + } + Ok(json!({"widgets": widgets, "count": count, "truncated": count > widgets.len()})) +} diff --git a/crates/automation/src/control.rs b/crates/automation/src/control.rs index 12d57a2247..b1c005dadf 100644 --- a/crates/automation/src/control.rs +++ b/crates/automation/src/control.rs @@ -20,7 +20,7 @@ use craft_ui::runtime::windows::WindowHost; use serde_json::{Value, json}; use web_time::Instant; -use crate::screenshot::{Captures, DocumentId, Finished, ScreenshotRequest, screenshot_reply}; +use crate::screenshot::{Captures, DocumentId, Finished, ScreenshotParams, ScreenshotRequest, screenshot_reply}; use crate::synthetic::TARGET_CHANGED; /// A reply: the JSON object the transport writes as one line. @@ -112,13 +112,16 @@ pub enum Reply { /// Reply with this JSON now. Done(Value), /// A `ui.screenshot`: admit `token` to the queue; `path` is where the app's write authority - /// puts the PNG, `None` inlines it as base64 in the reply. + /// puts the PNG, `None` inlines it as base64 in the reply; `region` is refused at admission + /// when it lies outside the window. #[non_exhaustive] Screenshot { /// Identifies the capture; must differ from every pending token. token: u64, /// File to write the PNG to, or `None` to inline it. path: Option, + /// The part of the window to capture, in points; `None` captures the whole window. + region: Option, /// The viewport to capture. viewport: egui::ViewportId, }, @@ -138,10 +141,10 @@ impl Reply { Reply::AccessTree } - /// A `ui.screenshot` reply for `token` of `viewport`, writing the PNG to `path` or inlining it - /// when `None`. - pub fn screenshot(token: u64, path: Option, viewport: egui::ViewportId) -> Self { - Self::Screenshot { token, path, viewport } + /// A `ui.screenshot` reply for `token` of `viewport` with what [`ScreenshotParams::from_params`] read: the PNG + /// goes to `params.path` or is inlined when `None`, and shows `params.region` or the whole window. + pub fn screenshot(token: u64, params: ScreenshotParams, viewport: egui::ViewportId) -> Self { + Self::Screenshot { token, path: params.path, region: params.region, viewport } } /// `Done` with the [`result_reply`] of a method's result. @@ -207,8 +210,9 @@ impl ControlChannel { Reply::AfterInput => self.input_waiters.push(reply), Reply::AfterJob(job) => self.job_waiters.push((job, reply)), Reply::AccessTree => self.tree_waiters.push(reply), - Reply::Screenshot { token, path, viewport } => { - if let Err((reply, e)) = self.captures.admit(ScreenshotRequest { token, path, viewport, reply, document, settle_ms }, motion::now()) { + Reply::Screenshot { token, path, region, viewport } => { + let request = ScreenshotRequest { token, path, region, viewport, reply, document, settle_ms }; + if let Err((reply, e)) = self.captures.admit(request, motion::now()) { let _ = reply.send(json!({"ok": false, "error": e})); } } @@ -316,7 +320,7 @@ impl ControlChannel { pub fn finish_captures(&mut self, finished: Vec, write: &mut crate::screenshot::PngWriter<'_>) { for f in finished { let reply = match f.result { - Ok(image) => screenshot_reply(f.token, image, f.path.as_deref(), write), + Ok(image) => screenshot_reply(f.token, image, f.region, f.geometry, f.path.as_deref(), write), Err(e) => json!({"ok": false, "error": e}), }; if let Some(tx) = f.reply { diff --git a/crates/automation/src/dock.rs b/crates/automation/src/dock.rs new file mode 100644 index 0000000000..4b8bcbcd49 --- /dev/null +++ b/crates/automation/src/dock.rs @@ -0,0 +1,47 @@ +//! `ui.dock.apply`: one dock action applied to the app's workspace, and the workspace's `ui.inspect` listing. + +use std::hash::Hash; + +use craft_behavior::dock::{Action, Workspace}; +use craft_ui::docking::PanelSpecs; +use serde::Serialize; +use serde::de::DeserializeOwned; +use serde_json::{Value, json}; + +use crate::protocol::Params; + +/// `ui.dock.apply {action}`: deserializes one dock action and applies it to `workspace` with the permissions `specs` +/// gives, as the dock area does. It returns `Ok({applied: [...]})`, the panels the action closed, in group order; an +/// error is the dock error's text. `None` for any other method. +pub fn dock_method( + workspace: &mut Workspace

, + specs: &impl PanelSpecs

, + locked: bool, + method: &str, + params: &Value, +) -> Option> { + if method != "ui.dock.apply" { + return None; + } + Some(apply(workspace, specs, locked, params)) +} + +fn apply( + workspace: &mut Workspace

, + specs: &impl PanelSpecs

, + locked: bool, + params: &Value, +) -> Result { + let params = Params(params).only(None, &["action"])?; + let action = params.get("action").cloned().ok_or("missing `action`")?; + let action: Action

= serde_json::from_value(action).map_err(|e| format!("`action` is not a dock action: {e}"))?; + let applied = workspace.apply(action, locked, |panel| specs.permissions(panel)).map_err(|e| e.to_string())?; + let applied = serde_json::to_value(applied).map_err(|e| e.to_string())?; + Ok(json!({ "applied": applied })) +} + +/// The `dock` field of the app's one `ui.inspect`: the workspace as JSON. +pub fn inspect(workspace: &Workspace

) -> Value { + // A panel id that cannot be written lists the dock as null rather than failing the whole `ui.inspect`. + serde_json::to_value(workspace).unwrap_or(Value::Null) +} diff --git a/crates/automation/src/files.rs b/crates/automation/src/files.rs new file mode 100644 index 0000000000..0d97d9d8e3 --- /dev/null +++ b/crates/automation/src/files.rs @@ -0,0 +1,50 @@ +//! `ui.pick`: answers the next file picker of a running app. + +use std::fmt::Display; +use std::path::PathBuf; + +use craft_host::{FileError, Files, Picked}; +use serde_json::{Value, json}; + +use crate::protocol::Params; + +/// The fields of `ui.pick`, of which a request names exactly one. +const FIELDS: [&str; 4] = ["files", "folder", "save", "cancel"]; + +/// `None` for any method other than `ui.pick`. `ui.pick` takes exactly one of `{files: [path, ..]}`, `{folder: path}`, +/// `{save: path}` or `{cancel: true}` and answers through `Files::answer_next` with `Picked::Paths` or `Cancelled`. +/// Paths are taken as given; the service settles them as it would a panel's answer. +pub fn pick_method(files: &dyn Files, method: &str, params: &Value) -> Option> { + (method == "ui.pick").then(|| pick(files, params)) +} + +fn pick(files: &dyn Files, params: &Value) -> Result { + let params = Params(params).only(None, &FIELDS)?; + let read = Params(¶ms); + let given: Vec<&str> = FIELDS.iter().copied().filter(|field| params.get(*field).is_some()).collect(); + let [field] = given.as_slice() else { return Err(refused("give exactly one field")) }; + let picked = match *field { + "files" => Picked::Paths(paths(params.get("files"))?), + "cancel" => match read.bool_field("cancel").map_err(refused)? { + Some(true) => Picked::Cancelled, + _ => return Err(refused("cancel must be true")), + }, + one => Picked::Paths(vec![PathBuf::from(read.str_field(one).map_err(refused)?.ok_or_else(|| refused(format!("missing `{one}`")))?)]), + }; + files.answer_next(picked).map_err(|e| match e { + FileError::Unsupported => "this window's file service takes no automated answers".to_owned(), + other => other.to_string(), + })?; + Ok(json!({"answered": "next"})) +} + +/// `files` as a non-empty list of paths. +fn paths(files: Option<&Value>) -> Result, String> { + let list = files.and_then(Value::as_array).filter(|list| !list.is_empty()); + let paths = list.and_then(|list| list.iter().map(|path| path.as_str().map(PathBuf::from)).collect::>>()); + paths.ok_or_else(|| refused("files must be a non-empty array of path strings")) +} + +fn refused(why: impl Display) -> String { + format!("{why}; ui.pick takes exactly one of: {}", FIELDS.join(", ")) +} diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rs index 21fa503cc1..97a14d3103 100644 --- a/crates/automation/src/lib.rs +++ b/crates/automation/src/lib.rs @@ -3,7 +3,10 @@ //! Drive a running Craft app from tests, agents and the CLI, and record and play actions. //! //! [`actions`] and [`ui::actions`] build on every target: the recorded-action list, its player -//! and the Actions panel; so do the agent settings in [`agents`]. The rest is desktop only. +//! and the Actions panel; so do the agent settings in [`agents`] and, with `ui`, the control +//! channel, its screenshots, synthetic input and the access-tree lookups (a web page feeds +//! [`control::ControlChannel`] from its own request queue). The server, client, token files, +//! profiler and trace are desktop only. //! //! A transport thread ([`server`], or a channel in tests) turns each JSON line into a //! [`control::ControlRequest`]; the UI thread drains them between frames through @@ -29,6 +32,10 @@ pub mod args; pub mod control; #[cfg(feature = "ui")] pub mod dialogs; +#[cfg(all(feature = "ui", not(target_arch = "wasm32")))] +pub mod dock; +#[cfg(feature = "ui")] +pub mod files; #[cfg(not(target_arch = "wasm32"))] pub mod profiler; pub mod protocol; @@ -40,6 +47,8 @@ pub mod security; pub mod synthetic; #[cfg(not(target_arch = "wasm32"))] pub mod trace; +#[cfg(all(feature = "ui", not(target_arch = "wasm32")))] +pub mod window; #[cfg(not(target_arch = "wasm32"))] pub mod client; diff --git a/crates/automation/src/screenshot.rs b/crates/automation/src/screenshot.rs index 292ecab600..2b37383a8e 100644 --- a/crates/automation/src/screenshot.rs +++ b/crates/automation/src/screenshot.rs @@ -1,7 +1,8 @@ //! `ui.screenshot`: bounded, cancellable capture requests over [`WindowHost::screenshot`]. //! //! The slot correlates one capture with one image. This queue owns what the slot leaves to the -//! app: request identity (token, output path, reply, the viewport it shoots), deadlines and +//! app: request identity (token, output path, reply, the viewport it shoots and the region of it, +//! refused at admission when outside the window and cropped in [`screenshot_reply`]), deadlines and //! settling, the admission budget ([`MAX_PENDING`] requests, [`MAX_IMAGE_BYTES`] per image, //! [`MAX_TOTAL_BYTES`] in all), the document identity fixed at admission, each viewport's geometry //! epoch recorded at issue so an image is saved only for the layout it was rendered from (a size, @@ -18,13 +19,16 @@ use std::collections::HashMap; use std::sync::Arc; use std::sync::mpsc::Sender; -use web_time::{Duration, Instant}; +use std::time::Duration; use base64::Engine as _; use craft_ui::runtime::windows::{ScreenshotFacts, ScreenshotSlot, WindowHost}; -use egui::{ColorImage, ViewportId}; +use egui::{ColorImage, Rect, ViewportId}; +use serde_json::Value; +use web_time::Instant; use crate::control::ControlResponse; +use crate::protocol::Params; /// Requests outstanding at once (issued, completed, waiting for geometry or waiting to be issued). pub const MAX_PENDING: usize = 4; @@ -146,6 +150,7 @@ pub struct PendingCapture { token: u64, viewport: ViewportId, path: Option, + region: Option, reply: Option>, deadline: Instant, ready_at: Instant, @@ -178,6 +183,10 @@ pub struct Finished { pub token: u64, /// File to write the PNG to; `None` inlines it in the reply. pub path: Option, + /// The part of the window to crop the image to, in points; `None` keeps the whole window. + pub region: Option, + /// The layout the image was captured from; the crop and the reply's `pixels_per_point` read it. + pub geometry: CaptureGeometry, /// Where to send the answer. pub reply: Option>, /// The captured image, or the error text for the reply. @@ -185,9 +194,17 @@ pub struct Finished { } impl Finished { - /// A finished request for `token`: `result` answers `reply`, and an image is written to `path` when given. - pub fn new(token: u64, path: Option, reply: Option>, result: Result, String>) -> Self { - Self { token, path, reply, result } + /// A finished request for `token`: `result` answers `reply`, and an image is written to `path` when given, + /// cropped to `region` as `geometry` scales it. + pub fn new( + token: u64, + path: Option, + region: Option, + geometry: CaptureGeometry, + reply: Option>, + result: Result, String>, + ) -> Self { + Self { token, path, region, geometry, reply, result } } } @@ -198,6 +215,8 @@ pub struct ScreenshotRequest { pub token: u64, /// Where to write the PNG, when the reply is a file. pub path: Option, + /// The part of the window to capture, in points; `None` captures the whole window. + pub region: Option, /// The viewport to capture. pub viewport: ViewportId, /// Where the reply goes. @@ -209,9 +228,9 @@ pub struct ScreenshotRequest { } impl ScreenshotRequest { - /// A request for `viewport` answered on `reply`: no file, no document, no settle delay. + /// A request for the whole of `viewport` answered on `reply`: no file, no document, no settle delay. pub fn new(token: u64, viewport: ViewportId, reply: Sender) -> Self { - Self { token, path: None, viewport, reply, document: None, settle_ms: 0.0 } + Self { token, path: None, region: None, viewport, reply, document: None, settle_ms: 0.0 } } } @@ -220,6 +239,7 @@ struct WaitingAdmit { token: u64, viewport: ViewportId, path: Option, + region: Option, reply: Sender, deadline: Instant, settle_ms: f64, @@ -312,17 +332,19 @@ impl Captures { /// `the viewport is not capturable ({w}×{h} points at {ppp} px/pt, texture side {side})`, /// `a {N} MiB screenshot is over the {MAX_IMAGE_BYTES / 1 MiB} MiB per-image limit` (`N` the /// expected bytes / 1 MiB, integer division), or - /// `screenshot budget exhausted: {total} bytes reserved of a {MAX_TOTAL_BYTES}-byte aggregate limit`. + /// `screenshot budget exhausted: {total} bytes reserved of a {MAX_TOTAL_BYTES}-byte aggregate limit`, or + /// `screenshot {token} failed: the region must lie inside the {w}×{h}-point window`. The budget is reserved for + /// the whole window, region or not: the slot retains the whole image until it is cropped. /// While the viewport's geometry is not recorded the request waits. pub fn admit(&mut self, request: ScreenshotRequest, now: Instant) -> Result<(), (Sender, String)> { - let ScreenshotRequest { token, path, viewport, reply, document, settle_ms } = request; + let ScreenshotRequest { token, path, region, viewport, reply, document, settle_ms } = request; if self.records.iter().any(|r| r.token == token) || self.waiting.iter().any(|w| w.token == token) { return Err((reply, format!("screenshot token {token} is already pending"))); } if self.pending() >= MAX_PENDING { return Err((reply, format!("too many screenshots pending (at most {MAX_PENDING})"))); } - let request = WaitingAdmit { token, viewport, path, reply, deadline: now + DEADLINE, settle_ms, document }; + let request = WaitingAdmit { token, viewport, path, region, reply, deadline: now + DEADLINE, settle_ms, document }; match self.windows.get(&viewport).copied() { None => { self.waiting.push(request); @@ -335,7 +357,7 @@ impl Captures { /// Queues `request` at `geometry` and `epoch`, what its viewport's window recorded. fn admit_with_geometry(&mut self, request: WaitingAdmit, geometry: CaptureGeometry, epoch: u64) -> Result<(), (Sender, String)> { - let WaitingAdmit { token, viewport, path, reply, deadline, settle_ms, document } = request; + let WaitingAdmit { token, viewport, path, region, reply, deadline, settle_ms, document } = request; // The request's clock started when it arrived. let arrived = deadline - DEADLINE; if self.records.iter().any(|r| r.token == token) { @@ -348,6 +370,9 @@ impl Captures { Ok(bytes) => bytes, Err(e) => return Err((reply, e)), }; + if let Err(e) = check_region(token, region, &geometry) { + return Err((reply, e)); + } if let Err(e) = aggregate_budget(self.reserved_bytes(), expected) { return Err((reply, e)); } @@ -357,6 +382,7 @@ impl Captures { token, viewport, path, + region, reply: Some(reply), deadline, ready_at: arrived + Duration::from_secs_f64(settle / 1000.0), @@ -538,6 +564,9 @@ impl Captures { finished.push(Finished { token: w.token, path: w.path, + region: w.region, + // No geometry was recorded for a waiting request; the result is an error, so nothing reads it. + geometry: CaptureGeometry::new([0.0, 0.0], 0), reply: Some(w.reply), result: Err(format!("screenshot {} cancelled: {reason}", w.token)), }); @@ -549,6 +578,8 @@ impl Captures { finished.push(Finished { token: r.token, path: r.path.take(), + region: r.region, + geometry: r.geometry, reply: r.reply.take(), result: Err(format!("screenshot {} cancelled: {reason}", r.token)), }); @@ -580,11 +611,23 @@ fn aggregate_budget(others: usize, expected: usize) -> Result<(), String> { Ok(()) } +/// Whether `region` lies inside the window of `geometry`: the request is refused otherwise, never cropped to a +/// smaller image than it asked for. `None` (the whole window) always fits. +fn check_region(token: u64, region: Option, geometry: &CaptureGeometry) -> Result<(), String> { + let Some(region) = region else { return Ok(()) }; + let [width, height] = geometry.size_points; + if region.min.x >= 0.0 && region.min.y >= 0.0 && region.max.x <= width && region.max.y <= height { + return Ok(()); + } + Err(format!("screenshot {token} failed: the region must lie inside the {width}×{height}-point window")) +} + /// Finalise a request at a new geometry: recheck the per-image and aggregate limits (excluding -/// its old reservation), take the new reservation and restart settling. +/// its old reservation) and that its region still fits, take the new reservation and restart settling. fn revalidate_reservation(r: &mut PendingCapture, others: usize, geometry: CaptureGeometry, epoch: u64) -> Result<(), String> { let expected = image_budget(&geometry)?; aggregate_budget(others, expected)?; + check_region(r.token, r.region, &geometry)?; r.reserved_bytes = expected; r.geometry = geometry; r.epoch = epoch; @@ -597,7 +640,7 @@ fn finish(r: &mut PendingCapture, result: Result, String>) -> Fi if let Some(slot) = r.slot.take() { slot.cancel(); } - Finished { token: r.token, path: r.path.take(), reply: r.reply.take(), result } + Finished { token: r.token, path: r.path.take(), region: r.region, geometry: r.geometry, reply: r.reply.take(), result } } /// The returned image must be the issued viewport (within a pixel) or a uniform renderer fit @@ -678,40 +721,127 @@ pub fn encode_png(width: usize, height: usize, rgba: &[u8]) -> Result, S /// authorized workspace. `Err` is the reply's error text. pub type PngWriter<'a> = dyn FnMut(&str, &[u8]) -> Result<(), String> + 'a; -/// The reply for a finished image: -/// - an image over [`MAX_IMAGE_BYTES`] as RGBA (or whose size overflows): +/// A validated `ui.screenshot`: where the PNG goes and which part of the window it shows. +#[derive(Clone, Debug, Default, PartialEq)] +#[non_exhaustive] +pub struct ScreenshotParams { + /// File to write the PNG to, or `None` to inline it. + pub path: Option, + /// The part of the window to capture as `[x0, y0, x1, y1]` in points, finite and ordered; `None` captures the + /// whole window. + pub region: Option, +} + +impl ScreenshotParams { + /// `{path?, region?}`, no other fields. `path` is a string; `region` is `[x0, y0, x1, y1]` in points, four finite + /// numbers with `x0 < x1` and `y0 < y1`: ``"region must be [x0, y0, x1, y1] in points, finite, with x0 < x1 and + /// y0 < y1"`` otherwise. Whether it lies inside the window is checked at admission, against the window's geometry. + pub fn from_params(params: &Value) -> Result { + let p = Params(params).only(None, &["path", "region"])?; + let p = Params(&p); + let path = p.str_field("path")?.map(str::to_owned); + let region = p.0.get("region").map(region_param).transpose()?; + Ok(ScreenshotParams { path, region }) + } +} + +/// `region`: `[x0, y0, x1, y1]`, finite and ordered. +fn region_param(region: &Value) -> Result { + const SHAPE: &str = "region must be [x0, y0, x1, y1] in points, finite, with x0 < x1 and y0 < y1"; + let number = |v: &Value| v.as_f64().map(|n| n as f32).filter(|n| n.is_finite()); + let corners = match region.as_array().map(Vec::as_slice) { + Some([x0, y0, x1, y1]) => number(x0).zip(number(y0)).zip(number(x1).zip(number(y1))), + _ => None, + }; + corners + .filter(|((x0, y0), (x1, y1))| x0 < x1 && y0 < y1) + .map(|((x0, y0), (x1, y1))| Rect::from_min_max(egui::pos2(x0, y0), egui::pos2(x1, y1))) + .ok_or_else(|| SHAPE.into()) +} + +/// The pixel columns and rows `[x0, y0, x1, y1)` of `region` in an image of `size` captured at `geometry`. The image +/// scale is `size / geometry.size_points`, never `pixels_per_point`: a renderer that fitted the surface to its +/// texture side returns a smaller image of the same layout. Edges round to the nearest pixel and are clamped to the +/// image; `None` when nothing of the region is left or the geometry has no area. +fn crop_pixels(region: Rect, geometry: &CaptureGeometry, size: [usize; 2]) -> Option<[usize; 4]> { + let [width, height] = geometry.size_points; + if !(width.is_finite() && height.is_finite() && width > 0.0 && height > 0.0) { + return None; + } + let (sx, sy) = (size[0] as f32 / width, size[1] as f32 / height); + // `as usize` saturates: a negative or NaN edge is 0, an edge past the image is clamped below. + let px = |v: f32, scale: f32, max: usize| ((v * scale).round() as usize).min(max); + let [x0, x1] = [px(region.min.x, sx, size[0]), px(region.max.x, sx, size[0])]; + let [y0, y1] = [px(region.min.y, sy, size[1]), px(region.max.y, sy, size[1])]; + (x0 < x1 && y0 < y1).then_some([x0, y0, x1, y1]) +} + +/// The reply for a finished image, cropped to `region` (in points; `None` keeps the whole image) at the scale of the +/// image to `geometry`, the layout it was captured from: +/// - a region with no pixels left in the image: +/// `{"ok": false, "error": "screenshot {token} failed: the region has no pixels in the captured image"}`; +/// - a crop over [`MAX_IMAGE_BYTES`] as RGBA (or whose size overflows): /// `{"ok": false, "error": "screenshot {token} failed: the image exceeds the {MAX_IMAGE_BYTES / 1 MiB} MiB encode budget"}`; -/// - no `path`: `{"ok": true, "result": {"base64": , "mime": "image/png", "width", "height"}}`, -/// with no size limit beyond the encode budget; +/// - no `path`: `{"ok": true, "result": {"base64": , "mime": "image/png", "width", "height", +/// "pixels_per_point"}}`, with no size limit beyond the encode budget; /// - a `path`: the PNG goes to `write(path, bytes)`, the app's file authority (limited to its /// authorized workspace), and the reply is -/// `{"ok": true, "result": {"path", "width", "height"}}`; +/// `{"ok": true, "result": {"path", "width", "height", "pixels_per_point"}}`; /// - an encode or write error `e`: `{"ok": false, "error": e}`. /// +/// `width` and `height` are the crop's pixels; `pixels_per_point` is `geometry`'s, the window's scale. /// Flatten the pixels to RGBA and drop the image before encoding, so the two copies don't overlap. -pub fn screenshot_reply(token: u64, image: Arc, path: Option<&str>, write: &mut PngWriter<'_>) -> ControlResponse { +pub fn screenshot_reply( + token: u64, + image: Arc, + region: Option, + geometry: CaptureGeometry, + path: Option<&str>, + write: &mut PngWriter<'_>, +) -> ControlResponse { let [w, h] = image.size; - let Some(bytes) = w.checked_mul(h).and_then(|n| n.checked_mul(4)).filter(|&n| n <= MAX_IMAGE_BYTES) else { + let crop = match region { + None => Some([0, 0, w, h]), + Some(region) => crop_pixels(region, &geometry, [w, h]), + }; + let Some([x0, y0, x1, y1]) = crop.filter(|[x0, y0, x1, y1]| x0 < x1 && y0 < y1) else { + return serde_json::json!({"ok": false, "error": format!("screenshot {token} failed: the region has no pixels in the captured image")}); + }; + let (cw, ch) = (x1 - x0, y1 - y0); + let Some(bytes) = cw.checked_mul(ch).and_then(|n| n.checked_mul(4)).filter(|&n| n <= MAX_IMAGE_BYTES) else { return serde_json::json!({ "ok": false, "error": format!("screenshot {token} failed: the image exceeds the {} MiB encode budget", MAX_IMAGE_BYTES / (1 << 20)), }); }; let mut rgba = Vec::with_capacity(bytes); - rgba.extend(image.pixels.iter().flat_map(|c| c.to_array())); + for y in y0..y1 { + let row = y.checked_mul(w).and_then(|start| image.pixels.get(start + x0..start + x1)); + let Some(row) = row else { + return serde_json::json!({"ok": false, "error": format!("screenshot {token} failed: the image has fewer pixels than its size")}); + }; + rgba.extend(row.iter().flat_map(|c| c.to_array())); + } drop(image); - let png = match encode_png(w, h, &rgba) { + let png = match encode_png(cw, ch, &rgba) { Ok(png) => png, Err(e) => return serde_json::json!({"ok": false, "error": e}), }; + let ppp = geometry.pixels_per_point; let Some(path) = path else { return serde_json::json!({ "ok": true, - "result": {"base64": base64::engine::general_purpose::STANDARD.encode(png), "mime": "image/png", "width": w, "height": h}, + "result": { + "base64": base64::engine::general_purpose::STANDARD.encode(png), + "mime": "image/png", + "width": cw, + "height": ch, + "pixels_per_point": ppp, + }, }); }; match write(path, &png) { - Ok(()) => serde_json::json!({"ok": true, "result": {"path": path, "width": w, "height": h}}), + Ok(()) => serde_json::json!({"ok": true, "result": {"path": path, "width": cw, "height": ch, "pixels_per_point": ppp}}), Err(e) => serde_json::json!({"ok": false, "error": e}), } } diff --git a/crates/automation/src/security.rs b/crates/automation/src/security.rs index b294c15ddf..259d2f3cb2 100644 --- a/crates/automation/src/security.rs +++ b/crates/automation/src/security.rs @@ -271,11 +271,15 @@ fn token_conflict() -> AutomationError { AutomationError::BadRequest("use either a control token or a control token file, not both".into()) } +/// The most a Windows token file read takes: a token, its newline and room for stray whitespace. +#[cfg(windows)] +const TOKEN_FILE_MAX_BYTES: u64 = 4096; + /// Validates what was opened, not just the name: the file must be a regular file that no other /// local principal can read, so a group- or world-readable token is refused rather than trusted. fn read_token_file(path: &Path) -> Result { let io = |e: std::io::Error| AutomationError::Io(format!("{}: {e}", path.display())); - let mut file = std::fs::File::open(path).map_err(io)?; + let file = std::fs::File::open(path).map_err(io)?; let meta = file.metadata().map_err(io)?; if !meta.is_file() { return Err(AutomationError::Io(format!("{}: control token file is not a regular file", path.display()))); @@ -291,7 +295,25 @@ fn read_token_file(path: &Path) -> Result { ))); } } - let token = std::io::read_to_string(&mut file).map_err(io)?; + // A Windows file inherits its folder's access list, so the owner and the access list are read with the contents + // through one handle: nothing swapped in at the path between the check and the read gets through. + + #[cfg(windows)] + let token = { + use craft_platform::owner_only; + drop(file); + let me = owner_only::current_user_sid().map_err(io)?; + let (sddl, bytes) = owner_only::read_with_sddl(path, TOKEN_FILE_MAX_BYTES).map_err(io)?; + if let Some(problem) = owner_only::foreign_access(&sddl, &me) { + return Err(AutomationError::Io(format!( + "{}: control token file can be reached by others: {problem}; restrict it to its owner", + path.display() + ))); + } + String::from_utf8(bytes).map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))? + }; + #[cfg(not(windows))] + let token = std::io::read_to_string(&file).map_err(io)?; let token = token.trim().to_owned(); validate_token(&token)?; Ok(token) @@ -309,6 +331,17 @@ fn create_token_file(path: &Path, token: &str) -> Result<(), AutomationError> { options.mode(0o600); } let mut file = options.open(path).map_err(|e| AutomationError::Io(format!("{}: {e}", path.display())))?; + // On Windows the new file has its folder's access list: it is restricted to its user and SYSTEM before the token + // is written, and a file that cannot be restricted is removed rather than left for the token to go into later. + #[cfg(windows)] + { + use craft_platform::owner_only; + if let Err(e) = owner_only::current_user_sid().and_then(|me| owner_only::restrict_to_owner(path, &me)) { + drop(file); + let _ = std::fs::remove_file(path); + return Err(AutomationError::Io(format!("{}: cannot restrict the control token file to its owner: {e}", path.display()))); + } + } writeln!(file, "{token}").map_err(|e| AutomationError::Io(format!("{}: {e}", path.display()))) } @@ -317,10 +350,12 @@ fn create_token_file(path: &Path, token: &str) -> Result<(), AutomationError> { /// validated. Neither given: a generated token. A `token_file` that exists is read: it must be a /// regular file (`I/O: : control token file is not a regular file`) and on Unix have no /// group or other permission bits (`I/O: : control token file is readable by group or -/// others (mode {mode & 0o777:o}); restrict it to its owner (e.g. chmod 600)`), and its trimmed -/// content is validated. A missing one is created with a generated token (parent directories -/// created, `create_new`, mode 0600 on Unix, the token and a newline); losing that create race to -/// another process reads the winner's file instead. +/// others (mode {mode & 0o777:o}); restrict it to its owner (e.g. chmod 600)`), on Windows be +/// owned by the user with an access list of the user and SYSTEM only (`I/O: : control token +/// file can be reached by others: ; restrict it to its owner`), and its trimmed content is +/// validated. A missing one is created with a generated token (parent directories created, +/// `create_new`, mode 0600 on Unix, the user and SYSTEM only on Windows, the token and a +/// newline); losing that create race to another process reads the winner's file instead. pub fn server_token(supplied: Option<&str>, token_file: Option<&Path>) -> Result { if supplied.is_some() && token_file.is_some() { return Err(token_conflict()); diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index 875d84ed72..b2f9fdd1d0 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -56,7 +56,8 @@ pub fn listen(port: u16, token: String, host: WindowHost) -> std::io::Result<(Re /// Serves a listener bound earlier (an app's `--control`, bound before its window opens) until the /// returned [`Listening`] is dropped: authenticates each connection with `token`, forwards its -/// requests to the receiver and wakes the root window through `host`. The app prints +/// requests to the receiver and wakes the root window through `host`, which keeps each window's access tree +/// ([`WindowHost::keep_access_tree`]) for [`crate::access`]. The app prints /// `control server listening on `. pub fn serve(listener: TcpListener, token: String, host: WindowHost) -> std::io::Result<(Receiver, Listening)> { serve_with_deadline(listener, token, host, AUTH_DEADLINE) @@ -73,6 +74,9 @@ pub fn serve_with_deadline( ) -> std::io::Result<(Receiver, Listening)> { let (tx, rx) = channel::(); let addr = listener.local_addr()?; + // `ui.inspect`, `ui.click {label}` and `ui.focus` read the kept tree of the last presented frame; it is kept + // from before the first connection, so the first request already finds it. + host.keep_access_tree(); let stop = Arc::new(AtomicBool::new(false)); let stopped = Arc::clone(&stop); let accept = std::thread::Builder::new().name("control server".into()).spawn(move || { diff --git a/crates/automation/src/synthetic.rs b/crates/automation/src/synthetic.rs index a2e1c6d23e..bea9c8d5a5 100644 --- a/crates/automation/src/synthetic.rs +++ b/crates/automation/src/synthetic.rs @@ -1,10 +1,11 @@ -//! Synthetic pointer, keyboard and input-method input: `ui.click`, `ui.move`, `ui.wheel`, `ui.key`, `ui.release`, -//! `ui.type`, `ui.ime` and `ui.capsLock`. +//! Synthetic pointer, keyboard, input-method, file-drop and access-tree input: `ui.click`, `ui.focus`, `ui.move`, +//! `ui.wheel`, `ui.key`, `ui.release`, `ui.type`, `ui.ime`, `ui.drop` and `ui.capsLock`. //! //! This module reads and validates the protocol's parameters; the window host queues the input //! ([`WindowHost::inject_move`], [`WindowHost::inject_click`], [`WindowHost::inject_wheel`], //! [`WindowHost::inject_key`], [`WindowHost::inject_release`], [`WindowHost::inject_text`], -//! [`WindowHost::inject_ime`]), one step per pass, so a move, a press, a release, a key's down and up and each +//! [`WindowHost::inject_ime`], [`WindowHost::inject_files`], [`WindowHost::inject_access`]), one step per pass, so a +//! move, a press, a release, a key's down and up and each //! composition step land on separate passes as real input does. A request is validated whole before anything of it is //! queued, so a refused one leaves no half-queued press. The host answers the //! waiting replies once [`WindowHost::injected_idle`] turns true ([`crate::control::ControlChannel::poll_input`]), and @@ -18,6 +19,13 @@ //! maps to the screen through its canvas ([`DocumentMap`]). Document-coordinate `ui.pointer` events are the //! application's own method: they drive its tool host, not the window. With `control: {name, role?, within?, index?}` //! a point is the centre of that control's rect, `x` and `y` an offset from it ([`access::Target`]). +//! +//! A node of the access tree (`id` or `label`, [`NodeTarget`]) is clicked or focused through the node's own action +//! instead of a point: [`crate::access::resolve`] finds it in the window's kept tree when the request arrives, so a +//! missing, ambiguous, disabled or undeclared node is refused before anything is queued. There is no `ui.drag`: a +//! drag is `ui.click {hold}`, `ui.move` and `ui.release`. + +use std::path::PathBuf; use craft_behavior::PointerButton; use craft_keymap::{Key, Mods}; @@ -25,7 +33,7 @@ use craft_ui::runtime::windows::{Released, WindowHost}; use egui::{Pos2, Vec2, ViewportId, pos2, vec2}; use serde_json::Value; -use crate::access; +use crate::access::{self, NodeTarget, inject_click, inject_context_menu, inject_focus}; use crate::protocol::{BUTTONS, KEY_MODIFIERS, Params}; /// Most clicks one `ui.click` may ask for (`count`). @@ -86,9 +94,21 @@ impl At { } return Ok(Self::Control { target: access::Target::from_params(control)?, offset: vec2(x, y) }); } + Self::in_space(p, pos2(x, y)) + } + + /// `x` and `y`, both required, in the space `coordinates` names (`screen`, the default, or `document`). + fn required(p: &Params<'_>) -> Result { + let range = Some((-MAX_SCREEN_POINT, MAX_SCREEN_POINT)); + let x = p.number_in("x", "x", range)?.ok_or_else(|| "missing `x`".to_owned())? as f32; + let y = p.number_in("y", "y", range)?.ok_or_else(|| "missing `y`".to_owned())? as f32; + Self::in_space(p, pos2(x, y)) + } + + fn in_space(p: &Params<'_>, pos: Pos2) -> Result { Ok(match p.choice("coordinates", "coordinates", &["screen", "document"])?.unwrap_or("screen") { - "document" => Self::Document(pos2(x, y), p.uint_field("page")?.map_or(0, |page| usize::try_from(page).unwrap_or(usize::MAX))), - _ => Self::Screen(pos2(x, y)), + "document" => Self::Document(pos, p.uint_field("page")?.map_or(0, |page| usize::try_from(page).unwrap_or(usize::MAX))), + _ => Self::Screen(pos), }) } @@ -141,12 +161,44 @@ fn key(p: &Params<'_>) -> Result, String> { p.choice("key", "key", &[])?.map(|name| Key::parse(name).ok_or_else(|| format!("unknown key `{name}`"))).transpose() } +/// Where a `ui.click` goes. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub enum ClickTarget { + /// A position. + At(At), + /// A node of the access tree. + Node(NodeTarget), +} + +/// A validated `ui.focus`: moves the focus to a node of the access tree. +#[derive(Clone, Debug, PartialEq, Eq)] +#[non_exhaustive] +pub struct Focus { + /// The node that takes the focus. + pub target: NodeTarget, +} + +impl Focus { + /// `{id | label}`: the node to focus, exactly one of the two, no other fields (``"missing `id` or `label`"``). + pub fn from_params(params: &Value) -> Result { + let p = Params(params).only(None, &["id", "label"])?; + NodeTarget::from_params(&p)?.map(|target| Focus { target }).ok_or_else(|| "missing `id` or `label`".into()) + } + + /// Queues the focus request for the node in `viewport`; a node the kept tree does not have as one reported, + /// enabled, focusable node is refused ([`crate::access::resolve`]). + pub fn inject(&self, host: &WindowHost, viewport: ViewportId) -> Result<(), String> { + inject_focus(host, viewport, &self.target) + } +} + /// A validated `ui.click`. #[derive(Clone, Debug, PartialEq)] #[non_exhaustive] pub struct Click { - /// Target position. - pub at: At, + /// Where the click goes: a position or a node of the access tree. + pub target: ClickTarget, /// The button pressed. pub button: PointerButton, /// Number of clicks (2 is a double click). @@ -158,31 +210,63 @@ pub struct Click { } impl Click { - /// `{x?, y?, coordinates?, button?, count?, hold?, modifiers…}`, no other fields (`Params::only`). `button` - /// defaults to `left`. `count` is an unsigned integer, default 1; over [`MAX_CLICKS`] is - /// ``"`count` must be at most 256 (got {count})"``. Other errors are the `Params` validators'. + /// `{x?, y?, coordinates?, button?, count?, hold?, modifiers…}` for a point, or `{id | label, button?}` for a node + /// of the access tree ([`NodeTarget::from_params`]); no other fields (`Params::only`). `button` defaults to + /// `left`. `count` is an unsigned integer, default 1; over [`MAX_CLICKS`] is + /// ``"`count` must be at most 256 (got {count})"``. A node is clicked by its own action, so with one only the + /// primary button (its click) and the secondary one (its context menu) are allowed, and a point, `count` above 1, + /// `hold` and held modifiers are refused. Other errors are the `Params` validators'. pub fn from_params(params: &Value) -> Result { - let p = only(params, &["button", "count", "hold"])?; + let p = only(params, &["button", "count", "hold", "id", "label"])?; let p = Params(&p); let count = p.uint_field("count")?.unwrap_or(1); if count > MAX_CLICKS { return Err(format!("`count` must be at most {MAX_CLICKS} (got {count})")); } - Ok(Self { - at: At::from_params(&p)?, - button: button(&p)?.unwrap_or(PointerButton::Primary), - count, - mods: p.modifiers(&KEY_MODIFIERS)?, - hold: p.bool_field("hold")?.unwrap_or(false), - }) + let pressed = button(&p)?; + let mods = p.modifiers(&KEY_MODIFIERS)?; + let hold = p.bool_field("hold")?.unwrap_or(false); + if let Some(node) = NodeTarget::from_params(p.0)? { + if POINT.iter().any(|field| p.0.get(field).is_some()) { + return Err("a click names a node (`id` or `label`) or a point (`x`, `y`), not both".into()); + } + if count > 1 { + return Err("`count` goes with a point, not a node".into()); + } + if hold { + return Err("`hold` goes with a point, not a node".into()); + } + if !mods.is_none() { + return Err("modifiers go with a point, not a node".into()); + } + let button = match pressed { + None | Some(PointerButton::Primary) => PointerButton::Primary, + Some(PointerButton::Secondary) => PointerButton::Secondary, + Some(_) => return Err("a node takes a primary or a secondary click, not the middle button".into()), + }; + return Ok(Self { target: ClickTarget::Node(node), button, count: 1, mods, hold: false }); + } + Ok(Self { target: ClickTarget::At(At::from_params(&p)?), button: pressed.unwrap_or(PointerButton::Primary), count, mods, hold }) } - /// Queues a move to the target, then `count` presses and releases of the button, in `viewport`. + /// Queues a move to the point, then `count` presses and releases of the button, in `viewport`; for a node, its + /// click, or its context menu for the secondary button, once the kept tree has it as one reported, enabled node + /// that declares the action ([`crate::access::resolve`]). pub fn inject(&self, host: &WindowHost, viewport: ViewportId, map: DocumentMap<'_>) -> Result<(), String> { - let count = u32::try_from(self.count).unwrap_or(u32::MAX); - let at = self.at.place(host, viewport, map)?; - host.inject_click(viewport, at, self.button, count, self.mods, self.hold); - Ok(()) + match &self.target { + ClickTarget::At(at) => { + let count = u32::try_from(self.count).unwrap_or(u32::MAX); + host.inject_click(viewport, at.place(host, viewport, map)?, self.button, count, self.mods, self.hold); + Ok(()) + } + ClickTarget::Node(node) => { + if matches!(self.button, PointerButton::Secondary) { + inject_context_menu(host, viewport, node) + } else { + inject_click(host, viewport, node) + } + } + } } } @@ -199,12 +283,12 @@ pub struct Move { } impl Move { - /// `{x?, y?, coordinates?, rest?, modifiers…}`, no other fields. `rest` is seconds between 0 and [`MAX_REST`]. + /// `{x, y, coordinates?, rest?, modifiers…}`, no other fields. `rest` is seconds between 0 and [`MAX_REST`]. pub fn from_params(params: &Value) -> Result { let p = only(params, &["rest"])?; let p = Params(&p); Ok(Self { - at: At::from_params(&p)?, + at: At::required(&p)?, mods: p.modifiers(&KEY_MODIFIERS)?, rest: p.number_in("rest", "rest", Some((0.0, MAX_REST)))?.unwrap_or(0.0), }) @@ -342,6 +426,8 @@ pub fn caps_lock_from_params(params: &Value) -> Result, String> { pub fn input_method(method: &str, params: &Value, host: &WindowHost, viewport: ViewportId, map: DocumentMap<'_>) -> Option> { Some(match method { "ui.click" => Click::from_params(params).and_then(|click| click.inject(host, viewport, map)), + "ui.focus" => Focus::from_params(params).and_then(|focus| focus.inject(host, viewport)), + "ui.drop" => drop_files(params, host, viewport, map), "ui.move" => Move::from_params(params).and_then(|step| step.inject(host, viewport, map)), "ui.wheel" => Wheel::from_params(params).and_then(|wheel| wheel.inject(host, viewport, map)), "ui.key" => KeyPress::from_params(params).map(|key| key.inject(host, viewport)), @@ -353,6 +439,32 @@ pub fn input_method(method: &str, params: &Value, host: &WindowHost, viewport: V }) } +/// `ui.drop {paths, hover_only?, x?, y?, coordinates?}`: hovers the files `paths` names (a non-empty array of +/// strings) over the point, where the pointer is when neither `x` nor `y` is given, and drops them in the following +/// step unless `hover_only`. The point is mapped as every request's is; a drop carries no modifiers, so a held one is +/// refused. +fn drop_files(params: &Value, host: &WindowHost, viewport: ViewportId, map: DocumentMap<'_>) -> Result<(), String> { + const PATHS: &str = "paths must be a non-empty array of strings"; + let p = only(params, &["paths", "hover_only"])?; + let p = Params(&p); + if !p.modifiers(&KEY_MODIFIERS)?.is_none() { + return Err("`ui.drop` takes no modifiers".into()); + } + let paths: Vec = match p.0.get("paths") { + None => return Err("missing `paths`".into()), + Some(Value::Array(items)) => items.iter().map(|item| item.as_str().map(PathBuf::from)).collect::>().ok_or(PATHS)?, + Some(_) => return Err(PATHS.into()), + }; + if paths.is_empty() { + return Err(PATHS.into()); + } + let hover_only = p.bool_field("hover_only")?.unwrap_or(false); + let at = (p.0.get("x").is_some() || p.0.get("y").is_some() || p.0.get("control").is_some()).then(|| At::from_params(&p)).transpose()?; + let at = at.map(|at| at.place(host, viewport, map)).transpose()?; + host.inject_files(viewport, at, paths, !hover_only); + Ok(()) +} + /// A validated `ui.type`: `{text}`, a string. fn text(params: &Value) -> Result { let p = Params(params).only(None, &["text"])?; diff --git a/crates/automation/src/window.rs b/crates/automation/src/window.rs new file mode 100644 index 0000000000..ae5af54dae --- /dev/null +++ b/crates/automation/src/window.rs @@ -0,0 +1,25 @@ +//! `ui.window`: window commands through the framework's one window-command path. + +use craft_ui::runtime::windows::{WindowAction, WindowHost}; +use egui::ViewportId; +use serde_json::{Value, json}; + +use crate::protocol::Params; + +/// `ui.window {maximized: bool}` sends `WindowAction::SetMaximized` through `WindowHost::act` and returns `Ok({})`, or +/// `Err` when `act` returns false (no window commands, as on wasm). `None` for any other method. It keeps no state. +pub fn window_method(host: &WindowHost, viewport: ViewportId, method: &str, params: &Value) -> Option> { + if method != "ui.window" { + return None; + } + Some(run(host, viewport, params)) +} + +fn run(host: &WindowHost, viewport: ViewportId, params: &Value) -> Result { + let params = Params(params).only(None, &["maximized"])?; + let maximized = Params(¶ms).bool_field("maximized")?.ok_or("missing `maximized`")?; + if !host.act(viewport, WindowAction::SetMaximized(maximized)) { + return Err("this platform has no window commands".to_owned()); + } + Ok(json!({})) +} diff --git a/crates/automation/tests/it/access.rs b/crates/automation/tests/it/access.rs index 9ce1acc664..96d050d5a3 100644 --- a/crates/automation/tests/it/access.rs +++ b/crates/automation/tests/it/access.rs @@ -1,14 +1,20 @@ -//! Named controls through the protocol: a `control` target places a click on the control, `ui.find` describes it, and -//! a target that is ambiguous, unknown or asked for too early queues nothing. +//! Named controls through the protocol (`control` targets, `ui.find`), `ui.inspect` over the window's kept access +//! tree, and `ui.click` and `ui.focus` on a node it names: tree order and filters, what an open modal hides, a click, +//! a context menu and a focus reaching their widget, and the targets refused before anything is queued. use std::cell::{Cell, RefCell}; use std::rc::Rc; -use craft_automation::access::{AMBIGUOUS, NO_CONTROL, NO_TREE, access_method}; +use craft_automation::access::{AMBIGUOUS, NO_CONTROL, NO_TREE, NodeTarget, access_method, inspect, resolve}; use craft_automation::synthetic::input_method; use craft_ui::buttons::Button; -use craft_ui::contract::{Bind, Show as _, clicked}; +use craft_ui::contract::{Bind, Props as _, Show as _, ShowContainer as _, clicked}; +use craft_ui::dialog::Dialog; +use craft_ui::menu::{Menu, MenuItem}; +use craft_ui::runtime::egui::access::Declared; +use craft_ui::runtime::egui::injected::hook_without_pass; use craft_ui::runtime::windows::WindowHost; +use craft_ui::sections::{DialogRole, FooterButton}; use craft_ui::testing::{Fixture, trial}; use craft_ui::text::TextField; use egui::{Pos2, ViewportId}; @@ -112,3 +118,151 @@ fn an_ambiguous_or_missing_name_queues_nothing() { rig.send("ui.click", json!({"control": {"name": "Go", "index": 1}})).expect("valid"); assert_eq!(rig.counts(), [0, 1], "index 1 is the second in reading order"); } + +/// The listed widgets of `params`, from the window's kept tree. +fn listed(host: &WindowHost, params: Value) -> Value { + inspect(host, ViewportId::ROOT, ¶ms).expect("an inspect reply") +} + +/// The labels of a reply's widgets, in its order. +fn labels(reply: &Value) -> Vec { + reply["widgets"].as_array().into_iter().flatten().filter_map(|w| w["label"].as_str().map(str::to_owned)).collect() +} + +/// The widget of a reply labelled `label`. +fn widget<'a>(reply: &'a Value, label: &str) -> &'a Value { + reply["widgets"].as_array().into_iter().flatten().find(|w| w["label"] == label).unwrap_or_else(|| panic!("{label} is listed: {reply}")) +} + +/// Where `label` sits in `order`. +fn place(order: &[String], label: &str) -> usize { + order.iter().position(|l| l == label).unwrap_or_else(|| panic!("{label} is listed in {order:?}")) +} + +/// Every reported node is listed once in tree order with its state, the root left out; `query`, `role` and `focused` +/// keep a subset, `limit` cuts the list but not the count; a node behind an open modal is neither listed nor +/// resolved, and the modal's own buttons are. +#[trial] +fn inspect_lists_reported_nodes_in_tree_order_with_their_filters() { + let open = Rc::new(Cell::new(false)); + let (shown, name) = (open.clone(), Rc::new(RefCell::new(String::from("Draft")))); + let mut fx = Fixture::new(move |ui| { + Button::new("Open").show(ui); + Button::new("Save").show(ui); + Button::new("Archive").enabled(false).show(ui); + TextField::new("Name", Bind::bound(&mut *name.borrow_mut())).show(ui); + let mut now = shown.get(); + Dialog::new("Options").opened(Bind::bound(&mut now)).buttons([FooterButton::new("Apply", DialogRole::Accept)]).show(ui, |_, _| {}); + shown.set(now); + }); + let host = WindowHost::of(fx.ctx()); + host.keep_access_tree(); + fx.settle(); + + let all = listed(&host, json!({})); + let order = labels(&all); + assert!(place(&order, "Open") < place(&order, "Save") && place(&order, "Save") < place(&order, "Archive"), "tree order: {order:?}"); + let widgets = all["widgets"].as_array().expect("a widget list"); + assert_eq!(all["count"].as_u64(), Some(widgets.len() as u64), "{all}"); + assert_eq!(all["truncated"], false); + assert!(widgets.iter().all(|w| w["depth"].as_u64().is_some_and(|depth| depth >= 1)), "the root is not listed: {all}"); + let ids: Vec<&str> = widgets.iter().filter_map(|w| w["id"].as_str()).collect(); + assert!(ids.iter().enumerate().all(|(i, id)| !ids[..i].contains(id)), "each node once: {ids:?}"); + let (save, archive) = (widget(&all, "Save"), widget(&all, "Archive")); + assert!(save["enabled"] == true && save["clickable"] == true, "{save}"); + assert!(archive["enabled"] == false, "{archive}"); + let rect = |w: &Value| w["rect"].as_array().map(|r| r.iter().filter_map(Value::as_f64).collect::>()).expect("a rect"); + assert!(rect(widget(&all, "Open"))[3] <= rect(save)[1] + 0.5, "Open lies above Save"); + + let queried = listed(&host, json!({"query": "SAV"})); + assert!(labels(&queried).contains(&"Save".to_owned()) && !labels(&queried).contains(&"Open".to_owned()), "{queried}"); + let buttons = listed(&host, json!({"role": "button"})); + assert!(["Open", "Save", "Archive"].iter().all(|label| labels(&buttons).contains(&(*label).to_owned())), "{buttons}"); + assert!(buttons["widgets"].as_array().into_iter().flatten().all(|w| w["role"].as_str().is_some_and(|role| role.eq_ignore_ascii_case("button")))); + let fields = listed(&host, json!({"role": "textinput"})); + assert_eq!(fields["count"], 1, "the one text field, its role matched ignoring case: {fields}"); + assert!(buttons["widgets"].as_array().into_iter().flatten().all(|w| w["id"] != fields["widgets"][0]["id"]), "the field is no button"); + + let (focused, unfocused) = (listed(&host, json!({"focused": true})), listed(&host, json!({"focused": false}))); + assert_eq!(focused["count"].as_u64().unwrap_or(0) + unfocused["count"].as_u64().unwrap_or(0), all["count"].as_u64().unwrap_or(0)); + assert!(focused["widgets"].as_array().into_iter().flatten().all(|w| w["focused"] == true), "{focused}"); + + let first = listed(&host, json!({"limit": 1})); + assert_eq!(first["widgets"].as_array().map(Vec::len), Some(1)); + assert_eq!((first["count"].clone(), first["truncated"].clone()), (all["count"].clone(), json!(true))); + assert_eq!(first["widgets"][0], all["widgets"][0], "the limit keeps the first in tree order"); + assert!(inspect(&host, ViewportId::ROOT, &json!({"nodes": true})).is_err(), "an unknown field is refused"); + + open.set(true); + fx.idle(30); + let tree = host.access_tree_view(ViewportId::ROOT).expect("the kept tree"); + let behind = listed(&host, json!({})); + assert!(!labels(&behind).contains(&"Open".to_owned()), "a node behind the modal is not listed: {behind}"); + assert!(labels(&behind).contains(&"Apply".to_owned()), "the modal's own button is: {behind}"); + assert!(resolve(&tree, &NodeTarget::Label("Open".into()), Declared::Click).is_err(), "nor is it resolved"); + assert!(resolve(&tree, &NodeTarget::Label("apply".into()), Declared::Click).is_ok(), "a label matches ignoring case"); +} + +/// A click by label activates its button once; a secondary click opens the node's context menu; a focus by the id +/// `ui.inspect` lists moves the key focus there. A missing, ambiguous, disabled or undeclared target is refused and +/// queues nothing. +#[trial] +fn click_and_focus_by_label_or_id_reach_the_widget_and_refuse_what_they_cannot_name() { + let saves = Rc::new(Cell::new(0)); + let (counted, name) = (saves.clone(), Rc::new(RefCell::new(String::new()))); + let mut fx = Fixture::new(move |ui| { + if Button::new("Save").show(ui).clicked() { + counted.set(counted.get() + 1); + } + let layer = Button::new("Layer").show(ui); + Menu::context("Layer menu", &layer).show(ui, |ui, _| { + MenuItem::new("Delete layer").show(ui); + }); + Button::new("Copy").id_salt("first copy").show(ui); + Button::new("Copy").id_salt("second copy").show(ui); + Button::new("Archive").enabled(false).show(ui); + TextField::new("Name", Bind::bound(&mut *name.borrow_mut())).show(ui); + }); + let (host, ctx) = (WindowHost::of(fx.ctx()), fx.ctx().clone()); + host.keep_access_tree(); + fx.settle(); + let none = |_: usize, _: Pos2| None; + let send = |fx: &mut Fixture, method: &str, params: Value| { + input_method(method, ¶ms, &host, ViewportId::ROOT, &none).expect("an input method").expect("a target it can name"); + fx.run_injected().settle(); + }; + + send(&mut fx, "ui.click", json!({"label": "save"})); + assert_eq!(saves.get(), 1, "the click by label activated Save once"); + + let field = listed(&host, json!({"role": "TextInput"}))["widgets"][0]["id"].clone(); + assert!(field.is_string(), "the text field is listed with its id"); + let before = listed(&host, json!({"focused": true})); + assert!(before["widgets"].as_array().into_iter().flatten().all(|w| w["id"] != field), "the field has no focus yet: {before}"); + send(&mut fx, "ui.focus", json!({"id": field})); + let focused = listed(&host, json!({"focused": true})); + assert_eq!(focused["widgets"].as_array().map(|w| w.iter().map(|w| w["id"].clone()).collect::>()), Some(vec![field]), "{focused}"); + + // Refused while no popup is open, so each is refused for what it names, not for a covered window. + let refused = [ + ("ui.click", json!({"label": "Nothing here"})), + ("ui.click", json!({"id": "1"})), + ("ui.click", json!({"label": "copy"})), + ("ui.click", json!({"label": "Archive"})), + ("ui.click", json!({"label": "Save", "button": "secondary"})), + ("ui.focus", json!({"label": "Nothing here"})), + ]; + for (method, params) in refused { + let answer = input_method(method, ¶ms, &host, ViewportId::ROOT, &none); + assert!(matches!(answer, Some(Err(_))), "{method} {params} is refused: {answer:?}"); + assert!(host.injected_idle(), "{method} {params} left nothing waiting"); + assert!(hook_without_pass(&ctx, ViewportId::ROOT).is_empty(), "{method} {params} queued nothing"); + } + fx.settle(); + assert_eq!(saves.get(), 1, "no refused request clicked"); + + assert_eq!(listed(&host, json!({"query": "Delete layer"}))["count"], 0, "the menu starts closed"); + send(&mut fx, "ui.click", json!({"label": "Layer", "button": "secondary"})); + assert!(listed(&host, json!({"query": "Delete layer"}))["count"].as_u64().is_some_and(|n| n >= 1), "the context menu opened"); + assert_eq!(saves.get(), 1, "nothing else was clicked"); +} diff --git a/crates/automation/tests/it/control.rs b/crates/automation/tests/it/control.rs index d04fee0923..913d02d16a 100644 --- a/crates/automation/tests/it/control.rs +++ b/crates/automation/tests/it/control.rs @@ -1,4 +1,4 @@ -//! `ControlChannel` deadlines and the loopback server's limits. +//! `ControlChannel` deadlines and the loopback server's limits: connections, request size, authentication. use std::io::{BufRead, BufReader, Write}; use std::net::{SocketAddr, TcpListener, TcpStream}; @@ -8,7 +8,7 @@ use std::time::Duration; use craft_automation::client::ControlClient; use craft_automation::control::{ControlChannel, ControlRequest, ControlResponse, Reply, expired_error, result_reply, timeout_error}; use craft_automation::protocol::MAX_RESPONSE_BYTES; -use craft_automation::security::{CHALLENGE_METHOD, MAX_REQUEST_BYTES, ProofRole, generate_nonce, handshake_proof, proof_matches}; +use craft_automation::security::{CHALLENGE_METHOD, MAX_CONNECTIONS, MAX_REQUEST_BYTES, ProofRole, generate_nonce, handshake_proof, proof_matches}; use craft_automation::server; use craft_ui::runtime::motion; use craft_ui::runtime::windows::WindowHost; @@ -123,6 +123,70 @@ fn an_unauthenticated_connection_is_closed_at_the_deadline_whatever_it_sends() { assert!(rx.try_recv().is_err(), "nothing was dispatched"); } +/// Whether the server closed the connection: the next read is the end of the stream, not a timeout or an error. +fn is_closed(reader: &mut impl BufRead) -> bool { + let mut line = String::new(); + matches!(reader.read_line(&mut line), Ok(0)) +} + +/// With `MAX_CONNECTIONS` connections open, the next one is told `connection limit reached` and closed; once one of +/// the open ones ends, its place serves a new connection. +#[trial] +fn connections_past_the_limit_are_refused_with_the_reason() { + let (rx, server) = server::listen(0, TOKEN.into(), host()).expect("started"); + let connect = || { + let stream = TcpStream::connect(server.addr).expect("connected"); + stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); + let reader = BufReader::new(stream.try_clone().expect("cloned")); + (stream, reader) + }; + // Unauthenticated, so each holds its place until it closes or the authentication deadline passes. + let mut open: Vec = (0..MAX_CONNECTIONS).map(|_| connect().0).collect(); + + let (_extra, mut reader) = connect(); + let refused = read_json(&mut reader).expect("a refusal"); + assert_eq!(refused, json!({"id": null, "ok": false, "error": "connection limit reached"})); + assert!(is_closed(&mut reader), "the refused connection is closed"); + + drop(open.pop()); + // The server frees the place when it reads the close; a new connection is served once it has. + let started = motion::now(); + let served = loop { + let (mut stream, mut reader) = connect(); + writeln!(stream, "{}", json!({"id": 1, "method": "auth", "params": {"token": TOKEN}})).expect("written"); + let reply = read_json(&mut reader).expect("a reply"); + if reply["ok"] == true || started.elapsed() > Duration::from_secs(5) { + break reply; + } + assert_eq!(reply["error"], "connection limit reached", "{reply}"); + std::thread::sleep(Duration::from_millis(20)); + }; + assert_eq!(served["result"]["authenticated"], true, "the freed place serves: {served}"); + assert!(rx.try_recv().is_err(), "nothing was dispatched"); + drop(open); +} + +/// A first frame that is not JSON, and one with a wrong token, each get the `authentication required` refusal and the +/// connection closes at once, without waiting for the deadline and without dispatching anything: a client cannot keep +/// guessing on one connection. +#[trial] +fn a_refused_first_frame_closes_the_connection() { + let (rx, server) = server::listen(0, TOKEN.into(), host()).expect("started"); + let wrong = "f".repeat(TOKEN.len()); + for (first, id) in [("not json".to_owned(), Value::Null), (json!({"id": 4, "method": "auth", "params": {"token": wrong}}).to_string(), json!(4))] + { + let mut stream = TcpStream::connect(server.addr).expect("connected"); + stream.set_read_timeout(Some(Duration::from_secs(5))).expect("timeout"); + let mut reader = BufReader::new(stream.try_clone().expect("cloned")); + writeln!(stream, "{first}").expect("written"); + assert_eq!(read_json(&mut reader).expect("a refusal"), json!({"id": id, "ok": false, "error": "authentication required"}), "{first}"); + // The server may already have closed while this is written. + let _ = writeln!(stream, "{}", json!({"id": 5, "method": "auth", "params": {"token": TOKEN}})); + assert!(is_closed(&mut reader), "{first}: the connection is closed, the second guess unanswered"); + } + assert!(rx.try_recv().is_err(), "nothing was dispatched"); +} + /// A web page can reach loopback: a browser `POST` whose body is a valid `auth` line is refused at its request line /// and the connection closed, so neither the body's `auth` nor a request after it reaches the app. #[trial] diff --git a/crates/automation/tests/it/dock.rs b/crates/automation/tests/it/dock.rs new file mode 100644 index 0000000000..91e1fa97f0 --- /dev/null +++ b/crates/automation/tests/it/dock.rs @@ -0,0 +1,65 @@ +//! `ui.dock.apply` on a workspace, with the host's permissions and lock. + +use craft_automation::dock::{dock_method, inspect}; +use craft_behavior::DockSide; +use craft_behavior::dock::{Action, DockError, DockPlacement, Layout, Node, PanelState, Permissions, Workspace}; +use craft_ui::contract::PlainData; +use craft_ui::docking::{PanelSpec, PanelSpecs}; +use craft_ui::testing::trial; +use serde_json::{Value, json}; + +/// Two panels, the first protected as a canvas is. +#[derive(PlainData)] +struct Panels; + +impl PanelSpecs for Panels { + fn spec(&self, panel: &u8) -> PanelSpec { + PanelSpec::new(format!("Panel {panel}")) + } + + fn permissions(&self, panel: &u8) -> Permissions { + if *panel == 1 { Permissions::PROTECTED } else { Permissions::ALL } + } +} + +fn call(workspace: &mut Workspace, locked: bool, params: Value) -> Result { + dock_method(workspace, &Panels, locked, "ui.dock.apply", ¶ms).expect("a ui.dock method") +} + +/// A JSON action applies to the workspace with the host's permissions and lock; a refused one replies the dock error +/// and changes nothing, and `inspect` lists the workspace. +#[trial] +fn a_dock_action_from_json_applies_to_the_workspace() { + let mut workspace = Workspace::new(Layout::new(Some(Node::tabs(vec![1u8, 2], 0)), Vec::new())); + assert_eq!(workspace.layout().panel_state(&2), PanelState::Open); + + assert_eq!(call(&mut workspace, false, json!({"action": {"Activate": {"panel": 2}}})), Ok(json!({"applied": []}))); + assert_eq!(workspace.layout().panel_state(&2), PanelState::Front, "the activate action brings panel 2 to the front"); + + let before = workspace.clone(); + assert_eq!( + call(&mut workspace, false, json!({"action": Action::close(1u8)})), + Err(DockError::NotAllowed.to_string()), + "the host's permissions protect panel 1" + ); + assert_eq!(workspace, before, "a refused action leaves the workspace as it was"); + assert!(call(&mut workspace, false, json!({"action": Action::activate(1u8), "panel": 1})).is_err(), "an unknown key is refused"); + assert!(call(&mut workspace, false, json!({})).is_err(), "a missing action is refused"); + assert!(call(&mut workspace, false, json!({"action": {"Activate": {}}})).is_err()); + assert_eq!(workspace, before); + + let split = Action::move_beside(2u8, 1, DockPlacement::Split(DockSide::End)); + assert_eq!(call(&mut workspace, true, json!({"action": split})), Err(DockError::NotAllowed.to_string()), "a locked workspace refuses a move"); + assert_eq!(workspace, before); + assert_eq!(call(&mut workspace, true, json!({"action": Action::activate(1u8)})), Ok(json!({"applied": []})), "a locked workspace activates"); + assert_eq!(workspace.layout().panel_state(&1), PanelState::Front); + + assert_eq!(call(&mut workspace, false, json!({"action": Action::close(2u8)})), Ok(json!({"applied": [2]})), "the reply lists the closed panel"); + assert_eq!(workspace.layout().panel_state(&2), PanelState::Hidden); + + assert!(dock_method(&mut workspace, &Panels, false, "ui.dock.close", &json!({})).is_none()); + + let listed = inspect(&workspace); + assert_eq!(serde_json::from_value::>(listed).ok(), Some(workspace.clone()), "inspect lists the whole workspace"); + assert_eq!(workspace.layout().panels(), vec![&1]); +} diff --git a/crates/automation/tests/it/files.rs b/crates/automation/tests/it/files.rs new file mode 100644 index 0000000000..6efa12062a --- /dev/null +++ b/crates/automation/tests/it/files.rs @@ -0,0 +1,71 @@ +//! `ui.pick` at the protocol boundary. + +use std::path::PathBuf; + +use craft_automation::files::pick_method; +use craft_host::{Files, NoPickFiles, PickRequest, Picked, ScriptedFiles}; +use craft_ui::testing::trial; +use serde_json::{Value, json}; + +fn call(files: &dyn Files, params: Value) -> Result { + pick_method(files, "ui.pick", ¶ms).expect("ui.pick is the pick method") +} + +fn path(p: &str) -> PathBuf { + PathBuf::from(p) +} + +/// Each field reaches the service as its `Picked`; with picks on screen the oldest is answered; a bad request is +/// refused with the field list and answers nothing; a service that takes no automated answers says so. +#[trial] +fn ui_pick_answers_the_next_picker_and_refuses_bad_params() { + let answered = Ok(json!({"answered": "next"})); + let files = ScriptedFiles::new(); + assert_eq!(call(&files, json!({"files": ["/w/a.pdf", "/w/b.pdf"]})), answered); + assert_eq!(call(&files, json!({"folder": "/w/out"})), answered); + assert_eq!(call(&files, json!({"save": "/w/c.pdf"})), answered); + assert_eq!(call(&files, json!({"cancel": true, "files": null})), answered, "a null field is omitted"); + let picked: Vec = (0..4) + .map(|_| { + let id = files.pick(PickRequest::open("document")); + files.take_answer(id).expect("a queued answer comes at once") + }) + .collect(); + assert_eq!( + picked, + [ + Picked::Paths(vec![path("/w/a.pdf"), path("/w/b.pdf")]), + Picked::Paths(vec![path("/w/out")]), + Picked::Paths(vec![path("/w/c.pdf")]), + Picked::Cancelled + ] + ); + + let held = ScriptedFiles::held(); + let oldest = held.pick(PickRequest::open("first")); + let newest = held.pick(PickRequest::open("second")); + assert_eq!(call(&held, json!({"files": ["/w/first.pdf"]})), answered); + assert_eq!(held.take_answer(oldest), Some(Picked::Paths(vec![path("/w/first.pdf")])), "the oldest open pick is answered"); + assert_eq!(held.take_answer(newest), None); + assert_eq!(held.open(), 1); + + for bad in [ + json!({"files": ["/w/a.pdf"], "save": "/w/b.pdf"}), + json!({}), + json!({"files": []}), + json!({"files": ["/w/a.pdf", 3]}), + json!({"save": 3}), + json!({"cancel": false}), + json!({"path": "/w/a.pdf"}), + ] { + let error = call(&files, bad.clone()).expect_err("refused"); + assert!(error.contains("files, folder, save, cancel"), "{bad}: {error}"); + } + assert_eq!(call(&files, json!({"folder": "/w/after"})), answered); + let id = files.pick(PickRequest::folder("export")); + assert_eq!(files.take_answer(id), Some(Picked::Paths(vec![path("/w/after")])), "no refused request queued an answer"); + + let unsupported = call(&NoPickFiles::default(), json!({"cancel": true})).expect_err("a service without automated answers refuses"); + assert!(!unsupported.contains("files, folder, save, cancel"), "an unsupported service is not a field-list refusal: {unsupported}"); + assert!(pick_method(&files, "ui.click", &json!({})).is_none()); +} diff --git a/crates/automation/tests/it/main.rs b/crates/automation/tests/it/main.rs index 282a9aed49..1637690af8 100644 --- a/crates/automation/tests/it/main.rs +++ b/crates/automation/tests/it/main.rs @@ -7,5 +7,7 @@ pub(crate) mod actions; pub(crate) mod agents; pub(crate) mod control; pub(crate) mod dialogs; +pub(crate) mod dock; +pub(crate) mod files; pub(crate) mod screenshot; pub(crate) mod synthetic; diff --git a/crates/automation/tests/it/screenshot.rs b/crates/automation/tests/it/screenshot.rs index 56b9fa63ab..e9f06c409e 100644 --- a/crates/automation/tests/it/screenshot.rs +++ b/crates/automation/tests/it/screenshot.rs @@ -1,5 +1,6 @@ //! `Captures`: admission budgets, settling, deadlines, cancellation, document identity, the -//! geometry epoch per viewport, the window a capture names, and the image checks. +//! geometry epoch per viewport, the window a capture names, the image checks, and the region a +//! reply is cropped to. use std::cell::RefCell; use std::sync::Arc; @@ -396,6 +397,98 @@ fn the_image_must_match_the_issued_viewport() { } } +/// The first pixel of a PNG, decoded. +fn first_pixel(png: &[u8]) -> [u8; 4] { + let mut reader = png::Decoder::new(std::io::Cursor::new(png)).read_info().expect("a PNG"); + let mut pixels = vec![0; reader.output_buffer_size()]; + reader.next_frame(&mut pixels).expect("a frame"); + [pixels[0], pixels[1], pixels[2], pixels[3]] +} + +/// A region is checked against the window at admission (and again when the layout changed before issue) and refused +/// when it does not lie inside; the whole window is reserved for it. The reply crops it at the image's own scale to +/// the window, so a fitted image is cropped at its fit, and both reply shapes carry the window's point scale. +#[trial] +fn a_region_is_cropped_at_the_image_scale_and_one_outside_the_window_is_refused() { + use craft_automation::control::ControlChannel; + use craft_automation::screenshot::ScreenshotParams; + use serde_json::json; + + let params = |value| ScreenshotParams::from_params(&value); + let region = Rect::from_min_max(Pos2::new(10.0, 5.0), Pos2::new(60.0, 30.0)); + assert_eq!(params(json!({"path": "a.png", "region": [10, 5, 60, 30]})).map(|p| (p.path, p.region)), Ok((Some("a.png".to_owned()), Some(region)))); + for bad in [json!({"region": [60, 5, 10, 30]}), json!({"region": [10, 5, 60]}), json!({"region": [10, 5, 60, "30"]}), json!({"zoom": 2})] { + assert!(params(bad.clone()).is_err(), "{bad} is refused"); + } + + let ctx = Context::default(); + let now = motion::now(); + let (_transport, requests) = channel(); + let mut control = ControlChannel::new(requests); + let mut g = geometry(100.0, 50.0); + g.pixels_per_point = 2.0; + control.captures.note_geometry(ViewportId::ROOT, g); + let request = |token: u64, region: Rect| { + let (tx, rx) = channel(); + let mut request = ScreenshotRequest::new(token, ViewportId::ROOT, tx); + request.region = Some(region); + (request, rx) + }; + + let (outside, _) = request(1, Rect::from_min_max(Pos2::new(90.0, 40.0), Pos2::new(110.0, 60.0))); + let e = control.captures.admit(outside, now).map_err(|(_, e)| e).expect_err("outside the window"); + assert!(e.contains("inside"), "{e}"); + assert_eq!(control.captures.pending(), 0); + + let (inside, rx) = request(2, region); + control.captures.admit(inside, now).map_err(|(_, e)| e).expect("inside the window"); + assert_eq!(control.captures.reserved_bytes(), 200 * 100 * 4, "the whole window is reserved"); + let mut picture = ColorImage::filled([200, 100], Color32::BLUE); + picture.pixels[10 * 200 + 20] = Color32::RED; + issue_one(&mut control.captures, &ctx, now).complete(Arc::new(picture)); + let finished = control.captures.drain(now, None); + let mut written = Vec::new(); + control.finish_captures(finished, &mut |_, bytes| { + written = bytes.to_vec(); + Ok(()) + }); + let reply = rx.try_recv().expect("a reply"); + assert_eq!((reply["result"]["width"].clone(), reply["result"]["height"].clone()), (json!(100), json!(50)), "{reply}"); + assert_eq!(reply["result"]["pixels_per_point"], 2.0); + assert!(written.is_empty(), "no path, no file"); + use base64::Engine as _; + let png = base64::engine::general_purpose::STANDARD.decode(reply["result"]["base64"].as_str().expect("an inline PNG")).expect("base64"); + assert_eq!(first_pixel(&png), Color32::RED.to_array(), "the crop starts at the region's corner at two pixels per point"); + + // A fitted surface: 600×300 points through a 400-pixel texture side come back as 400×200. + let mut fitted = geometry(600.0, 300.0); + fitted.max_texture_side = 400; + control.captures.note_geometry(ViewportId::ROOT, fitted); + let (mut half, rx) = request(3, Rect::from_min_max(Pos2::new(300.0, 150.0), Pos2::new(600.0, 300.0))); + half.path = Some("half.png".into()); + control.captures.admit(half, now).map_err(|(_, e)| e).expect("inside the window"); + issue_one(&mut control.captures, &ctx, now).complete(filled([400, 200], Color32::WHITE)); + let finished = control.captures.drain(now, None); + control.finish_captures(finished, &mut |path, bytes| { + assert_eq!(path, "half.png"); + written = bytes.to_vec(); + Ok(()) + }); + let reply = rx.try_recv().expect("a reply"); + assert_eq!((reply["result"]["width"].clone(), reply["result"]["height"].clone()), (json!(200), json!(100)), "{reply}"); + assert_eq!(reply["result"]["pixels_per_point"], 1.0); + assert!(!written.is_empty(), "the PNG went to the writer"); + + // A region that a shrink before issue leaves outside is refused then, not cut to a smaller picture. + let (late, _reply) = request(4, region); + control.captures.admit(late, now).map_err(|(_, e)| e).expect("inside the window"); + control.captures.note_geometry(ViewportId::ROOT, geometry(40.0, 20.0)); + let (finished, callbacks) = settle_and_issue(&mut control.captures, &ctx, now, None); + assert!(callbacks.is_empty(), "nothing is captured for it"); + assert!(finished.len() == 1 && error(&finished[0]).contains("inside"), "refused at issue"); + assert_eq!(control.captures.pending(), 0); +} + const ROOT_SIZE: Vec2 = Vec2::new(800.0, 600.0); const CHILD_SIZE: Vec2 = Vec2::new(400.0, 300.0); diff --git a/crates/automation/tests/it/synthetic.rs b/crates/automation/tests/it/synthetic.rs index 07c47287eb..ee2c484f6c 100644 --- a/crates/automation/tests/it/synthetic.rs +++ b/crates/automation/tests/it/synthetic.rs @@ -6,7 +6,7 @@ use std::cell::{Cell, RefCell}; use std::rc::Rc; use craft_automation::access::NO_TREE; -use craft_automation::synthetic::{At, MAX_CLICKS, MAX_SCREEN_POINT, NO_DOCUMENT, NOT_FINITE, input_method}; +use craft_automation::synthetic::{At, Click, Focus, MAX_CLICKS, MAX_SCREEN_POINT, NO_DOCUMENT, NOT_FINITE, input_method}; use craft_ui::contract::{Bind, Show as _}; use craft_ui::runtime::egui::injected::hook_without_pass; use craft_ui::runtime::windows::WindowHost; @@ -340,7 +340,8 @@ fn queued_input_is_withdrawn_when_its_target_changes() { } /// An unknown field, a wrong type, an unknown name, too many clicks or a point too far out refuses the whole request -/// before any of it is queued: no half-queued press or held key is left behind. +/// before any of it is queued: no half-queued press or held key is left behind. A node target takes no point, repeat, +/// hold, modifier or button but the secondary one, and names exactly one of `id` and `label`. #[trial] fn bad_input_params_are_refused_before_anything_is_queued() { let mut rig = Rig::new(); @@ -353,21 +354,90 @@ fn bad_input_params_are_refused_before_anything_is_queued() { ("ui.click", json!({"x": 10, "button": "thumb"})), ("ui.click", json!({"x": 10, "hold": true, "count": MAX_CLICKS + 1})), ("ui.click", json!({"x": far, "hold": true})), - ("ui.move", json!({"x": 10, "nudge": 1})), - ("ui.move", json!({"x": 10, "rest": "long"})), - ("ui.move", json!({"x": 10, "coordinates": "page"})), - ("ui.move", json!({"y": -far})), + ("ui.move", json!({"x": 10, "y": 10, "nudge": 1})), + ("ui.move", json!({"x": 10, "y": 10, "rest": "long"})), + ("ui.move", json!({"x": 10, "y": 10, "coordinates": "page"})), + ("ui.move", json!({"x": 10, "y": -far})), ("ui.key", json!({"key": "A", "hold": true, "nudge": 1})), ("ui.key", json!({"key": 5})), ("ui.key", json!({"key": "NoSuchKey", "hold": true})), ("ui.ime", json!({"preedit": "ab", "cursor": [1, 9]})), + ("ui.click", json!({"x": 10, "y": 10, "label": "Save"})), + ("ui.click", json!({"label": "Save", "count": 2})), + ("ui.click", json!({"label": "Save", "hold": true})), + ("ui.click", json!({"label": "Save", "shift": true})), + ("ui.click", json!({"label": "Save", "button": "middle"})), + ("ui.click", json!({"id": "12", "button": "middle"})), + ("ui.click", json!({"id": "twelve"})), + ("ui.focus", json!({"id": "12", "label": "Save"})), + ("ui.focus", json!({})), + ("ui.drop", json!({"paths": []})), + ("ui.drop", json!({"paths": ["a.pdf"], "alt": true})), ]; - for (method, params) in refused { - let answer = input_method(method, ¶ms, &host, ViewportId::ROOT, &map); + for (method, params) in &refused { + let answer = input_method(method, params, &host, ViewportId::ROOT, &map); assert!(matches!(answer, Some(Err(_))), "{method} {params} is refused: {answer:?}"); assert!(host.injected_idle(), "{method} {params} left nothing waiting"); assert!(hook_without_pass(&ctx, ViewportId::ROOT).is_empty(), "{method} {params} queued nothing"); } + // This window keeps no access tree, so a node request is refused there whatever it says; its parameters alone + // refuse the node rows, and the secondary button, a node's context menu, is allowed. + for (method, params) in refused.iter().filter(|(_, params)| params.get("id").is_some() || params.get("label").is_some() || params == &json!({})) { + let by_params = if *method == "ui.focus" { Focus::from_params(params).is_err() } else { Click::from_params(params).is_err() }; + assert!(by_params, "{method} {params} is refused by its parameters"); + } + assert!(Click::from_params(&json!({"label": "Save", "button": "secondary"})).is_ok()); +} + +/// A key whose press moves the focus (Tab from one field to the next) still has its release carried out: the release +/// is not cancelled as input whose focus changed, no key stays down, and the waiter is answered as processed. The +/// framework takes the Tab press it acts on out of egui's input, so egui's fields never read it. +#[trial] +fn a_key_release_is_carried_out_after_its_press_moves_focus() { + use craft_automation::control::{ControlChannel, ControlRequest, Reply}; + + let passes: Rc>> = Rc::default(); + let rects = Rc::new(Cell::new([Rect::NOTHING; 2])); + let (seen, shown) = (passes.clone(), rects.clone()); + let (first, second) = (Rc::new(RefCell::new(String::new())), Rc::new(RefCell::new(String::new()))); + let fx = Fixture::new(move |ui| { + let a = TextField::new("First", Bind::bound(&mut *first.borrow_mut())).show(ui).response.rect; + let b = TextField::new("Second", Bind::bound(&mut *second.borrow_mut())).show(ui).response.rect; + shown.set([a, b]); + seen.borrow_mut().push(ui.input(|i| Seen { any_key_down: !i.keys_down.is_empty(), events: i.events.clone(), ..Seen::default() })); + }); + let mut rig = Rig { fx, passes }; + rig.fx.settle(); + let at = rects.get()[0].center(); + rig.send("ui.click", json!({"x": at.x, "y": at.y})); + let before = rig.fx.focused(); + assert!(before.is_some(), "the click focused the first field"); + + let (_transport, requests) = std::sync::mpsc::channel(); + let mut channel = ControlChannel::new(requests); + let host = rig.host(); + rig.take(); + input_method("ui.key", &json!({"key": "Tab"}), &host, ViewportId::ROOT, &map).expect("a method").expect("valid"); + let (req, reply) = ControlRequest::new("ui.key", json!({"key": "Tab"})); + channel.settle(req, Reply::AfterInput, None, 0.0); + let mut answer = None; + for _ in 0..32 { + rig.fx.frame(Vec::new()); + channel.poll_input(&host); + answer = reply.try_recv().ok(); + if answer.is_some() { + break; + } + } + rig.fx.frame(Vec::new()); + + let answer = answer.expect("the waiter is answered"); + assert_eq!(answer["ok"], true, "processed, not cancelled: {answer}"); + assert!(rig.fx.focused().is_some() && rig.fx.focused() != before, "the press moved the focus"); + let passes = rig.take(); + let tab = |event: &Event| matches!(event, Event::Key { key: Key::Tab, pressed: true, .. }); + assert!(!passes.iter().any(|pass| pass.events.iter().any(tab)), "the Tab press the framework took reaches no field in egui"); + assert!(passes.last().is_some_and(|pass| !pass.any_key_down), "no key stays down"); } /// `ui.ime` queues behind the input before it: typed text, then the composition with its converted segment, then @@ -448,3 +518,18 @@ fn a_wheel_in_lines_turns_by_notches() { assert!(matches!(refused, Some(Err(_))), "{refused:?}"); assert!(rig.host().injected_idle(), "the refused turn queued nothing"); } + +/// `ui.move` requires both `x` and `y`: omitting either coordinate refuses the request before anything is queued +/// instead of silently moving to 0 on the missing axis. +#[trial] +fn ui_move_refuses_a_missing_coordinate() { + let mut rig = Rig::new(); + rig.fx.settle(); + let (host, ctx) = (rig.host(), rig.fx.ctx().clone()); + for params in [json!({"x": 1}), json!({"y": 1}), json!({})] { + let answer = input_method("ui.move", ¶ms, &host, ViewportId::ROOT, &map); + assert!(matches!(answer, Some(Err(_))), "ui.move {params} is refused: {answer:?}"); + assert!(host.injected_idle(), "ui.move {params} left nothing waiting"); + assert!(hook_without_pass(&ctx, ViewportId::ROOT).is_empty(), "ui.move {params} queued nothing"); + } +} diff --git a/crates/behavior/src/codec.rs b/crates/behavior/src/codec.rs index 17c12ce585..cb45db81a6 100644 --- a/crates/behavior/src/codec.rs +++ b/crates/behavior/src/codec.rs @@ -169,6 +169,7 @@ pub struct NumberCodec { zoom: bool, /// A lone percentage is that share of the start value ([`NumberCodec::share_of_start`]). share: bool, + signed_zoom: bool, } impl fmt::Debug for NumberCodec { @@ -179,6 +180,7 @@ impl fmt::Debug for NumberCodec { .field("fixed", &self.fixed) .field("zoom", &self.zoom) .field("share", &self.share) + .field("signed_zoom", &self.signed_zoom) .field("custom", &self.custom.is_some()) .finish() } @@ -196,6 +198,7 @@ impl PartialEq for NumberCodec { && self.fixed == other.fixed && self.zoom == other.zoom && self.share == other.share + && self.signed_zoom == other.signed_zoom && same_custom } } @@ -230,7 +233,7 @@ const NUMBER_SAMPLE: &str = "0000.00"; impl NumberCodec { /// A codec reading with `reader` and writing at most `decimals` decimal places. pub fn new(reader: Reader, decimals: usize) -> Self { - NumberCodec { reader, decimals, fixed: false, custom: None, zoom: false, share: false } + NumberCodec { reader, decimals, fixed: false, custom: None, zoom: false, share: false, signed_zoom: false } } /// The same codec writing every decimal place, trailing zeros included ("1.00"), as a field of a quantity shown @@ -247,8 +250,14 @@ impl NumberCodec { self } + /// Allow a leading minus in zoom input so the field can reject negative values instead of discarding the sign. + pub fn signed_zoom(mut self) -> Self { + self.signed_zoom = true; + self + } + /// The zoom reading of trimmed, non-empty `text`: the text before a second decimal separator, then `a/b` as a - /// percentage or a plain number. The filter keeps `+`, `-` and `*` out, so the reader's expressions never run. + /// percentage or a plain number. The filter keeps `+` and `*` out, so the reader's expressions never run. fn read_zoom(&self, text: &str) -> Result<(f64, ParseNote), NotAValue> { let separator = self.reader.decimal_separator(); let second = text.char_indices().filter(|&(_, c)| c == separator).nth(1).map(|(at, _)| at); @@ -256,6 +265,9 @@ impl NumberCodec { Some(at) => (&text[..at], true), None => (text, false), }; + if kept.strip_prefix('-').unwrap_or(kept).contains('-') { + return Err(NotAValue); + } let number = match kept.split_once('/') { Some((part, whole)) => { let part = self.reader.read(part, None)?; @@ -371,9 +383,9 @@ impl Codec for NumberCodec { } } - /// Zoom typing takes ASCII digits, `/` and the decimal separator; every other number field takes every character. + /// Zoom typing takes ASCII digits, `/` and the decimal separator, with an optional minus; other fields take every character. fn filter(&self, c: char) -> bool { - !self.zoom || c.is_ascii_digit() || c == '/' || c == self.reader.decimal_separator() + !self.zoom || c.is_ascii_digit() || (self.signed_zoom && c == '-') || c == '/' || c == self.reader.decimal_separator() } fn sample(&self, _current: &Option) -> Cow<'_, str> { diff --git a/crates/behavior/src/cursor.rs b/crates/behavior/src/cursor.rs index af14c260b4..3b6a67f783 100644 --- a/crates/behavior/src/cursor.rs +++ b/crates/behavior/src/cursor.rs @@ -351,6 +351,8 @@ pub enum CursorPriority { DropTarget, /// A drag in progress. Drag, + /// Hides the pointer over everything, links included, while a presentation runs. + Hidden, } /// The winning request: the highest priority, the later request on a tie. diff --git a/crates/behavior/src/edit_history.rs b/crates/behavior/src/edit_history.rs index cc2144d7d1..0b05d3c00c 100644 --- a/crates/behavior/src/edit_history.rs +++ b/crates/behavior/src/edit_history.rs @@ -1,6 +1,6 @@ //! `EditHistory`: the undo and redo of a dialog, a tool session or the keymap editor, fed by edit events. -use crate::value::{EditEvent, GestureId, Value}; +use crate::value::{EditEvent, GestureId, Mixed, Value}; use std::sync::Arc; /// Most steps a history keeps. @@ -78,14 +78,15 @@ impl EditHistory { self.undo.drain(..gone); } - /// Takes in one event. Events of a gesture other than the open one are ignored. + /// Takes in one event. Events of a gesture other than the open one are ignored. A concrete + /// before value captures changes made outside history since the preceding edit. pub fn record(&mut self, event: &EditEvent) { match event { EditEvent::Begin { id, label, .. } => self.open = Some(Open { id: *id, name: label.clone() }), EditEvent::Update { .. } => {} - EditEvent::Commit { id, after, .. } => { + EditEvent::Commit { id, before, after } => { if let Some(open) = self.open.take_if(|open| open.id == *id) { - self.push(after, open.name); + self.push(before, after, open.name); } } EditEvent::Cancel { id, .. } => { @@ -93,9 +94,9 @@ impl EditHistory { self.open = None; } } - EditEvent::Set { after, label, .. } => { + EditEvent::Set { before, after, label, .. } => { self.open = None; - self.push(after, label.clone()); + self.push(before, after, label.clone()); } } } @@ -105,17 +106,21 @@ impl EditHistory { self.open.is_some() } - fn push(&mut self, after: &T, name: Arc) { - if *after == self.settled { + fn push(&mut self, before: &Mixed, after: &T, name: Arc) { + let weight = match before.same() { + Some(value) => self.budget.map_or(0, |(_, weigh)| weigh(value)), + None => self.settled_weight, + }; + let before = before.same().unwrap_or(&self.settled).clone(); + self.settled = after.clone(); + self.settled_weight = self.budget.map_or(0, |(_, weigh)| weigh(after)); + if *after == before { return; } if self.undo.len() >= LIMIT { self.undo.remove(0); } - let weight = self.budget.map_or(0, |(_, weigh)| weigh(after)); - let value = std::mem::replace(&mut self.settled, after.clone()); - let weight = std::mem::replace(&mut self.settled_weight, weight); - self.undo.push(Entry { value, name, weight }); + self.undo.push(Entry { value: before, name, weight }); self.redo.clear(); self.trim(); } @@ -170,6 +175,17 @@ mod tests { EditEvent::set(Mixed::Same(before), after, "Fill".into(), None) } + #[test] + fn undo_restores_selection_changed_between_edits() { + let mut history = EditHistory::new(&(0, 0)); + history.record(&EditEvent::set(Mixed::Same((0, 1)), (1, 0), "Remove".into(), None)); + let mut now = (1, 0); + assert!(history.step(&mut now, Step::Undo)); + assert_eq!(now, (0, 1)); + assert!(history.step(&mut now, Step::Redo)); + assert_eq!(now, (1, 0)); + } + #[test] fn a_take_back_returns_the_earlier_value_keeps_redo_and_settles() { let mut history = EditHistory::new(&0); diff --git a/crates/behavior/src/frame_step.rs b/crates/behavior/src/frame_step.rs new file mode 100644 index 0000000000..a293d5a1ff --- /dev/null +++ b/crates/behavior/src/frame_step.rs @@ -0,0 +1,10 @@ +//! The step of one pass of motion: a Hand glide, a held Zoom press and an autoscroll integrate over it. + +/// The longest step motion integrates, in seconds, so a stalled pass never jumps the view. +pub const FRAME_STEP_MAX: f64 = 0.1; + +/// The step of a pass that came `dt` seconds after the previous one, `dt` being the time between two readings of the +/// caller's pass clock: `dt` within `0..=FRAME_STEP_MAX`, and 0 where it is not a number. +pub fn frame_step(dt: f64) -> f64 { + if dt.is_finite() { dt.clamp(0.0, FRAME_STEP_MAX) } else { 0.0 } +} diff --git a/crates/behavior/src/geometry/crop.rs b/crates/behavior/src/geometry/crop.rs index 153be1ffa5..7fa0422777 100644 --- a/crates/behavior/src/geometry/crop.rs +++ b/crates/behavior/src/geometry/crop.rs @@ -148,9 +148,11 @@ impl CropBox { (w.is_finite() && h.is_finite()).then(|| (w.round().max(1.0), h.round().max(1.0))) } - /// Whether both sides are at least one document unit. - pub fn size_ok(&self) -> bool { - self.rect.width() >= MIN_FRAME && self.rect.height() >= MIN_FRAME + /// Whether both sides are at least `min`, and never under one document unit whatever `min` says (a `min` that is + /// not a number counts as one unit). + pub fn size_ok(&self, min: f64) -> bool { + let min = min.max(MIN_FRAME); + self.rect.width() >= min && self.rect.height() >= min } /// The frame with `part` dragged by the page vector `by`: along the frame's own axes, the opposite edges kept on diff --git a/crates/behavior/src/geometry/mod.rs b/crates/behavior/src/geometry/mod.rs index 434fd68dfd..4e064fbfce 100644 --- a/crates/behavior/src/geometry/mod.rs +++ b/crates/behavior/src/geometry/mod.rs @@ -24,7 +24,7 @@ pub use lock::{ pub use marquee::{Constraint, MarqueeGesture, MarqueeRect, fixed_size_pixels, marquee_pixels, square_pixels}; pub use move_gesture::{ConstrainStyle, MoveGesture, MoveValue, StrokeLock}; pub use outside::outside_pieces; -pub use quad::{BoxAllow, BoxDrag, BoxPart, BoxRules, BoxState, Homography, Parts, SKEW_LIMIT, ScaleRule, TransformMode, drag}; +pub use quad::{BoxAllow, BoxDrag, BoxHandles, BoxPart, BoxRules, BoxState, Homography, Parts, SKEW_LIMIT, ScaleRule, TransformMode, drag}; pub use selection_op::SelectionOperation; pub use snap::{ SNAP_PX, SnapGesture, SnapKind, SnapKinds, SnapLine, SnapOptions, SnapSuspend, SnapTarget, SnapTargets, across_axis, coordinate_across, diff --git a/crates/behavior/src/geometry/quad.rs b/crates/behavior/src/geometry/quad.rs index 6b44078e0f..c61e76723d 100644 --- a/crates/behavior/src/geometry/quad.rs +++ b/crates/behavior/src/geometry/quad.rs @@ -97,6 +97,8 @@ pub enum ScaleRule { /// PhotoCraft's Use Legacy Free Transform, DesignCraft and VectorCraft: corners stretch freely /// and ⇧ keeps the proportions; edges stretch their one axis. Free, + /// Corners keep their proportions using the larger relative axis change; ⇧ frees them. + LargerAxis, /// A shape or path bounds box: a corner scales by the projection of the drag on the anchor-corner diagonal, /// keeping the proportions; an edge stretches its one axis. Shape, @@ -203,6 +205,25 @@ pub struct BoxRules { /// minimum keeps a scale drag from flipping the box, and a side already shorter than it at /// the press keeps its length as its floor, so a click changes nothing. pub min_side: f64, + /// Which handles the box shows and takes keys and drags for. + pub handles: BoxHandles, + /// How far either side of a side's line a press grabs that side, in screen points, along the whole side and as + /// far past its ends: a paragraph frame whose edges rewrap it. Inside the box the band reaches at most a quarter of + /// the way across, so a narrow box keeps its middle. 0, the default, leaves each side its band outside the box. + pub edge_band: f32, +} + +/// Which handles of a box are shown. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub enum BoxHandles { + /// The four corners and the four sides. + #[default] + All, + /// The four corners. + Corners, + /// The right and left sides. + Sides, } impl Default for BoxRules { @@ -214,6 +235,8 @@ impl Default for BoxRules { allow: BoxAllow::default(), rotate_step: 15.0, min_side: 0.0, + handles: BoxHandles::default(), + edge_band: 0.0, } } } @@ -249,6 +272,28 @@ impl BoxRules { self } + /// The rules with `handles` as the handles the box shows. + pub fn with_handles(mut self, handles: BoxHandles) -> BoxRules { + self.handles = handles; + self + } + + /// The rules with each side grabbed within `points` of its line ([`edge_band`](Self::edge_band)). + pub fn with_edge_band(mut self, points: f32) -> BoxRules { + self.edge_band = points; + self + } + + /// Whether the box shows `part`: `Corners` shows the four corners and no side, `Sides` the right and left sides + /// and no corner. The inside, the outside and the reference point always show. + pub fn shows(&self, part: BoxPart) -> bool { + match (self.handles, part) { + (BoxHandles::Corners, BoxPart::Edge(_)) | (BoxHandles::Sides, BoxPart::Corner(_)) => false, + (BoxHandles::Sides, BoxPart::Edge(k)) => k % 2 == 1, + _ => true, + } + } + /// The mode drags follow: a mode the content refuses scales as Free Transform does. pub fn effective_mode(&self) -> TransformMode { let refused = match self.mode { @@ -262,14 +307,15 @@ impl BoxRules { /// Whether a drag of `part` changes the box: in Distort only the corners, the inside and the /// reference point; in Skew everything but the outside; the outside only where rotating is - /// allowed. A click outside a refused zone still applies the box (the overlay's rule). + /// allowed; and never a handle the box does not [show](Self::shows). A click outside a refused + /// zone still applies the box (the overlay's rule). pub fn allows(&self, part: BoxPart) -> bool { let by_mode = match self.effective_mode() { TransformMode::Distort => !matches!(part, BoxPart::Outside | BoxPart::Edge(_)), TransformMode::Skew => part != BoxPart::Outside, _ => true, }; - by_mode && (self.allow.rotate || part != BoxPart::Outside) + by_mode && (self.allow.rotate || part != BoxPart::Outside) && self.shows(part) } /// The modifiers a drag of `part` acts on, from the keys held: ⌘ is dropped on a corner or @@ -504,16 +550,22 @@ fn apply_drag(g: &Gesture, p: Point, mods: Mods, rules: &BoxRules) -> BoxState { } BoxState { quad, pivot: carry_pivot(q0, quad, c) } } - BoxPart::Corner(_) | BoxPart::Edge(_) => scale_drag(g, p, mods, rules.min_side).unwrap_or(BoxState { quad: q0, pivot: c }), + BoxPart::Corner(_) | BoxPart::Edge(_) => { + scale_drag(g, p, mods, rules.min_side, rules.scale == ScaleRule::LargerAxis).unwrap_or(BoxState { quad: q0, pivot: c }) + } } } /// A plain corner or edge drag: scaling in the box's own frame (the unit square through the /// homography), so rotated and skewed boxes scale along their axes. A proportional corner follows -/// the pointer's projection on the line from the anchor to the corner, so a distorted box scales -/// along its own diagonal; past the anchor the factor turns negative and the box flips. Each -/// scaled side keeps at least `min_side` ([`scale_floor`]). `None` for a collapsed box. -fn scale_drag(g: &Gesture, p: Point, mods: Mods, min_side: f64) -> Option { +/// the pointer's projection on the diagonal, or the larger relative axis change when selected. Past the anchor +/// the factor turns negative and the box flips. Each scaled side keeps at least `min_side` +/// ([`scale_floor`]). `None` for a collapsed box. +fn scale_drag(g: &Gesture, p: Point, mods: Mods, min_side: f64, larger_axis: bool) -> Option { + let p = match g.part { + BoxPart::Corner(i) => g.quad0[usize::from(i) % 4] + (p - g.start), + _ => p, + }; let h = Homography::unit_to_quad(g.quad0)?; let inv = h.inverse()?; let Point { x: u, y: v } = inv.apply(p); @@ -556,16 +608,14 @@ fn scale_drag(g: &Gesture, p: Point, mods: Mods, min_side: f64) -> Option 1e-12 { + let k = if larger_axis { + if (ku - 1.0).abs() > (kv - 1.0).abs() { ku } else { kv } + } else if len2 > 1e-12 { let q = inv.apply(a + d * ((p - a).dot(d) / len2)); if (hu - au).abs() >= (hv - av).abs() { (q.x - au) / (hu - au) } else { (q.y - av) / (hv - av) } } else { diff --git a/crates/behavior/src/hit.rs b/crates/behavior/src/hit.rs index 809e32666f..d2cd1f848b 100644 --- a/crates/behavior/src/hit.rs +++ b/crates/behavior/src/hit.rs @@ -309,6 +309,11 @@ pub struct Shape { pub local: bool, /// The least size across the hit area has, in points. pub min_across: f32, + /// The named stacking order: stacked parts of one priority rank by it before the nearest centre, the higher order + /// winning. + pub stacking: u32, + /// Whether a passed drag targets the arena root instead of the next shape. + pub drag_to_root: bool, } impl Shape { @@ -330,7 +335,7 @@ impl Shape { impl Shape { /// A shape of `owner` at stack `position`. pub const fn new(shape: HitShape, sense: Sense, owner: O, part: Option, priority: HitPriority, position: u32) -> Self { - Shape { shape, sense, owner, part, priority, position, local: false, min_across: 0.0 } + Shape { shape, sense, owner, part, priority, position, local: false, min_across: 0.0, stacking: 0, drag_to_root: false } } /// The hit area is at least `across` points wide and high. @@ -339,6 +344,12 @@ impl Shape { self } + /// The shape's stacking order among shapes of its priority: the higher order wins before the nearest centre. + pub const fn stacking(mut self, order: u32) -> Self { + self.stacking = order; + self + } + /// The shape lies in the body layer's space. pub const fn local(mut self, local: bool) -> Self { self.local = local; @@ -376,10 +387,12 @@ pub struct Winner { pub sense: Sense, /// Its shape lies in the body layer's space. pub local: bool, + /// A passed drag targets the arena root. + pub drag_to_root: bool, } -/// The winner among `shapes` at `point`: stack position first, then level, sub-level, the nearest centre, the last -/// registered. A press considers only shapes that sense a click or a drag. +/// The winner among `shapes` at `point`: stack position first, then level, sub-level, stacking order, the nearest +/// centre, the last registered. A press considers only shapes that sense a click or a drag. pub fn resolve(shapes: &[Shape], point: Pos2, what: ResolveFor) -> Option> { resolve_mapped(shapes, point, what, |_| point) } @@ -394,12 +407,19 @@ pub fn resolve_mapped(shapes: &[Shape], point: Pos2, what: ResolveFo .filter(|(_, shape)| what == ResolveFor::Hover || shape.sense.takes_press()) .filter(|(_, shape)| shape.hits(at(shape))) .max_by(|(ia, a), (ib, b)| { - (a.position, a.priority.level, a.priority.sub) - .cmp(&(b.position, b.priority.level, b.priority.sub)) + (a.position, a.priority.level, a.priority.sub, a.stacking) + .cmp(&(b.position, b.priority.level, b.priority.sub, b.stacking)) .then_with(|| distance(b).partial_cmp(&distance(a)).unwrap_or(Ordering::Equal)) .then(ia.cmp(ib)) }) - .map(|(index, shape)| Winner { index, owner: shape.owner, part: shape.part, sense: shape.sense, local: shape.local }) + .map(|(index, shape)| Winner { + index, + owner: shape.owner, + part: shape.part, + sense: shape.sense, + local: shape.local, + drag_to_root: shape.drag_to_root, + }) } #[cfg(test)] @@ -436,6 +456,17 @@ mod tests { assert_eq!(owner(&tie), Some(2)); } + #[test] + fn stacked_parts_of_one_priority_rank_by_their_order_before_the_nearest_centre() { + let at = pos2(50.0, 50.0); + let owner = |shapes: &[Shape]| resolve(shapes, at, ResolveFor::Press).map(|w| w.owner); + let near = || shape(rect(40.0, 40.0, 20.0, 20.0), Sense::CLICK, 1, 0, HitLevel::Body, 0); + let far = || shape(rect(0.0, 0.0, 200.0, 200.0), Sense::CLICK, 2, 0, HitLevel::Body, 0); + assert_eq!(owner(&[far(), near()]), Some(1), "unstacked, the nearer centre wins"); + assert_eq!(owner(&[far().stacking(1), near()]), Some(2), "the higher stacking order wins though the press is nearer the other's centre"); + assert_eq!(owner(&[near().stacking(1), far().stacking(1)]), Some(1), "one order: the nearest centre decides"); + } + #[test] fn a_polyline_hits_within_its_own_reach_and_a_bad_reach_is_a_lines() { let points = vec![pos2(0.0, 0.0), pos2(100.0, 0.0)]; diff --git a/crates/behavior/src/item_layout.rs b/crates/behavior/src/item_layout.rs index b29a32b993..49bd039554 100644 --- a/crates/behavior/src/item_layout.rs +++ b/crates/behavior/src/item_layout.rs @@ -30,6 +30,12 @@ pub trait ItemLayout { /// The item under `point`. fn hit(&self, point: Pos2, offset: ScrollPos) -> Option; + /// The item whose drop area contains `point`. Layouts with visible gaps can include those in a drop area while + /// leaving them out of ordinary pointer hits. + fn drop_hit(&self, point: Pos2, offset: ScrollPos) -> Option { + self.hit(point, offset) + } + /// How arrow keys move through the items. fn nav(&self) -> NavShape; @@ -105,7 +111,8 @@ pub trait ItemLayout { /// Whether the items are as wide as they measure themselves. A layout that asks for widths places the items /// from their measured ideal and minimum widths (`set_width`), so every item must be built and measured: its - /// `visible` lists all items, and the collection does not virtualise it. + /// `visible` lists all items, and the collection does not virtualise it. Its items sit side by side, so where the + /// collection's width comes from its rows (a room that does not bound it) it is their ideal widths' sum. fn auto_widths(&self) -> bool { false } diff --git a/crates/behavior/src/item_source.rs b/crates/behavior/src/item_source.rs index 871e43d4c5..edac87c282 100644 --- a/crates/behavior/src/item_source.rs +++ b/crates/behavior/src/item_source.rs @@ -59,13 +59,18 @@ pub trait DisplayOrder { } /// Whether section `at` is a stop of navigation: it holds the lead, takes Enter, the context-menu key and a - /// press, and opens or closes with Forward and Back when it has children. A move stops on it, and it is never - /// selected, extended over, toggled, marqueed, dragged, renamed or reached by type-ahead. Only meaningful for a - /// section. + /// press, and opens or closes with Forward and Back when it has children. A move stops on it. By default it is + /// not selected or extended over; see `selectable_section`. It is not toggled, marqueed, dragged, renamed or + /// reached by type-ahead. Only meaningful for a section. fn section_stop(&self, _at: usize) -> bool { false } + /// Whether a section stop also represents an item that keyboard selection can pick or extend over. + fn selectable_section(&self, _at: usize) -> bool { + false + } + /// How many section stops (`section_stop`) come before entry `at`. They are not members of the set of items, so /// the positions an item reports to assistive technology do not count them. fn section_stops_before(&self, _at: usize) -> usize { diff --git a/crates/behavior/src/keys.rs b/crates/behavior/src/keys.rs index a24e52bf5e..c7fbcc40ff 100644 --- a/crates/behavior/src/keys.rs +++ b/crates/behavior/src/keys.rs @@ -7,9 +7,20 @@ use crate::intent::{Granularity, Intent, MoveMods, NavMove}; use craft_host::target::Os; use craft_keymap::{Chord, Key, Mods}; -/// What the focused stop is, as far as the table's rows differ. +/// The named key scheme of a reorderable collection. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[non_exhaustive] +pub enum ReorderKeys { + /// The stacking keys (`REORDER_KEYS`): Cmd+] and Cmd+[. + #[default] + Stacking, + /// Alt with the arrows (`ALT_ARROW_KEYS`). + AltArrows, +} + +/// What the focused stop is, as far as the table's rows differ. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +#[non_exhaustive] pub struct KeyRole { /// A value control with a reset value and no text part: Delete resets it. pub resettable: bool, @@ -17,8 +28,10 @@ pub struct KeyRole { pub space: bool, /// A collection that selects several items: Ctrl+Space (Control on macOS) toggles the lead's pick. pub multi_select: bool, - /// A reorderable collection: the stacking keys (`REORDER_KEYS`) move the selected items. - pub reorderable: bool, + /// The scheme whose keys move the selected items of a reorderable collection, `None` when it does not reorder. + pub reorderable: Option, + /// The axis the collection's order is laid out along. + pub reorder_axis: Axis, /// A collection with `CollectionProps.rename`. pub rename: bool, /// `FocusPolicy.pages`: Ctrl+Tab switches pages. @@ -52,6 +65,12 @@ pub struct KeyRole { pub home_row: usize, } +impl Default for KeyRole { + fn default() -> Self { + Self::new() + } +} + impl KeyRole { /// A role with no special rows. pub const fn new() -> KeyRole { @@ -59,7 +78,8 @@ impl KeyRole { resettable: false, space: false, multi_select: false, - reorderable: false, + reorderable: None, + reorder_axis: Axis::Y, rename: false, pages: false, nudge: false, @@ -94,9 +114,15 @@ impl KeyRole { self } - /// The stacking keys move the selected items. - pub const fn reorderable(mut self, on: bool) -> Self { - self.reorderable = on; + /// The scheme's keys move the selected items; `None` when the stop does not reorder. + pub const fn reorderable(mut self, keys: Option) -> Self { + self.reorderable = keys; + self + } + + /// The axis the order is laid out along. + pub const fn reorder_axis(mut self, axis: Axis) -> Self { + self.reorder_axis = axis; self } @@ -191,12 +217,29 @@ pub enum DropOperation { Link, } -/// The drop operation the held modifiers pick. -pub fn drop_operation(os: Os, mods: Mods) -> DropOperation { - let link = if os == Os::Mac { mods.cmd && mods.alt } else { mods.cmd && mods.shift }; +/// Which held key turns a drag into a copy over a target. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum CopyKeys { + /// Alt, Option on macOS: a design app's duplicating drag (Photoshop's layers). + #[default] + Alt, + /// The file manager's: Ctrl off macOS, Option on macOS (Explorer, Finder, a document's page grid). + Platform, +} + +/// The drop operation the held modifiers pick over a target that copies with `copy`. Link is Ctrl+Shift, Cmd+Option on +/// macOS, whatever the copy keys. +pub fn drop_operation(os: Os, mods: Mods, copy: CopyKeys) -> DropOperation { + let mac = os == Os::Mac; + let link = if mac { mods.cmd && mods.alt } else { mods.cmd && mods.shift }; + let copies = match copy { + CopyKeys::Platform if !mac => mods.cmd, + _ => mods.alt, + }; if link { DropOperation::Link - } else if mods.alt { + } else if copies { DropOperation::Copy } else { DropOperation::Move @@ -221,14 +264,32 @@ pub const REORDER_KEYS: [Chord; 6] = [ Chord::new(Mods { shift: true, ..Mods::CMD }, Key::OpenCurlyBracket), ]; -/// The `Intent::MoveItem` a stacking key asks for, `None` for any other press. -pub fn reorder_intent(key: Key, mods: Mods) -> Option { +/// The four Alt+arrow chords of `ReorderKeys::AltArrows`. +pub const ALT_ARROW_KEYS: [Chord; 4] = + [Chord::new(Mods::ALT, Key::Up), Chord::new(Mods::ALT, Key::Down), Chord::new(Mods::ALT, Key::Left), Chord::new(Mods::ALT, Key::Right)]; + +/// The `Intent::MoveItem` a key of the scheme `keys` asks for in an order laid out along `axis`, `None` for any other +/// press. +pub fn reorder_intent(key: Key, mods: Mods, keys: ReorderKeys, axis: Axis) -> Option { let chord = Chord::new(mods, key); - if !REORDER_KEYS.contains(&chord) { - return None; + match keys { + ReorderKeys::Stacking => { + if !REORDER_KEYS.contains(&chord) { + return None; + } + let front = matches!(key, Key::CloseBracket | Key::CloseCurlyBracket); + Some(Intent::move_item(front, mods.shift)) + } + ReorderKeys::AltArrows => { + if !ALT_ARROW_KEYS.contains(&chord) { + return None; + } + // Down and Right are one place later in reading order on either axis; the item step turns `front` back + // into a direction with `toward_end` over the same axis, which is its own inverse. + let later = matches!(key, Key::Down | Key::Right); + Some(Intent::move_item(toward_end(later, axis), false)) + } } - let front = matches!(key, Key::CloseBracket | Key::CloseCurlyBracket); - Some(Intent::move_item(front, mods.shift)) } /// Whether a move toward the front goes toward the end of an order laid out along `axis`. The front of a vertical @@ -256,8 +317,12 @@ pub fn intent(os: Os, key: Key, mods: Mods, role: KeyRole) -> Option { if let Some(fine) = fine_move(key, mods, role) { return Some(fine); } - if role.reorderable - && let Some(reorder) = reorder_intent(key, mods) + // Before the Alt+Up and Alt+Down rows, so that the Alt+arrow scheme reorders instead of opening or closing. Rows + // stacked one per line have no neighbour across their axis: the arrows across it stay their move rows there. + let across = if role.reorder_axis == Axis::X { matches!(key, Key::Up | Key::Down) } else { matches!(key, Key::Left | Key::Right) }; + if let Some(keys) = role.reorderable + && !(role.stacked && across) + && let Some(reorder) = reorder_intent(key, mods, keys, role.reorder_axis) { return Some(reorder); } diff --git a/crates/behavior/src/lib.rs b/crates/behavior/src/lib.rs index 12bc90ba77..617f1f0347 100644 --- a/crates/behavior/src/lib.rs +++ b/crates/behavior/src/lib.rs @@ -23,6 +23,7 @@ pub mod eviction; pub mod fit; pub mod flow; pub mod focus; +pub mod frame_step; pub mod grid; pub mod hit; pub mod hold_repeat; @@ -34,6 +35,7 @@ pub mod item_source; pub mod keys; pub mod label_column; pub mod layout_memory; +pub mod middle_scroll; pub mod monitor; pub mod motion; pub mod nav; @@ -80,6 +82,7 @@ pub use edit_history::EditHistory; pub use editor::{EditorInput, SurroundingUnit}; pub use flow::{Axis, Flow, Insets}; pub use focus::{CancelRule, KeyOwner, OwnerClass, PressFocus, ScopeKind}; +pub use frame_step::{FRAME_STEP_MAX, frame_step}; pub use grid::{GridCursor, GridMeasure, resolve_columns}; pub use hit::{HitLevel, HitPriority, HitShape, ResolveFor, Shape, Winner, resolve, resolve_mapped}; pub use input::Input; @@ -87,9 +90,10 @@ pub use intent::{AccessRequest, EditCommand, Granularity, Intent, MoveMods, NavM pub use item_layout::{FreeLayout, ItemLayout, LineIndex, SHEET_ZOOM, SheetLayout, SpanLayout, TileLayout}; pub use item_marquee::{MarqueeMode, MarqueeSelect}; pub use item_source::{DisplayOrder, ItemSource, Keyed, Outline, SizeHint, keyed}; -pub use keys::{DropOperation, KeyRole}; +pub use keys::{CopyKeys, DropOperation, KeyRole, ReorderKeys}; pub use label_column::{LabelColumn, LabelPlacement}; pub use layout_memory::SizeTween; +pub use middle_scroll::{MiddleButton, MiddleScroll}; pub use monitor::{Monitor, MonitorKey}; pub use motion::{MotionKind, MotionMode, Playback}; pub use nav::{Arrows, Letters, NavOutline, NavShape, NavState, NavStep, Roving, TypeAhead, lead_step, wheel_step}; @@ -99,8 +103,8 @@ pub use pixel_size::PixelSize; pub use hold_repeat::HoldRepeat; pub use press::{ - Buttons, MultiTap, MultiTouch, PassInput, PointerButton, PointerEvent, PointerKind, PointerSample, PressCancel, PressMachine, PressPhase, - PressStart, PressState, PressStep, count_clicks, + Buttons, MultiTap, MultiTouch, PassInput, PointerButton, PointerEvent, PointerKind, PointerSample, PressAside, PressCancel, PressMachine, + PressPhase, PressPick, PressStart, PressState, PressStep, count_clicks, }; pub use quantity::Reader; pub use role_rule::{GridFacts, RoleRule, is_checkable, is_selectable, role_violations}; @@ -117,7 +121,7 @@ pub use value::{ same_in_f32, same_in_f32_at, }; pub use value_drag::{DragWarp, ValueDrag, wrap_value}; -pub use wheel::{GESTURE_GAP, Wheel, WheelFocus, WheelGesture, WheelNotch, WheelPhase, WheelRoom, WheelSource, WheelTaker, WheelUnit}; +pub use wheel::{GESTURE_GAP, Wheel, WheelEase, WheelFocus, WheelGesture, WheelNotch, WheelPhase, WheelRoom, WheelSource, WheelTaker, WheelUnit}; #[cfg(test)] extern crate self as craft_behavior; diff --git a/crates/behavior/src/middle_scroll.rs b/crates/behavior/src/middle_scroll.rs new file mode 100644 index 0000000000..16d2bbe3ae --- /dev/null +++ b/crates/behavior/src/middle_scroll.rs @@ -0,0 +1,115 @@ +//! The middle button's auto-scroll latch: the gesture state of one middle press. + +use crate::frame_step; +use crate::press::PressPhase; +use emath::{Pos2, Vec2}; + +/// How far, in points, the pointer may sit above or below the anchor without scrolling. +const DEAD_ZONE: f32 = 15.0; +/// Held passes past the dead zone after which a release ends the latch: a shorter hold is a click, which keeps it. +const HELD_PASSES: u32 = 2; +/// The power of the distance the speed grows with. +const SPEED_EXPONENT: f32 = 2.2; +/// Points per second per unit of the distance raised to [`SPEED_EXPONENT`]. +const SPEED_MULTIPLIER: f32 = 0.04; +/// The farthest distance the speed is computed from, so the power of a hostile pointer position stays finite. No +/// pointer on a real screen reaches it. +const MAX_DISPLACEMENT: f32 = 1_000_000.0; + +/// What the middle button does over a scroll area. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub enum MiddleButton { + /// Drags the view. + #[default] + Pan, + /// Latches an auto-scroll anchor. + AutoScroll, +} + +/// The auto-scroll latch of one middle press. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct MiddleScroll { + anchor: Option, + held_passes: u32, + swallowing: bool, +} + +impl MiddleScroll { + /// A middle press: inside the scroll area it latches at `at`; a second press ends the latch. + pub fn press(&mut self, at: Pos2, inside: bool) { + if self.active() { + self.cancel(); + } else if inside && at.is_finite() { + self.anchor = Some(at); + self.held_passes = 0; + } + } + + /// The button went up: after two held passes with the pointer past the dead zone the latch ends; an earlier + /// release keeps it. + pub fn release(&mut self) { + if self.held_passes >= HELD_PASSES { + self.cancel(); + } + } + + /// Whether a press's `phase` belongs to the press that ended a latch and so reaches nothing else: true for the + /// `Down` that cancels an active latch and for each later phase of that press through its release or cancel. A + /// press that begins while nothing is latched is not swallowed. + pub fn swallows(&mut self, phase: PressPhase) -> bool { + match phase { + PressPhase::Down { .. } => { + self.swallowing = self.active(); + if self.swallowing { + self.cancel(); + } + self.swallowing + } + PressPhase::Release { .. } | PressPhase::Cancel { .. } => std::mem::take(&mut self.swallowing), + PressPhase::Idle | PressPhase::Hover => false, + _ => self.swallowing, + } + } + + /// Ends the latch. + pub fn cancel(&mut self) { + self.anchor = None; + self.held_passes = 0; + } + + /// One pass: with this pass's `pointer` and `held` state it counts the held passes past the 15 pt dead zone and + /// returns the vertical scroll for the step `frame_step(dt)`, at `|d|^2.2 × 0.04` points per second, reversed by + /// `invert`. The result moves the content: with the pointer below the anchor it is negative, so the view scrolls + /// down. Zero while nothing is latched. + pub fn step(&mut self, pointer: Pos2, held: bool, dt: f64, invert: bool) -> Vec2 { + let Some(anchor) = self.anchor else { return Vec2::ZERO }; + let displacement = pointer.y - anchor.y; + if !displacement.is_finite() { + return Vec2::ZERO; + } + let distance = displacement.abs(); + if distance <= DEAD_ZONE { + return Vec2::ZERO; + } + let step = frame_step(dt); + // A frame's later passes take no time: counting them would count one frame's hold twice and end a click. + if held && step > 0.0 { + self.held_passes = self.held_passes.saturating_add(1); + } + // The full distance sets the speed, not the part past the dead zone. + let speed = distance.min(MAX_DISPLACEMENT).powf(SPEED_EXPONENT) * SPEED_MULTIPLIER; + let delta = -displacement.signum() * speed * step as f32; + Vec2::new(0.0, if invert { -delta } else { delta }) + } + + /// Where the latch is anchored, `None` when there is none. + pub fn anchor(&self) -> Option { + self.anchor + } + + /// Whether a latch is active. + pub fn active(&self) -> bool { + self.anchor.is_some() + } +} diff --git a/crates/behavior/src/overlay.rs b/crates/behavior/src/overlay.rs index 627b078c74..680c616ecb 100644 --- a/crates/behavior/src/overlay.rs +++ b/crates/behavior/src/overlay.rs @@ -314,6 +314,20 @@ mod tests { assert_eq!(neither.bottom(), BOUNDS.bottom(), "fits neither way: slides up to stay inside"); } + #[test] + fn an_overlay_with_no_room_on_its_side_opens_on_the_other() { + let size = Vec2::new(200.0, 80.0); + let low = rect(300.0, 540.0, 100.0, 30.0); + let placed = place(&PlaceRequest::new(low, size, BOUNDS).side(Side::Below).gap(4.0)); + assert_eq!(placed.side, Side::Above, "no room below the anchor: {placed:?}"); + assert!(placed.rect.bottom() <= low.top(), "above the anchor: {placed:?}"); + assert!(BOUNDS.contains_rect(placed.rect), "{placed:?}"); + let high = rect(300.0, 100.0, 100.0, 30.0); + let placed = place(&PlaceRequest::new(high, size, BOUNDS).side(Side::Below).gap(4.0)); + assert_eq!(placed.side, Side::Below, "room below: {placed:?}"); + assert!(placed.rect.top() >= high.bottom(), "below the anchor: {placed:?}"); + } + #[test] fn a_menu_that_covers_its_anchor_and_fits_neither_side_keeps_its_height_and_slides_over_the_anchor() { let point = rect(300.0, 400.0, 0.0, 0.0); diff --git a/crates/behavior/src/press.rs b/crates/behavior/src/press.rs index b8e5834eb3..50269615ff 100644 --- a/crates/behavior/src/press.rs +++ b/crates/behavior/src/press.rs @@ -306,15 +306,24 @@ pub struct PressState { pub sample: Option, /// A drag holds the pointer: nothing else hovers. pub captured: bool, + /// Where a secondary press made during another open press came up on this part in this pass + /// ([`PressStep::aside`]): a context request beside the running phase, which goes on. + pub context: Option, } impl PressState { /// A part with no press history. pub const IDLE: PressState = PressState::new(PressPhase::Idle); - /// A state in `phase` with no modifiers, sample or capture. + /// A state in `phase` with no modifiers, sample, capture or aside context request. pub const fn new(phase: PressPhase) -> Self { - PressState { phase, mods: Mods::NONE, sample: None, captured: false } + PressState { phase, mods: Mods::NONE, sample: None, captured: false, context: None } + } + + /// The aside secondary press that came up on the part at `at` in this pass. + pub const fn context(mut self, at: Option) -> Self { + self.context = at; + self } /// The modifiers held. @@ -484,11 +493,56 @@ pub struct PressStep { pub dragging: bool, /// The target released as a click in this pass. pub activated: Option, + /// The start of an open press whose sense has `PASSES_DRAG` and no `DRAG` that moved past slop in this pass: + /// the caller may hand it to the shape below with [`PressMachine::hand_over`]. + pub passes: Option, + /// A secondary press that came up in this pass while a primary press stayed open: a right-click during a drag. The + /// open press goes on; the aside asks its target for a context menu. + pub aside: Option>, } impl Default for PressStep { fn default() -> Self { - PressStep { target: None, phase: None, dragging: false, activated: None } + PressStep { target: None, phase: None, dragging: false, activated: None, passes: None, aside: None } + } +} + +/// A secondary press made and released while a primary press was open ([`PressStep::aside`]). Its target is the one +/// `pick` gave the secondary press, so it senses `Sense::CONTEXT_CLICK`. +#[derive(Clone, Copy, Debug, PartialEq)] +#[non_exhaustive] +pub struct PressAside { + /// The target of the secondary press. + pub target: T, + /// Where and when the secondary button went down. + pub start: PressStart, + /// Where it came up, in screen space. + pub pos: Pos2, +} + +/// The press winner a root picks at a press position, as [`PressMachine::step`]'s `pick` returns it. +#[derive(Clone, Copy, Debug, PartialEq)] +#[non_exhaustive] +pub struct PressPick { + /// The press winner. + pub target: T, + /// What it senses of the press. + pub sense: Sense, + /// The press's click went to a shape above that passes its drag to this target (`Sense::PASSES_DRAG`): the press + /// opens silent and is the target's only once its drag starts. + pub passed: bool, +} + +impl PressPick { + /// `target`, sensing `sense`, takes the press. + pub fn new(target: T, sense: Sense) -> Self { + PressPick { target, sense, passed: false } + } + + /// The press's click went to a shape above that passes its drag to this target. + pub fn passed(mut self) -> Self { + self.passed = true; + self } } @@ -500,6 +554,13 @@ struct Open { dragging: bool, /// Moved past slop on a target that senses no drag: the click is gone and nothing starts. abandoned: bool, + /// Moved past slop in this pass on a target that clicks and passes its drag (`Sense::PASSES_DRAG`), with the + /// pointer at the pass's end: no click and no drag until [`PressMachine::hand_over`] gives the press its new + /// target. The next pass abandons a press no shape took. + passing: Option, + /// A press passed to this target ([`PressPick::passed`]) whose drag has not started: it reports nothing, and a + /// release or cancel ends it unreported. Its move past slop starts the drag with `DragStart`, as a hand-over does. + silent: bool, /// The pointer left the window ([`PointerEvent::Gone`]): the click is gone, but a target that senses a drag still /// starts it from the moves that follow. The button is still down and the window keeps getting the pointer's moves /// and release while it is outside, so a press near a window edge (a window's resize grip) that leaves the window @@ -516,14 +577,14 @@ struct Open { } impl Open { - /// A phase before the release is still to be reported. + /// A phase before the release is still to be reported, or the press waits for its hand-over. fn owes_phase(&self) -> bool { - !self.reported || (self.dragging && !self.drag_reported) + !self.reported || (self.dragging && !self.drag_reported) || self.passing.is_some() } /// A release now is a click. fn clicks(&self) -> bool { - !self.dragging && !self.abandoned && !self.left && self.sense.contains(Sense::CLICK) + !self.dragging && !self.abandoned && !self.left && self.passing.is_none() && self.sense.contains(Sense::CLICK) } } @@ -531,18 +592,20 @@ impl Open { #[derive(Clone, Copy, Debug)] pub struct PressMachine { open: Option>, + /// The secondary press held beside the open primary press, with its target and start. + aside: Option<(T, PressStart)>, } impl Default for PressMachine { fn default() -> Self { - PressMachine { open: None } + PressMachine { open: None, aside: None } } } impl PressMachine { /// A machine with no press. pub const fn new() -> Self { - PressMachine { open: None } + PressMachine { open: None, aside: None } } /// The target of the open press. @@ -584,6 +647,8 @@ impl PressMachine { reported: true, drag_reported: false, released_at: None, + passing: None, + silent: false, }); } @@ -593,21 +658,32 @@ impl PressMachine { self.open.is_some_and(|open| open.released_at.is_some()) } - /// Runs one pass. `pick` chooses the press winner and what it senses at a press position; it returns `None` - /// when no shape of this root takes the press. - pub fn step(&mut self, input: PassInput<'_>, mut pick: impl FnMut(Pos2) -> Option<(T, Sense)>) -> PressStep { + /// Runs one pass. `pick` chooses the press winner and what it senses at a press position, for the button pressed + /// there; it returns `None` when no shape of this root takes the press. A secondary press goes only to a shape that + /// senses `Sense::CONTEXT_CLICK`, so `pick` passes over the others for it, to the next shape under the press. + pub fn step(&mut self, input: PassInput<'_>, mut pick: impl FnMut(Pos2, PointerButton) -> Option>) -> PressStep { let mut pos = input.pos; - let mut released: Option<(T, PressStart, Pos2, bool, bool)> = None; - let mut cancelled: Option<(T, PressStart, PressCancel)> = None; + // The press released or cancelled in this pass, and whether it was silent: one that ends silent reports nothing. + let mut released: Option<(T, PressStart, Pos2, bool, bool, bool)> = None; + let mut cancelled: Option<(T, PressStart, PressCancel, bool)> = None; + let mut aside: Option> = None; + // A press passed in the last pass that no shape took is abandoned; that pass reported its `Down`. + if let Some(open) = &mut self.open + && open.passing.is_some() + { + open.passing = None; + open.abandoned = true; + open.reported = true; + } if let Some(open) = self.open && let Some((at, click)) = open.released_at && !open.owes_phase() { - released = Some((open.target, open.start, at, open.dragging, click)); + released = Some((open.target, open.start, at, open.dragging, click, open.silent)); self.open = None; } if let (Some(reason), Some(open)) = (input.cancel, self.open) { - cancelled = Some((open.target, open.start, reason)); + cancelled = Some((open.target, open.start, reason, open.silent)); self.open = None; } for event in input.events { @@ -618,10 +694,14 @@ impl PressMachine { && open.released_at.is_none() && !open.dragging && !open.abandoned + && open.passing.is_none() && at.distance(open.start.origin) > input.slop { if open.sense.contains(Sense::DRAG) { open.dragging = true; + open.silent = false; + } else if open.sense.contains(Sense::CLICK | Sense::PASSES_DRAG) { + open.passing = Some(at); } else { open.abandoned = true; } @@ -638,44 +718,70 @@ impl PressMachine { if let Some(open) = self.open && let Some((up, click)) = open.released_at { - released = Some((open.target, open.start, up, open.dragging, click)); + released = Some((open.target, open.start, up, open.dragging, click, open.silent)); self.open = None; } + // A secondary press during an open primary press goes beside it, to the context target `pick` gives + // it, and the primary press goes on (a right-click during a drag asks for the menu there). + if button == PointerButton::Secondary + && self.aside.is_none() + && self.open.is_some_and(|open| open.start.button == PointerButton::Primary) + { + let start = PressStart::new(at, button, time, clicks); + self.aside = pick(at, button).filter(|pick| pick.sense.contains(Sense::CONTEXT_CLICK)).map(|pick| (pick.target, start)); + continue; + } // An open press keeps the pointer until its button comes up: no press starts over it, of its own // button (a repeated Down, as a window never sends one) or another. Its moves and its release still - // reach it when a modal opened over its target since. A middle or secondary press captures for a - // drag (a canvas pan, a drag with the secondary button) and never clicks. A target that senses - // `MIDDLE_CLICK` also takes a middle press that can click (a tab closes on it), and one that senses - // `CONTEXT_CLICK` takes a secondary press, which a click-only target would not capture. + // reach it when a modal opened over its target since. A middle press captures for a drag (a canvas + // pan) and never clicks, unless its target senses `MIDDLE_CLICK` (a tab closes on it). A secondary + // press is only a target's that senses `CONTEXT_CLICK`, which clicks and drags with it; a target that + // only drags (a transform box) leaves it to the context target under it. let capture_only = button != PointerButton::Primary; if !matches!(button, PointerButton::Primary | PointerButton::Middle | PointerButton::Secondary) || self.open.is_some() { continue; } - self.open = pick(at) - .map(|(target, sense)| { + self.open = pick(at, button) + .map(|pick| { let clicks = match button { - PointerButton::Middle => sense.contains(Sense::MIDDLE_CLICK), - PointerButton::Secondary => sense.contains(Sense::CONTEXT_CLICK), + PointerButton::Middle => pick.sense.contains(Sense::MIDDLE_CLICK), + PointerButton::Secondary => pick.sense.contains(Sense::CONTEXT_CLICK), _ => false, }; - (target, if capture_only && !clicks { sense - Sense::CLICK } else { sense }, clicks) + let sense = if capture_only && !clicks { pick.sense - Sense::CLICK } else { pick.sense }; + (pick, sense, clicks) }) - .filter(|(_, sense, clicks)| !capture_only || *clicks || sense.contains(Sense::DRAG)) - .map(|(target, sense, _)| (target, sense)) - .map(|(target, sense)| Open { - target, - sense, - start: PressStart::new(at, button, time, clicks), - dragging: false, - abandoned: false, - left: false, - reported: false, - drag_reported: false, - released_at: None, + .filter(|(_, sense, clicks)| match button { + PointerButton::Primary => true, + PointerButton::Middle => *clicks || sense.contains(Sense::DRAG), + _ => *clicks, + }) + .map(|(pick, sense, _)| { + // A silent press owes no `Down`: its first phase is its `DragStart`. + let silent = pick.passed && sense.contains(Sense::DRAG); + Open { + target: pick.target, + sense, + start: PressStart::new(at, button, time, clicks), + dragging: false, + abandoned: false, + left: false, + passing: None, + silent, + reported: silent, + drag_reported: false, + released_at: None, + } }); } PointerEvent::Released { button, pos: at } => { pos = at; + if button == PointerButton::Secondary + && let Some((target, start)) = self.aside.take() + { + aside = Some(PressAside { target, start, pos: at }); + continue; + } if self.open.is_some_and(|open| open.start.button != button || open.released_at.is_some()) { continue; } @@ -684,7 +790,7 @@ impl PressMachine { { open.released_at = Some((at, open.clicks())); } else if let Some(open) = self.open.take() { - released = Some((open.target, open.start, at, open.dragging, open.clicks())); + released = Some((open.target, open.start, at, open.dragging, open.clicks(), open.silent)); } } } @@ -693,20 +799,38 @@ impl PressMachine { if self.open.is_some_and(|open| open.released_at.is_none()) && !input.held && released.is_none() { self.open = None; } - if let Some((target, start, reason)) = cancelled { - let phase = PressPhase::Cancel { start, reason }; - return PressStep { target: Some(target), phase: Some(phase), dragging: false, activated: None }; + // An aside press lasts no longer than the press it went beside. + if self.open.is_none() { + self.aside = None; } - if let Some((target, start, at, was_dragging, click)) = released { + let quiet = PressStep { aside, ..PressStep::default() }; + if let Some((target, start, reason, silent)) = cancelled { + if silent { + return quiet; + } + let phase = PressPhase::Cancel { start, reason }; + return PressStep { target: Some(target), phase: Some(phase), ..quiet }; + } + if let Some((target, start, at, was_dragging, click, silent)) = released { + if silent { + return quiet; + } let phase = PressPhase::Release { start, pos: at, click }; return PressStep { target: Some(target), phase: Some(phase), dragging: was_dragging, activated: (click && start.button == PointerButton::Primary).then_some(target), + ..quiet }; } - let Some(open) = self.open.as_mut() else { return PressStep::default() }; + let Some(open) = self.open.as_mut() else { return quiet }; + if open.silent { + return quiet; + } + if let Some(at) = &mut open.passing { + *at = pos; + } let phase = if !open.reported { PressPhase::Down { start: open.start } } else if open.dragging && !open.drag_reported { @@ -717,8 +841,33 @@ impl PressMachine { } else { PressPhase::Held { start: open.start, pos } }; - open.reported = true; - PressStep { target: Some(open.target), phase: Some(phase), dragging: open.drag_reported, activated: None } + // A passing press owes its `Down` to the shape `hand_over` gives it when this pass is its first. + if open.passing.is_none() { + open.reported = true; + } + let passes = open.passing.map(|_| open.start); + PressStep { target: Some(open.target), phase: Some(phase), dragging: open.drag_reported, passes, ..quiet } + } + + /// Makes `target` the open press's target in the pass that reported `passes`, dragging from the same + /// `PressStart`. It returns the `DragStart` step when an earlier pass reported the press, and the `Down` step + /// (the `DragStart` follows in the next pass) when the move past slop came in the pass of the press itself. + /// `None` when no press passes in this pass or `sense` has no `DRAG`; the next pass abandons the press. The step + /// has no [`aside`](PressStep::aside): that stays the pass's own step's. + pub fn hand_over(&mut self, target: T, sense: Sense) -> Option> { + let open = self.open.as_mut().filter(|open| !open.abandoned && sense.contains(Sense::DRAG))?; + let at = open.passing.take()?; + open.target = target; + open.sense = sense; + open.dragging = true; + let phase = if open.reported { + open.drag_reported = true; + PressPhase::DragStart { start: open.start, pos: at } + } else { + open.reported = true; + PressPhase::Down { start: open.start } + }; + Some(PressStep { target: Some(target), phase: Some(phase), dragging: open.drag_reported, ..PressStep::default() }) } } @@ -731,7 +880,7 @@ mod tests { fn pass(machine: &mut PressMachine, events: &[PointerEvent], sense: Sense) -> PressStep { let held = machine.open.is_some() || matches!(events.last(), Some(PointerEvent::Pressed { .. })); - machine.step(PassInput::new(events, SLOP, pos2(0.0, 0.0), held), |_| Some((1, sense))) + machine.step(PassInput::new(events, SLOP, pos2(0.0, 0.0), held), |_, _| Some(PressPick::new(1, sense))) } fn press(x: f32, time: f64) -> PointerEvent { @@ -754,6 +903,37 @@ mod tests { assert_eq!(step.activated, Some(1)); } + /// A right-click during a drag goes beside it: the secondary release reports an aside on the context target, and the + /// drag goes on to its own release. A secondary press on a target without `CONTEXT_CLICK` reports none. + #[test] + fn a_secondary_click_during_a_drag_reports_an_aside_and_the_drag_goes_on() { + let (from, to, menu) = (pos2(0.0, 0.0), pos2(40.0, 0.0), pos2(40.0, 5.0)); + let mut machine = PressMachine::new(); + let mut pass = |events: &[PointerEvent]| { + machine.step(PassInput::new(events, SLOP, to, true), |_, button| match button { + PointerButton::Secondary => Some(PressPick::new(2, Sense::CLICK | Sense::CONTEXT_CLICK)), + _ => Some(PressPick::new(1, Sense::DRAG)), + }) + }; + pass(&[PointerEvent::pressed(from, 1.0, 1)]); + pass(&[PointerEvent::moved(to, None)]); + let down = pass(&[PointerEvent::pressed_by(PointerButton::Secondary, menu, 1.2, 1)]); + assert!(down.aside.is_none(), "nothing asks before the secondary button comes up"); + assert!(matches!(down.phase, Some(PressPhase::Drag { .. })), "the drag goes on: {down:?}"); + let up = pass(&[PointerEvent::released_by(PointerButton::Secondary, menu)]); + assert_eq!(up.aside.map(|aside| (aside.target, aside.pos)), Some((2, menu)), "the release asks the context target"); + assert_eq!(up.target, Some(1), "the drag keeps its target"); + assert!(up.phase.is_some_and(|phase| phase.is_drag()), "and its drag: {up:?}"); + let end = pass(&[PointerEvent::released(to)]); + assert!(matches!(end.phase, Some(PressPhase::Release { .. })) && end.aside.is_none(), "the drag ends on its own release: {end:?}"); + + let mut machine = PressMachine::new(); + let mut pass = |events: &[PointerEvent]| machine.step(PassInput::new(events, SLOP, to, true), |_, _| Some(PressPick::new(1, Sense::DRAG))); + pass(&[PointerEvent::pressed(from, 1.0, 1)]); + pass(&[PointerEvent::pressed_by(PointerButton::Secondary, menu, 1.2, 1)]); + assert!(pass(&[PointerEvent::released_by(PointerButton::Secondary, menu)]).aside.is_none(), "a drag-only target takes no aside"); + } + /// The phases a sequence of passes reports, as `D`own, `H`eld, `S` (drag start), `G` (drag), `R`elease with `!` for an /// activation, `-` for none. fn phases(passes: &[&[PointerEvent]], sense: Sense) -> String { @@ -783,8 +963,9 @@ mod tests { fn a_press_of_the_held_button_leaves_the_open_drag_its_moves_and_release() { let first = pos2(0.0, 0.0); let mut machine = PressMachine::new(); - let mut step = - |events: &[PointerEvent]| machine.step(PassInput::new(events, SLOP, first, true), |at| (at == first).then_some((1u8, Sense::DRAG))); + let mut step = |events: &[PointerEvent]| { + machine.step(PassInput::new(events, SLOP, first, true), |at, _| (at == first).then_some(PressPick::new(1u8, Sense::DRAG))) + }; step(&[press(0.0, 1.0)]); step(&[PointerEvent::Moved { at: pos2(40.0, 0.0), sample: None }]); let repeated = step(&[press(50.0, 1.2)]); @@ -855,4 +1036,79 @@ mod tests { let passes: [&[PointerEvent]; 5] = [&[press(0.0, 1.0)], &[up, second], &[far, up], &[], &[]]; assert_eq!(phases(&passes, Sense::CLICK | Sense::DRAG), "D R! D S R"); } + + const PASSES: Sense = Sense::CLICK.union(Sense::PASSES_DRAG); + + /// One pass with the button held at its end, over a root whose press winner is target 1 and passes its drag. + fn passing_pass(machine: &mut PressMachine, events: &[PointerEvent]) -> PressStep { + machine.step(PassInput::new(events, SLOP, pos2(0.0, 0.0), true), |_, _| Some(PressPick::new(1, PASSES))) + } + + fn moved(x: f32) -> PointerEvent { + PointerEvent::Moved { at: pos2(x, 0.0), sample: None } + } + + fn up(x: f32) -> PointerEvent { + PointerEvent::released(pos2(x, 0.0)) + } + + #[test] + fn a_drag_past_slop_on_a_part_that_passes_it_goes_to_the_shape_below() { + let origin = pos2(0.0, 0.0); + assert_eq!(phases(&[&[press(0.0, 1.0)], &[up(SLOP / 2.0)]], PASSES), "D R!", "within slop the press is the shape's click"); + + // The press was reported in an earlier pass: the shape below drags from the pass of the move. + let mut machine = PressMachine::new(); + let down = passing_pass(&mut machine, &[press(0.0, 1.0)]); + assert!(matches!(down.phase, Some(PressPhase::Down { .. })) && down.passes.is_none(), "{down:?}"); + assert!(machine.hand_over(2, Sense::DRAG).is_none(), "a press within slop passes nothing"); + let passed = passing_pass(&mut machine, &[moved(40.0)]); + assert_eq!(passed.passes.map(|start| start.origin), Some(origin), "{passed:?}"); + let handed = machine.hand_over(2, Sense::DRAG).expect("the shape below takes the drag"); + assert_eq!(handed.target, Some(2)); + assert!( + matches!(handed.phase, Some(PressPhase::DragStart { start, pos }) if start.origin == origin && pos == pos2(40.0, 0.0)), + "{:?}", + handed.phase + ); + let drag = passing_pass(&mut machine, &[moved(60.0)]); + assert_eq!(drag.target, Some(2)); + assert!(matches!(drag.phase, Some(PressPhase::Drag { .. })), "{:?}", drag.phase); + let end = passing_pass(&mut machine, &[up(60.0)]); + assert_eq!(end.target, Some(2)); + assert!(matches!(end.phase, Some(PressPhase::Release { click: false, .. })), "{:?}", end.phase); + assert_eq!(end.activated, None, "a passed press is no click"); + } + + /// The move past slop came in the press's own pass: the shape below gets the Down, its DragStart next pass, and a + /// release in between waits for it. + #[test] + fn a_drag_past_slop_in_the_press_pass_hands_the_down_over() { + let origin = pos2(0.0, 0.0); + let mut machine = PressMachine::new(); + let first = passing_pass(&mut machine, &[press(0.0, 1.0), moved(40.0)]); + assert!(matches!(first.phase, Some(PressPhase::Down { .. })) && first.passes.is_some(), "{first:?}"); + let handed = machine.hand_over(2, Sense::DRAG).expect("the shape below takes the drag"); + assert_eq!(handed.target, Some(2)); + assert!(matches!(handed.phase, Some(PressPhase::Down { start }) if start.origin == origin), "{:?}", handed.phase); + let start = passing_pass(&mut machine, &[up(40.0)]); + assert_eq!(start.target, Some(2)); + assert!(matches!(start.phase, Some(PressPhase::DragStart { .. })), "{:?}", start.phase); + assert!(machine.release_held(), "the release waits for the owed DragStart"); + let end = passing_pass(&mut machine, &[]); + assert_eq!(end.target, Some(2)); + assert!(matches!(end.phase, Some(PressPhase::Release { click: false, .. })), "{:?}", end.phase); + } + + /// No shape took the passed press: it is abandoned, and its release is no click. + #[test] + fn a_passed_press_no_shape_takes_is_abandoned() { + let mut machine = PressMachine::new(); + let _ = passing_pass(&mut machine, &[press(0.0, 1.0)]); + assert!(passing_pass(&mut machine, &[moved(40.0)]).passes.is_some()); + let end = passing_pass(&mut machine, &[up(40.0)]); + assert_eq!(end.target, Some(1)); + assert!(matches!(end.phase, Some(PressPhase::Release { click: false, .. })), "{:?}", end.phase); + assert_eq!(end.activated, None); + } } diff --git a/crates/behavior/src/sense.rs b/crates/behavior/src/sense.rs index 077310f662..c64efa2fbd 100644 --- a/crates/behavior/src/sense.rs +++ b/crates/behavior/src/sense.rs @@ -30,7 +30,8 @@ bitflags! { /// The zoom share (Ctrl or Cmd with the wheel, pinch), taken without scroll; the split rule passes both scroll shares on. const WHEEL_ZOOM = 1024; /// A secondary press captures the part and its release is reported to it, so a part that senses only a click - /// still gets its context click. Without this bit a secondary press only captures for a drag. + /// still gets its context click, and one that drags drags with the secondary button too. Without this bit the + /// shape takes no secondary press: it goes to the next shape under it that senses this bit. const CONTEXT_CLICK = 2048; /// A container root learns of a primary press on its own surface: inside its rect, on its layer, where no /// shape takes the press. The root takes no press and no focus by it, so it is no click target. @@ -50,6 +51,10 @@ bitflags! { /// with `DRAG` by a part whose click does nothing a drag could be mistaken for (a transform box's handles). /// The component begins the gesture from `PressPhase::Held`. const FOLLOWS_IN_SLOP = 65536; + /// A press on this shape that moves past slop is not the shape's: the press passes to the shape ranked under + /// it that senses a drag, with its start. Released within slop it is the shape's click. Declared with `CLICK`, + /// without `DRAG`. + const PASSES_DRAG = 131072; } } diff --git a/crates/behavior/src/typing.rs b/crates/behavior/src/typing.rs index 00d7d228e3..c95fe4c8c5 100644 --- a/crates/behavior/src/typing.rs +++ b/crates/behavior/src/typing.rs @@ -238,4 +238,22 @@ mod tests { typing.edit(&mut run, &Some(5.0), "9"); assert_eq!(typing.escape(&mut run), Escaped::Restore(Some(5.0))); } + + /// A field's value can change under a half-typed draft (a panel's selection changes): the draft and the value the + /// run began from must stay, so the commit and Escape work from what the user started typing over. + #[test] + fn a_draft_survives_an_outside_value_change_until_commit() { + let typing = TypingRun::new(NumberCodec::default()); + let (began, outside) = (Some(12.0), Some(24.0)); + let mut run = EditRun::new(began); + typing.edit(&mut run, &began, "+"); + typing.edit(&mut run, &outside, "+6"); + assert_eq!(typing.shown(&run, &outside), "+6", "the open draft is shown, not the value that changed under it"); + assert_eq!(run.start, began, "the run keeps the value it began from"); + assert_eq!(typing.commit(&mut run), Ended::Commit(Some(18.0)), "relative input applies to the value the run began from"); + + typing.edit(&mut run, &began, "9"); + typing.edit(&mut run, &outside, "90"); + assert_eq!(typing.escape(&mut run), Escaped::Restore(began), "Escape restores the value from before the run"); + } } diff --git a/crates/behavior/src/wheel.rs b/crates/behavior/src/wheel.rs index b32d5090c4..1985e4bf9c 100644 --- a/crates/behavior/src/wheel.rs +++ b/crates/behavior/src/wheel.rs @@ -88,6 +88,133 @@ pub struct Wheel { pub touch_rotation: f32, /// Two fingers' movement this pass, in points. pub touch_pan: Vec2, + /// The running gesture's scroll gathered so far, this share included, in its owner's points. + pub gathered: Vec2, + /// Whether the owner marked the running gesture moved (`Pointer::mark_wheel_moved`). + pub moved: bool, +} + +/// The eased motion of a canvas's line wheel: notches gather into owed motion that later passes pay out. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct WheelEase { + owed: kurbo::Vec2, + burst: u32, + last_notch: f64, + last_sign: Vec2, + last_paid: f64, +} + +/// Notches closer than this many seconds are a fast spin and grow the burst. +const FAST_NOTCH: f64 = 0.08; +/// Notches this many seconds apart, or more, start a new burst. +const BURST_RESET: f64 = 0.3; +/// The multiplier one fast notch adds. +const BURST_STEP: f32 = 0.4; +/// The burst notches that count toward the multiplier. +const BURST_TICKS: u32 = 13; +/// Notches kept past `BURST_TICKS`, so a few slower notches in a spin do not drop the multiplier at once. +const BURST_HOLD: u32 = 4; +/// The largest multiplier. +const BURST_CAP: f32 = 6.0; +/// The most motion owed on an axis, in points: a hostile run of notches cannot grow it without bound. +const MAX_OWED: f32 = 16384.0; +/// The longest pass the ease pays for, in seconds: after a stall it does not jump the whole way at once. +const LONGEST_PASS: f64 = 0.1; +/// The seconds a pass is taken to last when the ease starts from rest, so the first notch moves in its own pass. +const FIRST_PASS: f64 = 1.0 / 60.0; +/// Owed motion this small, in points, is paid whole. +const SETTLE: f32 = 0.01; + +/// The sign of `v`: 0 for zero, where `f32::signum` gives 1. +fn sign(v: f32) -> f32 { + if v > 0.0 { + 1.0 + } else if v < 0.0 { + -1.0 + } else { + 0.0 + } +} + +impl WheelEase { + /// Adds the line pan `pan` of this pass, at time `now`, to the owed motion; a burst of notches under 0.08 s apart + /// accelerates it, a reversal or 0.3 s idle resets the burst. + pub fn feed(&mut self, pan: Vec2, now: f64) { + if !now.is_finite() || !pan.is_finite() || pan == Vec2::ZERO { + return; + } + let signs = Vec2::new(sign(pan.x), sign(pan.y)); + let idle = now - self.last_notch; + let reversed = signs.x * self.last_sign.x < 0.0 || signs.y * self.last_sign.y < 0.0; + if self.last_sign == Vec2::ZERO || !(0.0..BURST_RESET).contains(&idle) || reversed { + self.burst = 0; + } else if idle < FAST_NOTCH { + self.burst = (self.burst + 1).min(BURST_TICKS + BURST_HOLD); + } else { + // A slower notch in the same direction sheds one, rather than extending the burst. + self.burst = self.burst.saturating_sub(1); + } + self.last_notch = now; + self.last_sign = signs; + let boost = (1.0 + BURST_STEP * self.burst.min(BURST_TICKS) as f32).min(BURST_CAP); + if !self.owes() { + self.last_paid = now - FIRST_PASS; + } + self.owed = kurbo::Vec2::new(owe(self.owed.x, f64::from(pan.x * boost)), owe(self.owed.y, f64::from(pan.y * boost))); + } + + /// Drops the owed motion on the axes marked. + pub fn cancel_axis(&mut self, x: bool, y: bool) { + if x { + self.owed.x = 0.0; + } + if y { + self.owed.y = 0.0; + } + } + + /// The step this pass pays at time `now`: `1 − 0.1^(dt/0.1)` of the owed motion, with `dt` since the last paid pass. + pub fn step(&mut self, now: f64) -> Vec2 { + if !now.is_finite() || now < self.last_paid { + // A clock that runs backwards or breaks cannot tell how much to pay: the tail goes. + self.owed = kurbo::Vec2::ZERO; + self.last_paid = if now.is_finite() { now } else { self.last_paid }; + return Vec2::ZERO; + } + let dt = (now - self.last_paid).min(LONGEST_PASS); + self.last_paid = now; + if !self.owes() || dt <= 0.0 { + return Vec2::ZERO; + } + let fraction = 1.0 - 0.1_f64.powf(dt / 0.1); + let paid = Vec2::new(pay(self.owed.x, fraction), pay(self.owed.y, fraction)); + self.owed -= kurbo::Vec2::new(f64::from(paid.x), f64::from(paid.y)); + // A tail below normal f32 precision cannot move a view and must not keep scheduling frames. + if self.owed.x.abs() < f64::from(f32::MIN_POSITIVE) { + self.owed.x = 0.0; + } + if self.owed.y.abs() < f64::from(f32::MIN_POSITIVE) { + self.owed.y = 0.0; + } + paid + } + + /// Whether motion is still owed. + pub fn owes(&self) -> bool { + self.owed != kurbo::Vec2::ZERO + } +} + +/// `owed` with `more` added on one axis: motion the other way drops what was owed, and the sum stays within +/// `MAX_OWED`. +fn owe(owed: f64, more: f64) -> f64 { + let owed = if more * owed < 0.0 { 0.0 } else { owed }; + (owed + more).clamp(-f64::from(MAX_OWED), f64::from(MAX_OWED)) +} + +/// The part of `owed` one pass pays, `fraction` of it; a remainder under `SETTLE` is paid whole. +fn pay(owed: f64, fraction: f64) -> f32 { + if owed.abs() <= f64::from(SETTLE) { owed as f32 } else { (owed * fraction) as f32 } } impl Wheel { @@ -107,6 +234,8 @@ impl Wheel { rotation: 0.0, touch_rotation: 0.0, touch_pan: Vec2::ZERO, + gathered: Vec2::ZERO, + moved: false, } } @@ -658,4 +787,39 @@ mod tests { let shares = split(&[region, view, zone], at, wheel(4.0, 0.0), WheelFocus::new(None), None, &mut WheelGesture::default(), 0.0); assert_eq!(shares.iter().map(|(o, w)| (*o, w.zooms)).collect::>(), [(2, false)], "the horizontal share passes the zone"); } + + #[test] + fn fast_notches_accelerate_to_a_cap_and_reset_on_reversal_or_idle_but_a_lone_notch_does_not() { + const NOTCH: f64 = 40.0; + // What one notch of `y` points adds to the owed motion. + let notch = |ease: &mut WheelEase, y: f64, now: f64| { + let before = ease.owed.y; + ease.feed(Vec2::new(0.0, y as f32), now); + ease.owed.y - before + }; + let mut ease = WheelEase::default(); + assert_eq!(notch(&mut ease, NOTCH, 1.0), NOTCH, "a lone notch is one notch"); + assert_eq!(notch(&mut ease, NOTCH, 1.5), NOTCH, "a slow notch is one notch"); + + let mut gains = Vec::new(); + for i in 1..=20 { + gains.push(notch(&mut ease, NOTCH, 1.5 + f64::from(i) * 0.02)); + } + // The owed sum rounds in its last bits, so per-notch gains compare within a hundredth of a point. + let near = |a: f64, b: f64| (a - b).abs() < 0.01; + assert!(gains.windows(2).all(|pair| pair[1] > pair[0] - 0.01), "a fast run never pays less per notch: {gains:?}"); + let fastest = gains.iter().copied().fold(0.0, f64::max); + assert!(fastest > 2.0 * NOTCH, "a fast run accelerates: {gains:?}"); + assert!(fastest < 6.0 * NOTCH + 0.01, "the acceleration is capped: {gains:?}"); + assert!(gains.last().is_some_and(|&last| near(last, 6.0 * NOTCH)), "a long run reaches the cap and stays there: {gains:?}"); + + notch(&mut ease, -NOTCH, 1.5 + 21.0 * 0.02); + assert_eq!(ease.owed.y, -NOTCH, "a reversal drops what was owed and starts again at one notch"); + + for i in 1..=10 { + notch(&mut ease, -NOTCH, 2.0 + f64::from(i) * 0.02); + } + assert!(notch(&mut ease, -NOTCH, 2.0 + 11.0 * 0.02) < -NOTCH - 1.0, "precondition: the run is fast again"); + assert!(near(notch(&mut ease, -NOTCH, 5.0), -NOTCH), "an idle gap starts again at one notch"); + } } diff --git a/crates/behavior/tests/geometry/move_gesture.rs b/crates/behavior/tests/geometry/move_gesture.rs index 074de32669..029106960e 100644 --- a/crates/behavior/tests/geometry/move_gesture.rs +++ b/crates/behavior/tests/geometry/move_gesture.rs @@ -1,7 +1,8 @@ //! The direction lock of the move gesture. -use craft_behavior::geometry::{Directions, lock_direction}; -use kurbo::Vec2; +use craft_behavior::geometry::{ConstrainStyle, Directions, MoveGesture, lock_direction}; +use craft_keymap::Mods; +use kurbo::{Point, Vec2}; fn polar(deg: f64, len: f64) -> Vec2 { let a = deg.to_radians(); @@ -19,3 +20,16 @@ fn lock_direction_keeps_the_axis_until_eight_degrees_past_half() { let switched = lock_direction(polar(31.0, 10.0), Some(axis), Directions::Eight); assert!((switched.y - switched.x).abs() < 1e-9 && switched.y > 0.0); } + +#[test] +fn a_shift_move_with_four_directions_locks_an_axis_and_frees_it_when_shift_is_let_go() { + let mut drag = MoveGesture::press(&ConstrainStyle::new(4.0, 4.0), Point::ZERO, Mods::SHIFT, Directions::Four); + let at = Point::new(10.0, 3.0); + let locked = drag.follow(at, Mods::SHIFT, 1.0).expect("the move changed the value"); + assert_eq!(locked.delta.y, 0.0, "Shift holds the offset to the horizontal axis: {:?}", locked.delta); + assert!(locked.delta.x > 0.0, "{:?}", locked.delta); + assert!(drag.locked().is_some(), "the lock is remembered while Shift is down"); + let free = drag.follow(at, Mods::NONE, 1.0).expect("letting Shift go changed the value"); + assert_eq!(free.delta, Vec2::new(10.0, 3.0), "without Shift the offset is free"); + assert_eq!(drag.locked(), None, "the lock is forgotten when Shift is let go"); +} diff --git a/crates/behavior/tests/geometry/quad.rs b/crates/behavior/tests/geometry/quad.rs index e716f2511d..2350de7957 100644 --- a/crates/behavior/tests/geometry/quad.rs +++ b/crates/behavior/tests/geometry/quad.rs @@ -13,6 +13,18 @@ fn session() -> BoxState { BoxState::from_rect(Rect::new(0.0, 0.0, 100.0, 50.0)) } +#[test] +fn corner_drag_preserves_the_offset_of_the_press() { + let start = session(); + let press = p(96.0, 47.0); + let rules = BoxRules::default(); + let back = drag(&start, &start, BoxPart::Corner(2), press, press, Mods::default(), &rules); + assert_eq!(back, start, "returning to the press must restore the box"); + let moved = drag(&start, &start, BoxPart::Corner(2), press, press + Vec2::new(20.0, 10.0), Mods::SHIFT, &rules); + assert!(near(moved.quad[2], start.quad[2] + Vec2::new(20.0, 10.0)), "the corner follows the movement, keeping the press offset"); + assert!(near(moved.quad[0], start.quad[0]), "the opposite corner stays fixed"); +} + fn dragged(from: Point, to: Point, mods: Mods, rules: &BoxRules) -> BoxState { let start = session(); drag(&start, &start, start.part_at(from, 8.0), from, to, mods, rules) @@ -31,6 +43,15 @@ fn turns(q: &[Point; 4]) -> [f64; 4] { std::array::from_fn(|k| (q[(k + 1) % 4] - q[k]).cross(q[(k + 2) % 4] - q[(k + 1) % 4])) } +#[test] +fn proportional_corner_uses_the_larger_relative_drag_even_when_shrinking() { + let rules = BoxRules::default().with_scale(ScaleRule::LargerAxis); + let wider = dragged(p(100.0, 50.0), p(200.0, 60.0), Mods::NONE, &rules); + assert!(corners_are(&wider, 0.0, 0.0, 200.0, 100.0)); + let smaller = dragged(p(100.0, 50.0), p(75.0, 50.0), Mods::NONE, &rules); + assert!(corners_are(&smaller, 0.0, 0.0, 75.0, 37.5)); +} + #[test] fn a_proportional_corner_follows_the_diagonal_and_flips_past_the_anchor() { let rules = BoxRules::default(); diff --git a/crates/behavior/tests/main.rs b/crates/behavior/tests/main.rs index 7526cf4122..c52c1045ec 100644 --- a/crates/behavior/tests/main.rs +++ b/crates/behavior/tests/main.rs @@ -10,3 +10,4 @@ mod fit; mod geometry; mod hit_excluding; mod key_table; +mod middle_scroll; diff --git a/crates/behavior/tests/middle_scroll.rs b/crates/behavior/tests/middle_scroll.rs new file mode 100644 index 0000000000..e43423fe41 --- /dev/null +++ b/crates/behavior/tests/middle_scroll.rs @@ -0,0 +1,77 @@ +//! The middle button's auto-scroll latch. + +use craft_behavior::{MiddleScroll, PointerButton, PressCancel, PressPhase, PressStart}; +use emath::{Vec2, pos2}; + +/// One frame's elapsed time. +const FRAME: f64 = 1.0 / 60.0; + +/// A click keeps the latch, as does a hold of one frame even when that frame runs a second pass; a hold of two frames +/// past the dead zone ends it on release. +#[test] +fn a_click_inside_the_dead_zone_latches_and_a_hold_past_it_ends_on_release() { + let anchor = pos2(100.0, 100.0); + let past = pos2(100.0, 140.0); + + let mut latch = MiddleScroll::default(); + latch.press(anchor, true); + assert_eq!(latch.step(pos2(100.0, 105.0), true, FRAME, false), Vec2::ZERO, "inside the dead zone nothing scrolls"); + latch.release(); + assert!(latch.active(), "a click latches"); + assert_eq!(latch.anchor(), Some(anchor)); + let scroll = latch.step(past, false, FRAME, false); + assert!(scroll.y < 0.0 && scroll.x == 0.0, "past the dead zone below the anchor the view scrolls down: {scroll:?}"); + latch.step(past, false, FRAME, false); + latch.release(); + assert!(latch.active(), "passes with the button up count no hold"); + latch.press(anchor, true); + assert!(!latch.active(), "a second press ends the latch"); + assert_eq!(latch.anchor(), None); + + // One frame held past the dead zone, rerun as a second pass with no elapsed time. + latch.press(anchor, true); + latch.step(past, true, FRAME, false); + latch.step(past, true, 0.0, false); + latch.release(); + assert!(latch.active(), "one held frame is a click, however many passes it runs"); + + // A fresh latch starts its count over: one more held frame is still a click. + latch.press(anchor, true); + latch.press(anchor, true); + latch.step(past, true, FRAME, false); + latch.release(); + assert!(latch.active(), "the count starts over at each latch"); + + latch.press(anchor, true); + latch.press(anchor, true); + latch.step(past, true, FRAME, false); + latch.step(past, true, FRAME, false); + latch.release(); + assert!(!latch.active(), "a hold of two frames past the dead zone ends on release"); + assert_eq!(latch.anchor(), None); +} + +/// A primary click that ends the latch is swallowed from its press through its release; the next click is not. +#[test] +fn a_primary_click_that_ends_auto_scroll_is_swallowed_through_its_release() { + let at = pos2(100.0, 100.0); + let start = PressStart::new(at, PointerButton::Primary, 0.0, 1); + let down = PressPhase::Down { start }; + let held = PressPhase::Held { start, pos: at }; + let release = PressPhase::Release { start, pos: at, click: true }; + + let mut latch = MiddleScroll::default(); + latch.press(at, true); + assert!(latch.swallows(down), "the press that ends the latch is swallowed"); + assert!(!latch.active()); + assert!(latch.swallows(held), "its later phases are too"); + assert!(latch.swallows(release), "through its release"); + assert!(!latch.swallows(down), "the next click, with nothing latched, is not"); + assert!(!latch.swallows(held)); + assert!(!latch.swallows(release)); + + latch.press(at, true); + assert!(latch.swallows(down)); + assert!(latch.swallows(PressPhase::Cancel { start, reason: PressCancel::Escape })); + assert!(!latch.swallows(held), "a cancel ends the swallowed press"); +} diff --git a/crates/browse/src/links/mod.rs b/crates/browse/src/links/mod.rs index 0884e5e4d7..4d992a02ef 100644 --- a/crates/browse/src/links/mod.rs +++ b/crates/browse/src/links/mod.rs @@ -223,7 +223,7 @@ impl SearchRun { wake: Wake, ) -> Self { // filmcraft: crates/ui-egui/src/panels/media_dialogs.rs:146 (`link_media` ran `media.search` on the UI thread). - let queue = JobQueue::new(jobs, wake.clone(), QueueOptions { lanes: 1, name: "relink-search" }); + let queue = JobQueue::new(jobs, wake.clone(), QueueOptions { lanes: 1, name: "relink-search", ..QueueOptions::default() }); let updates = Arc::new(Mutex::new(Vec::new())); let cancel = Cancel::new(); let inbox = Arc::clone(&updates); diff --git a/crates/browse/src/ui/bin/icon.rs b/crates/browse/src/ui/bin/icon.rs index c6b5c40029..118a11870d 100644 --- a/crates/browse/src/ui/bin/icon.rs +++ b/crates/browse/src/ui/bin/icon.rs @@ -11,7 +11,7 @@ use craft_ui::contract::{ use craft_ui::list::ThumbAspect; use craft_ui::primitives::ContentPainterCx; use craft_ui::primitives::textures::{Priority, TextureKey, ThumbPaint, ThumbRequest, ThumbSource, Thumbnails}; -use craft_ui::tile_grid::{CaptionPlace, Tile, TileGrid, TilePartEvent}; +use craft_ui::tile_grid::{CaptionPlace, GridZoom, Tile, TileGrid, TilePartEvent}; use egui::{Rect, Ui}; use super::list::{drop_items, inside_any, item_of, open_event, rename_event, reorder_event, sort_entries, stack_event}; @@ -172,7 +172,7 @@ where .caption(CaptionPlace::Below) .detail_line() .aspect(ASPECT) - .zoom(state.settings.zoom as f32) + .zoom(GridZoom::Fixed(state.settings.zoom)) .rename(true) .deletable(true) .rows_stamp(stamp_of(state.shown.as_ref(), &state.search, state.settings.icon_sort.as_ref())) diff --git a/crates/browse/src/ui/relink/dialog.rs b/crates/browse/src/ui/relink/dialog.rs index 348d84ec84..247d78a88f 100644 --- a/crates/browse/src/ui/relink/dialog.rs +++ b/crates/browse/src/ui/relink/dialog.rs @@ -634,7 +634,7 @@ impl Model { let ctx = ctx.clone(); Wake::new(move || ctx.request_repaint()) }; - let checks = JobQueue::new(Arc::clone(&jobs), wake.clone(), QueueOptions { lanes: 1, name: "relink-check" }); + let checks = JobQueue::new(Arc::clone(&jobs), wake.clone(), QueueOptions { lanes: 1, name: "relink-check", ..QueueOptions::default() }); self.runtime = Some(Runtime { jobs, wake, checks }); } self.poll_pick(); diff --git a/crates/color-ui/src/ui/paint_chip.rs b/crates/color-ui/src/ui/paint_chip.rs index d15ac21c6b..e6887a0e76 100644 --- a/crates/color-ui/src/ui/paint_chip.rs +++ b/crates/color-ui/src/ui/paint_chip.rs @@ -20,7 +20,6 @@ use craft_ui::contract::{ Access, Activation, Bind, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Entry, Meta as _, Outcome, Overlay, OverlayUi, Overlays as _, Pages, PaintUi, PartsCx, Pointer as _, PopupKind, Props as _, Remember as _, Role, Show as _, ShowContainer as _, WordSetCx as _, }; -use craft_ui::display::{Shade, Text}; use craft_ui::layout_components::Row; use craft_ui::patterns::presets::{DefaultOpen, PresetBrowser, PresetEvent, PresetRowMenu, PresetState}; use craft_ui::primitives::textures::CachedTexture; @@ -217,7 +216,7 @@ pub struct PaintChipStyle { radius: egui::CornerRadius, /// The ring on the chip's outline. edge: StyleColor, - /// The fill of an empty chip: the field's. + /// The fill of a picture chip with no texture yet: the field's. none_fill: StyleColor, /// The No Color diagonal. none_mark: StyleColor, @@ -594,7 +593,7 @@ impl Component for PaintChip<'_> { let solid = cx.memory::().0.unwrap_or(self.fallback); let current = FillKind::of(&paint); let sampled = self.sampled; - let recent_cells: Vec<(Label, Srgba)> = self.recent.iter().map(|color| (Label::from(color.to_hex()), *color)).collect(); + let recent = self.recent; let full_picker = self.full_picker; let cmyk = self.cmyk.unwrap_or_else(|| CmykConverter::coated()); let solid_now = if let Paint::Solid(color) = &paint { Some(*color) } else { None }; @@ -624,11 +623,12 @@ impl Component for PaintChip<'_> { compact_picker(name.clone(), Bind::given(PickedColor::rgb(*color)), sampled).alpha(true).eyedropper(true).show(ui); shown.edit = picked.events; shown.screen_pick = picked.screen_pick; - if !recent_cells.is_empty() { - Text::new(words.recent.clone()).shade(Shade::Faint).show(ui); + if !recent.is_empty() { + // A palette of no swatches: the recent row alone, under its caption. let mut chosen = *color; - let recent = SwatchPalette::new(words.recent.clone(), Bind::bound(&mut chosen), &recent_cells).show(ui); - shown.picked = recent.edit.as_ref().and_then(|edit| edit.value()).copied(); + let row = + SwatchPalette::new(words.recent.clone(), Bind::bound(&mut chosen), &[]).recent(words.recent.clone(), recent).show(ui); + shown.picked = row.picked; } if let Some((groups, state)) = swatches.as_mut() { let groups: &[SwatchGroup] = groups; diff --git a/crates/color-ui/src/ui/pair.rs b/crates/color-ui/src/ui/pair.rs index fb376f6e1f..8cb8cda739 100644 --- a/crates/color-ui/src/ui/pair.rs +++ b/crates/color-ui/src/ui/pair.rs @@ -8,7 +8,7 @@ use craft_ui::contract::{ Access, Bind, BindMut, Common, Component, Cx, DragPreview, DropMark, DropOperation, DropTarget, Edit as _, EditResponse, Focus as _, MeasureCx, Meta as _, Outcome, Overlay, OverlayUi, Overlays as _, PaintUi, PartsCx, Pointer as _, Props as _, Remember as _, Role, WordSetCx as _, }; -use craft_ui::primitives::{Glyph, IconSpec, PaintShape, StrokeWidth}; +use craft_ui::primitives::{Glyph, IconSpec, PaintShape, StrokeWidth, WellFill}; use craft_ui::runtime::commands::FireSource; use craft_ui::runtime::env::Label; use craft_ui::style::{ComponentStyle, Flags, FocusLook, GlyphRole, StyleColor, StyleCx, SurfaceEdge, SurfaceStyle, UiTokens}; @@ -606,7 +606,7 @@ impl Component for SwatchPair<'_, P> { }; paint_well(ui, cx, at, paint, &look); } - None => ui.draw().swatch_well(at, style.radius, None), + None => ui.draw().swatch_well(at, style.radius, WellFill::Mixed), } // A ring well draws its own outlines. if shown.paint.same().is_none() || !shown.ring { diff --git a/crates/color-ui/src/ui/palette.rs b/crates/color-ui/src/ui/palette.rs index 2dcefb16cd..000e8ca818 100644 --- a/crates/color-ui/src/ui/palette.rs +++ b/crates/color-ui/src/ui/palette.rs @@ -1,12 +1,16 @@ //! `SwatchPalette`: a wrapping grid of colour cells that chooses one colour. Its table of cells is //! `craft_ui::choice::SwatchTable`. -use craft_behavior::{EditEvent, Mixed, Selection}; +use craft_behavior::{EditEvent, IconId, Mixed, Selection}; use craft_theme::Srgba; use craft_ui::choice::{SwatchSpacing, SwatchTable}; -use craft_ui::contract::{Bind, Held, ListDrag, NoValue, Outcome, Pattern, ShowContainer as _}; +use craft_ui::contract::{ActivateOn, Bind, Held, ListDrag, NoValue, Outcome, Pattern, Show as _, ShowContainer as _}; +use craft_ui::display::{Shade, Text}; use craft_ui::layout_components::Stack; use craft_ui::runtime::env::Label; +use craft_ui::runtime::memory::StageAccess; +use craft_ui::runtime::requests::ColorRequest; +use craft_ui::style::TypeRole; use egui::{Response, Ui}; use std::sync::Arc; @@ -23,9 +27,14 @@ type TableMap = Arc Fn(SwatchTable<'t>) -> SwatchTable<'t>>; pub struct SwatchPaletteOutput { /// The palette's response. pub response: Response, - /// The pick of this pass as one `Set` of the swatch's colour; `None` when nothing was picked. The palette has - /// already written it to its binding. + /// The pick of this pass as one `Set` of the swatch's colour; `None` when nothing was picked or the pick was the + /// colour already bound. The palette has already written it to its binding. pub edit: Option>, + /// The request of the Other… cell for the host's colour picker, at the bound colour and keyed by the key given to + /// [`SwatchPalette::other`], when it was activated this pass. + pub pick_color: Option, + /// Every swatch click of this pass, also a click on the colour already bound, which files no `edit`. + pub picked: Option, } impl Outcome for SwatchPaletteOutput { @@ -39,27 +48,104 @@ impl Outcome for SwatchPaletteOutput { /// A wrapping grid of colour cells from the host's list of named colours that chooses one colour. /// /// - The swatch equal to the colour (compared in 8 bits, the first when several are) is selected; the name is its -/// tooltip. -/// - A click, Space or Enter on a swatch, or a screen reader's click, sets its colour as one `Set`. +/// tooltip. An [`optional`](Self::optional) palette bound to no colour, or to a mixed one, selects none. +/// - A click, Space or Enter on a swatch, or a screen reader's click, sets its colour as one `Set`; a click on the +/// colour already bound sets nothing and still reports `picked`. /// - The palette is one Tab stop: Tab enters on the selected swatch (the first when none is) and the next Tab leaves. /// Arrows move the focus through the cells as the rows lie, Up and Down to the cell above or below; they choose /// nothing. +/// - [`other`](Self::other) adds an Other… cell after the swatches, in the same Tab stop and arrow walk: activating it +/// files `pick_color` and sets nothing. [`recent`](Self::recent) adds a captioned row of recent colours under the +/// grid, its own Tab stop, whose pick sets the colour as a swatch's does. /// - AccessKit: a list box named by the label; each cell a list box option named by its name, with the hex colour as /// its value. #[must_use = "show the palette with `show`"] #[derive(Pattern)] pub struct SwatchPalette<'a> { label: Label, - color: Bind<'a, Srgba>, + color: PaletteColor<'a>, swatches: &'a [(Label, Srgba)], spacing: SwatchSpacing, drag: Option, + /// The Other… cell: the key of its colour request and its name. + other: Option<(String, Label)>, + /// The recent row: its caption and colours. + recent: Option<(Label, &'a [Srgba])>, +} + +/// What a palette binds: a colour, or a colour that may be none. +enum PaletteColor<'a> { + Color(Held<'a, Srgba>), + Optional(Bind<'a, Option>), +} + +impl PaletteColor<'_> { + /// The bound colour as the palette shows it: `Same(None)` for no colour (or an optional binding that holds + /// nothing), `Mixed` for several. `None` while a plain colour's binding holds no single colour, and the palette + /// shows nothing. + fn read(&mut self, cx: &mut impl StageAccess) -> Option>> { + match self { + PaletteColor::Color(held) => held.read(cx).map(|color| Mixed::Same(Some(color))), + PaletteColor::Optional(bind) => Some(bind.reborrow().read(cx).unwrap_or(Mixed::Same(None))), + } + } + + /// Writes `after` over `before` as one `Set` named `name`. + fn write(&mut self, cx: &mut impl StageAccess, before: Mixed>, after: Srgba, name: &str) { + match self { + PaletteColor::Color(held) => { + if let Mixed::Same(Some(before)) = before { + held.write(cx, &before, after, name); + } + } + PaletteColor::Optional(bind) => { + let _ = bind.reborrow().write(cx, &EditEvent::set(before, Some(after), Arc::from(name), None)); + } + } + } +} + +/// What the body picked in its pass. +#[derive(Clone, Copy)] +enum Pick { + /// A swatch or a recent colour. + Color(Srgba), + /// The Other… cell. + Other, +} + +/// The cell of `swatches` whose colour is `color`, compared in 8 bits: the first when several are. +fn cell_of(swatches: &[(Label, Srgba)], color: Option) -> Selection { + color.and_then(|color| swatches.iter().position(|(_, c)| c.to_rgba() == color.to_rgba())).map_or_else(Selection::default, Selection::single) } impl<'a> SwatchPalette<'a> { /// A palette named `label` of `swatches`, each a name and a colour, choosing the colour bound to `color`. pub fn new(label: impl Into

/.log` with `RUST_LOG`-style filters, rotation to `.1`/`.2`, per-instance logs while another instance runs, a size cap; `logs::crash`: the panic hook, crash log (redacted message, written to standard error only when no logger takes errors), last panic for the error window, and `catch`. | | always | `session::Session` and `SessionKeeper`: the documents open at the last quit and where the user was in each, stored in the app's settings (serde) for a "Reopen Last Session" preference; `to_reopen` skips what is already open; a stored list longer than 64 documents is cut. No egui. | | `usage` | `usage::sample`: the process's resident memory and the memory it may still use (`MemorySample`, `None` when unknown), for the status readout's Scratch and Efficiency items. Linux reads `/proc`; other platforms return `None`. | -| always | `open::FileIntake` with `IntakeSender` (OS open requests, second-instance hand-over and `IntakeSender::dropped` and `quit` feed it; `open::apple_events` under `apple-events` on macOS): one queue for files the OS asks the app to open and files dropped on the window (`DroppedFile`); `natural_cmp` and `same_file` for opening order and duplicates; `reveal`, `open_external`, `open_with` and `is_application`; the shared open-error texts. No egui. | +| always | `open::FileIntake` with `IntakeSender` (OS open requests, second-instance hand-over, the web host and `IntakeSender::dropped` and `quit` feed it; `open::apple_events` under `apple-events` on macOS): one queue, in arrival order, for files the OS asks the app to open (`open`, as `Intake::Open`), files it asks to open for one of the app's own actions such as combining (`open_for`, as `Intake::OpenFor` with the action's name; made absolute and sorted like `open`), files that arrive as bytes with no path (`open_bytes`, as `Intake::Bytes`), files dropped on the window (`DroppedFile`, `DropTarget`: canvas, tab strip or window) and the OS asking the app to quit (`Intake::Quit`). Each batch stays separate, empty input is ignored, and every sender call wakes the UI. `natural_cmp` and `same_file` for opening order and duplicates; `reveal` (on the caller's thread; on Linux and BSD it can wait up to 2 s for the file manager, so hosts run it on their `Jobs`), `open_external` (on the web, a new tab without `window.opener`), `open_with` and `is_application`; the shared open-error texts. No egui. | | always | `autosave::Autosave` (the timer: which documents are due, results by revision), `recovery_dir`, `adopt_legacy_recovery` and `RecoveryStore`: the recovery folder of copies with a JSON sidecar each (`RecoveryEntry`, the fields craft-ui's `RecoveryDialog` lists), `AUTOSAVE_FAILED`. The app serializes its documents. | | `clipboard`, `clipboard-system` | `clipboard` has no system crates: `Clipboard`, `EventClipboard` (with `LateOffers`), `MemoryClipboard` and the probe. `clipboard-system` adds `SystemClipboard`. `clipboard::Clipboard` over a `ClipboardBackend`: every copy and paste goes through it, with size limits (`ClipboardLimits`, `TooLarge`), a fence that keeps synthetic (automation) input from replacing what the user copied, and `holds_ours` to tell the app's own copy from another app's. `SystemClipboard` (arboard) reads text, HTML, RTF, one bitmap and copied files, and writes one offer; `EventClipboard` is the browser's, fed from paste events (`flavors_from_event`). `EventClipboard` keeps an offered paste for the pass it was offered in and counts passes itself (the pass clock the host gives it), so a menu Paste in a later pass finds nothing and the app has nothing to call at the end of a pass. A write reports which flavor the backend wrote; `holds_ours` asks the backend's owner marker first (`ClipboardBackend::owns`) and compares that flavor's content only when the backend cannot tell. The web writes only the best flavor (eframe makes each copy command its own `navigator.clipboard` write, so a second replaces the first). `has` and `formats` never read or decode: they list the formats on offer (`offer::formats`: Windows' and macOS' formats, Wayland's MIME types, X11's `TARGETS`); a bitmap counts only as `image/png`, the one arboard reads on Linux. `ClipboardProbe` asks a second handle on a worker thread whether Paste has anything, so a slow owner never stalls a frame. Bitmaps are read as straight RGBA8, not PNG: the `BITMAP` and `RGBA8` reads return an `image/x-rgba8` flavor (width and height as little-endian `u32`s, then the pixels) and `read_image` returns `ClipboardImage`; the crate has no PNG encoder, and `SystemClipboard::decoder` takes the app's PNG decoder for writes. SVG and PDF flavors are neither written nor read by `SystemClipboard`; RTF is read, and RTF and MathML are written beside arboard's flavors (a write of only unsupported flavors fails with `Other`); a bitmap offered only as `image/jpeg` or `image/bmp` on Wayland reads as `None`. | | always | `watch::FileWatch` and `Changed`: open files that changed on disk. One worker thread (`craft-file-watch`) compares each file's metadata (`FileStamp`) every 250 ms and sleeps while nothing is watched; a changed file is reported once it has settled and, with `ReadPolicy::Whole`, looks complete. The app's own saves are recognised by `known_now`; `disk_differs` answers at Save time; `take_changes` runs on the frame the worker's `Wake` asks for. | | always (native) | `default_app::make_default`: the Preferences button that makes the app the system default for its file types. Windows opens Settings › Default apps (`SettingsOpened`), Linux and BSD run `xdg-mime default` (`MadeDefault`, refused inside Flatpak or without an installed desktop entry), macOS answers `Unsupported`. `path_from_arg` and `rejoin_split_paths` read the paths a launcher hands the app. Only a button may call it. | | always (native) | `temp::TempDir` and `TempFiles`: private temporary folders created exclusively with owner-only permissions (`0700`, files `0600`, `create_new`), named with the process id and a counter, removed on drop. | +| always (native) | `owner_only`: files only their user can read on Windows, as mode `0600` makes them on Unix. `restrict_to_owner` and `create_private_dir` give a file or new folder an access list of the user and SYSTEM only, `read_with_sddl` reads a file with its security descriptor through one handle, and `foreign_access` says why a descriptor is not the user's alone. They run the tools Windows ships (`whoami`, PowerShell, `icacls`, from System32) because the security API would need `unsafe`. | | always | `PlatformText`: a user-visible message of a platform service (id, English text with `{name}` placeholders) that the app looks up in its own catalog. The open, clipboard, watch, default-app and temp services and craft-dialogs' save flow use it. No words table lists them yet, so the missing-translation list does not show them. | | `screen` | Screen capture for the screen colour picker (`craft_platform::screen`). | | `apple-events` | Apple Events requests on macOS (`open::apple_events`), through `fmv-macos-events`. | diff --git a/crates/platform/src/appearance.rs b/crates/platform/src/appearance.rs index 9052011b0d..380ec9dcff 100644 --- a/crates/platform/src/appearance.rs +++ b/crates/platform/src/appearance.rs @@ -1,6 +1,6 @@ -//! Desktop colour, contrast and motion preferences and GNOME's window-button layout through the -//! XDG Settings portal, the system's animation setting on Windows and macOS, plus the browser's -//! contrast and motion media queries on the web. +//! Desktop colour, contrast, motion and text-scale preferences and GNOME's window-button layout +//! through the XDG Settings portal, the system's animation setting on Windows and macOS, plus the +//! browser's contrast and motion media queries on the web. //! //! Derived from PdfCraft's activation-safe subscription and GNOME schema fallback, //! CADCraft's BSD support, and ArtCraft Launcher's ReadOne/Read compatibility. @@ -10,7 +10,7 @@ pub use reader::{Reading, SystemReader}; use std::{ sync::{ Arc, Condvar, Mutex, PoisonError, - atomic::{AtomicBool, AtomicU8, AtomicU64, Ordering}, + atomic::{AtomicBool, AtomicU8, AtomicU32, AtomicU64, Ordering}, }, time::Duration, }; @@ -39,7 +39,10 @@ struct Shared { contrast: AtomicU8, /// 0 unknown, 1 animations allowed, 2 reduced motion. motion: AtomicU8, - /// Raised each time the theme, contrast or reduced motion changes; layout and icon changes leave it. + /// The text scale's `f32` bits; 0 unknown (no usable scale is 0.0). + text_scale: AtomicU32, + /// Raised each time the theme, contrast, reduced motion or text scale changes; layout and icon + /// changes leave it. generation: AtomicU64, active: AtomicBool, /// True once the source has answered, found no answer, or been cancelled. @@ -62,6 +65,7 @@ impl Shared { value: AtomicU8::new(0), contrast: AtomicU8::new(0), motion: AtomicU8::new(0), + text_scale: AtomicU32::new(0), generation: AtomicU64::new(0), active: AtomicBool::new(active), settled: Mutex::new(false), @@ -103,9 +107,13 @@ impl Shared { } #[cfg(not(target_arch = "wasm32"))] fn publish_code(&self, slot: &AtomicU8, code: u8) { - if slot.swap(code, Ordering::AcqRel) == code { - return; + if slot.swap(code, Ordering::AcqRel) != code { + self.changed(); } + } + /// Raises the generation for a value just stored, then wakes an active host. + #[cfg(not(target_arch = "wasm32"))] + fn changed(&self) { self.generation.fetch_add(1, Ordering::AcqRel); if self.active.load(Ordering::Acquire) { (self.wake)(); @@ -125,6 +133,14 @@ impl Shared { fn publish_motion(&self, reduced: bool) { self.publish_code(&self.motion, if reduced { 2 } else { 1 }); } + /// `None` is no scaling: the desktop's value is out of range, or there is none. + #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] + fn publish_text_scale(&self, scale: Option) { + let bits = scale.map_or(0, f32::to_bits); + if self.text_scale.swap(bits, Ordering::AcqRel) != bits { + self.changed(); + } + } #[cfg(all(unix, not(target_os = "macos"), not(target_arch = "wasm32")))] fn publish_layout(&self, layout: String) { self.publish_text(&self.layout, layout); @@ -204,9 +220,10 @@ impl Watcher { pub fn current(&self) -> Option { self.shared.get() } - /// Rises each time the theme, [`Watcher::contrast`] or [`Watcher::reduced_motion`] changes, before the wake - /// callback runs; a layout or icon theme change leaves it. Read the preferences again when it moved, - /// after reading this: a value is stored before the generation rises. + /// Rises each time the theme, [`Watcher::contrast`], [`Watcher::reduced_motion`] or + /// [`Watcher::text_scale`] changes, before the wake callback runs; a layout or icon theme + /// change leaves it. Read the preferences again when it moved, after reading this: a value is + /// stored before the generation rises. pub fn generation(&self) -> u64 { self.shared.generation.load(Ordering::Acquire) } @@ -270,6 +287,18 @@ impl Watcher { _ => None, } } + /// GNOME's `org.gnome.desktop.interface` `text-scaling-factor` (Settings ▸ Accessibility ▸ + /// Large Text sets 1.25) through the portal, or the `gsettings` fallback when the portal has no + /// such key. A finite value within 0.5..=3.0 is the scale; one outside that range or one that + /// doesn't parse is no scaling and gives `None`, never a clamped value. A change raises the + /// generation and wakes, as the other appearance values do. + /// + /// `None` where the platform does not say: other Linux desktops, macOS, Windows and the web, + /// which scale the whole display instead. + pub fn text_scale(&self) -> Option { + let bits = self.shared.text_scale.load(Ordering::Acquire); + (bits != 0).then(|| f32::from_bits(bits)) + } /// Block until the first answer is known, then return it; at most `timeout`. /// /// Returns early, with `current()`, when the portal is absent and the `gsettings` fallback diff --git a/crates/platform/src/appearance/portal.rs b/crates/platform/src/appearance/portal.rs index f5366ba8cd..a28c25b6de 100644 --- a/crates/platform/src/appearance/portal.rs +++ b/crates/platform/src/appearance/portal.rs @@ -1,4 +1,5 @@ -//! The XDG Settings portal: reading colour scheme, contrast, motion, button layout and icons, and watching for changes. +//! The XDG Settings portal: reading colour scheme, contrast, motion, text scale, button layout and icons, and +//! watching for changes. use super::files::{kde_factor_reduces, reduced_motion_from_files}; use super::{Contrast, Shared, Theme}; @@ -19,6 +20,11 @@ const MOTION_KEY: &str = "reduced-motion"; const ANIMATIONS_KEY: &str = "enable-animations"; const KDE: &str = "org.kde.kdeglobals.KDE"; const KDE_MOTION_KEY: &str = "AnimationDurationFactor"; +// Read on GNOME-like sessions only (`Shared::gnome`): elsewhere the schema's key holds its default +// or a GNOME session's value, not what this desktop applies to its own text. +const TEXT_SCALE_KEY: &str = "text-scaling-factor"; +/// The text scales applied; outside them a desktop's factor is no scaling, never clamped. +const TEXT_SCALES: std::ops::RangeInclusive = 0.5..=3.0; const TIMEOUT: Duration = Duration::from_secs(2); // Outer None means unknown/malformed; Some(None) is an explicit no-preference answer. @@ -95,6 +101,19 @@ fn decode_icons(value: &Value<'_>) -> Option { fn icons_reply(value: &Value<'_>, legacy: bool) -> Option { decode_icons(unwrap_legacy(value, legacy)?) } +// GNOME's `text-scaling-factor`, a double. Outer `None` means malformed; `Some(None)` is a +// factor that is not finite or outside `TEXT_SCALES`, which means no scaling. +fn decode_text_scale(value: &Value<'_>) -> Option> { + let Value::F64(factor) = value else { return None }; + Some((factor.is_finite() && TEXT_SCALES.contains(factor)).then_some(*factor as f32)) +} +fn text_scale_reply(value: &Value<'_>, legacy: bool) -> Option> { + decode_text_scale(unwrap_legacy(value, legacy)?) +} +// `gsettings get` prints the double as text (`1.25`); text that isn't a number is malformed. +fn gsettings_text_scale(text: &str) -> Option> { + decode_text_scale(&Value::F64(text.trim().parse().ok()?)) +} fn combined(standard: Option>, gnome: Option>) -> Option> { if standard.is_none() && gnome.is_none() { None } else { Some(standard.flatten().or(gnome.flatten())) } } @@ -146,6 +165,7 @@ pub(super) struct Fallbacks { layout_used: bool, icons_used: bool, motion_used: bool, + text_scale_used: bool, path: Option, /// `$XDG_CONFIG_HOME`, or `~/.config` when that is empty or unset. config_home: Option, @@ -156,7 +176,15 @@ impl Fallbacks { .filter(|dir| !dir.is_empty()) .map(PathBuf::from) .or_else(|| std::env::var_os("HOME").filter(|home| !home.is_empty()).map(|home| PathBuf::from(home).join(".config"))); - Self { theme_used: false, layout_used: false, icons_used: false, motion_used: false, path: std::env::var_os("PATH"), config_home } + Self { + theme_used: false, + layout_used: false, + icons_used: false, + motion_used: false, + text_scale_used: false, + path: std::env::var_os("PATH"), + config_home, + } } /// The settings files' motion answer, for a session with no bus or a portal that knows none /// of the three motion keys. @@ -203,6 +231,16 @@ impl Fallbacks { shared.publish_layout(answer); } } + async fn text_scale(&mut self, shared: &Shared) { + if std::mem::replace(&mut self.text_scale_used, true) || !shared.gnome { + return; + } + if let Some(text) = self.get(GNOME, TEXT_SCALE_KEY).await + && let Some(answer) = gsettings_text_scale(&text) + { + shared.publish_text_scale(answer); + } + } } pub(super) async fn watch(shared: Arc) { let mut retry = Duration::from_secs(5); @@ -236,6 +274,7 @@ async fn session(shared: &Shared, fallbacks: &mut Fallbacks, connected: &mut boo fallbacks.theme(shared).await; fallbacks.layout(shared).await; fallbacks.icons(shared).await; + fallbacks.text_scale(shared).await; return None; }; watch_connection(shared, fallbacks, connected, connection).await @@ -287,6 +326,11 @@ impl Answers { shared.publish_contrast(contrast); } } + (GNOME, TEXT_SCALE_KEY) if shared.gnome => { + if let Some(scale) = decode_text_scale(value) { + shared.publish_text_scale(scale); + } + } (STANDARD, MOTION_KEY) | (GNOME, ANIMATIONS_KEY) | (KDE, KDE_MOTION_KEY) => { let Some(reduced) = decode_motion(namespace, value) else { return }; match namespace { @@ -341,6 +385,24 @@ async fn next_event(settings: &mut [zbus::MessageStream], owners: &mut zbus::Mes }); futures_lite::future::race(setting, async { owners.next().await.map(Event::Owner) }).await } +/// GNOME's text scale, read on GNOME-like sessions only (`TEXT_SCALE_KEY`). +async fn read_text_scale(connection: &zbus::Connection, gnome: bool) -> Option> { + if gnome { read_with(connection, GNOME, TEXT_SCALE_KEY, text_scale_reply).await } else { None } +} +/// Publishes the contrast, motion and text scale of the first concurrent read. +fn publish_first_reads(shared: &Shared, fallbacks: &mut Fallbacks, contrast: Option, answers: &Answers, text_scale: Option>) { + if let Some(contrast) = contrast { + shared.publish_contrast(contrast); + } + match answers.reduced_motion() { + Some(reduced) => shared.publish_motion(reduced), + // A portal that knows none of the keys (a bare window manager's) leaves the files to answer. + None => fallbacks.motion(shared), + } + if let Some(scale) = text_scale { + shared.publish_text_scale(scale); + } +} async fn watch_connection(shared: &Shared, fallbacks: &mut Fallbacks, connected: &mut bool, connection: zbus::Connection) -> Option<()> { // MatchRule installs before activation: unlike a proxy subscription it needs no current owner. let mut settings = [ @@ -351,24 +413,21 @@ async fn watch_connection(shared: &Shared, fallbacks: &mut Fallbacks, connected: subscribe(&connection, rule(MOTION_KEY), 8).await?, subscribe(&connection, rule(ANIMATIONS_KEY), 8).await?, subscribe(&connection, rule(KDE_MOTION_KEY), 8).await?, + subscribe(&connection, rule(TEXT_SCALE_KEY), 8).await?, ]; let mut owners = subscribe(&connection, owner_rule(), 8).await?; - // Concurrent reads, so contrast and motion are known by the time the theme settles - // `wait_first` without adding round trips before it. - let ((standard, gnome), (contrast, (motion, gnome_motion, kde_motion))) = zip( - zip(read(&connection, STANDARD, shared.gnome), read(&connection, GNOME, shared.gnome)), - zip(read_with(&connection, STANDARD, CONTRAST_KEY, contrast_reply), read_motion(&connection)), + // Concurrent reads, so contrast, motion and text scale are known by the time the theme + // settles `wait_first` without adding round trips before it. + let (((standard, gnome), (contrast, (motion, gnome_motion, kde_motion))), text_scale) = zip( + zip( + zip(read(&connection, STANDARD, shared.gnome), read(&connection, GNOME, shared.gnome)), + zip(read_with(&connection, STANDARD, CONTRAST_KEY, contrast_reply), read_motion(&connection)), + ), + read_text_scale(&connection, shared.gnome), ) .await; let mut answers = Answers { standard, gnome, motion, gnome_motion, kde_motion }; - if let Some(contrast) = contrast { - shared.publish_contrast(contrast); - } - match answers.reduced_motion() { - Some(reduced) => shared.publish_motion(reduced), - // A portal that knows none of the keys (a bare window manager's) leaves the files to answer. - None => fallbacks.motion(shared), - } + publish_first_reads(shared, fallbacks, contrast, &answers, text_scale); match combined(standard, gnome) { Some(answer) => { *connected = true; @@ -378,6 +437,7 @@ async fn watch_connection(shared: &Shared, fallbacks: &mut Fallbacks, connected: fallbacks.theme(shared).await; fallbacks.layout(shared).await; fallbacks.icons(shared).await; + fallbacks.text_scale(shared).await; return None; } } @@ -390,6 +450,10 @@ async fn watch_connection(shared: &Shared, fallbacks: &mut Fallbacks, connected: Some(icons) => shared.publish_icons(icons), None => fallbacks.icons(shared).await, } + // A portal without GNOME's keys answered nothing for the text scale either. + if text_scale.is_none() { + fallbacks.text_scale(shared).await; + } follow(shared, &connection, &mut settings, &mut owners, &mut answers).await } /// Follows the settings after the first read until the portal's owner goes away or a stream ends. @@ -512,6 +576,28 @@ mod tests { assert!(!gnome(&[("SWAYSOCK", "/run/sway.sock"), ("XDG_CURRENT_DESKTOP", "GNOME")])); assert!(!gnome(&[])); } + // A desktop's text scale is applied only when it is a usable factor: Large Text's 1.25 and the + // ends of the range are, while a factor that isn't finite or lies outside 0.5..=3.0 is no + // scaling (not a clamped one), and text `gsettings` prints that isn't a number is no answer. + #[test] + fn gnome_text_scaling_factor_reads_in_range_or_not_at_all() { + use super::{decode_text_scale, gsettings_text_scale, text_scale_reply}; + for (text, scale) in [("1.25\n", 1.25), ("1.0", 1.0), ("0.5", 0.5), ("3.0", 3.0)] { + assert_eq!(gsettings_text_scale(text), Some(Some(scale)), "{text}"); + assert_eq!(decode_text_scale(&Value::F64(f64::from(scale))), Some(Some(scale)), "{text}"); + } + for out_of_range in ["nan", "inf", "-2", "0", "0.49", "3.01", "100"] { + assert_eq!(gsettings_text_scale(out_of_range), Some(None), "{out_of_range}"); + } + for not_a_number in ["", "uint32 0", "'1.25'", "1,25"] { + assert_eq!(gsettings_text_scale(not_a_number), None, "{not_a_number}"); + } + // The portal answers a double; any other type is malformed. The legacy `Read` wraps it once more. + assert_eq!(decode_text_scale(&Value::U32(1)), None); + assert_eq!(decode_text_scale(&Value::from("1.25")), None); + assert_eq!(text_scale_reply(&Value::Value(Box::new(Value::F64(1.5))), true), Some(Some(1.5))); + assert_eq!(text_scale_reply(&Value::F64(1.5), true), None); + } #[test] fn the_generation_rises_once_per_appearance_change_and_never_for_the_layout() -> Result<(), Box> { use crate::appearance::{Contrast, SystemReader}; @@ -525,14 +611,17 @@ mod tests { shared.publish_contrast(Contrast::High); shared.publish_contrast(Contrast::High); shared.publish_motion(true); + shared.publish_text_scale(Some(1.25)); + shared.publish_text_scale(Some(1.25)); shared.publish_layout("appmenu:close".to_owned()); let _ = done.send(()); }, ) .ok_or("worker creation failed")?; finished.recv_timeout(Duration::from_secs(2))?; - assert_eq!(watcher.generation(), 3, "theme, contrast and motion each changed once"); + assert_eq!(watcher.generation(), 4, "theme, contrast, motion and text scale each changed once"); assert_eq!((watcher.current(), watcher.contrast()), (Some(Theme::Dark), Some(Contrast::High))); + assert_eq!(watcher.text_scale(), Some(1.25)); let reader = SystemReader::unwatched(); let before = reader.generation(); diff --git a/crates/platform/src/appearance/reader.rs b/crates/platform/src/appearance/reader.rs index e554555670..27bba2c94a 100644 --- a/crates/platform/src/appearance/reader.rs +++ b/crates/platform/src/appearance/reader.rs @@ -3,7 +3,7 @@ //! and the colour scheme the windowing integration reports. use super::{Contrast, Theme, Watcher}; -use std::sync::atomic::{AtomicU8, AtomicU64, Ordering}; +use std::sync::atomic::{AtomicU8, AtomicU32, AtomicU64, Ordering}; /// What the OS reports now. `None` is no answer; the host decides the fallback. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] @@ -42,12 +42,13 @@ pub struct SystemReader { } /// What the host reported. Codes: 0 no answer; theme 1 dark, 2 light; contrast 1 standard, -/// 2 high; motion 1 animations allowed, 2 reduced. +/// 2 high; motion 1 animations allowed, 2 reduced; text scale the factor's bits, 0 no scaling. #[derive(Default)] struct Reported { theme: AtomicU8, contrast: AtomicU8, motion: AtomicU8, + text_scale: AtomicU32, /// Raised on each change of a reported value. generation: AtomicU64, } @@ -58,6 +59,13 @@ impl Reported { self.generation.fetch_add(1, Ordering::AcqRel); } } + + #[cfg(feature = "testing")] + fn set_text_scale(&self, bits: u32) { + if self.text_scale.swap(bits, Ordering::AcqRel) != bits { + self.generation.fetch_add(1, Ordering::AcqRel); + } + } } impl SystemReader { @@ -78,6 +86,16 @@ impl SystemReader { self.watcher.is_some() } + /// Enables or suppresses the watcher's change notifications; see [`Watcher::set_active`]. The host + /// calls it with `true` when its root window gains focus, which on Windows re-reads the animation + /// effects setting the user may have changed in Settings meanwhile. Nothing happens where no + /// watcher runs. + pub fn set_active(&self, active: bool) { + if let Some(watcher) = &self.watcher { + watcher.set_active(active); + } + } + /// Takes the colour scheme the windowing integration reports (egui's `Event::SystemTheme`). pub fn report_theme(&self, theme: Theme) { let reported = &self.reported; @@ -98,8 +116,16 @@ impl SystemReader { reported.set(&reported.motion, if reduced { 2 } else { 1 }); } - /// Rises each time a preference [`SystemReader::read`] answers from changes, as its source - /// reports it: the watcher's theme, contrast or reduced motion, or a reported value. Read + /// Takes a desktop text scale in place of an OS source; `None` is no scaling. A value that is not a positive, + /// finite factor is no scaling, as the watcher treats an out-of-range one. + #[cfg(feature = "testing")] + pub fn report_text_scale(&self, scale: Option) { + self.reported.set_text_scale(scale.filter(|scale| scale.is_finite() && *scale > 0.0).map_or(0, f32::to_bits)); + } + + /// Rises each time a preference [`SystemReader::read`] or [`SystemReader::text_scale`] answers + /// from changes, as its source reports it: the watcher's theme, contrast, reduced motion or text + /// scale, or a reported value. Read /// again when it moved. On the web the browser's queries raise it in no case. Read it before /// [`SystemReader::read`]: the watcher stores a value before it raises the generation. pub fn generation(&self) -> u64 { @@ -118,6 +144,13 @@ impl SystemReader { self.watcher.as_ref().and_then(Watcher::icon_theme) } + /// The desktop text scale as the watcher last heard it; see [`Watcher::text_scale`]. `None` where the platform + /// does not say, on the web and where no watcher runs; the host then applies no text scaling. + pub fn text_scale(&self) -> Option { + let reported = self.reported.text_scale.load(Ordering::Acquire); + self.watcher.as_ref().and_then(Watcher::text_scale).or_else(|| (reported != 0).then(|| f32::from_bits(reported))) + } + /// The preferences now, without blocking. pub fn read(&self) -> Reading { let reported = &self.reported; diff --git a/crates/platform/src/autosave/recovery.rs b/crates/platform/src/autosave/recovery.rs index 90e3b84c74..440e244750 100644 --- a/crates/platform/src/autosave/recovery.rs +++ b/crates/platform/src/autosave/recovery.rs @@ -78,6 +78,9 @@ pub struct RecoveryMeta { pub extension: String, /// The edit revision the copy holds. pub revision: u64, + /// The recovered copy needs a password to open. Old sidecars read as `false`. + #[serde(default)] + pub protected: bool, } /// A copy an earlier run left. @@ -165,8 +168,11 @@ impl RecoveryStore { adopted.get(&id).cloned().unwrap_or_else(|| format!("doc-{}-{id}", self.session)) } - /// Writes a copy of document `id`; call from a job. + /// Writes a copy of document `id`; call from a job. Makes the folder again if it was removed + /// since the store opened. + // pdfcraft: crates/ui-egui/src/persist/recovery.rs:215 (create_dir before the write) pub fn write(&self, id: u64, meta: &RecoveryMeta, bytes: &[u8]) -> std::io::Result<()> { + create_private_dir(&self.dir)?; let key = self.key(id); let mut meta = meta.clone(); meta.extension = sanitize_extension(&meta.extension); @@ -225,7 +231,7 @@ impl RecoveryStore { None if self.owns_key(&key) || self.other_instance_alive() => None, None => copies.first().map(|(ext, path)| { let saved = std::fs::metadata(path).and_then(|m| m.modified()).unwrap_or(SystemTime::UNIX_EPOCH); - let meta = RecoveryMeta { name: key.clone(), original: None, extension: ext.clone(), revision: 0 }; + let meta = RecoveryMeta { name: key.clone(), original: None, extension: ext.clone(), revision: 0, protected: false }; RecoveryEntry { key: key.clone(), meta, saved, path: path.clone() } }), }; @@ -309,7 +315,7 @@ pub(super) struct Sidecar { /// A sidecar larger than this is not read. #[cfg(not(target_arch = "wasm32"))] -pub(super) const MAX_SIDECAR: u64 = 1 << 20; +pub(crate) const MAX_SIDECAR: u64 = 1 << 20; /// How long a temp file of an interrupted write must have been left before it is removed, far /// longer than any write, so another run's write in progress is never touched. diff --git a/crates/platform/src/autosave/timer.rs b/crates/platform/src/autosave/timer.rs index 0f08170b3c..55b11fb284 100644 --- a/crates/platform/src/autosave/timer.rs +++ b/crates/platform/src/autosave/timer.rs @@ -82,12 +82,15 @@ pub struct Autosave { saved: HashMap, in_flight: HashMap, due_now: bool, + /// A document has changes no autosave holds or is writing: a dirty revision neither autosaved + /// nor in flight, or one whose autosave failed. + pending: bool, } impl Autosave { /// `None` turns autosave off (PhotoCraft's `fileHandling.autosave = false`). pub fn new(interval: Option) -> Self { - Self { interval, next: None, saved: HashMap::new(), in_flight: HashMap::new(), due_now: false } + Self { interval, next: None, saved: HashMap::new(), in_flight: HashMap::new(), due_now: false, pending: false } } /// A changed preference; the next deadline moves to now plus the new interval. @@ -131,6 +134,7 @@ impl Autosave { self.in_flight.remove(id); } let mut due = AutosaveDue { save: Vec::new(), discard }; + self.pending = docs.iter().any(|d| self.needs_save(d)); let Some(interval) = self.interval else { self.next = None; return due; @@ -146,14 +150,20 @@ impl Autosave { } self.next = Some(now + interval); for d in docs { - if d.dirty && self.saved.get(&d.id) != Some(&d.revision) && !self.in_flight.contains_key(&d.id) { + if self.needs_save(&d) { self.in_flight.insert(d.id, d.revision); due.save.push(d.id); } } + self.pending = false; due } + /// Whether `doc` has a revision to autosave that no autosave holds or is writing. + fn needs_save(&self, doc: &AutosaveDoc) -> bool { + doc.dirty && self.saved.get(&doc.id) != Some(&doc.revision) && !self.in_flight.contains_key(&doc.id) + } + /// An autosave ended. On success `revision` is remembered; on failure the status text /// ([`AUTOSAVE_FAILED`] filled in) comes back for the status bar. pub fn finished(&mut self, id: u64, revision: u64, result: Result<(), String>) -> Option { @@ -168,7 +178,10 @@ impl Autosave { self.saved.insert(id, revision); None } - Err(error) => Some(AUTOSAVE_FAILED.replace("{error}", &error)), + Err(error) => { + self.pending = true; + Some(AUTOSAVE_FAILED.replace("{error}", &error)) + } } } @@ -179,8 +192,11 @@ impl Autosave { self.in_flight.remove(&id); } - /// When the next interval ends, for `request_repaint_after`. + /// When the next interval ends, for `request_repaint_after`; `None` while nothing is left to + /// autosave (as of the last [`due`](Self::due), or a failed [`finished`](Self::finished)), so + /// an idle window can sleep. The clock keeps running: an edit wakes the window, and its `due` + /// call brings the deadline back. pub fn deadline(&self) -> Option { - self.next + self.next.filter(|_| self.pending) } } diff --git a/crates/platform/src/autosave_tests.rs b/crates/platform/src/autosave_tests.rs index f26ec3891b..34170c1e6e 100644 --- a/crates/platform/src/autosave_tests.rs +++ b/crates/platform/src/autosave_tests.rs @@ -30,7 +30,7 @@ fn doc(id: u64, revision: u64, dirty: bool) -> AutosaveDoc { } fn meta(name: &str, revision: u64) -> RecoveryMeta { - RecoveryMeta { name: name.into(), original: None, extension: "pcraft".into(), revision } + RecoveryMeta { name: name.into(), original: None, extension: "pcraft".into(), revision, protected: false } } // Nothing is due before the interval; then only dirty documents with a new revision and no @@ -78,6 +78,40 @@ fn due_picks_dirty_changed_documents_each_interval() { assert_eq!(timer.deadline(), None); } +// The deadline wakes the window only while something waits to be autosaved: none when every +// document is clean, autosaved or being written; back on an edit or a failed write. +#[test] +fn the_deadline_is_none_while_nothing_waits_to_be_autosaved() { + let minute = Duration::from_secs(60); + let t0 = Instant::now(); + let mut timer = Autosave::new(Some(minute)); + timer.due(t0, [doc(1, 1, false)]); + assert_eq!(timer.deadline(), None, "a clean document has nothing to save"); + timer.due(t0 + minute / 2, [doc(1, 2, true)]); + assert!(timer.deadline().is_some(), "an edit brings the deadline back"); + assert_eq!(timer.due(t0 + minute, [doc(1, 2, true)]).save, vec![1]); + assert_eq!(timer.deadline(), None, "the revision is being written"); + assert_eq!(timer.finished(1, 2, Ok(())), None); + timer.due(t0 + minute * 2, [doc(1, 2, true)]); + assert_eq!(timer.deadline(), None, "the revision is autosaved"); + timer.due(t0 + minute * 5 / 2, [doc(1, 3, true)]); + assert!(timer.deadline().is_some()); + assert_eq!(timer.due(t0 + minute * 3, [doc(1, 3, true)]).save, vec![1]); + assert!(timer.finished(1, 3, Err("disk full".into())).is_some()); + assert!(timer.deadline().is_some(), "a failed revision is tried again"); +} + +// An autosave after the recovery folder was removed (a cleaner, the user) makes it again. +#[test] +fn a_write_after_the_folder_was_removed_makes_it_again() { + let scratch = Scratch::new(); + let dir = scratch.0.join("Recovery"); + let store = RecoveryStore::open(&dir).unwrap(); + std::fs::remove_dir_all(&dir).unwrap(); + store.write(1, &meta("a.psd", 1), b"work").unwrap(); + assert_eq!(std::fs::read(dir.join(format!("{}.pcraft", store.key(1)))).unwrap(), b"work"); +} + // A copy written by a run that is gone is a leftover; one of a live instance (its lock held) is // not; discard removes copy and sidecar. #[test] @@ -111,3 +145,96 @@ fn leftovers_skip_live_instances() { second.remove(&found[0]).unwrap(); assert!(!found[0].path.exists()); } + +/// The sidecar of an earlier run, as `RecoveryStore::write` lays it out, written by hand. +fn sidecar(name: &str, instance: Option<&str>) -> String { + serde_json::json!({"name": name, "original": null, "extension": "pcraft", "revision": 1, "instance": instance}).to_string() +} + +/// The leftover listed under `key`. +fn listed(store: &RecoveryStore, key: &str) -> Option { + store.leftovers().into_iter().find(|e| e.key == key) +} + +// The recovery folder is untrusted: a planted sidecar over MAX_SIDECAR is never read whole (its +// copy is still offered, under its key), while one at the cap is read. +#[test] +fn a_sidecar_over_the_size_cap_is_ignored_and_one_under_it_is_read() { + let scratch = Scratch::new(); + let store = RecoveryStore::open(scratch.0.join("Recovery")).unwrap(); + let cap = usize::try_from(MAX_SIDECAR).unwrap(); + std::fs::write(store.dir().join("big.pcraft"), b"copy").unwrap(); + let oversized = sidecar(&"x".repeat(cap), None); + assert!(oversized.len() > cap); + std::fs::write(store.dir().join("big.json"), &oversized).unwrap(); + let entry = listed(&store, "big").unwrap(); + assert_eq!((entry.meta.name.as_str(), entry.meta.revision), ("big", 0), "the oversized sidecar was read"); + assert_eq!(std::fs::read(&entry.path).unwrap(), b"copy"); + + let mut at_cap = sidecar("work.pdf", None); + at_cap.push_str(&" ".repeat(cap - at_cap.len())); + std::fs::write(store.dir().join("big.json"), &at_cap).unwrap(); + assert_eq!(listed(&store, "big").unwrap().meta.name, "work.pdf"); +} + +// A copy whose sidecar never got written (a crash between the two writes) or can't be parsed is +// still the user's work: it is offered under its key, and listing deletes nothing. +#[test] +fn an_orphan_copy_and_a_broken_sidecar_are_offered_and_listing_removes_nothing() { + let scratch = Scratch::new(); + let store = RecoveryStore::open(scratch.0.join("Recovery")).unwrap(); + let files = ["orphan.pdf", "broken.pcraft", "broken.json"]; + for file in files { + let bytes: &[u8] = if file.ends_with(".json") { b"{\"name\": " } else { b"work" }; + std::fs::write(store.dir().join(file), bytes).unwrap(); + } + for _ in 0..2 { + let orphan = listed(&store, "orphan").unwrap(); + assert_eq!((orphan.meta.name.as_str(), orphan.path.file_name().and_then(|n| n.to_str())), ("orphan", Some("orphan.pdf"))); + let broken = listed(&store, "broken").unwrap(); + assert_eq!((broken.meta.name.as_str(), broken.path.file_name().and_then(|n| n.to_str())), ("broken", Some("broken.pcraft"))); + } + for file in files { + assert!(store.dir().join(file).exists(), "{file} was removed by listing"); + } +} + +// The copy is written before its sidecar. When the sidecar can't be written (here a folder stands +// at its name) the write reports the failure, and the copy stays and is offered after a crash. +#[test] +fn a_failed_sidecar_write_keeps_the_copy_offered() { + let scratch = Scratch::new(); + let dir = scratch.0.join("Recovery"); + let crashed = RecoveryStore::open(&dir).unwrap(); + let key = crashed.key(1); + std::fs::create_dir(dir.join(format!("{key}.json"))).unwrap(); + assert!(crashed.write(1, &meta("a.pdf", 2), b"work").is_err()); + let copy = dir.join(format!("{key}.pcraft")); + assert_eq!(std::fs::read(©).unwrap(), b"work"); + drop(crashed); + + let next = RecoveryStore::open(&dir).unwrap(); + let entry = listed(&next, &key).unwrap(); + assert_eq!(entry.path, copy); +} + +// The lock name in a sidecar is untrusted. One that leaves the folder is never opened: here it +// would name a lock another run holds outside the folder, which would hide the copy, so the copy +// is offered as a plain leftover and the outside file is left alone. +#[test] +fn a_sidecar_naming_a_lock_outside_the_folder_is_a_plain_leftover() { + let scratch = Scratch::new(); + let store = RecoveryStore::open(scratch.0.join("Recovery")).unwrap(); + let outside = scratch.0.join("instance-held.lock"); + let held = std::fs::OpenOptions::new().read(true).write(true).create(true).truncate(false).open(&outside).unwrap(); + held.try_lock().unwrap(); + // Makes the escaping name resolve on every platform, were it ever opened. + std::fs::create_dir(store.dir().join("instance-x")).unwrap(); + for (key, instance) in [("up", "instance-x/../../instance-held.lock"), ("back", r"instance-x\..\..\instance-held.lock")] { + std::fs::write(store.dir().join(format!("{key}.pcraft")), b"work").unwrap(); + std::fs::write(store.dir().join(format!("{key}.json")), sidecar("a.pdf", Some(instance))).unwrap(); + let entry = listed(&store, key); + assert_eq!(entry.map(|e| e.meta.name), Some("a.pdf".to_owned()), "{instance}"); + } + assert!(outside.exists()); +} diff --git a/crates/platform/src/browser_files.rs b/crates/platform/src/browser_files.rs index e21a131b84..a00309b253 100644 --- a/crates/platform/src/browser_files.rs +++ b/crates/platform/src/browser_files.rs @@ -3,7 +3,7 @@ use std::path::{Path, PathBuf}; use std::sync::{Arc, Mutex, MutexGuard}; -use craft_host::{FileError, Files, PendingPick, PickId, PickKind, PickRequest, Picked, Wake}; +use craft_host::{FileError, Files, PendingPick, PickId, PickKind, PickRequest, Picked, Wake, WriteIntent}; use js_sys::{Array, Function, Object, Promise, Reflect}; use wasm_bindgen::{JsCast, JsValue}; use wasm_bindgen_futures::{JsFuture, spawn_local}; @@ -33,8 +33,13 @@ pub struct BrowserFiles { state: Arc>, wake: Wake, limits: PickLimits, + page_save: Option, } +/// An embedding page's save ([`BrowserFiles::page_saves`]): given the file name, the bytes and whether the user asked +/// for Save As, `None` when no page hosts the app, else the page's answer. +pub type PageSave = Arc Option> + Send + Sync>; + /// Tickets of one service, shared with the tasks that answer them. #[derive(Default)] struct State { @@ -89,7 +94,14 @@ fn finish(state: &Mutex, wake: &Wake, id: PickId, picked: Picked) { impl BrowserFiles { /// A service whose late answers call `wake`. pub fn new(wake: impl Fn() + Send + Sync + 'static) -> Self { - Self { state: Arc::new(Mutex::new(State::default())), wake: Wake::new(wake), limits: PickLimits::DEFAULT } + Self { state: Arc::new(Mutex::new(State::default())), wake: Wake::new(wake), limits: PickLimits::DEFAULT, page_save: None } + } + + /// The service whose [`Files::write`] goes to the page embedding the app (a host that saves the document back + /// itself, as a file manager's viewer does) whenever `save` answers; otherwise, and with no `save`, a write + /// downloads the bytes. + pub fn page_saves(self, save: impl Fn(&str, &[u8], bool) -> Option> + Send + Sync + 'static) -> Self { + Self { page_save: Some(Arc::new(save)), ..self } } /// The service with `limits` in place of [`PickLimits::DEFAULT`]. @@ -157,6 +169,27 @@ fn downloaded(name: &str, result: Result<(), String>) -> Picked { } /// One download of `bytes` as `name`. +/// The name a write of `path` goes out under: its last part without control characters, `document` when that is empty. +fn write_name(path: &Path) -> String { + let base: String = path.file_name().map(|n| n.to_string_lossy().chars().filter(|c| !c.is_control()).collect()).unwrap_or_default(); + let base = base.trim(); + if base.is_empty() { "document".to_owned() } else { base.to_owned() } +} + +/// A write's route: the embedding page when `page` answers (`Ok(true)`), else `download` (`Ok(false)`). +pub(crate) fn page_or_download( + page: Option<&(dyn Fn(&str, &[u8], bool) -> Option> + Send + Sync)>, + name: &str, + bytes: &[u8], + save_as: bool, + download: impl FnOnce() -> Result<(), String>, +) -> Result { + match page.and_then(|save| save(name, bytes, save_as)) { + Some(answer) => answer.map(|()| true).map_err(FileError::Other), + None => download().map(|()| false).map_err(FileError::Other), + } +} + fn download(name: &str, mime: &str, bytes: &[u8]) -> Result<(), String> { download_bytes(name, mime, bytes, DownloadOptions { revoke_after_ms: REVOKE_AFTER_MS }).map_err(|e| js_text(&e)) } @@ -301,8 +334,10 @@ impl Files for BrowserFiles { Err(FileError::Unsupported) } - fn write(&self, _path: &Path, _bytes: &[u8]) -> Result<(), FileError> { - Err(FileError::Unsupported) + /// `Ok(true)` when the embedding page saved the bytes, `Ok(false)` when they were downloaded. + fn write(&self, path: &Path, bytes: &[u8], intent: WriteIntent) -> Result { + let name = write_name(path); + page_or_download(self.page_save.as_deref(), &name, bytes, intent == WriteIntent::SaveAs, || download(&name, mime_for(&name), bytes)) } fn last_folder(&self, _purpose: &str) -> Option { diff --git a/crates/platform/src/browser_files_tests.rs b/crates/platform/src/browser_files_tests.rs index 49db884993..c2ab10a064 100644 --- a/crates/platform/src/browser_files_tests.rs +++ b/crates/platform/src/browser_files_tests.rs @@ -3,7 +3,7 @@ use craft_host::Picked; use wasm_bindgen_test::{wasm_bindgen_test, wasm_bindgen_test_configure}; -use crate::browser_files::rejected; +use crate::browser_files::{page_or_download, rejected}; wasm_bindgen_test_configure!(run_in_browser); @@ -35,3 +35,43 @@ fn a_rejected_picker_downloads_once_unless_cancelled() { assert_eq!(calls, 1); assert_eq!(picked, Picked::Failed("the download was blocked".into()), "a failed fallback stays a failed save"); } + +/// A write goes to the embedding page whenever it answers, Save As passed on, and downloads only when no page hosts +/// the app: an app embedded in a file manager saves back into it, not into the downloads folder. +#[wasm_bindgen_test] +fn a_write_goes_to_the_embedding_page_and_downloads_only_without_one() { + let page = |name: &str, bytes: &[u8], save_as: bool| Some(if save_as { Err(format!("{name} {}", bytes.len())) } else { Ok(()) }); + let mut downloads = 0; + assert_eq!( + page_or_download(Some(&page), "a.pdf", b"pdf", false, || { + downloads += 1; + Ok(()) + }), + Ok(true) + ); + assert_eq!( + page_or_download(Some(&page), "a.pdf", b"pdf", true, || { + downloads += 1; + Ok(()) + }), + Err(craft_host::FileError::Other("a.pdf 3".into())), + "the page's refusal is the write's" + ); + assert_eq!(downloads, 0, "a page that answers is the only save"); + let unhosted = |_: &str, _: &[u8], _: bool| None; + assert_eq!( + page_or_download(Some(&unhosted), "a.pdf", b"pdf", false, || { + downloads += 1; + Ok(()) + }), + Ok(false) + ); + assert_eq!( + page_or_download(None, "a.pdf", b"pdf", false, || { + downloads += 1; + Ok(()) + }), + Ok(false) + ); + assert_eq!(downloads, 2, "without a page each write downloads once"); +} diff --git a/crates/platform/src/clipboard/offer/macos.rs b/crates/platform/src/clipboard/offer/macos.rs index 7faa00a61d..ed4153b98b 100644 --- a/crates/platform/src/clipboard/offer/macos.rs +++ b/crates/platform/src/clipboard/offer/macos.rs @@ -68,6 +68,8 @@ pub(super) fn write(handle: &mut arboard::Clipboard, state: &mut State, plan: &P string("public.html", &html.text); } } + // arboard's file list is the whole copy. + Primary::Files => {} } state.change = Some(board.changeCount()); Ok(index) diff --git a/crates/platform/src/clipboard/offer/mod.rs b/crates/platform/src/clipboard/offer/mod.rs index cb7fe0736d..085469882b 100644 --- a/crates/platform/src/clipboard/offer/mod.rs +++ b/crates/platform/src/clipboard/offer/mod.rs @@ -26,8 +26,8 @@ use self::windows as platform; use std::borrow::Cow; use super::backend::{Decode, system_error}; -use super::convert::rgba8_image; -use super::types::{ClipboardError, ClipboardImage, Flavor, HTML, MATHML, PNG, RGBA8, RTF, TEXT}; +use super::convert::{parse_uri_list, rgba8_image}; +use super::types::{ClipboardError, ClipboardImage, Flavor, HTML, MATHML, PNG, RGBA8, RTF, TEXT, URI_LIST}; /// The platform's offer state: the cached X11 `TARGETS` connection and the macOS change count recorded at a write. pub(super) struct Offer { @@ -55,6 +55,12 @@ struct Picture<'a> { png: Option<&'a [u8]>, } +/// The copied files a write offers: the local paths of the first file list that names any. +struct FileList { + index: usize, + paths: Vec, +} + /// What a write puts on the clipboard: the first flavour of each kind among the caller's. struct Plan<'a> { text: Option>, @@ -62,13 +68,16 @@ struct Plan<'a> { rtf: Option>, mathml: Option>, picture: Option>, + files: Option, } -/// Which of a plan's two shapes a write takes: arboard holds a bitmap or rich text, not both. -#[derive(Clone, Copy, PartialEq, Eq)] +/// Which of a plan's shapes a write takes: arboard holds a bitmap, rich text or a file list, one of them. +#[derive(Clone, Copy, PartialEq, Eq, Debug)] enum Primary { Picture, Rich, + /// Copied files, the way a file manager's Copy puts them. + Files, } impl<'a> Plan<'a> { @@ -89,18 +98,26 @@ impl<'a> Plan<'a> { }?; pixels.is_whole().then_some(Picture { index, pixels, png }) }); - Self { text: part(TEXT), html: part(HTML), rtf: part(RTF), mathml: part(MATHML), picture } + // Only `file:` URIs become files; a list that names none leaves the write to the other flavours. + let files = flavors.iter().enumerate().find_map(|(index, flavor)| { + let paths = (flavor.mime == URI_LIST).then(|| parse_uri_list(&String::from_utf8_lossy(&flavor.data)))?; + (!paths.is_empty()).then_some(FileList { index, paths }) + }); + Self { text: part(TEXT), html: part(HTML), rtf: part(RTF), mathml: part(MATHML), picture, files } } - /// The shape of the write: whichever of the bitmap and the HTML or text the caller put first. + /// The shape of the write: whichever of the bitmap, the HTML or text and the file list the caller put first. fn primary(&self) -> Option { let rich = [&self.html, &self.text].into_iter().flatten().map(|part| part.index).min(); - match (self.picture.as_ref().map(|picture| picture.index), rich) { - (Some(picture), Some(rich)) if rich < picture => Some(Primary::Rich), - (Some(_), _) => Some(Primary::Picture), - (None, Some(_)) => Some(Primary::Rich), - (None, None) => None, - } + [ + self.picture.as_ref().map(|picture| (picture.index, Primary::Picture)), + rich.map(|index| (index, Primary::Rich)), + self.files.as_ref().map(|files| (files.index, Primary::Files)), + ] + .into_iter() + .flatten() + .min_by_key(|&(index, _)| index) + .map(|(_, primary)| primary) } } @@ -127,6 +144,11 @@ fn arboard_write(handle: &mut arboard::Clipboard, plan: &Plan<'_>) -> Result<(us } (None, None) => Err(ClipboardError::NoFormat), }, + Primary::Files => { + let files = plan.files.as_ref().ok_or(ClipboardError::NoFormat)?; + handle.set().file_list(&files.paths).map_err(system_error)?; + Ok((files.index, Primary::Files)) + } } } diff --git a/crates/platform/src/clipboard/offer/tests.rs b/crates/platform/src/clipboard/offer/tests.rs index 0f330430e8..944076c1cf 100644 --- a/crates/platform/src/clipboard/offer/tests.rs +++ b/crates/platform/src/clipboard/offer/tests.rs @@ -27,6 +27,38 @@ fn cf_html_offsets_delimit_the_fragment_bytes() { assert_eq!(end_html, data.len() - 1); } +// Copied files reach the system clipboard as a file list holding the same paths, spaces and +// non-ASCII names included; a URI that names no local file is never written as one, and a list +// with no file in it leaves the write to the next flavour. +#[test] +fn a_file_list_is_written_as_files() { + use super::{Plan, Primary}; + use crate::clipboard::types::{Flavor, URI_LIST}; + + let paths = vec![std::env::temp_dir().join("a b#1.pdf"), std::env::temp_dir().join("café 100%.png")]; + let flavors = [Flavor::files(&paths), Flavor::text("names")]; + let plan = Plan::new(&flavors, None); + assert_eq!(plan.primary(), Some(Primary::Files)); + assert_eq!(plan.files.as_ref().map(|files| (files.index, files.paths.clone())), Some((0, paths.clone()))); + + let mut mixed = b"# copied\r\nhttps://example.com/a.pdf\r\n".to_vec(); + mixed.extend(Flavor::files(&paths[..1]).data); + let flavors = [Flavor::new(URI_LIST, mixed)]; + let plan = Plan::new(&flavors, None); + assert_eq!(plan.primary(), Some(Primary::Files)); + assert_eq!(plan.files.as_ref().map(|files| files.paths.clone()), Some(paths[..1].to_vec())); + + let flavors = [Flavor::new(URI_LIST, b"https://example.com/a.pdf\r\n".to_vec()), Flavor::text("names")]; + let plan = Plan::new(&flavors, None); + assert!(plan.files.is_none()); + assert_eq!(plan.primary(), Some(Primary::Rich)); + assert_eq!(plan.text.as_ref().map(|text| text.index), Some(1)); + + // Text put first stays the write's shape even with files beside it. + let flavors = [Flavor::text("names"), Flavor::files(&paths)]; + assert_eq!(Plan::new(&flavors, None).primary(), Some(Primary::Rich)); +} + /// Ported from WordCraft (#7317). An X11 property read is taken only when it came whole and within the cap: over the /// cap, or with bytes still left to read, it is refused rather than pasted truncated. #[cfg(all(unix, not(target_os = "macos")))] diff --git a/crates/platform/src/clipboard/offer/unix.rs b/crates/platform/src/clipboard/offer/unix.rs index 9539d4200e..ab8eef8a54 100644 --- a/crates/platform/src/clipboard/offer/unix.rs +++ b/crates/platform/src/clipboard/offer/unix.rs @@ -127,6 +127,8 @@ fn wayland_write(plan: &Plan<'_>, owner: &[u8]) -> Result, Clipboa let Some((index, png)) = plan.picture.as_ref().and_then(|picture| Some((picture.index, picture.png?))) else { return Ok(None) }; [Some((index, PNG, png.to_vec())), text(&plan.html, HTML), text(&plan.text, UTF8_TEXT)].into_iter().flatten().collect() } + // arboard offers a file list with the names file managers read (`text/uri-list` and GNOME's own). + Some(Primary::Files) => return Ok(None), // The text first: the plain-text aliases serve the first text type offered. _ => [text(&plan.text, UTF8_TEXT), text(&plan.html, HTML), text(&plan.rtf, RTF), text(&plan.mathml, MATHML)].into_iter().flatten().collect(), }; diff --git a/crates/platform/src/clipboard/offer/windows.rs b/crates/platform/src/clipboard/offer/windows.rs index 6439749062..770a7847dd 100644 --- a/crates/platform/src/clipboard/offer/windows.rs +++ b/crates/platform/src/clipboard/offer/windows.rs @@ -94,6 +94,8 @@ pub(super) fn write(handle: &mut arboard::Clipboard, state: &mut State, plan: &P add(HTML_FORMAT, &wrap_cf_html(&html.text)); } } + // arboard's file list is the whole copy. + Primary::Files => {} } state.unmarked = !add(OWNER_FORMAT, owner); Ok(index) diff --git a/crates/platform/src/clipboard/types.rs b/crates/platform/src/clipboard/types.rs index bd91eed8fa..d5b6651264 100644 --- a/crates/platform/src/clipboard/types.rs +++ b/crates/platform/src/clipboard/types.rs @@ -38,6 +38,13 @@ pub struct Flavor { } impl Flavor { + /// A [`URI_LIST`] flavor (RFC 2483) of the files `paths`, which a write puts on the system + /// clipboard as copied files, the way a file manager's Copy does. + #[cfg(all(feature = "clipboard-system", not(target_arch = "wasm32")))] + pub fn files(paths: &[std::path::PathBuf]) -> Flavor { + Self::new(URI_LIST, super::convert::uri_list(paths, cfg!(windows)).into_bytes()) + } + /// A flavor of `data` with the given MIME type. pub fn new(mime: impl Into>, data: Vec) -> Self { Self { mime: mime.into(), data } diff --git a/crates/platform/src/default_app_tests.rs b/crates/platform/src/default_app_tests.rs index aa706ba72a..1d451ae6b0 100644 --- a/crates/platform/src/default_app_tests.rs +++ b/crates/platform/src/default_app_tests.rs @@ -1,6 +1,6 @@ //! `craft_platform::default_app`. -use crate::default_app::path_from_arg; +use crate::default_app::{path_from_arg, rejoin_split_paths}; // XDG_DATA_HOME (else ~/.local/share) comes first, then each XDG_DATA_DIRS entry (else // /usr/local/share:/usr/share); relative and empty entries are skipped, and no home is fine. @@ -22,17 +22,35 @@ fn application_dirs_follow_the_xdg_spec() { assert_eq!(application_dirs(Some("rel"), None, Some("also-rel")), [p("/usr/local/share/applications"), p("/usr/share/applications")]); } -// file:///a%20b.pdf and file://localhost/x decode to paths; http://, file://host/x, plain paths -// and non-UTF-8 escapes pass through; file:///C:/x.pdf is C:/x.pdf on Windows. +// file:///a%20b.pdf and file://localhost/x decode to paths; truncated and invalid escapes are +// kept as written; http://, file://host/x, a bare file://, plain paths and non-UTF-8 escapes pass +// through; file:///C:/x.pdf is C:/x.pdf on Windows. #[test] fn file_uris_become_paths() { assert_eq!(path_from_arg("file:///a%20b.pdf".into()), "/a b.pdf"); assert_eq!(path_from_arg("file://localhost/x".into()), "/x"); assert_eq!(path_from_arg("file:///caf%C3%A9.pdf".into()), "/café.pdf"); assert_eq!(path_from_arg("file:///100%.pdf".into()), "/100%.pdf"); - for same in ["http://example.com/a.pdf", "file://host/x", "/plain/path.pdf", "file:///bad%FF.pdf", "mailto:a@b.c"] { + assert_eq!(path_from_arg("file:///tmp/a%2".into()), "/tmp/a%2"); + assert_eq!(path_from_arg("file:///tmp/%zz%".into()), "/tmp/%zz%"); + for same in ["http://example.com/a.pdf", "file://host/x", "file://", "report.pdf", "/plain/path.pdf", "file:///bad%FF.pdf", "mailto:a@b.c"] { assert_eq!(path_from_arg(same.into()), same); } let drive = path_from_arg("file:///C:/x.pdf".into()); assert_eq!(drive, if cfg!(windows) { "C:/x.pdf" } else { "/C:/x.pdf" }); } + +// A launcher that passes a path with spaces unquoted splits it; the pieces are joined back into +// the longest run that names a file, files that exist on their own stay apart, and arguments +// that join into nothing are kept as given so a missing file is still reported by its name. +#[test] +fn split_paths_with_spaces_are_rejoined() { + let have = [r"P:\Archive\00042A26 Contract.PDF", r"C:\a b c.pdf", r"C:\a.pdf", r"C:\x y.pdf"]; + let exists = |p: &str| have.contains(&p); + let args = |a: &[&str]| a.iter().map(|s| s.to_string()).collect::>(); + assert_eq!(rejoin_split_paths(args(&[r"P:\Archive\00042A26", "Contract.PDF"]), exists), args(&[r"P:\Archive\00042A26 Contract.PDF"])); + assert_eq!(rejoin_split_paths(args(&[r"C:\a", "b", "c.pdf", r"C:\a.pdf"]), exists), args(&[r"C:\a b c.pdf", r"C:\a.pdf"])); + assert_eq!(rejoin_split_paths(args(&[r"C:\a.pdf", r"C:\x", "y.pdf"]), exists), args(&[r"C:\a.pdf", r"C:\x y.pdf"])); + assert_eq!(rejoin_split_paths(args(&["missing.pdf", "other"]), exists), args(&["missing.pdf", "other"])); + assert!(rejoin_split_paths(Vec::new(), exists).is_empty()); +} diff --git a/crates/platform/src/lib.rs b/crates/platform/src/lib.rs index 70e54c0c05..80816c2a9b 100644 --- a/crates/platform/src/lib.rs +++ b/crates/platform/src/lib.rs @@ -31,6 +31,8 @@ mod message_tests; pub mod open; #[cfg(test)] mod open_tests; +#[cfg(not(target_arch = "wasm32"))] +pub mod owner_only; pub mod pacing; #[cfg(feature = "pointer")] pub mod pointer; diff --git a/crates/platform/src/logs_tests.rs b/crates/platform/src/logs_tests.rs index 8a61b9e26b..33cd62fe46 100644 --- a/crates/platform/src/logs_tests.rs +++ b/crates/platform/src/logs_tests.rs @@ -217,3 +217,94 @@ fn rotation_keeps_previous_logs_and_a_running_instance_log() { assert!(rotate(&blocked, NAMES).is_err()); let _ = std::fs::remove_file(&blocked); } + +// RUST_LOG is user input: the longest matching directive decides, `a` covers `a::b` but not +// `ab`, `a*` covers every target starting with `a`, unknown levels and empty parts are skipped, +// and a hostile spec never panics and leaves the default. +#[test] +fn filter_directives_pick_the_most_specific_match_and_hostile_specs_fall_back() { + for spec in ["warn,a=info,a::b=trace,c*=debug,d=bogus,,=error,e=,zz", "zz , a::b=trace ,a=info,warn, c*=debug"] { + let filter = Filter::parse(spec); + assert_eq!(filter.level_for("a::b::c"), LevelFilter::Trace, "{spec}: the longer directive wins"); + assert_eq!(filter.level_for("a::x"), LevelFilter::Info, "{spec}"); + assert_eq!(filter.level_for("a"), LevelFilter::Info, "{spec}"); + assert_eq!(filter.level_for("ab"), LevelFilter::Warn, "{spec}: `a` does not match `ab`"); + assert_eq!(filter.level_for("a::bc"), LevelFilter::Info, "{spec}: `a::b` does not match `a::bc`"); + assert_eq!((filter.level_for("c"), filter.level_for("cat::x")), (LevelFilter::Debug, LevelFilter::Debug), "{spec}"); + assert_eq!(filter.level_for("zz::q"), LevelFilter::Trace, "{spec}: a bare target turns everything on"); + assert!(filter.level_for("a::b") > filter.level_for("a") && filter.level_for("a") > filter.level_for("other"), "{spec}"); + assert_eq!(filter.max(), LevelFilter::Trace, "{spec}"); + } + let skipped = Filter::parse("warn,d=bogus,e=,=error"); + assert_eq!((skipped.level_for("d"), skipped.level_for("e"), skipped.level_for("")), (LevelFilter::Warn, LevelFilter::Warn, LevelFilter::Warn)); + let default = Filter::parse(""); + for hostile in ["", "=", ",,", "x=bogus", " = , = ", "=trace"] { + let filter = Filter::parse(hostile); + assert_eq!(filter, default, "{hostile:?}"); + assert_eq!((filter.level_for("x"), filter.max()), (LevelFilter::Error, LevelFilter::Error), "{hostile:?}"); + } +} + +// The date comes from hand-written civil-from-days arithmetic, which nothing else checks and +// whose mistakes look plausible: leap days, a century year without one, the epoch (and a clock +// before it), and the milliseconds of the instant. +#[test] +fn timestamps_are_utc_with_milliseconds_across_leap_days() { + use std::time::Duration; + let at = |millis: u64| timestamp(web_time::UNIX_EPOCH + Duration::from_millis(millis)); + // 2024-02-29T00:00:00Z is 1_709_164_800 s after the epoch. + assert_eq!(at(1_709_164_800_250), "2024-02-29T00:00:00.250Z"); + assert_eq!(at(1_709_251_199_999), "2024-02-29T23:59:59.999Z"); + assert_eq!(at(1_709_251_200_000), "2024-03-01T00:00:00.000Z", "the day after a leap day is 1 March"); + // 2000 is divisible by 400 and has a 29 February; 2100 is a century year that has none. + assert_eq!(at(951_782_400_000), "2000-02-29T00:00:00.000Z"); + assert_eq!(at(4_107_542_399_000), "2100-02-28T23:59:59.000Z"); + assert_eq!(at(4_107_542_400_000), "2100-03-01T00:00:00.000Z", "2100 has no 29 February"); + assert_eq!(at(0), "1970-01-01T00:00:00.000Z"); + assert_eq!(at(1), "1970-01-01T00:00:00.001Z"); + let before = web_time::UNIX_EPOCH.checked_sub(Duration::from_secs(5)).unwrap(); + assert_eq!(timestamp(before), "1970-01-01T00:00:00.000Z", "a clock before the epoch reads as the epoch"); +} + +// Lines logged before the file opens reach it in order, a flood before then keeps its first +// MAX_PENDING lines plus one note that the rest were dropped, and a runaway log stops at its size +// cap with one note and adds nothing after it. +#[test] +fn a_sink_keeps_early_lines_bounded_and_stops_at_its_size_cap() { + let dir = temp_dir("sink"); + std::fs::create_dir_all(&dir).unwrap(); + let early = dir.join("early.log"); + let mut sink = Sink::new(MAX_FILE_BYTES); + let extra = 3; + for i in 0..MAX_PENDING + extra { + sink.write(&format!("line {i}\n")); + } + sink.attach(std::fs::File::create(&early).unwrap()); + sink.write("after\n"); + let text = read(&early); + let lines: Vec<&str> = text.lines().collect(); + assert_eq!(lines.len(), MAX_PENDING + 2, "the kept lines, one note, the line after attaching"); + let kept: Vec = (0..MAX_PENDING).map(|i| format!("line {i}")).collect(); + assert_eq!(lines[..MAX_PENDING], kept[..]); + assert_eq!(lines.iter().filter(|line| line.contains("dropped")).count(), 1); + assert!(lines[MAX_PENDING].starts_with(&format!("{extra} ")), "{}", lines[MAX_PENDING]); + assert_eq!(lines[MAX_PENDING + 1], "after"); + + let capped = dir.join("capped.log"); + let line = "0123456789\n"; + let max_bytes = u64::try_from(line.len() * 3 / 2).unwrap(); + let mut sink = Sink::new(max_bytes); + sink.attach(std::fs::File::create(&capped).unwrap()); + sink.write(line); + sink.write(line); + let at_cap = read(&capped); + let lines: Vec<&str> = at_cap.lines().collect(); + assert_eq!(lines.len(), 2, "{at_cap}"); + assert_eq!(lines[0], line.trim_end()); + assert!(lines[1].contains(&max_bytes.to_string()), "one note naming the cap: {at_cap}"); + for _ in 0..3 { + sink.write(line); + } + assert_eq!(read(&capped), at_cap, "nothing follows the note"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/platform/src/message.rs b/crates/platform/src/message.rs index 59cb8e0e08..71bec9ffcd 100644 --- a/crates/platform/src/message.rs +++ b/crates/platform/src/message.rs @@ -1,6 +1,8 @@ //! [`PlatformText`]: a user-visible message of a platform service, with its catalog id and //! English text. craft-platform has no catalog; the app looks the id up in its own. +use craft_i18n::Word; + /// A message with `{name}`-style placeholders the app fills after looking `id` up (the /// English is the fallback). The open, clipboard, watch, default-app and temp services and /// craft-dialogs' save flow word their messages with these, so every app shows the same text. @@ -17,6 +19,12 @@ impl PlatformText { pub const fn key(&self) -> &'static str { self.id } + + /// The message as a catalog word, keyed by its id with the English text as the fallback: the app's `Words` + /// resolve it (`words.get(text.word())`) and fill its placeholders with `WordTemplate`. + pub const fn word(&self) -> Word { + Word::keyed(self.id, self.english) + } } /// Every message the library's services word with a [`PlatformText`] (the services this build diff --git a/crates/platform/src/message_tests.rs b/crates/platform/src/message_tests.rs index 1190b17c0f..8a383b70eb 100644 --- a/crates/platform/src/message_tests.rs +++ b/crates/platform/src/message_tests.rs @@ -26,3 +26,16 @@ fn every_message_is_in_the_registry_once() { } assert!(all.len() >= 15); } + +// A clipboard failure is worded in the app's language: the catalog row of a message's id reaches its text, and +// without a row the English stays. +#[test] +fn a_message_is_translated_by_its_id_and_reads_english_without_a_row() { + use craft_i18n::{WordRows, Words}; + for text in texts() { + let translated = format!("{} (translated)", text.english); + let words = Words::english().overlay(&WordRows::new().row(text.word(), translated.clone())); + assert_eq!(words.get(text.word()), translated, "{}", text.id); + assert_eq!(Words::english().get(text.word()), text.english, "{}", text.id); + } +} diff --git a/crates/platform/src/open.rs b/crates/platform/src/open.rs index 18426c5928..5ab96285af 100644 --- a/crates/platform/src/open.rs +++ b/crates/platform/src/open.rs @@ -72,6 +72,20 @@ pub enum Intake { }, /// The OS asked the app to quit. Quit, + /// The OS asked to open these absolute paths for the app's own action. + OpenFor { + /// The files, absolute and sorted. + paths: Vec, + /// The app's action name. + action: String, + }, + /// A file that arrived as bytes, with no path. + Bytes { + /// The file's name. + name: String, + /// The contents. + bytes: Arc<[u8]>, + }, } /// The sending side of a [`FileIntake`]: `Send + Clone`, for the threads that hear the OS (the @@ -136,9 +150,29 @@ impl IntakeSender { if paths.is_empty() { return; } - let mut paths: Vec = paths.iter().map(|p| absolute(p)).collect(); - paths.sort_by(|a, b| natural_cmp(&a.to_string_lossy(), &b.to_string_lossy())); - push(&self.queue, Intake::Open(paths)); + self.send(Intake::Open(ordered(paths))); + } + + /// Queues an open request for the app's own `action`, made absolute and sorted as [`open`](Self::open) does, and + /// wakes the UI. Empty input is ignored. + pub fn open_for(&self, paths: Vec, action: impl Into) { + if paths.is_empty() { + return; + } + self.send(Intake::OpenFor { paths: ordered(paths), action: action.into() }); + } + + /// Queues a file that arrived as bytes, and wakes the UI. A file with neither a name nor bytes is ignored. + pub fn open_bytes(&self, name: String, bytes: Arc<[u8]>) { + if name.is_empty() && bytes.is_empty() { + return; + } + self.send(Intake::Bytes { name, bytes }); + } + + /// Queues `batch` after every batch sent before it, then wakes the UI. + fn send(&self, batch: Intake) { + push(&self.queue, batch); self.wake.wake(); } @@ -158,13 +192,20 @@ impl IntakeSender { } } +/// `paths` made absolute and sorted by [`natural_cmp`] of the path text, the order an OS open request opens in. +fn ordered(paths: Vec) -> Vec { + let mut paths: Vec = paths.iter().map(|p| absolute(p)).collect(); + paths.sort_by(|a, b| natural_cmp(&a.to_string_lossy(), &b.to_string_lossy())); + paths +} + /// OS requests waiting for the app (files to open, files dropped, quit), read once per frame on /// the UI thread (spec Q-S4F-7). /// /// The app makes one at startup, gives [`sender`](Self::sender) to whatever hears the OS /// (`apple_events::install` on macOS, its single-instance socket elsewhere), pushes drops /// through a sender's [`dropped`](IntakeSender::dropped), and takes the requests with -/// [`take`](Self::take). An [`Intake::Open`] batch comes made absolute and sorted by +/// [`take`](Self::take). An [`Intake::Open`] or [`Intake::OpenFor`] batch comes made absolute and sorted by /// [`natural_cmp`] of the path text; the app focuses documents already open ([`same_file`]) and /// opens the rest, then brings its window to the front (on Wayland, a user-attention request). /// [`Intake::Quit`] closes the app the way its own Quit command does. @@ -268,9 +309,13 @@ pub const CAN_OPEN_WITH: bool = cfg!(not(target_arch = "wasm32")); /// Shows `path` selected in the system file manager: `open -R` on macOS, Explorer's /// `/select,""` on Windows (raw arguments; a path containing `"` is refused), and on Linux -/// and FreeBSD the FileManager1 D-Bus call through `dbus-send` on a thread of its own, falling back -/// to `xdg-open` on the folder. The path is made absolute first (so a name starting with `-` is -/// never an option); a path that no longer exists is [`FILE_GONE`]. Not on wasm. +/// and FreeBSD the FileManager1 D-Bus call through `dbus-send`, falling back to `xdg-open` on the +/// folder. The path is made absolute first (so a name starting with `-` is never an option); a +/// path that no longer exists is [`FILE_GONE`]. Not on wasm. +/// +/// It runs on the caller's thread and returns the real result. On Linux and FreeBSD it can block +/// up to the D-Bus reply timeout (2 s) before the fallback runs, so call it from the host's +/// `Jobs`, never from the UI thread. // pdfcraft: crates/ui-egui/src/menus/tab_context.rs:51 reveal, :77 reveal_process, :92 reveal_via #[cfg(not(target_arch = "wasm32"))] pub fn reveal(path: &Path) -> Result<(), String> { @@ -279,20 +324,8 @@ pub fn reveal(path: &Path) -> Result<(), String> { if !path.try_exists().map_err(|e| e.to_string())? { return Err(FILE_GONE.english.into()); } - let platform = std::env::consts::OS; let run = |program: &str, args: &[OsString]| reveal_process(program, args).output().map(|o| o.status.success()).map_err(|e| e.to_string()); - if matches!(platform, "linux" | "freebsd") { - // `dbus-send --print-reply` waits up to 2 s for the file manager (then xdg-open may run), - // so it runs off the UI thread; a failure there has nobody to tell. - return std::thread::Builder::new() - .name("craft-reveal".into()) - .spawn(move || { - let _ = reveal_via(platform, &path, run); - }) - .map(|_| ()) - .map_err(|e| e.to_string()); - } - reveal_via(platform, &path, run) + reveal_via(std::env::consts::OS, &path, run) } /// The process that runs `program` with `args`. Windows: the arguments go on the command line as @@ -370,9 +403,21 @@ fn reveal_command(platform: &str, path: &Path) -> Result<(&'static str, Vec Result<(), String> { + let window = web_sys::window().ok_or("There is no browser window to open the link in")?; + // With `noopener` the browser hands back no window, so `None` is the usual success. + window + .open_with_url_and_target_and_features(target, "_blank", "noopener,noreferrer") + .map(|_| ()) + .map_err(|e| e.as_string().unwrap_or_else(|| format!("{e:?}"))) +} + /// Opens a file or an `http(s)` URL with the system's handler (`open`, `rundll32 -/// url.dll,FileProtocolHandler`, `xdg-open`), without waiting for it. Not on wasm (the browser -/// module opens URLs there). +/// url.dll,FileProtocolHandler`, `xdg-open`), without waiting for it. On wasm the browser +/// build's `open_external` opens the URL in a new tab instead. /// /// No shell sees the target: on Windows `cmd` would run the part of a link after a `&`, and on /// macOS and Linux a target that starts with `-` would be read as an option, so `--` precedes it. diff --git a/crates/platform/src/open_tests.rs b/crates/platform/src/open_tests.rs index e39c22ec81..244505d2ba 100644 --- a/crates/platform/src/open_tests.rs +++ b/crates/platform/src/open_tests.rs @@ -1,5 +1,55 @@ //! `craft_platform::open`. +// Requests heard on another thread (a second launch, an Apple Event) reach the UI once each, in +// the order they arrived, an open for an action never merged with a plain open, and each wakes +// the UI: a lost wake leaves a file unopened until the user moves the mouse. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn an_intake_delivers_each_batch_once_in_order_and_wakes() { + use crate::open::{FileIntake, Intake}; + use craft_host::Wake; + use std::path::PathBuf; + use std::sync::Arc; + use std::sync::atomic::{AtomicUsize, Ordering}; + + let wakes = Arc::new(AtomicUsize::new(0)); + let counter = Arc::clone(&wakes); + let (intake, sender) = FileIntake::new(Wake::new(move || { + counter.fetch_add(1, Ordering::SeqCst); + })); + let root = std::env::temp_dir(); + let (b, a10, a2, c, d) = (root.join("b.pdf"), root.join("a10.pdf"), root.join("a2.pdf"), root.join("c.pdf"), root.join("d.pdf")); + let bytes: Arc<[u8]> = Arc::from(&b"%PDF-1.7"[..]); + let sent = bytes.clone(); + let (open, open_for) = ((b.clone(), a10.clone(), a2.clone()), (c.clone(), d.clone())); + std::thread::spawn(move || { + sender.open(vec![open.0, open.1, open.2]); + sender.open_for(vec![open_for.0], "combine"); + sender.open_for(vec![open_for.1], "combine"); + sender.open_bytes("scan.pdf".into(), sent); + // Empty requests queue nothing and wake nobody. + sender.open(Vec::new()); + sender.open_for(Vec::new(), "combine"); + sender.open_bytes(String::new(), Arc::from(Vec::::new())); + }) + .join() + .unwrap(); + assert_eq!( + intake.take(), + vec![ + Intake::Open(vec![a2, a10, b]), + Intake::OpenFor { paths: vec![c], action: "combine".into() }, + Intake::OpenFor { paths: vec![d], action: "combine".into() }, + Intake::Bytes { name: "scan.pdf".into(), bytes }, + ] + ); + assert_eq!(wakes.load(Ordering::SeqCst), 4, "one wake per queued batch"); + assert!(intake.take().is_empty(), "each batch is delivered once"); + // A relative path is made absolute against the working directory, as for a plain open. + intake.sender().open_for(vec![PathBuf::from("rel.pdf")], "print"); + assert!(matches!(intake.take().as_slice(), [Intake::OpenFor { paths, .. }] if paths.len() == 1 && paths[0].is_absolute())); +} + // A source whose push calls the wake while holding its own borrow (the Apple-event inbox does) // must not be drained from the wake: the wake only repaints, and the next `take` collects it. #[test] diff --git a/crates/platform/src/owner_only.rs b/crates/platform/src/owner_only.rs new file mode 100644 index 0000000000..506907e031 --- /dev/null +++ b/crates/platform/src/owner_only.rs @@ -0,0 +1,763 @@ +//! Owner-only files: a token file that only its user can read, as mode 0600 makes it on Unix. +//! +//! On Windows a file created in a folder inherits the folder's access list, and folders such as +//! a new folder at a drive root, `C:\Users\Public` or `C:\ProgramData` let every signed-in user +//! read what is created in them. [`restrict_to_owner`] replaces the whole list with the current +//! user and SYSTEM only, makes that user the owner, and checks the result. [`create_private_dir`] +//! does the same for a new folder whose list the files created in it inherit, so a file can be +//! private from the moment it exists. [`read_with_sddl`] reads a file and its security descriptor +//! through one handle. [`foreign_access`] reads the descriptor in SDDL form, which names accounts +//! by SID and so reads the same in every Windows language, and says why another user could have +//! written or could read the file. They run the tools Windows ships rather than calling the +//! security API directly, which would need `unsafe`. + +/// Why the file whose security descriptor is `sddl` (`O:` owner and `D:` access list, in SDDL or +/// as [`read_with_sddl`] writes it) can't be trusted as user `me`'s own: it is owned by someone else, it has no +/// access list (everyone may use it), or it lets an account other than `me` or SYSTEM use it. +/// Accounts are compared by SID; `None` means it is `me`'s alone. +/// +/// Stricter than OpenSSH's rule for private keys, which also lets Administrators in: an entry for +/// the Administrators group would let another administrator read the token without taking the +/// file over. [`restrict_to_owner`] never grants it, so the app's own file always passes; a file +/// that inherited it from a user's folder is refused. +pub fn foreign_access(sddl: &str, me: &str) -> Option { + let me = me.trim(); + let owner = section(sddl, "O:"); + match owner { + Some(o) if same_account(o, me) => {} + Some(o) => return Some(format!("it is owned by {}", another_account(o, ""))), + None => return Some("its owner can't be read".into()), + } + let Some(dacl) = section(sddl, "D:") else { + return Some("it has no access list, so every user may read it".into()); + }; + if dacl.starts_with("NO_ACCESS_CONTROL") { + return Some("it has no access control, so every user may read it".into()); + } + for ace in dacl.split('(').skip(1) { + let ace = ace.split(')').next().unwrap_or_default(); + let parts: Vec<&str> = ace.split(';').collect(); + // `type;flags;rights;object guid;inherited object guid;account SID[;(condition)]`. + let (Some(kind), Some(flags)) = (parts.first(), parts.get(1)) else { continue }; + // Deny entries take access away, and inherit-only entries apply to children, not the file. + let allows = matches!(*kind, "A" | "OA" | "XA" | "ZA"); + if !allows || flags.contains("IO") { + continue; + } + // An entry that grants access but names no account can't be shown to be the user's. + let Some(sid) = parts.get(5).filter(|s| !s.is_empty()) else { + return Some(format!("its access list has an entry that can't be read ({ace})")); + }; + if !(same_account(sid, me) || matches!(*sid, "SY" | "S-1-5-18" | "OW" | "S-1-3-4")) { + return Some(another_account(sid, "has access to it")); + } + } + None +} + +/// `another account () `, with the account's name before its SID when it is one of the +/// well-known accounts a token file can carry, such as `another account, Administrators +/// (S-1-5-32-544), has access to it`. The SID stays, so the message reads the same in every +/// Windows language and can still be looked up. +fn another_account(sid: &str, rest: &str) -> String { + match (well_known_name(sid), rest.is_empty()) { + (Some(name), true) => format!("another account, {name} ({sid})"), + (Some(name), false) => format!("another account, {name} ({sid}), {rest}"), + (None, true) => format!("another account ({sid})"), + (None, false) => format!("another account ({sid}) {rest}"), + } +} + +/// The English name Windows gives a well-known SID that can be on a file's access list or own it: +/// those a folder hands down at a drive root, in `C:\Users\Public` and in a user's profile, and +/// Everyone. The SIDs and names are Microsoft's public list of well-known SIDs +/// (); the names are +/// the ones `icacls` shows, without the `BUILTIN\` or `NT AUTHORITY\` prefix. Any other SID, +/// a user's or a domain group's, has no fixed name and gets `None`. +fn well_known_name(sid: &str) -> Option<&'static str> { + const NAMES: [(&str, &str); 8] = [ + ("S-1-1-0", "Everyone"), + ("S-1-5-3", "BATCH"), + ("S-1-5-4", "INTERACTIVE"), + ("S-1-5-6", "SERVICE"), + ("S-1-5-11", "Authenticated Users"), + ("S-1-5-18", "SYSTEM"), + ("S-1-5-32-544", "Administrators"), + ("S-1-5-32-545", "Users"), + ]; + NAMES.iter().find(|(known, _)| known.eq_ignore_ascii_case(sid)).map(|&(_, name)| name) +} + +/// `section(sddl, "O:")` is the owner, `"D:"` the access list: the text after the tag up to the +/// next top-level tag. +fn section<'a>(sddl: &'a str, tag: &str) -> Option<&'a str> { + let start = sddl.find(tag)?.checked_add(tag.len())?; + let rest = sddl.get(start..)?; + // The owner and group are bare SIDs; the access lists run until the next `X:` tag outside + // parentheses. + let mut depth = 0usize; + let mut end = rest.len(); + for (i, c) in rest.char_indices() { + match c { + '(' => depth = depth.saturating_add(1), + ')' => depth = depth.saturating_sub(1), + ':' if depth == 0 && i > 0 => { + // The tag is the one letter before this colon. + end = rest.get(..i).and_then(|s| s.char_indices().last()).map_or(i, |(j, _)| j); + break; + } + _ => {} + } + } + rest.get(..end).map(str::trim) +} + +/// Whether account `a` names user SID `me`. `OW` (owner rights) and `CO` are not users. An alias +/// is never taken for the user: [`read_with_sddl`] gives every account as a full SID, because +/// Windows' own SDDL writes some users by alias (the built-in Administrator as `LA`, whose SID +/// depends on the machine). +fn same_account(a: &str, me: &str) -> bool { + a.eq_ignore_ascii_case(me) +} + +/// The tools Windows ships that these checks run, by their path under `%SystemRoot%\System32`. +#[cfg(windows)] +const WHOAMI: &str = "whoami.exe"; +#[cfg(windows)] +const POWERSHELL: &str = r"WindowsPowerShell\v1.0\powershell.exe"; +#[cfg(windows)] +const ICACLS: &str = "icacls.exe"; + +/// A tool Windows ships, started by its full path. Started by bare name, a `whoami.exe`, +/// `powershell.exe` or `icacls.exe` found first (next to the app, or earlier on the search path) +/// would answer instead, and `whoami`'s answer is what every check here trusts. +/// +/// Each tool is a console program and the app is not, so without `CREATE_NO_WINDOW` Windows gives +/// every one of them a console window of its own, which flashes up while the app writes its +/// token file. The flag doesn't touch the pipes `output()` reads the answer through. +#[cfg(windows)] +fn system_tool(relative: &str) -> std::process::Command { + use std::os::windows::process::CommandExt as _; + /// `CREATE_NO_WINDOW`, from the Windows process creation flags. + const CREATE_NO_WINDOW: u32 = 0x0800_0000; + let root = std::env::var_os("SystemRoot").map_or_else(|| std::path::PathBuf::from(r"C:\Windows"), std::path::PathBuf::from); + let mut command = std::process::Command::new(root.join("System32").join(relative)); + command.creation_flags(CREATE_NO_WINDOW); + command +} + +/// The current user's SID (`whoami /user`). It starts a process, so a caller that needs it for +/// several steps reads it once and passes it to each. +#[cfg(windows)] +pub fn current_user_sid() -> std::io::Result { + let out = system_tool(WHOAMI).args(["/user", "/fo", "csv", "/nh"]).output()?; + if !out.status.success() { + return Err(std::io::Error::other("whoami /user failed")); + } + sid_from_whoami(&String::from_utf8_lossy(&out.stdout)).ok_or_else(|| std::io::Error::other("whoami /user printed no SID")) +} + +#[cfg(any(test, windows))] +/// The SID in `whoami /user /fo csv /nh` output, `"DOMAIN\user","S-1-5-21-…"`: the last quoted +/// field, when it is one. Anything else (an error message, nothing) gives `None`. +fn sid_from_whoami(text: &str) -> Option { + let last = text.trim().rsplit(',').next()?.trim().trim_matches('"'); + let digits = last.strip_prefix("S-1-")?; + // Every part after `S-1-` is a number; an empty remainder is one empty part, so it fails too. + digits.split('-').all(|part| !part.is_empty() && part.bytes().all(|b| b.is_ascii_digit())).then(|| last.to_string()) +} + +/// Replace `path`'s access list with one that only user `me` (the current user's SID, from +/// [`current_user_sid`], which the caller reads once for every step) and SYSTEM are on, then make +/// that user its owner (`icacls /setowner`), then read the file's descriptor back and check it with +/// [`foreign_access`]. The whole list is replaced, not just what was inherited: on the +/// windows-latest runner a new file in the temp folder carries an Administrators entry that `icacls +/// /inheritance:r` leaves in place. The owner is set because a file an elevated administrator creates +/// is owned by the Administrators group, not by the user. The list comes first: its owner may always +/// replace it, while setting the owner needs the Full control it grants (a folder may give Modify). +#[cfg(windows)] +pub fn restrict_to_owner(path: &std::path::Path, me: &str) -> std::io::Result<()> { + set_access_list(path, me, Kind::File)?; + icacls(path, &["/setowner".into(), format!("*{me}")])?; + still_foreign(&sddl_of(path)?, me) +} + +/// Create the folder `dir`, which must not exist yet, and give it an access list of user `me` (as +/// for [`restrict_to_owner`]) and SYSTEM only, which every file created in it inherits; then make +/// that user its owner and check the result as [`restrict_to_owner`] does. A file created in it is +/// private from the moment it exists. Restricting a file after creating it leaves a window in which another user +/// whom the parent folder lets read it can open a handle, and Windows checks access only when a +/// handle is opened, so a later change of the list doesn't revoke it. A handle on the folder +/// itself, opened during the folder's own window, gives no access to the files created in it +/// later. The folder is removed again when it can't be restricted. +#[cfg(windows)] +pub fn create_private_dir(dir: &std::path::Path, me: &str) -> std::io::Result<()> { + std::fs::create_dir(dir)?; + fn restrict(dir: &std::path::Path, me: &str) -> std::io::Result<()> { + set_access_list(dir, me, Kind::Folder)?; + icacls(dir, &["/setowner".into(), format!("*{me}")])?; + still_foreign(&sddl_of(dir)?, me) + } + let restricted = restrict(dir, me); + if restricted.is_err() { + let _ = std::fs::remove_dir(dir); + } + restricted +} + +/// `Err` naming the problem when the descriptor read back after restricting still isn't `me`'s +/// alone, so a file that only looks restricted is never used as one. +#[cfg(any(test, windows))] +fn still_foreign(sddl: &str, me: &str) -> std::io::Result<()> { + match foreign_access(sddl, me) { + None => Ok(()), + Some(problem) => Err(std::io::Error::other(format!("the file could not be restricted to its owner: {problem}"))), + } +} + +/// What [`set_access_list`] restricts: a file, or a folder whose entries the files and folders +/// created in it inherit. +#[cfg(windows)] +#[derive(Clone, Copy)] +enum Kind { + File, + Folder, +} + +/// Set `path`'s access list to Full control for `me` and SYSTEM and nothing else, protected from +/// inheritance; on a folder, what is created in it inherits the two entries. Only the list is +/// written, not the owner. `me` and the path reach PowerShell through environment variables, never +/// as script text. +#[cfg(windows)] +fn set_access_list(path: &std::path::Path, me: &str, kind: Kind) -> std::io::Result<()> { + // No double quotes: the command line would strip them. + const FILE: &str = "$s = New-Object Security.AccessControl.FileSecurity; \ + $s.SetSecurityDescriptorSddlForm('D:P(A;;FA;;;' + $env:CRAFT_ACL_USER + ')(A;;FA;;;SY)', 'Access'); \ + [IO.File]::SetAccessControl($env:CRAFT_ACL_PATH, $s)"; + const FOLDER: &str = "$s = New-Object Security.AccessControl.DirectorySecurity; \ + $s.SetSecurityDescriptorSddlForm('D:P(A;OICI;FA;;;' + $env:CRAFT_ACL_USER + ')(A;OICI;FA;;;SY)', 'Access'); \ + [IO.Directory]::SetAccessControl($env:CRAFT_ACL_PATH, $s)"; + let script = match kind { + Kind::File => FILE, + Kind::Folder => FOLDER, + }; + let out = system_tool(POWERSHELL) + .args(["-NoProfile", "-NonInteractive", "-Command", script]) + .env("CRAFT_ACL_PATH", path) + .env("CRAFT_ACL_USER", me) + .output()?; + if out.status.success() { + Ok(()) + } else { + Err(std::io::Error::other(format!("PowerShell could not restrict the file to its owner: {}", String::from_utf8_lossy(&out.stderr).trim()))) + } +} + +#[cfg(windows)] +fn icacls(path: &std::path::Path, args: &[String]) -> std::io::Result<()> { + let out = system_tool(ICACLS).arg(path).args(args).output()?; + if out.status.success() { + Ok(()) + } else { + Err(std::io::Error::other(format!("icacls could not restrict the file to its owner: {}", String::from_utf8_lossy(&out.stderr).trim()))) + } +} + +/// PowerShell that turns `$raw`, a `RawSecurityDescriptor`, into `$sddl` as [`read_with_sddl`] +/// describes it. No double quotes: the command line would strip them. An entry with no account (a +/// custom entry) is written with none, and `foreign_access` refuses it. +#[cfg(windows)] +macro_rules! describe_raw { + () => { + "$sddl = 'O:' + $raw.Owner.Value; if ($raw.DiscretionaryAcl -ne $null) { $sddl += 'D:'; foreach ($a in $raw.DiscretionaryAcl) { $t = 'A'; if ([string]$a.AceType -like 'AccessDenied*') { $t = 'D' }; $f = ''; if ($a.AceFlags.HasFlag([Security.AccessControl.AceFlags]::InheritOnly)) { $f = 'IO' }; $sid = ''; if ($a.SecurityIdentifier) { $sid = $a.SecurityIdentifier.Value }; $sddl += '(' + $t + ';' + $f + ';' + $a.AccessMask + ';;;' + $sid + ')' } }; " + }; +} + +/// Open `path` shared for reading only, so that while it is open it can't be replaced, renamed or +/// written, and read through that one handle both its security descriptor (owner and access list) +/// and its first `max + 1` bytes. The descriptor checked is the one of the handle the bytes come +/// from, so there is no moment at which the path could name a different file (a time-of-check to +/// time-of-use race). The path reaches PowerShell through an environment variable, never as script +/// text. +/// +/// The descriptor is written in SDDL's shape but with every account as a full SID, read from the +/// binary descriptor (`RawSecurityDescriptor`): `O:D:(;;;;;)…`, +/// where the type is `D` for a deny entry and `A` for any other, and the flags are `IO` for an +/// inherit-only entry. Windows' own SDDL writes some accounts by alias, and the built-in +/// Administrator's alias `LA` stands for a SID that depends on the machine. +#[cfg(windows)] +pub fn read_with_sddl(path: &std::path::Path, max: u64) -> std::io::Result<(String, Vec)> { + const SCRIPT: &str = concat!( + "$fs = [IO.File]::Open($env:CRAFT_ACL_PATH, 'Open', 'Read', 'Read'); try { $raw = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList @($fs.GetAccessControl().GetSecurityDescriptorBinaryForm(), 0); ", + describe_raw!(), + "$max = [int]$env:CRAFT_ACL_MAX + 1; $buf = New-Object byte[] $max; $total = 0; while ($total -lt $max) { $n = $fs.Read($buf, $total, $max - $total); if ($n -le 0) { break }; $total += $n }; [Console]::Out.Write($sddl + [char]10 + [BitConverter]::ToString($buf, 0, $total)) } finally { $fs.Dispose() }" + ); + // Bounded so the script's `[int]` and buffer stay small; a token file is far below this. + let max = max.min(1 << 20); + let out = system_tool(POWERSHELL) + .args(["-NoProfile", "-NonInteractive", "-Command", SCRIPT]) + .env("CRAFT_ACL_PATH", path) + .env("CRAFT_ACL_MAX", max.to_string()) + .output()?; + let read = if out.status.success() { sddl_and_bytes(&String::from_utf8_lossy(&out.stdout)) } else { None }; + read.ok_or_else(|| std::io::Error::other("PowerShell could not read the file with its owner and access list")) +} + +/// The security descriptor of `path` as [`read_with_sddl`] writes it, read by name without opening +/// the file's contents, so it works on a file that is open for writing (an app restricts its +/// token file before writing the token through the handle it created). +#[cfg(windows)] +pub fn sddl_of(path: &std::path::Path) -> std::io::Result { + const SCRIPT: &str = concat!( + // Stop: a failed read (a missing file) must end the script with an error, not print `O:`. + "$ErrorActionPreference = 'Stop'; $raw = New-Object Security.AccessControl.RawSecurityDescriptor -ArgumentList @([IO.File]::GetAccessControl($env:CRAFT_ACL_PATH).GetSecurityDescriptorBinaryForm(), 0); ", + describe_raw!(), + "[Console]::Out.Write($sddl + [char]10)" + ); + let out = system_tool(POWERSHELL).args(["-NoProfile", "-NonInteractive", "-Command", SCRIPT]).env("CRAFT_ACL_PATH", path).output()?; + let read = if out.status.success() { sddl_and_bytes(&String::from_utf8_lossy(&out.stdout)) } else { None }; + read.map(|(sddl, _)| sddl).ok_or_else(|| std::io::Error::other("PowerShell could not read the file's owner and access list")) +} + +/// [`read_with_sddl`]'s output: the SDDL, a newline, then the bytes as `[BitConverter]::ToString` +/// prints them (`7B-22-…`, empty for none). Anything else gives `None`. +#[cfg(any(test, windows))] +fn sddl_and_bytes(text: &str) -> Option<(String, Vec)> { + let (sddl, hex) = text.split_once('\n')?; + let sddl = sddl.trim(); + if !sddl.contains("O:") { + return None; + } + let hex = hex.trim(); + if hex.is_empty() { + return Some((sddl.to_string(), Vec::new())); + } + // Two hex digits each; `from_str_radix` alone would also take a sign, as in `+7`. + let byte = |pair: &str| (pair.len() == 2 && pair.bytes().all(|b| b.is_ascii_hexdigit())).then(|| u8::from_str_radix(pair, 16).ok()).flatten(); + let bytes = hex.split('-').map(byte).collect::>>()?; + Some((sddl.to_string(), bytes)) +} + +#[cfg(test)] +mod tests { + use super::*; + + const ME: &str = "S-1-5-21-1-2-3-1001"; + + /// The SID of the user running the tests, as a caller reads it once and passes on. + #[cfg(windows)] + fn user() -> String { + current_user_sid().unwrap() + } + + #[test] + fn the_users_own_file_with_system_is_trusted_and_administrators_are_not() { + assert_eq!(foreign_access(&format!("O:{ME}G:{ME}D:P(A;;FA;;;{ME})(A;;FA;;;SY)"), ME), None); + assert_eq!(foreign_access(&format!("O:{ME}D:(A;;2032127;;;S-1-5-18)(A;;2032127;;;{ME})"), ME), None); + // Another administrator could read it through the Administrators group, by alias or by SID. + for admins in ["BA", "S-1-5-32-544"] { + let sddl = format!("O:{ME}D:PAI(A;;FA;;;SY)(A;;FR;;;{admins})(A;;FA;;;{ME})"); + assert!(foreign_access(&sddl, ME).is_some_and(|p| p.contains(admins)), "{sddl}"); + } + // Inherit-only entries and deny entries don't grant access to the file itself. + assert_eq!(foreign_access(&format!("O:{ME}D:(A;OICIIO;GA;;;CO)(D;;FA;;;BU)(A;;FA;;;{ME})"), ME), None); + } + + /// Each tool is started by its full path in System32, never looked up by name. + #[cfg(windows)] + #[test] + fn the_tools_are_started_from_system32() { + for tool in [WHOAMI, POWERSHELL, ICACLS] { + let command = system_tool(tool); + let path = std::path::Path::new(command.get_program()); + assert!(path.is_absolute() && path.is_file(), "{path:?}"); + assert!(path.to_string_lossy().to_ascii_lowercase().contains(r"\system32\"), "{path:?}"); + } + } + + /// The tools start without a console window: the app has no console, so a tool that isn't + /// told otherwise gets a window of its own, which flashes up. The started PowerShell reports + /// its console's window and the processes attached to that console. Both are checked, because + /// a tool started without the flag by a process that has a console shares it instead, and that + /// console may itself have no window (a test run started by a service or an IDE). + #[cfg(windows)] + #[test] + fn the_tools_start_without_a_console_window() { + const PROBE: &str = r#"Add-Type -Namespace CraftProbe -Name Console -MemberDefinition '[DllImport("kernel32.dll")] public static extern System.IntPtr GetConsoleWindow(); [DllImport("kernel32.dll")] public static extern uint GetConsoleProcessList(uint[] ids, uint count);' +$ids = New-Object uint32[] 256 +$n = [CraftProbe.Console]::GetConsoleProcessList($ids, 256) +"$([CraftProbe.Console]::GetConsoleWindow()) $($ids[0..($n-1)] -join ',')""#; + let out = system_tool(POWERSHELL).args(["-NoProfile", "-NonInteractive", "-Command", PROBE]).output().unwrap(); + // The answer still comes back through the pipe. + let text = String::from_utf8_lossy(&out.stdout); + assert!(out.status.success(), "{text} {}", String::from_utf8_lossy(&out.stderr)); + let (window, attached) = text.trim().split_once(' ').unwrap(); + assert_eq!(window, "0", "the tool has a console window: {text}"); + let attached: Vec = attached.split(',').map(|id| id.parse().unwrap()).collect(); + assert!(!attached.is_empty() && !attached.contains(&std::process::id()), "the tool shares this process's console: {text}"); + } + + #[test] + fn other_owners_readers_and_missing_lists_are_refused() { + let other = "S-1-5-21-1-2-3-1002"; + assert!(foreign_access(&format!("O:{other}D:(A;;FA;;;{ME})"), ME).unwrap().contains("owned by another account")); + // Users (BU) and Authenticated Users (AU), as a folder at a drive root passes on. + assert!(foreign_access(&format!("O:{ME}D:AI(A;ID;FA;;;{ME})(A;ID;0x1301bf;;;AU)"), ME).unwrap().contains("AU")); + assert!(foreign_access(&format!("O:{ME}D:(A;;FR;;;BU)(A;;FA;;;{ME})"), ME).unwrap().contains("BU")); + assert!(foreign_access(&format!("O:{ME}D:(A;;FA;;;{other})"), ME).is_some()); + assert!(foreign_access(&format!("O:{ME}G:SY"), ME).unwrap().contains("no access list")); + assert!(foreign_access(&format!("O:{ME}D:NO_ACCESS_CONTROL"), ME).is_some()); + assert!(foreign_access("D:(A;;FA;;;SY)", ME).unwrap().contains("owner")); + } + + /// A conditional entry can hold a `:` in a string; the access list doesn't end there, so the + /// entry after it is still checked. + #[test] + fn a_colon_inside_an_entry_does_not_end_the_access_list() { + let sddl = format!(r#"O:{ME}D:(XA;;FA;;;{ME};(@User.dept == "a:b"))(A;;FR;;;BU)"#); + assert!(foreign_access(&sddl, ME).is_some_and(|p| p.contains("BU")), "{sddl}"); + } + + /// A conditional entry for the user is the user's; one that grants access but whose account + /// can't be read is refused rather than skipped. + #[test] + fn conditional_and_malformed_entries() { + assert_eq!(foreign_access(&format!(r#"O:{ME}D:(XA;;FA;;;{ME};(@User.dept == "x"))"#), ME), None); + assert!(foreign_access(&format!("O:{ME}D:(A;;FA;;;{ME})(A;;FR)"), ME).is_some_and(|p| p.contains("can't be read"))); + assert!(foreign_access(&format!("O:{ME}D:(A;;FA;;;)"), ME).is_some_and(|p| p.contains("can't be read"))); + // A conditional entry grants access like a plain one: another account on it is refused. + let other = format!(r#"O:{ME}D:(A;;FA;;;{ME})(XA;;FR;;;BU;(@User.dept == "x"))"#); + assert!(foreign_access(&other, ME).is_some_and(|p| p.contains("BU")), "{other}"); + } + + #[test] + fn the_sid_is_read_from_whoamis_output_and_nothing_else() { + assert_eq!(sid_from_whoami("\"desk\\ada\",\"S-1-5-21-1-2-3-1001\"\r\n").as_deref(), Some("S-1-5-21-1-2-3-1001")); + for bad in [ + "", + "ERROR: Access is denied.", + "\"desk\\ada\",\"\"", + "\"desk\\ada\",\"S-1-\"", + "\"S-1-5-x\"", + "\"desk\\ada\"", + "\"desk\\ada\",\"1-5-21-7\"", + ] { + assert_eq!(sid_from_whoami(bad), None, "{bad:?}"); + } + } + + /// The real tools: a file created in a folder that lets Users read what's in it inherits that + /// access; after `restrict_to_owner` only the current user and SYSTEM are left. + #[cfg(windows)] + #[test] + fn a_file_in_a_shared_folder_is_restricted_to_its_owner() { + let dir = std::env::temp_dir().join(format!("craft-owner-only-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let ok = std::process::Command::new("icacls").arg(&dir).arg("/grant").arg("*S-1-5-32-545:(OI)(CI)R").output().unwrap(); + assert!(ok.status.success(), "{}", String::from_utf8_lossy(&ok.stderr)); + let file = dir.join("ctl.json"); + std::fs::write(&file, b"{}").unwrap(); + let me = current_user_sid().unwrap(); + // Users inherit read access, so the file is refused. (Run elevated, the file is also owned + // by Administrators, which is the reason given first.) + let before = sddl_of(&file).unwrap(); + assert!(before.contains(";BU)") || before.contains(";S-1-5-32-545)"), "Users inherit read access: {before}"); + assert!(foreign_access(&before, &me).is_some(), "{before}"); + restrict_to_owner(&file, &user()).unwrap(); + let sddl = sddl_of(&file).unwrap(); + assert_eq!(section(&sddl, "O:"), Some(me.as_str()), "{sddl}"); + assert_eq!(foreign_access(&sddl, &me), None, "{sddl}"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A file created in a private folder inside a folder that lets Users read what's in it is the + /// user's alone from the moment it exists, before anything restricts it. + #[cfg(windows)] + #[test] + fn a_file_created_in_a_private_folder_is_private_from_the_start() { + let dir = std::env::temp_dir().join(format!("craft-owner-only-private-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let ok = std::process::Command::new("icacls").arg(&dir).arg("/grant").arg("*S-1-5-32-545:(OI)(CI)R").output().unwrap(); + assert!(ok.status.success(), "{}", String::from_utf8_lossy(&ok.stderr)); + let private = dir.join("staging"); + create_private_dir(&private, &user()).unwrap(); + let me = current_user_sid().unwrap(); + let folder = sddl_of(&private).unwrap(); + assert_eq!((section(&folder, "O:"), foreign_access(&folder, &me)), (Some(me.as_str()), None), "{folder}"); + let file = private.join("ctl.json"); + std::fs::OpenOptions::new().write(true).create_new(true).open(&file).unwrap(); + let sddl = sddl_of(&file).unwrap(); + assert!(!sddl.contains(";BU)") && !sddl.contains(";S-1-5-32-545)"), "Users must not inherit read access: {sddl}"); + assert_eq!(foreign_access(&sddl, &me), None, "{sddl}"); + // The name is taken: the folder isn't reused. + assert!(create_private_dir(&private, &user()).is_err()); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A folder may give its user Modify but not Full control, so a file created there doesn't let + /// its owner change the owner (no `WRITE_OWNER`). An owner can always replace the access list, + /// though, and the user's Full control on it then allows setting the owner. + #[cfg(windows)] + #[test] + fn a_file_in_a_folder_granting_only_modify_is_still_restricted() { + let dir = std::env::temp_dir().join(format!("craft-owner-only-modify-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let me = current_user_sid().unwrap(); + let modify = std::process::Command::new("icacls") + .arg(&dir) + .args(["/inheritance:r", "/grant:r"]) + .arg(format!("*{me}:(OI)(CI)M")) + .arg("*S-1-5-18:(OI)(CI)F") + .output() + .unwrap(); + assert!(modify.status.success(), "{}", String::from_utf8_lossy(&modify.stderr)); + let file = dir.join("ctl.json"); + std::fs::write(&file, b"{}").unwrap(); + restrict_to_owner(&file, &user()).unwrap(); + let sddl = sddl_of(&file).unwrap(); + assert_eq!((section(&sddl, "O:"), foreign_access(&sddl, &me)), (Some(me.as_str()), None), "{sddl}"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// A null access list (`NO_ACCESS_CONTROL`) lets every account use the file, so it is refused. + #[cfg(windows)] + #[test] + fn a_file_with_no_access_list_is_refused() { + let dir = std::env::temp_dir().join(format!("craft-owner-only-null-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("ctl.json"); + std::fs::write(&file, b"{}").unwrap(); + restrict_to_owner(&file, &user()).unwrap(); + // A null access list lets everyone in; the user, as owner, may set one. + let null = std::process::Command::new("powershell") + .args([ + "-NoProfile", + "-NonInteractive", + "-Command", + "$s = New-Object Security.AccessControl.FileSecurity; $s.SetSecurityDescriptorSddlForm('D:NO_ACCESS_CONTROL', 'Access'); [IO.File]::SetAccessControl($env:CRAFT_NULL_PATH, $s)", + ]) + .env("CRAFT_NULL_PATH", &file) + .output() + .unwrap(); + assert!(null.status.success(), "{}", String::from_utf8_lossy(&null.stderr)); + let (sddl, _) = read_with_sddl(&file, 64).unwrap(); + let me = current_user_sid().unwrap(); + assert!(foreign_access(&sddl, &me).is_some_and(|p| p.contains("no access list")), "{sddl}"); + let _ = std::fs::remove_dir_all(&dir); + } + + /// An `OWNER RIGHTS` entry replaces what an owner may do implicitly. Granting only *write + /// owner* that way, the access list can't be replaced although the owner can still be set: the + /// file isn't taken as restricted. Run elevated, it can be replaced, and then must be restricted. + #[cfg(windows)] + #[test] + fn a_file_whose_access_list_cant_be_replaced_is_not_restricted() { + let dir = std::env::temp_dir().join(format!("craft-owner-only-ow-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let me = current_user_sid().unwrap(); + let file = dir.join("ctl.json"); + std::fs::write(&file, b"{}").unwrap(); + // The whole list is written, as `restrict_to_owner` does: `icacls /inheritance:r` leaves + // the Administrators entry the windows-latest runner gives a new file, and with it an + // elevated administrator could replace the list after all. + let rights = std::process::Command::new("powershell") + .args([ + "-NoProfile", + "-NonInteractive", + "-Command", + "$s = New-Object Security.AccessControl.FileSecurity; $s.SetSecurityDescriptorSddlForm('D:P(A;;FR;;;' + $env:CRAFT_OW_USER + ')(A;;WO;;;OW)', 'Access'); [IO.File]::SetAccessControl($env:CRAFT_OW_PATH, $s)", + ]) + .env("CRAFT_OW_PATH", &file) + .env("CRAFT_OW_USER", &me) + .output() + .unwrap(); + assert!(rights.status.success(), "{}", String::from_utf8_lossy(&rights.stderr)); + // Nothing but the two entries: no Administrators entry for the elevated runner to use. + let sddl = sddl_of(&file).unwrap(); + assert_eq!(section(&sddl, "D:"), Some(format!("(A;;524288;;;S-1-3-4)(A;;1179785;;;{me})").as_str()), "{sddl}"); + // An elevated administrator (the windows-latest runner) may replace the list anyway; then the + // file must really be the user's alone, since the result is checked before it is trusted. + if restrict_to_owner(&file, &user()).is_ok() { + let after = sddl_of(&file).unwrap(); + assert!(elevated(), "the access list could not be replaced: {after}"); + assert_eq!(foreign_access(&after, &me), None, "{after}"); + } + let _ = std::fs::remove_dir_all(&dir); + } + + /// Whether the tests run elevated: `whoami /groups` lists the high (or system) mandatory label. + #[cfg(windows)] + fn elevated() -> bool { + let out = system_tool(WHOAMI).args(["/groups", "/fo", "csv", "/nh"]).output().unwrap(); + let text = String::from_utf8_lossy(&out.stdout); + text.contains("\"S-1-16-12288\"") || text.contains("\"S-1-16-16384\"") + } + + /// When the tools fail, the functions say so: nothing is taken as restricted or as checked. + #[cfg(windows)] + #[test] + fn tool_failures_are_errors() { + let missing = std::env::temp_dir().join(format!("craft-owner-only-missing-{}", std::process::id())).join("none.json"); + assert!(restrict_to_owner(&missing, &user()).is_err(), "icacls on a missing file"); + assert!(sddl_of(&missing).is_err(), "Get-Acl on a missing file"); + let me = current_user_sid().unwrap(); + assert!(me.starts_with("S-1-5-") && me.split('-').count() >= 4, "{me}"); + assert!(!me.contains('"') && !me.contains('\\'), "the SID alone, not the account name: {me}"); + } + + #[test] + fn the_descriptor_and_bytes_are_read_from_the_scripts_output_and_nothing_else() { + let sddl = format!("O:{ME}D:P(A;;FA;;;{ME})"); + assert_eq!(sddl_and_bytes(&format!("{sddl}\n7B-0A-ff\r\n")), Some((sddl.clone(), vec![0x7B, 0x0A, 0xFF]))); + assert_eq!(sddl_and_bytes(&format!("{sddl}\n")), Some((sddl.clone(), Vec::new()))); + for bad in [ + String::new(), + sddl.clone(), + "D:P(A;;FA;;;SY)\n7B".into(), + format!("{sddl}\n7B-2"), + format!("{sddl}\n7B--22"), + format!("{sddl}\n7G"), + format!("{sddl}\n+7-22"), + ] { + assert_eq!(sddl_and_bytes(&bad), None, "{bad:?}"); + } + } + + /// The bytes come with the descriptor of the same handle, capped at `max + 1` so an oversized + /// file shows, and the restricted file is owned by the user. + #[cfg(windows)] + #[test] + fn the_file_is_read_with_its_descriptor_through_one_handle() { + let dir = std::env::temp_dir().join(format!("craft-owner-only-read-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("ctl.json"); + std::fs::write(&file, br#"{"port":1}"#).unwrap(); + restrict_to_owner(&file, &user()).unwrap(); + let me = current_user_sid().unwrap(); + let (sddl, bytes) = read_with_sddl(&file, 64).unwrap(); + assert_eq!(section(&sddl, "O:"), Some(me.as_str()), "{sddl}"); + assert_eq!((foreign_access(&sddl, &me), bytes.as_slice()), (None, &br#"{"port":1}"#[..])); + assert_eq!(read_with_sddl(&file, 3).unwrap().1, br#"{"po"#); + // A limit past what the script's `[int]` holds is capped, not handed to it. + assert_eq!(read_with_sddl(&file, u64::MAX).unwrap().1, br#"{"port":1}"#); + assert!(read_with_sddl(&dir.join("none.json"), 64).is_err()); + // A deny entry is read as one: denying Guests takes nothing from the user. + let guests = std::process::Command::new("icacls").arg(&file).arg("/deny").arg("*S-1-5-32-546:(R)").output().unwrap(); + assert!(guests.status.success(), "{}", String::from_utf8_lossy(&guests.stderr)); + let (sddl, _) = read_with_sddl(&file, 64).unwrap(); + assert!(sddl.contains(";;;S-1-5-32-546)") && sddl.contains("(D;"), "{sddl}"); + assert_eq!(foreign_access(&sddl, &me), None, "{sddl}"); + // The handle shares the file for reading only: a file someone has open for writing (or + // could rename or delete) isn't read, and so can't change between the check and the read. + let writer = std::fs::OpenOptions::new().write(true).open(&file).unwrap(); + assert!(read_with_sddl(&file, 64).is_err(), "a file open for writing is not read"); + // Restricting reads the descriptor alone, so it works on the file an app holds open to + // write the token through. + restrict_to_owner(&file, &user()).unwrap(); + assert_eq!(foreign_access(&sddl_of(&file).unwrap(), &me), None); + drop(writer); + assert!(read_with_sddl(&file, 64).is_ok()); + let _ = std::fs::remove_dir_all(&dir); + } + + /// Entries of the file's own, not inherited, are replaced too: an Administrators or Users + /// entry (as the windows-latest runner's temp folder leaves on a new file) and a deny that + /// would keep the user from setting the owner. + #[cfg(windows)] + #[test] + fn entries_of_the_files_own_are_replaced() { + let dir = std::env::temp_dir().join(format!("craft-owner-only-own-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + let me = current_user_sid().unwrap(); + let mine = format!("*{me}:(R)"); + for (name, entries) in [ + ("others.json", ["/grant", "*S-1-5-32-544:(F)", "/grant", "*S-1-5-32-545:(R)"]), + ("deny.json", ["/deny", "*S-1-1-0:(WO)", "/grant", "*S-1-5-32-544:(F)"]), + ] { + let file = dir.join(name); + std::fs::write(&file, b"{}").unwrap(); + // The user keeps read access, so the descriptor can be read before restricting. + let own = std::process::Command::new("icacls").arg(&file).arg("/inheritance:r").args(entries).args(["/grant", &mine]).output().unwrap(); + assert!(own.status.success(), "{}", String::from_utf8_lossy(&own.stderr)); + assert!(foreign_access(&sddl_of(&file).unwrap(), &me).is_some(), "{name}"); + restrict_to_owner(&file, &user()).unwrap(); + let sddl = sddl_of(&file).unwrap(); + assert_eq!((section(&sddl, "O:"), foreign_access(&sddl, &me)), (Some(me.as_str()), None), "{name}: {sddl}"); + assert!(!sddl.contains("(D;"), "{name}: the deny is gone: {sddl}"); + } + let _ = std::fs::remove_dir_all(&dir); + } + + #[test] + fn a_descriptor_still_open_to_others_after_restricting_is_an_error() { + assert!(still_foreign(&format!("O:{ME}D:P(A;;FA;;;SY)(A;;FA;;;{ME})"), ME).is_ok()); + for bad in [format!("O:{ME}D:P(A;;FA;;;S-1-5-32-544)(A;;FA;;;{ME})"), format!("O:S-1-5-32-544D:P(A;;FA;;;{ME})"), format!("O:{ME}")] { + assert!(still_foreign(&bad, ME).is_err_and(|e| e.to_string().contains("could not be restricted")), "{bad}"); + } + } + + /// [`read_with_sddl`] gives accounts as full SIDs (rights as a number, no list flags), the way a + /// CI runner's built-in Administrator reads its own restricted file. An alias such as `LA` + /// is never taken for the user, whatever the user's RID: on a domain-joined machine a domain + /// account can share the local Administrator's RID 500. + #[test] + fn descriptors_with_full_sids_and_aliases_that_are_never_the_user() { + let admin = "S-1-5-21-1-2-3-500"; + let full = format!("O:{admin}D:(A;;2032127;;;S-1-5-18)(A;;2032127;;;{admin})"); + assert_eq!(foreign_access(&full, admin), None); + // Owner rights by SID, a deny by SID, an inherit-only entry for Creator Owner. + let more = format!("O:{ME}D:(D;;1179785;;;S-1-5-32-546)(A;IO;268435456;;;S-1-3-0)(A;;2032127;;;S-1-3-4)(A;;2032127;;;{ME})"); + assert_eq!(foreign_access(&more, ME), None); + assert!(foreign_access(&format!("O:{ME}D:(A;;1179785;;;S-1-5-32-545)(A;;2032127;;;{ME})"), ME).is_some_and(|p| p.contains("S-1-5-32-545"))); + for me in [admin, "S-1-5-21-1-2-3-501"] { + assert!(foreign_access("O:LAD:PAI(A;;FA;;;SY)(A;;FA;;;LA)", me).is_some_and(|p| p.contains("owned by another account (LA)")), "{me}"); + assert!(foreign_access("O:LGD:P(A;;FA;;;LG)", me).is_some(), "{me}"); + } + assert!(foreign_access(&format!("O:{admin}D:P(A;;FA;;;{admin})(A;;FR;;;LA)"), admin).is_some_and(|p| p.contains("LA"))); + } + + /// A refusal names a well-known account as well as giving its SID, so `S-1-5-32-544` reads as + /// Administrators without a lookup; any other SID is given alone. + #[test] + fn refusals_name_well_known_accounts_and_keep_their_sid() { + for (sid, name) in [ + ("S-1-5-32-544", "Administrators"), + ("S-1-5-32-545", "Users"), + ("S-1-5-11", "Authenticated Users"), + ("S-1-5-4", "INTERACTIVE"), + ("S-1-1-0", "Everyone"), + ("S-1-5-6", "SERVICE"), + ("S-1-5-3", "BATCH"), + ] { + let sddl = format!("O:{ME}D:PAI(A;;FA;;;{ME})(A;ID;1179817;;;{sid})"); + assert_eq!(foreign_access(&sddl, ME), Some(format!("another account, {name} ({sid}), has access to it")), "{sddl}"); + } + // SYSTEM may have access, but a file it owns isn't the user's. + assert_eq!(foreign_access(&format!("O:S-1-5-18D:P(A;;FA;;;{ME})"), ME).as_deref(), Some("it is owned by another account, SYSTEM (S-1-5-18)")); + assert_eq!( + foreign_access(&format!("O:S-1-5-32-544D:P(A;;FA;;;{ME})"), ME).as_deref(), + Some("it is owned by another account, Administrators (S-1-5-32-544)") + ); + // Another user, a lookalike and an alias have no fixed name: the account is given as it was. + for sid in ["S-1-5-21-1-2-3-1002", "S-1-5-32-5440", "S-1-5-1", "BA"] { + let sddl = format!("O:{ME}D:(A;;FA;;;{ME})(A;;FR;;;{sid})"); + assert_eq!(foreign_access(&sddl, ME), Some(format!("another account ({sid}) has access to it")), "{sddl}"); + } + assert_eq!( + foreign_access("O:S-1-5-21-1-2-3-1002D:(A;;FA;;;SY)", ME).as_deref(), + Some("it is owned by another account (S-1-5-21-1-2-3-1002)") + ); + } + + #[test] + fn sections_stop_at_the_next_tag() { + assert_eq!(section("O:S-1-5-18G:S-1-5-32-544D:(A;;FA;;;SY)", "O:"), Some("S-1-5-18")); + assert_eq!(section("O:BAG:SYD:P(A;;FA;;;SY)S:(AU;SA;FA;;;WD)", "D:"), Some("P(A;;FA;;;SY)")); + assert_eq!(section("O:BA", "D:"), None); + } +} diff --git a/crates/platform/src/session.rs b/crates/platform/src/session.rs index 6ef0f9a388..320f00b414 100644 --- a/crates/platform/src/session.rs +++ b/crates/platform/src/session.rs @@ -18,6 +18,9 @@ pub struct SessionDocument { pub window: Option, /// The app's view state for the document (PdfCraft's page, PhotoCraft's zoom and scroll), as /// the app wrote it; `Null` when it keeps none. + // TOML has no null: written as a null, the whole typed settings save would fail. Left out, it + // reads back as `Null` through `#[serde(default)]` and `from_json`. + #[serde(skip_serializing_if = "serde_json::Value::is_null")] pub view: serde_json::Value, } diff --git a/crates/platform/src/session_tests.rs b/crates/platform/src/session_tests.rs index 3e5ddc979b..31f7914723 100644 --- a/crates/platform/src/session_tests.rs +++ b/crates/platform/src/session_tests.rs @@ -19,3 +19,34 @@ fn quit_keeps_the_session_from_its_start() { keeper.quit_cancelled(); assert_eq!(keeper.to_save(true, one.clone()), one); } + +// The stored session is untrusted settings: entries without a usable path and non-text fields +// are skipped rather than failing the whole session, a missing view is `Null`, a huge list is +// cut at MAX_DOCUMENTS, and anything that isn't a session reads as none. +#[test] +fn malformed_entries_are_skipped_and_the_list_capped() { + let value = serde_json::json!({ + "documents": [{"path": 5}, {"path": ""}, "x", {"path": "/a.pdf", "window": 3}, {"path": "/b.pdf", "view": {"page": 7}}], + "active": 3, + }); + let session = Session::from_json(&value); + let read: Vec<(&str, Option<&str>, &serde_json::Value)> = + session.documents.iter().map(|d| (d.path.as_str(), d.window.as_deref(), &d.view)).collect(); + assert_eq!(read, [("/a.pdf", None, &serde_json::Value::Null), ("/b.pdf", None, &serde_json::json!({"page": 7}))]); + assert_eq!(session.active, None); + let many: Vec = (0..1000).map(|i| serde_json::json!({"path": format!("/{i}.pdf")})).collect(); + assert_eq!(Session::from_json(&serde_json::json!({"documents": many})).documents.len(), MAX_DOCUMENTS); + assert_eq!(Session::from_json(&serde_json::json!("garbage")), Session::default()); +} + +// TOML has no null, so a document without view state must not write one: the typed settings save +// would fail and lose the whole session. Left out, it reads back as `Null` both ways. +#[test] +fn a_null_view_is_left_out_and_reads_back_as_null() { + let session = Session { documents: vec![doc("/a.pdf"), SessionDocument { view: serde_json::json!({"page": 2}), ..doc("/b.pdf") }], active: None }; + let written = serde_json::to_value(&session).unwrap(); + assert_eq!(written["documents"][0].get("view"), None, "{written}"); + assert_eq!(written["documents"][1]["view"], serde_json::json!({"page": 2})); + assert_eq!(serde_json::from_value::(written.clone()).unwrap(), session); + assert_eq!(Session::from_json(&written), session); +} diff --git a/crates/platform/src/watch_tests.rs b/crates/platform/src/watch_tests.rs index 4cd8f60bf8..8624f45a6f 100644 --- a/crates/platform/src/watch_tests.rs +++ b/crates/platform/src/watch_tests.rs @@ -52,3 +52,30 @@ fn another_writer_is_a_change_and_an_own_save_is_not() { settle(&mut watch); assert!(watch.take_changes().is_empty()); } + +// A permission change (or a Finder tag, LaunchServices) moves only the Unix change time. With +// the bytes the app saved still on disk that is no edit, so Save doesn't ask about a change +// nobody made; different bytes, or none to compare, are still a difference. +#[cfg(unix)] +#[test] +fn a_stamp_that_differs_only_in_metadata_is_not_a_content_change() { + use std::os::unix::fs::PermissionsExt as _; + let dir = TempDir::new("craft-watch-test").unwrap(); + let path = file(&dir, "doc.txt", "saved"); + let mut watch = watcher(); + watch.known_now(1, &path); + let before = FileStamp::at(&path).unwrap(); + // Past the change time's resolution on every common file system. + std::thread::sleep(std::time::Duration::from_millis(20)); + let mode = std::fs::metadata(&path).unwrap().permissions().mode(); + std::fs::set_permissions(&path, std::fs::Permissions::from_mode(mode ^ 0o004)).unwrap(); + let after = FileStamp::at(&path).unwrap(); + assert!(after != before && after.metadata_only_change(before), "only the change time moved"); + + assert!(!watch.disk_differs(&1, &path, Some(b"saved"))); + assert!(watch.disk_differs(&1, &path, Some(b"other"))); + assert!(watch.disk_differs(&1, &path, None), "nothing to compare with"); + + std::fs::write(&path, "edits").unwrap(); + assert!(watch.disk_differs(&1, &path, Some(b"saved")), "a content edit"); +} diff --git a/crates/print/Cargo.toml b/crates/print/Cargo.toml index cfd44560cd..9b68122539 100644 --- a/crates/print/Cargo.toml +++ b/crates/print/Cargo.toml @@ -17,13 +17,15 @@ harness = false suite = ["screen-testing", "craft-ui/suite"] default = [] # The printer and job settings widgets (`craft_print::ui`). -ui = ["dep:craft-behavior", "dep:craft-ui", "dep:egui"] +ui = ["dep:craft-behavior", "dep:craft-theme", "dep:craft-ui", "dep:egui"] # The stories and the integration binary of the print panel. screen-testing = ["ui", "craft-ui/testing"] [dependencies] craft-behavior = { workspace = true, optional = true } craft-host = { workspace = true } +# `Tone` for the dialog's refusal notice; craft-ui does not re-export it. +craft-theme = { workspace = true, optional = true } craft-ui = { workspace = true, optional = true } serde = { workspace = true } serde_json = { workspace = true } diff --git a/crates/print/src/spool.rs b/crates/print/src/spool.rs index 6590ffc15f..1403f74479 100644 --- a/crates/print/src/spool.rs +++ b/crates/print/src/spool.rs @@ -95,7 +95,9 @@ impl Spool { #[cfg(feature = "ui")] pub fn discoverer(&self) -> crate::ui::Discover { let spool = self.clone(); - Box::new(move || spool.listed(|printer| crate::ui::Printer { name: printer.name, label: printer.description, default: printer.default })) + Box::new(move || { + spool.listed(|printer| crate::ui::Printer { name: printer.name, label: printer.description, default: printer.default, own_dialog: None }) + }) } /// Asks the backend for its printers in a job and sends them through `map`; a platform that diff --git a/crates/print/src/ui/dialog.rs b/crates/print/src/ui/dialog.rs index d4b3421336..3d4d7b0769 100644 --- a/crates/print/src/ui/dialog.rs +++ b/crates/print/src/ui/dialog.rs @@ -5,40 +5,46 @@ use std::sync::Arc; use std::sync::mpsc::Receiver; use craft_behavior::{CursorIcon, EditEvent, EditEvents, IconId, Metrics, Mixed, PartKey, PointerButton, PressPhase, Sense, Value, keyed}; -use craft_ui::buttons::IconButton; +use craft_theme::variant::Tone; +use craft_ui::buttons::{Button, IconButton}; use craft_ui::contract::{ - Access, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Input, MeasureCx, Name, NoValue, Outcome, PaintUi, PartsCx, Pointer as _, - Props as _, Remember as _, Role, Show as _, ShowContainer as _, Validity, WordSetCx as _, clicked, + Access, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Input, LabelScheme, MeasureCx, Name, NoValue, Outcome, PaintUi, PartsCx, + Pointer as _, Props as _, Remember as _, Role, Scroll, Show as _, ShowContainer as _, Validity, WordSetCx as _, clicked, }; use craft_ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, HeldAnswer, HeldOk, HoldsOk, StackDialog, dialog_id}; use craft_ui::display::{Shade, Text}; use craft_ui::form::Field; +use craft_ui::layout::RowAlign; use craft_ui::layout_components::{Row, Stack}; use craft_ui::list::ListRow; +use craft_ui::notices::{Notice, NoticeLayout}; use craft_ui::patterns::form_dialogs::{ - DialogFields, FieldValue, FormDialog, HostRequests, Param, ParamRows, SectionList, set_color_field, set_param_field, + DialogFields, FieldValue, FormDialog, HostRequests, PagerStep, PanePager, Param, ParamKind, ParamRows, SectionList, set_color_field, + set_param_field, }; use craft_ui::patterns::presets::{ NameCheck, NameRefuses, NamedPresetEvent, NamedPresetRow, Naming, PickerField, PresetError, PresetPicker, PresetRow, PresetSource, PresetState, PresetWords, }; +use craft_ui::primitives::{ContentPainterCx, TextRun, Wrap, fill_polygon}; use craft_ui::runtime::env::{Env, Label, Message}; use craft_ui::runtime::focus::{ActivateKeys, KeepKeys, KeyUse}; use craft_ui::runtime::overlay::CloseReason; use craft_ui::runtime::requests::HostAnswer; -use craft_ui::sections::{DialogRole, FooterButton, Section}; -use craft_ui::style::{ComponentStyle, Corners, RuleKind, StyleCx, SurfaceKind, TypeRole}; +use craft_ui::sections::{DialogRole, FooterButton, HeaderStrength, Section}; +use craft_ui::style::{ComponentStyle, Corners, RuleKind, StyleColor, StyleCx, SurfaceKind, TypeRole}; use craft_ui::text::TextField; use egui::load::SizedTexture; -use egui::{Pos2, Rect, Response, Ui, Vec2, pos2, vec2}; +use egui::{Color32, Mesh, Pos2, Rect, Response, Shape, TextureId, Ui, Vec2, pos2, vec2}; -use super::panel::{MOST_COPIES, PrintPanel, PrintPanelLayout}; -use super::{Duplex, Printer, Settings, State}; +use super::panel::{Destinations, DriverControls, MOST_COPIES, PrintPanel, PrintPanelLayout, PrintWords}; +use super::{Destination, Duplex, Printer, Settings, State}; craft_ui::words! { /// The words of the print dialog. pub struct PrintDialogWords { title: "printDialog.title" = "Print Settings"; + title_document: "printDialog.titleDocument" = "Print"; print: "printDialog.print" = "Print"; done: "printDialog.done" = "Done"; preview: "printDialog.preview" = "Print preview image"; @@ -55,12 +61,18 @@ craft_ui::words! { } } -/// The index `FormOutput::picked` gives the Done button: Print is 0, Cancel 1, and the extra buttons start at 2. +/// The index `FormOutput::picked` gives the Print button: Print is 0, Cancel 1, and the extra buttons start at 2. +const PRINT_BUTTON: usize = 0; + +/// The index `FormOutput::picked` gives the Done button of the `Image` layout, its one extra button. const DONE_BUTTON: usize = 2; /// The image box of the preview. const IMAGE: PartKey = PartKey::new("image"); +/// The message a preview shows instead of a sheet. +const MESSAGE: PartKey = PartKey::new("message"); + /// How far a crop or registration mark stands from the image box, and how long it is, in screen points. const MARK_GAP: f32 = 4.0; const MARK_LEN: f32 = 10.0; @@ -81,6 +93,68 @@ pub struct PrintMarks { pub labels: bool, } +/// How the print dialog is arranged. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub enum PrintLayout { + /// The preview at the start edge, the printer panel and the sections at the end edge. + #[default] + Image, + /// Printer Setup and the app's sections in a scrolling column, then the sheet preview, its pager, the readout and + /// the notes at the end edge; no Done button. + Document, + /// The preset row, the printer row and the header rows above a list of sections beside the shown one, with the + /// preview under the list. + Sections, +} + +/// What the sheet preview shows on the paper. +#[derive(Clone, Debug)] +#[non_exhaustive] +pub enum SheetContent { + /// One image box holding a picture; the box can be dragged. + #[non_exhaustive] + Image { + /// The image box on the paper. + image: egui::Rect, + /// The picture of the document. + picture: SizedTexture, + }, + /// The pages placed on the sheet, clipped to the paper. + Pages(Vec), + /// A message centred in the preview, with no paper. + Message(Label), +} + +/// One page placed on a sheet. +#[derive(Clone, Debug)] +#[non_exhaustive] +pub struct SheetPage { + /// The page's corners on the paper, in paper points. + pub corners: [Pos2; 4], + /// The page's picture; none draws a muted stand-in with `number` centred. + pub picture: Option, + /// The part of the picture to draw. + pub uv: egui::Rect, + /// The page's number, shown on the stand-in. + pub number: String, +} + +impl SheetPage { + /// A page at `corners` with no picture, numbered `number`. + pub fn new(corners: [Pos2; 4], number: impl Into) -> Self { + SheetPage { corners, picture: None, uv: Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)), number: number.into() } + } + + /// The page's picture `id` and the part `uv` of it to draw. + #[must_use] + pub fn picture(mut self, id: TextureId, uv: egui::Rect) -> Self { + self.picture = Some(id); + self.uv = uv; + self + } +} + /// What the app's layout says for this pass, in points. #[derive(Clone, Debug)] #[non_exhaustive] @@ -89,11 +163,7 @@ pub struct PrintSheet { pub paper: egui::Vec2, /// The printable area of the paper, when the printer says. pub printable: Option, - /// The image box on the paper. - pub image: egui::Rect, - /// The picture of the document. - pub picture: SizedTexture, - /// The marks to draw. + /// The marks to draw, around the image box or the pages. pub marks: PrintMarks, /// The readout under the preview. pub readout: Label, @@ -101,13 +171,77 @@ pub struct PrintSheet { pub count: usize, /// The outline of each sheet on the paper, in paper points, for a document that prints on several. pub outlines: Vec, + /// What the sheet shows on the paper. + pub content: SheetContent, + /// The borders drawn around the pages, in paper points. + pub borders: Vec, + /// The cut lines, in paper points. + pub cuts: Vec<[Pos2; 2]>, + /// The notes under the readout. + pub notes: Vec