diff --git a/crates/platform/README.md b/crates/platform/README.md index 5c1fe80ea..5ec1a619c 100644 --- a/crates/platform/README.md +++ b/crates/platform/README.md @@ -17,7 +17,7 @@ pull in heavier dependencies. | always | The app log: `log` records to standard error and `/.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, 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` (the app's Apple Events and second-instance hand-over feed it): one queue for files the OS asks the app to open and files dropped on the window (`DroppedFile`, `DropTarget`: canvas, tab strip or window); `natural_cmp` and `same_file` for opening order and duplicates; `reveal` and `open_external`; the shared open-error texts. No egui. | +| always | `open::FileIntake` with `IntakeSender` (the app's Apple Events and second-instance hand-over feed it): 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 | `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::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 and writes text, HTML, one bitmap and copied files; `EventClipboard` is the browser's, fed from paste events (`flavors_from_event`, `copy_through_egui` with `ui`). `EventClipboard` keeps an offered paste for the pass it was offered in and counts passes itself (`EventClipboard::for_egui` uses egui's pass number), 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, and `holds_ours` compares that one. The web writes only the best flavor (eframe makes each copy command its own `navigator.clipboard` write, so a second replaces the first). `has` never reads or decodes: it asks Windows and macOS for the formats on offer, Wayland for the offer's MIME types (`wl-clipboard-rs`) and X11 for the `TARGETS` list (`x11rb`); 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, PDF and RTF flavors are neither written nor read by `SystemClipboard` (a write of only those 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. | diff --git a/crates/platform/src/clipboard/backend.rs b/crates/platform/src/clipboard/backend.rs index c9becf3ca..502b2fcf6 100644 --- a/crates/platform/src/clipboard/backend.rs +++ b/crates/platform/src/clipboard/backend.rs @@ -40,8 +40,7 @@ pub trait ClipboardBackend: Send { /// As [`read`](Self::read), but the slow part (the Wayland pipe, a DIB conversion) is left in the returned /// closure, which runs off the UI thread. Reads now and wraps the result by default. fn read_later(&mut self, mimes: &[&str], limit: u64) -> Result Option + Send>>, ClipboardError> { - let _ = (mimes, limit); - todo!("sh.N1") + Ok(self.read(mimes, limit)?.map(|flavor| Box::new(move || Some(flavor)) as Box Option + Send>)) } /// Whether the clipboard can be read at any time; `false` where it can be read only inside a paste event (the /// web). diff --git a/crates/platform/src/clipboard/facade.rs b/crates/platform/src/clipboard/facade.rs index 02b678093..a71132d91 100644 --- a/crates/platform/src/clipboard/facade.rs +++ b/crates/platform/src/clipboard/facade.rs @@ -92,9 +92,8 @@ impl Clipboard { /// The first of `mimes` the clipboard holds, within [`ClipboardLimits::text_bytes`] for text /// types and [`ClipboardLimits::image_bytes`] for the rest. pub fn read(&mut self, mimes: &[&str]) -> Result, ClipboardError> { - let limit = if mimes.iter().all(|mime| is_text(mime)) { self.limits.text_bytes } else { self.limits.image_bytes }; - let Some(flavor) = self.backend.read(mimes, limit)? else { return Ok(None) }; - let cap = if is_text(&flavor.mime) { self.limits.text_bytes } else { self.limits.image_bytes }; + let Some(flavor) = self.backend.read(mimes, read_limit(&self.limits, mimes))? else { return Ok(None) }; + let cap = read_limit(&self.limits, &[&*flavor.mime]); if flavor.data.len() as u64 > cap { return Err(ClipboardError::TooLarge { limit: cap }); } @@ -102,10 +101,11 @@ impl Clipboard { } /// As [`read`](Self::read), with its limits and gates, but the slow part of the read is the returned closure, - /// which runs off the UI thread. + /// which runs off the UI thread. A flavour over its limit, found only once the closure has made it, is `None`. pub fn read_later(&mut self, mimes: &[&str]) -> Result Option + Send>>, ClipboardError> { - let _ = mimes; - todo!("sh.N1") + let Some(make) = self.backend.read_later(mimes, read_limit(&self.limits, mimes))? else { return Ok(None) }; + let limits = self.limits; + Ok(Some(Box::new(move || make().filter(|flavor| flavor.data.len() as u64 <= read_limit(&limits, &[&*flavor.mime]))))) } /// Whether the clipboard can be read at any time; `false` where it can be read only inside a paste event (the @@ -202,6 +202,11 @@ pub(super) fn is_text(mime: &str) -> bool { mime.starts_with("text/") || mime == SVG } +/// The byte limit a read of `mimes` runs under: text's when every type is text, else the image limit. +fn read_limit(limits: &ClipboardLimits, mimes: &[&str]) -> u64 { + if mimes.iter().all(|mime| is_text(mime)) { limits.text_bytes } else { limits.image_bytes } +} + pub(super) fn hash_bytes(bytes: &[u8]) -> u64 { let mut hasher = std::collections::hash_map::DefaultHasher::new(); bytes.hash(&mut hasher); diff --git a/crates/platform/src/clipboard/probe.rs b/crates/platform/src/clipboard/probe.rs index 007cc59bb..4d5b54525 100644 --- a/crates/platform/src/clipboard/probe.rs +++ b/crates/platform/src/clipboard/probe.rs @@ -8,7 +8,9 @@ use super::backend::ClipboardBackend; /// How often the probe's worker looks at the clipboard while the UI wants to know: 250 ms. pub const PROBE_INTERVAL: Duration = Duration::from_millis(250); -/// How long dropping the probe waits for the worker to let go of its handle: 27 s. +/// How long dropping the probe waits for the worker to let go of its handle: 27 s, an unanswered X11 read's limit +/// plus the worker's own stop, so on X11 the app's handle is the last one dropped and hands the copy to the clipboard +/// manager. The wait ends as soon as the worker drops its handle. pub const PROBE_STOP_WAIT: Duration = Duration::from_secs(27); /// Whether Paste has something to take from the system clipboard, asked on a worker thread. diff --git a/crates/platform/src/clipboard_tests.rs b/crates/platform/src/clipboard_tests.rs index 990189b32..909a70954 100644 --- a/crates/platform/src/clipboard_tests.rs +++ b/crates/platform/src/clipboard_tests.rs @@ -56,3 +56,68 @@ fn synthetic_input_never_replaces_what_the_user_copied() { assert_eq!(clipboard.write_text("mine").unwrap(), Written::Written); assert_eq!(clipboard.read_text().unwrap().as_deref(), Some("mine")); } + +// A paste read off the UI thread keeps a read's limits: the fake enforces none, so a flavour over +// the text limit gets through only if `read_later` drops its gate. +#[test] +fn a_later_read_keeps_the_limits_of_a_read_now() { + let fake = Fake::default(); + let mut clipboard = Clipboard::new(fake.clone()).limits(ClipboardLimits { text_bytes: 8, ..ClipboardLimits::DEFAULT }); + assert!(clipboard.read_later(&[TEXT]).unwrap().is_none(), "nothing copied"); + fake.copy_elsewhere(vec![Flavor::text("short")]); + let make = clipboard.read_later(&[TEXT]).unwrap().unwrap(); + assert_eq!(std::thread::spawn(make).join().unwrap().map(|f| f.data), Some(b"short".to_vec())); + fake.copy_elsewhere(vec![Flavor::text("longer than eight bytes")]); + let make = clipboard.read_later(&[TEXT]).unwrap().unwrap(); + assert!(make().is_none(), "over the text limit"); +} + +// The web's clipboard is read only inside a paste event; an app that reads it at any other time +// pastes nothing. +#[test] +fn only_a_clipboard_outside_paste_events_is_readable_any_time() { + assert!(Clipboard::new(Fake::default()).readable_any_time()); + assert!(!Clipboard::new(EventClipboard::new(|| 0, |_| Ok(0))).readable_any_time()); +} + +/// A backend that takes longer to drop than the probe's old 250 ms wait, as an X11 handle does +/// while it hands the copy to the clipboard manager. +struct SlowToDrop(Arc); + +impl ClipboardBackend for SlowToDrop { + fn write(&mut self, _flavors: &[Flavor]) -> Result { + Ok(0) + } + fn read(&mut self, _mimes: &[&str], _limit: u64) -> Result, ClipboardError> { + Ok(None) + } + fn read_image(&mut self, _limit: u64) -> Result, ClipboardError> { + Ok(None) + } + fn read_files(&mut self, _limit: usize) -> Result>, ClipboardError> { + Ok(None) + } + fn has(&mut self, _mimes: &[&str]) -> bool { + false + } +} + +impl Drop for SlowToDrop { + fn drop(&mut self) { + std::thread::sleep(std::time::Duration::from_millis(400)); + self.0.store(true, std::sync::atomic::Ordering::SeqCst); + } +} + +// Quitting drops the probe before the app's own handle: a probe that stopped waiting early would +// leave its handle the last one alive, and on X11 the copy would be lost at exit. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn dropping_the_probe_waits_until_its_handle_has_dropped() { + let dropped = Arc::new(std::sync::atomic::AtomicBool::new(false)); + let handle = dropped.clone(); + let probe = ClipboardProbe::start(Box::new(move || Box::new(SlowToDrop(handle)) as Box), vec![TEXT], craft_host::Wake::new(|| {})) + .unwrap(); + drop(probe); + assert!(dropped.load(std::sync::atomic::Ordering::SeqCst)); +} diff --git a/crates/platform/src/open.rs b/crates/platform/src/open.rs index 6d8990d2e..a0f32f152 100644 --- a/crates/platform/src/open.rs +++ b/crates/platform/src/open.rs @@ -2,15 +2,15 @@ //! //! - [`FileIntake`]: one queue for files the OS asks the app to open (Finder double-click, Open //! With, a Dock drop, a second launch handing its paths to the first) and files dropped on the -//! window, with where they were dropped ([`DropTarget`]). +//! window. //! - [`natural_cmp`], [`same_file`]: the order files open in and the check that keeps an open //! file from opening twice. //! - [`OPEN_FAILED`] and the other [`PlatformText`]s: the open errors every app words the same way. //! - [`reveal`], [`open_external`]: show a file in the system file manager; open a file or URL //! with the system's handler. +//! - [`open_with`], [`is_application`]: open a file in a chosen application; whether a path is one. //! -//! No egui: the app converts egui's dropped files into [`DroppedFile`]s and reads the pointer -//! position for [`DropTarget`] itself. +//! No egui: the app converts egui's dropped files into [`DroppedFile`]s itself. use std::collections::VecDeque; #[cfg(not(target_arch = "wasm32"))] @@ -43,21 +43,6 @@ pub const REVEAL_FAILED: PlatformText = PlatformText { id: "open.revealFailed", /// Every [`PlatformText`] of this module, for the missing-translation report ([`crate::texts`]). pub const TEXTS: &[PlatformText] = &[OPEN_FAILED, PLACE_FAILED, PATH_NOT_UNICODE_OPEN, PATH_NOT_UNICODE_SAVE, FILE_GONE, REVEAL_FAILED]; -/// Where files dropped on the window land. winit's drops carry no position, so the app finds it -/// from the pointer (PhotoCraft asks the OS while files hover); unknown counts as -/// [`Elsewhere`](DropTarget::Elsewhere). -#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] -pub enum DropTarget { - /// The active document's canvas: each file is placed as a layer, one at a time, each in Free - /// Transform (Photoshop's Place Embedded). Preset files (brushes, gradients) still open into - /// their libraries. - Canvas, - /// The tab strip: opened with their tabs from this position. - Tabs(usize), - /// Anywhere else (panels, a dialog, no document): opened like File › Open. - Elsewhere, -} - /// A dropped file as the app got it. On the web there is no path, only the name and bytes. #[derive(Clone, Debug, PartialEq)] pub struct DroppedFile { @@ -75,12 +60,10 @@ pub enum Intake { /// The OS asked to open these absolute paths: open them like File › Open, focusing a /// document that is already open instead of opening it again. Open(Vec), - /// Files dropped on the window, in drop order, with where they landed. + /// Files dropped on the window, in drop order. Dropped { /// The dropped files. files: Vec, - /// Where they landed. - target: DropTarget, }, } @@ -123,7 +106,7 @@ impl IntakeSender { /// let (intake, sender) = FileIntake::new(Wake::new(move || ctx.request_repaint())); /// // macOS: the app's Apple Event handler calls `sender.open(paths)`; elsewhere its single-instance socket does. /// // each frame: -/// intake.dropped(ctx.input(|i| i.raw.dropped_files.iter().map(to_dropped).collect()), target); +/// intake.dropped(ctx.input(|i| i.raw.dropped_files.iter().map(to_dropped).collect())); /// for batch in intake.take() { app.open_batch(batch); } /// ``` pub struct FileIntake { @@ -145,9 +128,9 @@ impl FileIntake { } /// Queues files dropped this frame; an empty list is ignored. - pub fn dropped(&self, files: Vec, target: DropTarget) { + pub fn dropped(&self, files: Vec) { if !files.is_empty() { - push(&self.queue, Intake::Dropped { files, target }); + push(&self.queue, Intake::Dropped { files }); } } @@ -329,17 +312,87 @@ pub fn open_external(target: &str) -> Result<(), String> { /// Opens `target` in the application at `app` (Edit Original's chosen application), never through a shell: on /// macOS `open -a app target`, waiting at most 2 s for Launch Services to refuse; elsewhere `app` runs with /// `target` as its only argument, without waiting. A path holding `"` is refused on Windows. +/// +/// A missing `app` is [`ErrorKind::NotFound`](std::io::ErrorKind::NotFound), so a caller can fall back to its default +/// editor; a path that is not an application ([`is_application`]) is `InvalidInput`, and nothing is started. +// PLAN: the contract row sh.B2a says `Result<(), String>`; the app needs the `NotFound` kind, so the error is `io::Error`. #[cfg(not(target_arch = "wasm32"))] pub fn open_with(app: &Path, target: &Path) -> std::io::Result<()> { - let _ = (app, target); - todo!("sh.B2a") + use std::io::{Error, ErrorKind}; + if cfg!(windows) && target.as_os_str().as_encoded_bytes().contains(&b'"') { + return Err(Error::new(ErrorKind::InvalidInput, "the file name can't be passed to an application on Windows")); + } + std::fs::metadata(app)?; + if !is_application(app) { + return Err(Error::new(ErrorKind::InvalidInput, format!("{} isn't an application files can be opened in", app.display()))); + } + launch(app, target) +} + +/// `open` returns once Launch Services has the request, so a short wait reports an app it can't open (a folder named +/// `.app` that isn't a bundle). The wait is capped so a stalled `open` never holds the window: past it, the launch is +/// left to run. +#[cfg(target_os = "macos")] +fn launch(app: &Path, target: &Path) -> std::io::Result<()> { + use std::time::{Duration, Instant}; + const WAIT: Duration = Duration::from_secs(2); + let mut child = Command::new("open").arg("-a").arg(app).arg(target).stderr(Stdio::piped()).spawn()?; + let started = Instant::now(); + loop { + match child.try_wait()? { + Some(status) if status.success() => return Ok(()), + Some(status) => { + let mut why = String::new(); + if let Some(mut err) = child.stderr.take() { + // Best effort: without its message the exit status says why. + let _ = std::io::Read::read_to_string(&mut err, &mut why); + } + let why = why.trim(); + return Err(std::io::Error::other(if why.is_empty() { status.to_string() } else { why.to_owned() })); + } + None if started.elapsed() < WAIT => std::thread::sleep(Duration::from_millis(20)), + None => { + // Reaped off the UI thread once it ends. + std::thread::spawn(move || { + let _ = child.wait(); + }); + return Ok(()); + } + } + } +} + +/// The editor itself runs, so waiting would last until it closes. +#[cfg(all(not(target_arch = "wasm32"), not(target_os = "macos")))] +fn launch(app: &Path, target: &Path) -> std::io::Result<()> { + Command::new(app).arg(target).spawn().map(|_| ()) } /// Whether `path` names an application the platform can launch: an `.app` folder on macOS, an `.exe` file on /// Windows, an executable file elsewhere; `false` on wasm. pub fn is_application(path: &Path) -> bool { - let _ = path; - todo!("sh.B2b") + if cfg!(target_arch = "wasm32") { + return false; + } + let ext = path.extension().map(|e| e.to_string_lossy().to_ascii_lowercase()).unwrap_or_default(); + if cfg!(target_os = "macos") { + ext == "app" && path.is_dir() + } else if cfg!(windows) { + ext == "exe" && path.is_file() + } else { + executable_file(path) + } +} + +#[cfg(unix)] +fn executable_file(path: &Path) -> bool { + use std::os::unix::fs::PermissionsExt as _; + std::fs::metadata(path).is_ok_and(|m| m.is_file() && m.permissions().mode() & 0o111 != 0) +} + +#[cfg(not(unix))] +fn executable_file(path: &Path) -> bool { + path.is_file() } /// The command that opens `target`; see [`open_external`]. diff --git a/crates/platform/src/open_tests.rs b/crates/platform/src/open_tests.rs index 9c05c13fb..d097935b9 100644 --- a/crates/platform/src/open_tests.rs +++ b/crates/platform/src/open_tests.rs @@ -14,3 +14,53 @@ fn open_command_keeps_the_target_one_inert_argument() { assert_eq!(args, ["--", target]); } } + +/// Only an application counts, never a document, a folder or a missing path. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn an_application_is_what_the_platform_launches() { + use crate::open::is_application; + let temp = crate::temp::TempDir::new("craft-open-app-").unwrap(); + let dir = temp.path(); + let doc = dir.join("notes.txt"); + std::fs::write(&doc, "hi").unwrap(); + assert!(!is_application(&doc), "a document"); + assert!(!is_application(dir), "a folder"); + assert!(!is_application(&dir.join("Missing.app")), "a missing path"); + if cfg!(target_os = "macos") { + let app = dir.join("Editor.app"); + std::fs::create_dir_all(&app).unwrap(); + assert!(is_application(&app), "an .app folder"); + } + if cfg!(windows) { + let exe = dir.join("editor.exe"); + std::fs::write(&exe, "").unwrap(); + assert!(is_application(&exe), "an .exe file"); + } + #[cfg(all(unix, not(target_os = "macos")))] + { + use std::os::unix::fs::PermissionsExt as _; + let tool = dir.join("editor"); + std::fs::write(&tool, "#!/bin/sh\n").unwrap(); + assert!(!is_application(&tool), "not executable yet"); + std::fs::set_permissions(&tool, std::fs::Permissions::from_mode(0o755)).unwrap(); + assert!(is_application(&tool), "an executable file"); + } +} + +/// A missing application is `NotFound` (the caller falls back to its default editor); anything else that is not an +/// application is refused as `InvalidInput` before anything is started. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn open_with_reports_a_missing_application_and_refuses_what_is_not_one() { + use crate::open::open_with; + use std::io::ErrorKind; + let temp = crate::temp::TempDir::new("craft-open-with-").unwrap(); + let dir = temp.path(); + let doc = dir.join("notes.txt"); + std::fs::write(&doc, "not an application").unwrap(); + let kind = |app: &std::path::Path| open_with(app, std::path::Path::new("image with spaces.png")).unwrap_err().kind(); + assert_eq!(kind(&dir.join("Missing.exe")), ErrorKind::NotFound); + assert_eq!(kind(&doc), ErrorKind::InvalidInput); + assert_eq!(kind(dir), ErrorKind::InvalidInput); +} diff --git a/crates/ui-contract/src/primitives/icon.rs b/crates/ui-contract/src/primitives/icon.rs index a7fd3dee3..8be920419 100644 --- a/crates/ui-contract/src/primitives/icon.rs +++ b/crates/ui-contract/src/primitives/icon.rs @@ -267,17 +267,26 @@ impl SvgIcon { svg_set::rasterise_entry(self.entry, self.set, px, stroke_px as f32 / 64.0, self.mirrored) } - /// Paints the icon in `color` centred in `square`, on whole pixels. + /// Paints the entry's fill in its fixed colour when it has one, then the icon in `color`, centred in `square`, on + /// whole pixels. pub(crate) fn paint(&self, painter: &Painter, square: Rect, color: Color32) { let ctx = painter.ctx(); let ppp = ctx.pixels_per_point(); let (px, stroke_px) = self.pixels(square.width(), ppp); - let key = (self.entry, self.set, px, stroke_px, self.mirrored); - let texture = TextureCache::texture(ctx, key, || self.mask(square.width(), ppp)); let side = px as f32 / ppp; let min = (square.center() - vec2(side, side) / 2.0).round_to_pixels(ppp); + let rect = Rect::from_min_size(min, vec2(side, side)); let uv = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0)); - crate::runtime::egui::textures::paint(painter, texture, Rect::from_min_size(min, vec2(side, side)), uv, color, egui::CornerRadius::ZERO); + // The fill flag keeps the fill's texture apart from the icon's. + let stamp = |fill: bool, tint: Color32, image: &dyn Fn() -> egui::ColorImage| { + let key = (self.entry, self.set, px, stroke_px, self.mirrored, fill); + let texture = TextureCache::texture(ctx, key, image); + crate::runtime::egui::textures::paint(painter, texture, rect, uv, tint, egui::CornerRadius::ZERO); + }; + if let Some((svg, [r, g, b, a])) = svg_set::fill_of(self.entry) { + stamp(true, Color32::from_rgba_unmultiplied(r, g, b, a), &|| svg_set::rasterise_fill(svg, px)); + } + stamp(false, color, &|| self.mask(square.width(), ppp)); } } diff --git a/crates/ui-contract/src/primitives/svg_set.rs b/crates/ui-contract/src/primitives/svg_set.rs index bede07cdc..771371da4 100644 --- a/crates/ui-contract/src/primitives/svg_set.rs +++ b/crates/ui-contract/src/primitives/svg_set.rs @@ -99,6 +99,22 @@ fn app_icon(set: usize, icon: usize) -> (&'static str, &'static [u8], Option Option<(&'static [u8], [u8; 4])> { + let Entry::App { set, icon } = entry else { return None }; + let registry = APPS.read().unwrap_or_else(PoisonError::into_inner); + let set = registry.sets[set]; + let name = set.icons[icon].0; + set.fills.iter().find(|(fill, ..)| *fill == name).map(|&(_, svg, color)| (svg, color)) +} + +/// A fill document in white at `px` x `px` physical pixels, drawn as drawn and never mirrored: no app icon is +/// directional. +pub(crate) fn rasterise_fill(svg: &[u8], px: u32) -> ColorImage { + image(draw(svg, None, px, 0.0, false), px, || "app icon fill".to_owned()) +} + /// The position of the icon called `name` in the catalog. pub(crate) fn find(name: &str) -> Option { NAMES.binary_search(&name).ok() diff --git a/crates/ui-contract/src/runtime/lock_keys.rs b/crates/ui-contract/src/runtime/lock_keys.rs index ed3b49f61..04804ce11 100644 --- a/crates/ui-contract/src/runtime/lock_keys.rs +++ b/crates/ui-contract/src/runtime/lock_keys.rs @@ -23,7 +23,7 @@ pub fn caps_lock(ctx: &Context) -> bool { let pass = ctx.cumulative_pass_nr(); with_session(ctx, global("craft-ui lock keys", ()), |reading: &mut Reading| { if reading.pass != Some(pass) { - *reading = Reading { pass: Some(pass), caps: craft_window::caps_lock(WindowHost::of(ctx).shell().backend) }; // P3(shell-w2): sh.K9 + *reading = Reading { pass: Some(pass), caps: craft_window::caps_lock(WindowHost::of(ctx).shell().backend) }; } reading.caps }) diff --git a/crates/ui-contract/src/testing/icon_trials.rs b/crates/ui-contract/src/testing/icon_trials.rs index 645d1e221..48d624be6 100644 --- a/crates/ui-contract/src/testing/icon_trials.rs +++ b/crates/ui-contract/src/testing/icon_trials.rs @@ -3,11 +3,11 @@ use crate::primitives::{AppIcons, Mirror, SvgIcon, icon_names, register_app_icons}; use crate::style::UiTokens; -use crate::testing::{style, trial}; +use crate::testing::{Frames, style, trial}; use craft_behavior::IconId; use craft_i18n::Direction; use craft_theme::{AppSizes, Appearance, Contrast, IconPackId, Mode, Size, TextSize, builtins}; -use egui::ColorImage; +use egui::{Color32, ColorImage, Rect, pos2, vec2}; // Built from parts so the workspace scan of icon-id literals does not read them. const FIRST_NAME: &str = concat!("zz_t10_", "first"); @@ -21,14 +21,17 @@ const FIRST_SET: AppIcons = AppIcons { name: "t10-first", stroke_width: None, icons: &[(FIRST_NAME, DISC), (CATALOG_NAME, DISC)], - fills: &[], /* P3(shell-w2): sh.K10 */ + fills: &[], }; const SECOND_SET: AppIcons = AppIcons { name: "t10-second", stroke_width: None, icons: &[(FIRST_NAME, SQUARE), (SECOND_NAME, SQUARE)], - fills: &[], /* P3(shell-w2): sh.K10 */ + fills: &[], }; +const FILLED_NAME: &str = concat!("zz_k10_", "filled"); +const FILL_COLOR: [u8; 4] = [255, 0, 0, 255]; +const FILLED_SET: AppIcons = AppIcons::new("k10-filled", None, &[(FILLED_NAME, DISC)]).with_fills(&[(FILLED_NAME, SQUARE, FILL_COLOR)]); fn icon(name: &'static str) -> Option { let tokens = style::tokens(Mode::Light, Contrast::Standard); @@ -91,3 +94,30 @@ fn a_theme_icon_pack_picks_the_set_and_an_unknown_pack_draws_the_default() { assert_eq!(mask_under_pack(Some("craft.lucide"), CATALOG_NAME), default, "the default set by name draws the default"); assert_eq!(mask_under_pack(Some("user.missing"), CATALOG_NAME), default, "a pack that is not installed draws the default"); } + +/// The colours of the textured shapes `name` paints under the tint `color`, first to last. +fn painted(name: &'static str, color: Color32) -> Vec { + let Some(svg) = icon(name) else { return Vec::new() }; + let square = Rect::from_min_size(pos2(10.0, 10.0), vec2(24.0, 24.0)); + Frames::new() + .frame_shapes(|ui| svg.paint(ui.painter(), square, color)) + .iter() + .filter_map(|shape| match shape { + egui::Shape::Mesh(mesh) => mesh.vertices.first().map(|vertex| vertex.color), + egui::Shape::Rect(rect) if rect.brush.is_some() => Some(rect.fill), + _ => None, + }) + .collect() +} + +#[trial] +fn an_icon_with_a_fill_keeps_its_colour_under_the_tint() { + register_app_icons(&FILLED_SET); + let [r, g, b, a] = FILL_COLOR; + let fill = Color32::from_rgba_unmultiplied(r, g, b, a); + for tint in [Color32::from_rgb(10, 200, 30), Color32::WHITE] { + assert_eq!(painted(FILLED_NAME, tint), [fill, tint], "the fill keeps its colour and the icon takes the tint"); + } + let tint = Color32::from_rgb(10, 200, 30); + assert_eq!(painted(CATALOG_NAME, tint), [tint], "an icon with no fill paints the icon only"); +} diff --git a/crates/ui-widgets/src/buttons/button.rs b/crates/ui-widgets/src/buttons/button.rs index 1d74f8e58..3f924f5e0 100644 --- a/crates/ui-widgets/src/buttons/button.rs +++ b/crates/ui-widgets/src/buttons/button.rs @@ -1,20 +1,24 @@ //! `Button`: a push button with an optional leading and trailing icon and a busy state. use super::face::{self, FaceLook, FaceSpec}; -use crate::contract::{Common, Component, Cx, LeastWidth, MeasureCx, NoValue, Outcome, PaintUi, PartsCx, Pointer as _, Props, Role, Styled as _}; -use crate::display::Spinner; +use crate::contract::{ + Access, Common, Component, Cx, LeastWidth, MeasureCx, NoValue, Outcome, PaintUi, PartsCx, Pointer as _, Props, Role, Styled as _, WordSetCx as _, +}; +use crate::display::{ChordWrite, DisplayWords, Kbd, Spinner}; use crate::primitives::{HAlign, IconSpec, PaintShape}; -use crate::runtime::commands::CommandRef; +use crate::runtime::commands::{CommandRef, ResolvedCommand}; use crate::runtime::env::Label; use crate::style::{ComponentStyle, DataColor, FocusLook, IconLook, StyleColor, StyleCx, SurfaceLook, TextLook, TypeRole}; -use craft_behavior::{Metrics, PartKey, PressPhase, Sense}; -use craft_keymap::Mods; +use craft_behavior::{Metrics, PartKey, PointerButton, PressPhase, Sense}; +use craft_host::target::Os; +use craft_keymap::{Mods, Trigger}; use craft_theme::{ Rgba, Stateful, Variant, variant::{Emphasis, Tone}, }; use egui::{Color32, Rect, Response, Vec2}; use std::ops::Deref; +use std::sync::Arc; /// The part a loading button shows its spinner in. const SPINNER: PartKey = PartKey::new("spinner"); @@ -62,6 +66,7 @@ impl ButtonStyle { let ink = cx.ink_on(DataColor::new(cx.color(tint).egui())); style.text = TextLook::new(TypeRole::Label, Stateful::new(ink)); style.icon = IconLook::new(cx.control().icon, Stateful::new(ink)); + style.face.muted = Stateful::new(ink); style } } @@ -96,7 +101,8 @@ impl ButtonOutput { (true, Some(activation)) => activation.mods, _ => Mods::NONE, }; - ButtonOutput { response: cx.response.clone(), clicks, mods, held: false } // P3(shell-w2): op.F1 + let held = cx.press().phase.button_down() && cx.press().phase.start().is_some_and(|start| start.button == PointerButton::Primary); + ButtonOutput { response: cx.response.clone(), clicks, mods, held } } /// Whether the button was clicked this pass, by pointer or by key, by the framework's click rule. It stands in @@ -170,11 +176,9 @@ pub struct Button<'a> { /// A muted caption-role second line, wrapped under the icon and label. The face grows to fit it. It is the /// accessible description unless `description` is set. #[prop(into)] - #[allow(dead_code)] // P3(shell-w2): dp.R3 detail: Option