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,
/// Whether a command button shows its command's chord after the label.
#[prop]
- #[allow(dead_code)] // P3(shell-w2): sh.K13
chord: ButtonChord,
}
@@ -201,7 +205,8 @@ impl<'a> Button<'a> {
::command(Button::new(Label::Empty), command)
}
- fn spec<'s>(&'s self, label: &'s str) -> FaceSpec<'s> {
+ /// The face of the button, with `chord` after the label.
+ fn spec<'s>(&'s self, label: &'s str, chord: Option<&'s str>) -> FaceSpec<'s> {
let label = self.painted.as_ref().map_or(label, Label::as_str);
FaceSpec {
label,
@@ -211,9 +216,17 @@ impl<'a> Button<'a> {
loading: self.loading,
mnemonic: None,
align: self.align,
- chord: None, // P3(shell-w2): sh.K13
+ chord,
+ detail: self.detail.as_ref().map(Label::as_str),
}
}
+
+ /// The chord a `Trailing` button shows: the bound `command`'s, written as `Kbd` writes it with the scope's key
+ /// names (`words`, asked only then). `None` for a hidden chord and for a command with none.
+ fn chord_text(&self, command: Option<&ResolvedCommand>, os: Os, words: impl FnOnce() -> Arc) -> Option {
+ let chord = command.filter(|_| self.chord == ButtonChord::Trailing)?.chord?;
+ Some(Kbd::text(&Trigger::from(chord), os, &words(), ChordWrite::default()))
+ }
}
impl Component for Button<'_> {
@@ -234,7 +247,8 @@ impl Component for Button<'_> {
}
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
- face::measure(cx, &self.spec(cx.resolved.label))
+ let chord = self.chord_text(cx.command(), cx.env.shell().os, || cx.words::());
+ face::measure(cx, &self.spec(cx.resolved.label, chord.as_deref()))
}
fn sense(&self) -> Sense {
@@ -247,7 +261,7 @@ impl Component for Button<'_> {
return;
}
let (area, rtl) = (cx.content_rect, cx.flow.is_rtl());
- let spinner = face::spinner_rect(cx, &self.spec(cx.resolved.label), &cx.style.face, cx.style.icon.side, area, rtl);
+ let spinner = face::spinner_rect(cx, &self.spec(cx.resolved.label, None), &cx.style.face, cx.style.icon.side, area, rtl);
if let Some(rect) = spinner {
cx.part(SPINNER, rect);
}
@@ -265,13 +279,23 @@ impl Component for Button<'_> {
if self.loading { crate::style::Flags::BUSY } else { crate::style::Flags::empty() }
}
+ fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) {
+ let detail = self.detail.as_ref().map(Label::as_str).filter(|detail| !detail.is_empty());
+ if let Some(detail) = detail
+ && cx.resolved.description.is_none()
+ {
+ access.description(detail);
+ }
+ }
+
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
if let Some(tint) = self.tint {
let shape = PaintShape::Rect(cx.rect, cx.style.surface.radius);
ui.draw().data_fill(&shape, DataColor::new(Color32::from(craft_theme::Srgba::from(tint))));
ui.draw().fill(&shape, cx.resolve(&cx.style.overlay));
}
- face::paint(ui, cx, (&cx.style.text, &cx.style.icon), &cx.style.face, &self.spec(cx.resolved.label), cx.content_rect);
+ let chord = self.chord_text(cx.command.as_deref(), cx.env.shell().os, || cx.words::());
+ face::paint(ui, cx, (&cx.style.text, &cx.style.icon), &cx.style.face, &self.spec(cx.resolved.label, chord.as_deref()), cx.content_rect);
if cx.part_if_declared(SPINNER).is_some() {
ui.face(SPINNER, Spinner::new().size(cx.resolved.size));
}
diff --git a/crates/ui-widgets/src/buttons/face.rs b/crates/ui-widgets/src/buttons/face.rs
index 13d477a7b..07e90e647 100644
--- a/crates/ui-widgets/src/buttons/face.rs
+++ b/crates/ui-widgets/src/buttons/face.rs
@@ -16,12 +16,14 @@ use egui::{Rect, Vec2, pos2};
pub(crate) struct FaceLook {
/// The gap between icon and label.
pub gap: f32,
+ /// The colour of the chord and of the detail line: the variant's muted ink, as a `Kbd` chord is muted.
+ pub muted: Stateful,
}
impl FaceLook {
- /// The face look of the instance's variant: the control's gap.
+ /// The face look of the instance's variant: the control's gap and the variant's muted ink.
pub(crate) fn of(cx: &StyleCx<'_>) -> FaceLook {
- FaceLook { gap: cx.control().gap }
+ FaceLook { gap: cx.control().gap, muted: cx.variant_look().muted }
}
}
@@ -45,8 +47,9 @@ pub(crate) struct FaceSpec<'a> {
/// Where the icons and the label sit along the area when it is wider than they are.
pub align: HAlign,
/// The command's chord, shown after the label and dropped before the label elides.
- #[allow(dead_code)] // P3(shell-w2): sh.K13
pub chord: Option<&'a str>,
+ /// A caption-role second line under the icon and label, wrapped to the face's width.
+ pub detail: Option<&'a str>,
}
impl FaceSpec<'_> {
@@ -66,6 +69,47 @@ impl FaceSpec<'_> {
fn gaps(&self) -> usize {
(self.icons() + usize::from(!self.label.is_empty())).saturating_sub(1)
}
+
+ /// The chord as a run: only after a label, and not while the face is busy. It keeps its left-to-right order under
+ /// right-to-left, as `ChordText` lays a chord out.
+ fn chord_run(&self) -> Option> {
+ self.chord.filter(|chord| !chord.is_empty() && !self.loading && !self.label.is_empty()).map(|chord| {
+ let mut run = TextRun::new(chord).role(TypeRole::Caption);
+ run.ltr = true;
+ run
+ })
+ }
+
+ fn detail_run(&self) -> Option> {
+ self.detail.filter(|detail| !detail.is_empty()).map(|detail| TextRun::new(detail).role(TypeRole::Caption))
+ }
+}
+
+/// Whether the chord, `chord` wide after a gap, fits with the whole label (`label` wide) and the icons and gaps (`fixed`)
+/// in `room`: the chord is dropped before the label elides.
+fn chord_fits(label: f32, chord: f32, fixed: f32, gap: f32, room: f32) -> bool {
+ fixed + label + gap + chord <= room
+}
+
+/// How far the parts start from the reading start of a row with `free` room to spare.
+fn lead_offset(align: HAlign, free: f32) -> f32 {
+ match align {
+ HAlign::Start => 0.0,
+ HAlign::Center => free / 2.0,
+ HAlign::End => free,
+ }
+}
+
+/// The row of icons, label and chord, `row_height` tall: all of `area` without a detail line; with one `detail_height`
+/// tall, the top of the block the two make, centred in `area`.
+fn row_rect(area: Rect, row_height: f32, detail_height: Option, gap: f32) -> Rect {
+ match detail_height {
+ Some(detail) => {
+ let block = row_height + gap + detail;
+ Rect::from_min_size(pos2(area.min.x, area.center().y - block / 2.0), Vec2::new(area.width(), row_height))
+ }
+ None => area,
+ }
}
/// The metrics of a button with a face: the control's, with the horizontal padding at least the corner radius plus
@@ -154,21 +198,37 @@ pub(crate) fn focus(cx: &StyleCx<'_>) -> FocusLook {
cx.focus_look()
}
-/// The size of the face: its parts and the gaps between them.
-/// The label elides in the room the icons and gaps leave, so a squeezed face is as wide as its room; at its least
-/// the label is at its readable least.
+/// The size of the face: its parts and the gaps between them, the detail line under them.
+/// The chord is dropped before the label elides; the label then elides in the room the icons and gaps leave, so a
+/// squeezed face is as wide as its room; at its least the label is at its readable least and the chord is dropped.
pub(crate) fn measure(cx: &MeasureCx<'_, C>, spec: &FaceSpec<'_>) -> Vec2 {
- let icon = cx.icon();
- let fixed = icon * spec.icons() as f32 + cx.gap() * spec.gaps() as f32;
- let text = if spec.label.is_empty() {
- Vec2::ZERO
+ let (icon, gap) = (cx.icon(), cx.gap());
+ let fixed = icon * spec.icons() as f32 + gap * spec.gaps() as f32;
+ let room = cx.room.unwrap_or(f32::INFINITY);
+ let (text, chord) = if spec.label.is_empty() {
+ (Vec2::ZERO, None)
} else if cx.proposal == Proposal::Min {
let run = spec.run();
- Vec2::new(cx.least_width(&run), cx.layout_at(&run, f32::INFINITY).size().y)
+ (Vec2::new(cx.least_width(&run), cx.layout_at(&run, f32::INFINITY).size().y), None)
} else {
- cx.layout_at(&spec.run(), cx.room.map_or(f32::INFINITY, |room| (room - fixed).max(0.0))).size()
+ let beside = spec.chord_run().and_then(|chord| {
+ let label = cx.layout_at(&spec.run(), f32::INFINITY).size();
+ let chord = cx.layout_at(&chord, f32::INFINITY).size();
+ chord_fits(label.x, chord.x, fixed, gap, room).then_some((label, chord))
+ });
+ match beside {
+ Some((label, chord)) => (Vec2::new(label.x, label.y.max(chord.y)), Some(chord.x)),
+ None => (cx.layout_at(&spec.run(), (room - fixed).max(0.0)).size(), None),
+ }
};
- Vec2::new(text.x + fixed, text.y.max(icon))
+ let row = Vec2::new(text.x + fixed + chord.map_or(0.0, |width| width + gap), text.y.max(icon));
+ let Some(detail) = spec.detail_run() else { return row };
+ let detail = if cx.proposal == Proposal::Min {
+ Vec2::new(cx.least_width(&detail), cx.layout_at(&detail, f32::INFINITY).size().y)
+ } else {
+ cx.layout_at(&detail, room).size()
+ };
+ Vec2::new(row.x.max(detail.x), row.y + gap + detail.y)
}
/// `icon` in `color`, unless the spec names a colour of its own.
@@ -181,26 +241,23 @@ pub(super) fn tinted<'a>(icon: &IconSpec<'a>, color: StyleColor) -> IconSpec<'a>
struct Slots {
lead: Option,
text: Option,
+ chord: Option,
trail: Option,
}
-/// Places the icons of `side` and a label `text_width` wide with `gap` between them, in `area` by `spec.align`: the leading
-/// icon at the reading start, the trailing icon at the reading end.
-fn slots(spec: &FaceSpec<'_>, side: f32, gap: f32, text_width: f32, area: Rect, rtl: bool) -> Slots {
- let width = side * spec.icons() as f32 + gap * spec.gaps() as f32 + text_width;
- let free = (area.width() - width).max(0.0);
- let lead = match spec.align {
- HAlign::Start => 0.0,
- HAlign::Center => free / 2.0,
- HAlign::End => free,
- };
+/// Places the icons of `side` and a label `text_width` wide with `gap` between them, and the chord of `chord` width
+/// after the label, in `area` by `spec.align`: the leading icon at the reading start, the trailing icon at the reading
+/// end.
+fn slots(spec: &FaceSpec<'_>, side: f32, gap: f32, text_width: f32, chord: Option, area: Rect, rtl: bool) -> Slots {
+ let width = side * spec.icons() as f32 + gap * spec.gaps() as f32 + text_width + chord.map_or(0.0, |width| width + gap);
+ let lead = lead_offset(spec.align, (area.width() - width).max(0.0));
let (_, mut rest) = Flow::new(area, rtl).take_start(lead);
let mut take = |extent: f32| {
let (slot, next) = rest.take_start(extent);
rest = next;
slot
};
- let mut slots = Slots { lead: None, text: None, trail: None };
+ let mut slots = Slots { lead: None, text: None, chord: None, trail: None };
let mut gapped = false;
if spec.lead.is_some() {
slots.lead = Some(take(side));
@@ -212,6 +269,10 @@ fn slots(spec: &FaceSpec<'_>, side: f32, gap: f32, text_width: f32, area: Rect,
}
slots.text = Some(take(text_width));
gapped = true;
+ if let Some(width) = chord {
+ take(gap);
+ slots.chord = Some(take(width));
+ }
}
if spec.trail.is_some() {
if gapped {
@@ -234,28 +295,53 @@ fn text_top(draw: &crate::primitives::Draw<'_>, area: Rect, text: &crate::primit
area.center().y - body.size().y / 2.0 + body.first_baseline - text.first_baseline
}
-/// Paints the face in `area`, placed by `spec.align`: the leading icon at the reading start, the trailing icon at the reading end.
+/// Paints the face in `area`, placed by `spec.align`: the leading icon at the reading start, the trailing icon at the
+/// reading end, the chord after the label when it fits beside the whole label, the detail line centred in `area` with
+/// them as one block.
pub(crate) fn paint(ui: &PaintUi<'_>, cx: &Cx<'_, C>, ink: (&TextLook, &IconLook), look: &FaceLook, spec: &FaceSpec<'_>, area: Rect) {
let (text_look, icon_look) = ink;
let (text_color, icon_color, side) = (cx.resolve(&text_look.color), cx.resolve(&icon_look.color), icon_look.side);
let draw = ui.draw();
let fixed = side * spec.icons() as f32 + look.gap * spec.gaps() as f32;
let run = spec.run().color(text_color);
- let text = if spec.label.is_empty() { None } else { Some(draw.layout(&run, (area.width() - fixed).max(0.0))) };
+ let muted = cx.resolve(&look.muted);
+ let beside = spec.chord_run().and_then(|chord| {
+ let label = draw.layout(&run, f32::INFINITY);
+ let chord = draw.layout(&chord.color(muted), f32::INFINITY);
+ chord_fits(label.size().x, chord.size().x, fixed, look.gap, area.width()).then_some((label, chord))
+ });
+ let (text, chord) = match beside {
+ Some((label, chord)) => (Some(label), Some(chord)),
+ None if spec.label.is_empty() => (None, None),
+ None => (Some(draw.layout(&run, (area.width() - fixed).max(0.0))), None),
+ };
+ let detail = spec.detail_run().map(|detail| draw.layout(&detail.color(muted), area.width()));
+ let height = |layout: &Option| layout.as_ref().map_or(0.0, |layout| layout.size().y);
+ let row = row_rect(area, height(&text).max(height(&chord)).max(side), detail.as_ref().map(|detail| detail.size().y), look.gap);
+ let rtl = cx.flow.is_rtl();
let text_width = text.as_ref().map_or(0.0, |text| text.size().x);
- let slots = slots(spec, side, look.gap, text_width, area, cx.flow.is_rtl());
+ let slots = slots(spec, side, look.gap, text_width, chord.as_ref().map(|chord| chord.size().x), row, rtl);
if let (Some(lead), Some(slot)) = (spec.lead, slots.lead)
&& !spec.loading
{
- draw.icon(icon_at(slot, area, side), &tinted(lead, icon_color));
+ draw.icon(icon_at(slot, row, side), &tinted(lead, icon_color));
}
if let (Some(text), Some(slot)) = (&text, slots.text)
&& !(spec.loading && spec.lead.is_none())
{
- draw.galley(pos2(slot.min.x, text_top(&draw, area, text)), text);
+ draw.galley(pos2(slot.min.x, text_top(&draw, row, text)), text);
+ }
+ if let (Some(chord), Some(slot)) = (&chord, slots.chord) {
+ draw.galley(pos2(slot.min.x, text_top(&draw, row, chord)), chord);
}
if let (Some(trail), Some(slot)) = (spec.trail, slots.trail) {
- draw.icon(icon_at(slot, area, side), &tinted(trail, icon_color));
+ draw.icon(icon_at(slot, row, side), &tinted(trail, icon_color));
+ }
+ if let Some(detail) = &detail {
+ let width = detail.size().x;
+ let (_, rest) = Flow::new(area, rtl).take_start(lead_offset(spec.align, (area.width() - width).max(0.0)));
+ let (slot, _) = rest.take_start(width);
+ draw.galley(pos2(slot.min.x, row.max.y + look.gap), detail);
}
}
@@ -270,8 +356,10 @@ pub(super) fn spinner_rect(
rtl: bool,
) -> Option {
let fixed = side * spec.icons() as f32 + look.gap * spec.gaps() as f32;
- let text_width = if spec.label.is_empty() { 0.0 } else { cx.layout_at(&spec.run(), (area.width() - fixed).max(0.0)).size().x };
- let slots = slots(spec, side, look.gap, text_width, area, rtl);
+ let text = if spec.label.is_empty() { Vec2::ZERO } else { cx.layout_at(&spec.run(), (area.width() - fixed).max(0.0)).size() };
+ let detail = spec.detail_run().map(|detail| cx.layout_at(&detail, area.width()).size().y);
+ let row = row_rect(area, text.y.max(side), detail, look.gap);
+ let slots = slots(spec, side, look.gap, text.x, None, row, rtl);
let slot = if spec.lead.is_some() { slots.lead } else { slots.text }?;
- Some(icon_at(slot, area, side))
+ Some(icon_at(slot, row, side))
}
diff --git a/crates/ui-widgets/src/buttons/split_button.rs b/crates/ui-widgets/src/buttons/split_button.rs
index b4bcd97ed..8b2eb81a8 100644
--- a/crates/ui-widgets/src/buttons/split_button.rs
+++ b/crates/ui-widgets/src/buttons/split_button.rs
@@ -102,7 +102,8 @@ impl<'a, T: Value + 'static> SplitButton<'a, T> {
loading: false,
mnemonic: None,
align: crate::primitives::HAlign::Center,
- chord: None, // P3(shell-w2): sh.K13
+ chord: None,
+ detail: None,
}
}
}
diff --git a/crates/ui-widgets/src/buttons/stories.rs b/crates/ui-widgets/src/buttons/stories.rs
index 51609eb1e..6fefa2309 100644
--- a/crates/ui-widgets/src/buttons/stories.rs
+++ b/crates/ui-widgets/src/buttons/stories.rs
@@ -1,10 +1,11 @@
//! Stories of the buttons.
-use super::{Button, IconButton, Link, SplitButton, ToggleButton};
+use super::{Button, ButtonChord, IconButton, Link, SplitButton, ToggleButton};
use crate::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _, Validity};
use crate::display::{Shade, Text};
use crate::layout_components::{Grid, Row};
use crate::primitives::IconSpec;
+use crate::runtime::commands::EditCommands;
use crate::runtime::env::Message;
use crate::style::DataColor;
use crate::testing::{Drive, Fixture, StoryData, StoryOutput, story};
@@ -166,3 +167,54 @@ fn split_button_open(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
fn link(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
Link::new("Show all your shortcuts").url("https://example.com/shortcuts").show(ui).into()
}
+
+/// A command button showing its command's chord after the label.
+#[story(Button<'static>, covers = [], drive = Drive::Never, group = "Variants", title = "Chord")]
+fn button_chord(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
+ Button::command(EditCommands::Copy).chord(ButtonChord::Trailing).show(ui).into()
+}
+
+/// A long painted label with the chord: the chord shows while the whole label fits beside it.
+#[story(Button<'static>, covers = [], drive = Drive::Never, group = "Variants", title = "Chord, long text")]
+fn button_chord_long_text(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
+ Button::command(EditCommands::Copy).chord(ButtonChord::Trailing).painted("Copy the selected objects to the clipboard").show(ui).into()
+}
+
+/// A room too short for label and chord together: the chord is dropped and the label stays whole.
+#[story(Button<'static>, covers = [], drive = Drive::Never, group = "Variants", title = "Chord, narrow room")]
+fn button_chord_narrow_room(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
+ let width = |chord| Button::command(EditCommands::Copy).chord(chord).measure_in(ui, Proposal::Ideal).x;
+ // Halfway between the button without its chord and with it: room for the whole label, not for the chord too.
+ let room = (width(ButtonChord::Hidden) + width(ButtonChord::Trailing)) / 2.0;
+ ui.scope(|ui| {
+ ui.set_max_width(room.min(ui.available_width()));
+ Button::command(EditCommands::Copy).chord(ButtonChord::Trailing).show(ui)
+ })
+ .inner
+ .into()
+}
+
+/// A button with a muted second line under its icon and label.
+#[story(Button<'static>, covers = [], drive = Drive::Never, group = "Variants", title = "With detail")]
+fn button_with_detail(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
+ Button::new("Quick start").icon(IconId::new("eye")).detail("Learn the basics of drawing in five minutes").show(ui).into()
+}
+
+/// A link inside a sentence.
+#[story(Link, covers = [], drive = Drive::Never, title = "In a sentence")]
+fn link_in_sentence(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
+ let shown = Row::new().show(ui, |ui, _| {
+ Text::new("Every shortcut is listed in").show(ui);
+ Link::new("the shortcuts guide").url("https://example.com/shortcuts").id_salt("guide").show(ui);
+ Text::new("and can be changed.").show(ui);
+ });
+ shown.into()
+}
+
+/// An icon button reporting that it is held, from the press to the release, also after the pointer leaves it.
+#[story(IconButton<'static>, covers = [], title = "Press and hold")]
+fn icon_button_held(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
+ let out = IconButton::new(IconId::new("eye")).label("Hold to preview").show(ui);
+ Text::new(if out.held { "Held" } else { "Not held" }).shade(Shade::Muted).show(ui);
+ out.into()
+}
diff --git a/crates/ui-widgets/src/buttons/toggle_button.rs b/crates/ui-widgets/src/buttons/toggle_button.rs
index f4c6d96ff..c227ae92e 100644
--- a/crates/ui-widgets/src/buttons/toggle_button.rs
+++ b/crates/ui-widgets/src/buttons/toggle_button.rs
@@ -114,7 +114,8 @@ impl<'a> ToggleButton<'a> {
loading: false,
mnemonic: None,
align: crate::primitives::HAlign::Center,
- chord: None, // P3(shell-w2): sh.K13
+ chord: None,
+ detail: None,
}
}
}
diff --git a/crates/ui-widgets/src/choice/segmented.rs b/crates/ui-widgets/src/choice/segmented.rs
index 79917740a..55ad5a4b2 100644
--- a/crates/ui-widgets/src/choice/segmented.rs
+++ b/crates/ui-widgets/src/choice/segmented.rs
@@ -192,7 +192,8 @@ impl Segment {
loading: false,
mnemonic: None,
align: crate::primitives::HAlign::Center,
- chord: None, // P3(shell-w2): sh.K13
+ chord: None,
+ detail: None,
}
}
}
diff --git a/crates/window/Cargo.toml b/crates/window/Cargo.toml
index 19b3f8ff4..16afde3ce 100644
--- a/crates/window/Cargo.toml
+++ b/crates/window/Cargo.toml
@@ -13,7 +13,7 @@ ui = ["dep:egui"]
# `mac::set_movable`: AppKit's `movable` flag, without egui. `system::SystemWindows`: AppKit's pointer, button and Cmd.
# `native_menu`: the application menu bar
# on macOS (other platforms build the same API as no-ops).
-appkit = ["dep:objc2", "dep:objc2-app-kit", "dep:objc2-foundation", "dep:muda"]
+appkit = ["dep:objc2", "dep:objc2-app-kit", "dep:objc2-foundation", "dep:muda", "dep:craft-appkit"]
[dependencies]
egui = { workspace = true, optional = true }
@@ -25,16 +25,19 @@ serde = { workspace = true }
serde_json = { workspace = true }
# Only Linux and the BSDs probe a Wayland compositor; everywhere else the frame is the OS's.
+# `caps_lock` reads the XKB lock state of an X11 window (XWayland included) over x11rb.
[target.'cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"))'.dependencies]
wayland-client = "0.31"
+x11rb = { version = "0.13", default-features = false, features = ["xkb"] }
# `mac::set_movable` (`NSWindow.movable`), `mac::measure` (button frames, OS version), `system::SystemWindows`
# (`NSEvent` pointer, buttons and modifiers, `NSScreen` for the primary screen),
# `native_menu` (muda menus, AppKit titles).
[target.'cfg(target_os = "macos")'.dependencies]
+craft-appkit = { workspace = true, optional = true }
muda = { version = "0.21.2", default-features = false, optional = true }
objc2 = { version = "0.6.4", default-features = false, features = ["std"], optional = true }
-objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "NSApplication", "NSButton", "NSControl", "NSEvent", "NSMenu", "NSMenuItem", "NSResponder", "NSScreen", "NSView", "NSWindow"], optional = true }
+objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "NSApplication", "NSButton", "NSControl", "NSEvent", "NSMenu", "NSMenuItem", "NSResponder", "NSScreen", "NSTextInputContext", "NSView", "NSWindow"], optional = true }
objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "NSArray", "NSBundle", "NSEnumerator", "NSGeometry", "NSLocale", "NSProcessInfo", "NSString"], optional = true }
# `caps_lock`: the toggle bit of the Caps Lock key, through winsafe's safe wrapper (the workspace forbids `unsafe`).
diff --git a/crates/window/src/lock_state.rs b/crates/window/src/lock_state.rs
index 5cc2bfeba..da06ed8f9 100644
--- a/crates/window/src/lock_state.rs
+++ b/crates/window/src/lock_state.rs
@@ -1,20 +1,22 @@
//! The Caps Lock toggle, which the keys' events don't carry: egui reports the key's presses, not whether the lock
//! is on.
+use craft_host::target::Backend;
+
/// Whether Caps Lock is on now.
///
/// macOS reads the modifier flags of AppKit's current event state, Windows the toggle bit of the Caps Lock key.
-/// Linux and the BSDs on X11 (XWayland included) read the XKB lock state; Wayland and the web report off.
-pub fn caps_lock(backend: craft_host::target::Backend) -> bool {
- let _ = backend; // P3(shell-w2): sh.K9
- imp::caps_lock()
+/// Linux and the BSDs read the XKB lock state when the window's `backend` is X11 (XWayland included); Wayland and the
+/// web report off.
+pub fn caps_lock(backend: Backend) -> bool {
+ imp::caps_lock(backend)
}
#[cfg(all(feature = "appkit", target_os = "macos"))]
mod imp {
use objc2_app_kit::{NSEvent, NSEventModifierFlags};
- pub(super) fn caps_lock() -> bool {
+ pub(super) fn caps_lock(_: super::Backend) -> bool {
NSEvent::modifierFlags_class().contains(NSEventModifierFlags::CapsLock)
}
}
@@ -23,15 +25,55 @@ mod imp {
mod imp {
use winsafe::{GetKeyState, co::VK};
- pub(super) fn caps_lock() -> bool {
+ pub(super) fn caps_lock(_: super::Backend) -> bool {
let (_, toggled) = GetKeyState(VK::CAPITAL);
toggled
}
}
-#[cfg(not(any(all(feature = "appkit", target_os = "macos"), windows)))]
+#[cfg(any(target_os = "linux", target_os = "freebsd", target_os = "openbsd", target_os = "netbsd"))]
mod imp {
- pub(super) fn caps_lock() -> bool {
+ use std::sync::OnceLock;
+ use x11rb::protocol::xkb;
+ use x11rb::protocol::xproto::ModMask;
+ use x11rb::rust_connection::RustConnection;
+
+ /// The process's one connection, opened at the first read; `None` without an X server or without XKB on it.
+ static CONNECTION: OnceLock> = OnceLock::new();
+
+ fn connection() -> Option<&'static RustConnection> {
+ CONNECTION
+ .get_or_init(|| {
+ let (connection, _) = x11rb::connect(None).ok()?;
+ let supported = xkb::use_extension(&connection, 1, 0).ok()?.reply().ok()?.supported;
+ supported.then_some(connection)
+ })
+ .as_ref()
+ }
+
+ /// One round trip per call; the caller reads once per pass. An error answers off.
+ pub(super) fn caps_lock(backend: super::Backend) -> bool {
+ if backend != super::Backend::X11 {
+ return false;
+ }
+ let Some(connection) = connection() else { return false };
+ xkb::get_state(connection, xkb::ID::USE_CORE_KBD.into())
+ .ok()
+ .and_then(|cookie| cookie.reply().ok())
+ .is_some_and(|state| u16::from(state.locked_mods) & u16::from(ModMask::LOCK) != 0)
+ }
+}
+
+#[cfg(not(any(
+ all(feature = "appkit", target_os = "macos"),
+ windows,
+ target_os = "linux",
+ target_os = "freebsd",
+ target_os = "openbsd",
+ target_os = "netbsd"
+)))]
+mod imp {
+ pub(super) fn caps_lock(_: super::Backend) -> bool {
false
}
}