diff --git a/.github/workflows/workspace.yml b/.github/workflows/workspace.yml index b63d1a79ec..c583402a58 100644 --- a/.github/workflows/workspace.yml +++ b/.github/workflows/workspace.yml @@ -76,6 +76,10 @@ jobs: cache-workspace-crates: true cold-build: ${{ github.event.schedule == '17 0 * * *' }} lint-cache: false + # The vendored crates are on the workspace `exclude` list, so unreached-rs has no module tree for them. + unreached-rs-allow: | + **/fixtures/** + vendor/** timeout-minutes: &timeout 120 # Every leg runs its tests with nextest, and its doctests with cargo test (.config/nextest.toml). tools: &tools cargo-nextest@0.9.150 diff --git a/Cargo.lock b/Cargo.lock index 1b38d62925..27b9e695a6 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1935,6 +1935,7 @@ dependencies = [ "craft-vectordrawable", "craft-video", "craft-wasm", + "craft-wayland", "craft-web-api", "craft-web-host", "craft-webp", @@ -2031,6 +2032,15 @@ dependencies = [ "serde_json", ] +[[package]] +name = "craft-appkit" +version = "0.1.0" +dependencies = [ + "block2 0.6.2", + "objc2-app-kit 0.3.2", + "objc2-foundation 0.3.2", +] + [[package]] name = "craft-assuan" version = "0.1.0" @@ -4503,6 +4513,7 @@ dependencies = [ "egui", "raw-window-handle", "serde", + "serde_json", "web-time", ] @@ -4625,6 +4636,15 @@ dependencies = [ "wasmprinter", ] +[[package]] +name = "craft-wayland" +version = "0.1.0" +dependencies = [ + "raw-window-handle", + "wayland-backend", + "wayland-client", +] + [[package]] name = "craft-web-api" version = "0.1.0" @@ -4668,6 +4688,7 @@ dependencies = [ name = "craft-window" version = "0.1.0" dependencies = [ + "craft-appkit", "craft-atomic", "craft-behavior", "craft-host", @@ -4684,6 +4705,7 @@ dependencies = [ "tempfile", "wayland-client", "winsafe", + "x11rb", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 5b9c085a84..9e861a40bd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -42,6 +42,8 @@ craft-png = { path = "crates/png" } craft-aep = { path = "crates/aep" } craft-affinity = { path = "crates/affinity" } craft-win32 = { path = "crates/win32" } +craft-appkit = { path = "crates/appkit" } +craft-wayland = { path = "crates/wayland" } craft-cdr = { path = "crates/cdr" } craft-ai = { path = "crates/ai" } craft-ai-core = { path = "crates/ai-core" } diff --git a/crates/appkit/Cargo.toml b/crates/appkit/Cargo.toml new file mode 100644 index 0000000000..ad602e383a --- /dev/null +++ b/crates/appkit/Cargo.toml @@ -0,0 +1,30 @@ +[package] +name = "craft-appkit" +description = "The macOS menu-tracking observers that need `unsafe`, behind a safe API, so no other crate allows `unsafe`." +version.workspace = true +edition.workspace = true +license.workspace = true +rust-version.workspace = true +repository.workspace = true + +# `NSMenuDidBeginTrackingNotification` and `NSMenuDidEndTrackingNotification`, observed through +# `NSNotificationCenter` with a block. +[target.'cfg(target_os = "macos")'.dependencies] +block2 = "0.6.2" +objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std", "NSMenu"] } +objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "block2", "NSNotification", "NSOperation", "NSString"] } + +# The workspace table with `unsafe_code` at `deny`: `lib.rs` allows it for this crate's FFI calls, and design-lint's +# `contract/unsafe-allow` rule names this crate's source as one of the places that may. Cargo cannot override one +# workspace lint. +[lints.rust] +unsafe_code = "deny" +missing_docs = "warn" +unexpected_cfgs = { level = "warn", check-cfg = ["cfg(craft_pdf_unicode_fixtures)"] } + +[lints.clippy] +cognitive_complexity = "deny" +too_many_arguments = "deny" +wildcard_imports = "deny" +dbg_macro = "warn" +todo = "warn" diff --git a/crates/appkit/src/lib.rs b/crates/appkit/src/lib.rs new file mode 100644 index 0000000000..78dd786b15 --- /dev/null +++ b/crates/appkit/src/lib.rs @@ -0,0 +1,37 @@ +//! The AppKit calls that need `unsafe`, behind a safe API: observing when a menu starts and stops tracking. macOS +//! only; the crate is empty elsewhere. +//! +//! This is one of the crates that may allow `unsafe`; the design-lint rule `contract/unsafe-allow` names it. Every +//! block says why it is sound. +#![warn(missing_docs)] +#![cfg(target_os = "macos")] +#![allow(unsafe_code)] + +use std::ptr::NonNull; +use std::sync::{Arc, Once}; + +use block2::RcBlock; +use objc2_app_kit::{NSMenuDidBeginTrackingNotification, NSMenuDidEndTrackingNotification}; +use objc2_foundation::{NSNotification, NSNotificationCenter}; + +/// Calls `on_change(true)` when a menu begins tracking (`NSMenuDidBeginTrackingNotification`) and `on_change(false)` +/// when it ends (`NSMenuDidEndTrackingNotification`), from the thread that posts the notification. Observes once +/// for the process; a later call replaces nothing and does nothing. +pub fn observe_menu_tracking(on_change: Arc) { + static OBSERVE: Once = Once::new(); + OBSERVE.call_once(|| { + // SAFETY: AppKit initializes these immutable notification-name constants before any code of the app runs. + let names = unsafe { [(NSMenuDidBeginTrackingNotification, true), (NSMenuDidEndTrackingNotification, false)] }; + let center = NSNotificationCenter::defaultCenter(); + for (name, tracking) in names { + let on_change = on_change.clone(); + let block = RcBlock::new(move |_: NonNull| on_change(tracking)); + // SAFETY: `name` is one of AppKit's notification names and the block takes the notification by pointer + // without reading it. The center copies the block and keeps the observer for the process's lifetime; + // nothing removes it, so the returned token is not needed. + unsafe { + center.addObserverForName_object_queue_usingBlock(Some(name), None, None, &block); + } + } + }); +} diff --git a/crates/atomic/src/lib.rs b/crates/atomic/src/lib.rs index c0bbcf5553..5aa3c75cd4 100644 --- a/crates/atomic/src/lib.rs +++ b/crates/atomic/src/lib.rs @@ -491,7 +491,6 @@ fn name_taken(e: &io::Error, tmp: &Path) -> bool { /// 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; @@ -549,8 +548,12 @@ const MAX_XATTR_TOTAL_BYTES: usize = 64 * 1024 * 1024; /// 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`). +/// extended attributes (`ENOTSUP`) is skipped. So is a file whose data the user may not read when +/// its attribute names can't be listed either, as with mode 0200: its attributes are dropped, as +/// before attributes were kept, since the user can't read them (or its bytes) at all. One whose +/// data is denied but whose names can be listed (an ACL that denies reading) refuses the save. +/// `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}; @@ -561,6 +564,7 @@ fn copy_xattrs(target: &Path, stage: &File) -> io::Result<()> { 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(Errno::ACCESS) => return unreadable_has_no_attributes(target), Err(e) => return Err(e.into()), }; if !source.metadata()?.is_file() { @@ -596,6 +600,27 @@ fn copy_xattrs(target: &Path, stage: &File) -> io::Result<()> { Ok(()) } +/// For a target whose data can't be opened for reading: `Ok` when the user can list no extended +/// attribute names on it (none, only `com.apple.provenance`, none supported, or listing is denied too, +/// as for mode 0200, whose attributes are then dropped); otherwise refuse the save, as the attributes +/// can't be copied without opening the file. The names are read without following a link, by path. +#[cfg(target_os = "macos")] +fn unreadable_has_no_attributes(target: &Path) -> io::Result<()> { + use rustix::fs::llistxattr; + use rustix::io::Errno; + let mut names = vec![0u8; MAX_XATTR_NAMES_BYTES]; + match llistxattr(target, names.as_mut_slice()) { + Ok(0) | Err(Errno::NOTSUP | Errno::ACCESS | Errno::NOENT) => Ok(()), + Ok(len) if names.get(..len).is_some_and(|names| names.split(|b| *b == 0).all(|name| name.is_empty() || name == b"com.apple.provenance")) => { + Ok(()) + } + Ok(_) | Err(Errno::RANGE) => { + Err(io::Error::new(io::ErrorKind::PermissionDenied, "the file can't be read, so its extended attributes can't be copied")) + } + Err(e) => Err(e.into()), + } +} + /// 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. diff --git a/crates/atomic/tests/atomic_tests.rs b/crates/atomic/tests/atomic_tests.rs index b1da9be0a2..fcafd2ca78 100644 --- a/crates/atomic/tests/atomic_tests.rs +++ b/crates/atomic/tests/atomic_tests.rs @@ -99,3 +99,49 @@ fn private_staging_preserves_existing_modes_after_callback() -> io::Result<()> { assert_no_temp(&d.0); Ok(()) } + +/// Extended attribute names on `path`, read by path. +#[cfg(target_os = "macos")] +fn xattr_names(path: &Path) -> Vec> { + let mut names = vec![0u8; 64 * 1024]; + let len = rustix::fs::listxattr(path, names.as_mut_slice()).unwrap_or(0); + names.truncate(len); + names.split(|b| *b == 0).filter(|n| !n.is_empty()).map(<[u8]>::to_vec).collect() +} + +/// A write-only file (mode 0200) saves: macOS lets its owner neither read its data nor list its +/// attributes, so its attributes are dropped, as before attributes were kept. +#[cfg(target_os = "macos")] +#[test] +fn a_write_only_file_saves_and_drops_the_attributes_it_cannot_read() -> io::Result<()> { + use std::os::unix::fs::PermissionsExt; + let d = TempDir::new("write_only_xattrs"); + let p = d.0.join("doc.craft"); + std::fs::write(&p, ORIGINAL)?; + rustix::fs::setxattr(&p, "com.craft.t", b"tag", rustix::fs::XattrFlags::empty())?; + std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o200))?; + atomic_write(&p, b"new")?; + std::fs::set_permissions(&p, std::fs::Permissions::from_mode(0o600))?; + assert_eq!(std::fs::read(&p)?, b"new"); + assert!(!xattr_names(&p).iter().any(|n| n == b"com.craft.t"), "the unreadable attribute is dropped"); + Ok(()) +} + +/// A file whose data an ACL denies but whose attribute names can be listed is not replaced: its +/// attributes can't be copied without its data, and the save refuses rather than drop them. +#[cfg(target_os = "macos")] +#[test] +fn an_unreadable_file_with_listable_attributes_is_not_replaced() -> io::Result<()> { + let d = TempDir::new("acl_denied_xattrs"); + let p = d.0.join("doc.craft"); + std::fs::write(&p, ORIGINAL)?; + rustix::fs::setxattr(&p, "com.craft.t", b"tag", rustix::fs::XattrFlags::empty())?; + let denied = std::process::Command::new("/bin/chmod").arg("+a").arg("everyone deny read").arg(&p).status()?; + assert!(denied.success(), "the ACL is set"); + let result = atomic_write(&p, b"new"); + let _ = std::process::Command::new("/bin/chmod").arg("-N").arg(&p).status(); + assert!(result.is_err(), "the save is refused"); + assert_eq!(std::fs::read(&p)?, ORIGINAL, "the original is unchanged"); + assert!(xattr_names(&p).iter().any(|n| n == b"com.craft.t"), "and keeps its attribute"); + Ok(()) +} diff --git a/crates/automation/Cargo.toml b/crates/automation/Cargo.toml index eaa5dc2dfe..7fd0ce225b 100644 --- a/crates/automation/Cargo.toml +++ b/crates/automation/Cargo.toml @@ -46,15 +46,15 @@ egui = { workspace = true, optional = true } png = "0.17" serde = { workspace = true } serde_json = { workspace = true } +craft-platform = { workspace = true } +log = "0.4" # `std::time::Instant` panics on wasm; this is the same type on native. web-time = "1.1" # The server, client, token files, profiler and trace. [target.'cfg(not(target_arch = "wasm32"))'.dependencies] -craft-platform = { workspace = true } getrandom = "0.3" hmac = "0.12" -log = "0.4" sha2 = { version = "0.10", default-features = false, features = ["std"] } thiserror = { workspace = true } diff --git a/crates/automation/README.md b/crates/automation/README.md index d82a01e5b5..2fdbf75be4 100644 --- a/crates/automation/README.md +++ b/crates/automation/README.md @@ -14,7 +14,8 @@ Features: `ui` (the egui parts), `agents` (agents in the open window: the launch | `security` | Tokens (`generate_token`, `validate_token`, `server_token`, `client_token`), the authentication handshake (`ServerHandshake`: the challenge handshake, which never sends the token, or the one-frame `auth {token}`), bounded line reads, connection and request limits. | | `protocol` | The JSON-lines wire format: one `{"id", "method", "params"}` request per line, one `{"id", "ok", "result" | "error"}` reply per line; `Params` validators that name the bad parameter. | | `control` | `ControlRequest`, `Reply`, `Dispatch` and `ControlChannel`: the UI-thread side that drains requests between frames, replies after injected input or a background job settles, and admits screenshots. The app supplies the method table. | -| `synthetic` | `Click`, `KeyPress` and `move_from_params`: the validated parameters of `ui.click`, `ui.move` and `ui.key`, and `input_method`'s `ui.ime` `{preedit, cursor}` and `{commit}` forms, queued through `WindowHost::inject_*` one step per pass. | +| `synthetic` | `Click`, `Move`, `Wheel`, `KeyPress` and `Release`: the validated parameters of `ui.click`, `ui.move`, `ui.wheel` (`unit: "points"` or `"lines"`), `ui.key` and `ui.release`, each point a screen point, a document point or a `control` target, and `input_method`'s `ui.ime` `{preedit, cursor}` and `{commit}` forms, queued through `WindowHost::inject_*` one step per pass. | +| `access` | Named controls over the window's access tree (`ui` feature): `Target` (`{name, role?, within?, index?}`, found in reading order), `describe`, and `access_method`, which answers `ui.find` from the tree `ControlChannel::poll_input` has the host keep. | | `server` | `listen` (bind a port) and `serve` (a listener bound earlier): the loopback TCP server that authenticates each connection and forwards requests to the channel, until its `Listening` is dropped. | | `client` | `ControlClient`: connect, authenticate, call (a screenshot is `call("ui.screenshot", ..)`); for integration tests and CLIs. | | `screenshot` | `Captures`: the bounded, cancellable screenshot queue over `WindowHost::screenshot`, with settling, geometry epochs, retries and the PNG reply. | diff --git a/crates/automation/src/access.rs b/crates/automation/src/access.rs index 6caa1ab131..d25f93d112 100644 --- a/crates/automation/src/access.rs +++ b/crates/automation/src/access.rs @@ -1,5 +1,5 @@ -//! `ui.inspect`: the reported widgets of a window's access tree, and the lookup of the one node a click or a focus -//! names. +//! 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, @@ -9,18 +9,57 @@ use std::collections::HashSet; use craft_behavior::Mixed; use craft_ui::runtime::access::Role; -use craft_ui::runtime::egui::access::{AccessTree, Declared, NodeKey}; +use craft_ui::runtime::egui::access::{AccessTree, Declared, NodeKey, name}; use craft_ui::runtime::windows::WindowHost; -use egui::ViewportId; +use egui::{Rect, ViewportId}; use serde_json::{Map, Value, json}; use crate::protocol::Params; +/// The error of a request made before the first kept pass has an access tree. +pub const NO_TREE: &str = "no accessibility tree yet: send the request after a frame was drawn"; + +/// The error of a target no control matches. +pub const NO_CONTROL: &str = "no control matches"; + +/// The error of a target several controls match, with no `index`. +pub const AMBIGUOUS: &str = "more than one control matches"; + +/// The error of a control with no bounds to place a point on. +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 error of a request that needs the access tree before the window presented a frame with one. -pub const NO_TREE: &str = "no accessibility tree yet; draw a frame first"; +/// 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; + +/// A control named by `{name, role?, within?, index?}`. +/// +/// A name match ignores surrounding white space and one trailing `:`; `role` is an AccessKit role name, compared +/// ignoring case; `within` is the name of any matching ancestor. Without `index` exactly one control matches; the +/// reading order is depth first. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub struct Target { + /// The control's accessible name. + pub name: String, + /// The control's role. + pub role: Option, + /// The name of an ancestor the control is inside. + pub within: Option, + /// Which match to take, in reading order. + pub index: Option, +} + +/// `text` as a name is compared: without surrounding white space and one trailing `:`. +fn plain(text: &str) -> &str { + let text = text.trim(); + text.strip_suffix(':').unwrap_or(text).trim() +} /// The node a method names: its id or its label. #[derive(Clone, Debug, PartialEq, Eq)] @@ -133,6 +172,136 @@ fn role_name(tree: &AccessTree, key: NodeKey) -> Option { } } +impl Target { + /// The target `value` names: `{name, role?, within?, index?}` and no other field. + pub fn from_params(value: &Value) -> Result { + let p = Params(value).only(None, &["name", "role", "within", "index"])?; + let p = Params(&p); + let target = p.str_field("name")?.ok_or_else(|| "missing `name`".to_owned())?; + if target.trim().is_empty() { + return Err("`name` must not be empty".into()); + } + let index = match p.uint_field("index")? { + Some(index) if index > MAX_INDEX as u64 => return Err(format!("`index` must be at most {MAX_INDEX} (got {index})")), + index => index.map(|index| index as usize), + }; + Ok(Self { name: target.to_owned(), role: p.str_field("role")?.map(str::to_owned), within: p.str_field("within")?.map(str::to_owned), index }) + } + + /// Whether the control `key` has this target's name, role and ancestor. + fn accepts(&self, tree: &AccessTree, key: NodeKey) -> bool { + let named = |key: NodeKey, wanted: &str| name(tree, key).is_some_and(|found| plain(found) == plain(wanted)); + if !named(key, &self.name) { + return false; + } + if self.role.as_deref().is_some_and(|wanted| !role_name(tree, key).is_some_and(|role| role.eq_ignore_ascii_case(wanted))) { + return false; + } + let Some(within) = self.within.as_deref() else { return true }; + let mut above = tree.parent_of_key(key); + while let Some(ancestor) = above { + if named(ancestor, within) { + return true; + } + above = tree.parent_of_key(ancestor); + } + false + } + + /// The error of no control matching, with the fields the target gave. + fn missing(&self) -> String { + let mut error = format!("{NO_CONTROL}: name `{}`", self.name); + if let Some(role) = &self.role { + error.push_str(&format!(" role `{role}`")); + } + if let Some(within) = &self.within { + error.push_str(&format!(" within `{within}`")); + } + if let Some(index) = self.index { + error.push_str(&format!(" index {index}")); + } + error + } + + /// The control of `tree` this target names: [`NO_CONTROL`] when none matches, [`AMBIGUOUS`] when several do and + /// there is no `index`. + pub fn find(&self, tree: &AccessTree) -> Result { + let reported: HashSet = tree.keys().into_iter().collect(); + let mut matches = Vec::new(); + let mut pending: Vec = tree.root_key().into_iter().collect(); + while let Some(key) = pending.pop() { + if reported.contains(&key) && self.accepts(tree, key) { + matches.push(key); + } + pending.extend(tree.children_of(key).into_iter().rev()); + } + match (self.index, matches.as_slice()) { + (_, []) => Err(self.missing()), + (Some(index), found) => found.get(index).copied().ok_or_else(|| format!("index {index} is past the {} matching controls", found.len())), + (None, [only]) => Ok(*only), + (None, found) => Err(format!("{AMBIGUOUS} ({}): add `role`, `within` or `index`", found.len())), + } + } + + /// The rect of this target's control in the tree the host kept for `viewport`: [`NO_TREE`] before the first, + /// [`NO_PLACE`] for a control with no area. + pub fn rect(&self, host: &WindowHost, viewport: ViewportId) -> Result { + let tree = host.access_tree(viewport).ok_or_else(|| NO_TREE.to_owned())?; + tree.bounds_of(self.find(&tree)?) + .filter(|rect| rect.is_finite() && rect.width() > 0.0 && rect.height() > 0.0) + .ok_or_else(|| NO_PLACE.to_owned()) + } +} + +/// What `ui.find` answers for the control `key`: `{name, role, rect or null, enabled, focused, value?, numeric?, +/// expanded?, selected?, toggled?}`, the rect in screen points. +pub fn describe(tree: &AccessTree, key: NodeKey) -> Value { + let mut out = Map::new(); + out.insert("name".into(), json!(name(tree, key))); + out.insert("role".into(), json!(role_name(tree, key))); + out.insert("rect".into(), json!(tree.bounds_of(key).map(|rect| [rect.left(), rect.top(), rect.width(), rect.height()]))); + out.insert("enabled".into(), json!(!tree.is_disabled_key(key))); + out.insert("focused".into(), json!(tree.focused_key() == key)); + if let Some(value) = tree.value_of(key) { + out.insert("value".into(), json!(value)); + } + if let Some(numeric) = tree.numeric_of(key) { + out.insert("numeric".into(), json!({"value": numeric.value, "range": [numeric.range.start(), numeric.range.end()], "step": numeric.step})); + } + if let Some(expanded) = tree.expanded_of(key) { + out.insert("expanded".into(), json!(expanded)); + } + if let Some(selected) = tree.selected_of(key) { + out.insert("selected".into(), json!(selected)); + } + if let Some(toggled) = tree.toggled_of(key) { + out.insert( + "toggled".into(), + match toggled { + Mixed::Same(on) => json!(on), + Mixed::Mixed => json!("mixed"), + }, + ); + } + Value::Object(out) +} + +/// Runs the access method `method` with `params` in `viewport` from the tree the host kept ([`NO_TREE`] before the +/// first); `None` for a method this module does not have. +pub fn access_method(method: &str, params: &Value, host: &WindowHost, viewport: ViewportId) -> Option> { + match method { + "ui.find" => Some(find(params, host, viewport)), + _ => None, + } +} + +/// `ui.find`: the description of the control `params` names. +fn find(params: &Value, host: &WindowHost, viewport: ViewportId) -> Result { + let target = Target::from_params(params)?; + let tree = host.access_tree(viewport).ok_or_else(|| NO_TREE.to_owned())?; + Ok(describe(&tree, target.find(&tree)?)) +} + /// One listed widget: `{id, role, depth, enabled, clickable, focusable}` and, where the node says, `label`, `value`, /// `description`, `rect` (`[x0, y0, x1, y1]` in points), `toggled` (`true`, `false` or `mixed`), `selected`, and /// `focused: true` for the focused node. The id is a decimal string: 64-bit ids do not survive JSON readers that use diff --git a/crates/automation/src/actions/file.rs b/crates/automation/src/actions/file.rs index 845fd82a0e..3553932c91 100644 --- a/crates/automation/src/actions/file.rs +++ b/crates/automation/src/actions/file.rs @@ -22,6 +22,12 @@ pub struct ActionsFile { /// Sets that hold no action. #[serde(default, skip_serializing_if = "Vec::is_empty")] pub sets: Vec, + /// Every set name in display order, empty sets included. Written only when loading `actions` + /// and `sets` would not give this order (the actions' sets in order of first appearance, then + /// the empty sets), so files in that natural order, PhotoCraft's included, save unchanged. + /// Files without it load in the natural order. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub set_order: Vec, /// The folder occurrences a PhotoCraft file carried; empty for every other file. #[serde(skip)] pub(super) occurrences: FileOccurrences, @@ -55,6 +61,8 @@ struct RawFile { #[serde(default)] sets: Vec, #[serde(default)] + set_order: Vec, + #[serde(default)] set_rows: Vec, } @@ -71,7 +79,7 @@ impl From for ActionsFile { let (actions, occurrences): (Vec, Vec) = raw.actions.into_iter().map(|raw| (raw.action, raw.occurrence)).unzip(); let empty = raw.set_rows.is_empty() && occurrences.iter().all(|occurrence| *occurrence == ActionOccurrence::default()); let occurrences = if empty { FileOccurrences::default() } else { FileOccurrences { set_rows: raw.set_rows, actions: occurrences } }; - ActionsFile { version: raw.version, actions, sets: raw.sets, occurrences } + ActionsFile { version: raw.version, actions, sets: raw.sets, set_order: raw.set_order, occurrences } } } @@ -117,7 +125,7 @@ impl ActionsFile { /// A file of version [`VERSION`](Self::VERSION) with `actions` and the empty `sets`. pub fn new(actions: Vec, sets: Vec) -> Self { - ActionsFile { version: Self::VERSION, actions, sets, occurrences: FileOccurrences::default() } + ActionsFile { version: Self::VERSION, actions, sets, set_order: Vec::new(), occurrences: FileOccurrences::default() } } /// Reads a file's JSON text. diff --git a/crates/automation/src/actions/list.rs b/crates/automation/src/actions/list.rs index 9415f9d850..ce533f7469 100644 --- a/crates/automation/src/actions/list.rs +++ b/crates/automation/src/actions/list.rs @@ -83,9 +83,9 @@ struct LibrarySnapshot { } /// The recorded actions: one flat list (PhotoCraft's engine, journal and file are flat), each -/// action with an optional set name, plus the names of sets that hold no action yet, so New Set -/// works before anything is recorded into it (VectorCraft's nested sets map onto -/// it). +/// action with an optional set name, plus the order of every set, with or without actions, so New +/// Set works before anything is recorded into it and a set keeps its place as it fills and empties +/// (VectorCraft's nested sets map onto it). /// /// The list is app data shared by the panel, the app's commands, the CLI and the control channel: /// the panel only reads it and reports events, and the app applies each event with these calls @@ -123,12 +123,11 @@ impl ActionList { self.actions.get(index) } - /// Every set name in display order: sets of actions in order of first appearance, then the - /// empty sets in the order they were made. + /// Every set name in display order: the order sets were made or loaded, with or without actions. + /// A set an action names that the order lacks follows, by first appearance. pub fn sets(&self) -> Vec<&str> { - let mut sets: Vec<&str> = Vec::new(); - let named = self.actions.iter().filter_map(|action| action.set.as_deref()); - for set in named.chain(self.sets.iter().map(String::as_str)) { + let mut sets: Vec<&str> = self.sets.iter().map(String::as_str).collect(); + for set in self.actions.iter().filter_map(|action| action.set.as_deref()) { if !sets.contains(&set) { sets.push(set); } @@ -183,6 +182,9 @@ impl ActionList { if self.name_in_use(name) { return Err(ActionListError::NameTaken(name.to_owned())); } + if let Some(set) = &set { + self.record_set(set); + } self.actions.push(Action { set, ..Action::new(name, Vec::new()) }); self.touch(); Ok(self.actions.len() - 1) @@ -227,7 +229,7 @@ impl ActionList { Ok(()) } - /// Removes and returns the action at `index`. + /// Removes and returns the action at `index`; the set it leaves empty stays, in its place. pub fn delete_action(&mut self, index: usize) -> Result { if index >= self.actions.len() { return Err(ActionListError::NoSuchAction(index)); @@ -270,22 +272,29 @@ impl ActionList { } /// Puts the action at `index` into `set` (`None`: out of any set), as a drop into or out of a - /// set folder does. + /// set folder does. A new set goes at the end of the order; the set the action leaves stays, in + /// its place, even when it is now empty. pub fn assign_set(&mut self, index: usize, set: Option) -> Result<(), ActionListError> { - let target = self.actions.get_mut(index).ok_or(ActionListError::NoSuchAction(index))?; + if index >= self.actions.len() { + return Err(ActionListError::NoSuchAction(index)); + } let set = match set { None => None, Some(set) if set.trim().is_empty() => return Err(ActionListError::EmptyName), Some(set) => Some(set.trim().to_owned()), }; - target.set = set; + if let Some(set) = &set { + self.record_set(set); + } + self.actions[index].set = set; self.touch(); Ok(()) } /// Moves step `step` of action `from` to position `to` of action `into` (the same action or /// another). Within one action `disabled` and `dialogs` follow [`moved_index`]; between - /// actions the step takes its include and dialog flags along. + /// actions the step takes its include and dialog flags along. A set never changes: one whose last + /// step moves away keeps its place. pub fn move_step(&mut self, from: usize, step: usize, into: usize, to: usize) -> Result<(), ActionListError> { let source = self.actions.get(from).ok_or(ActionListError::NoSuchAction(from))?; if step >= source.steps.len() { @@ -400,6 +409,17 @@ impl ActionList { Ok(()) } + /// Replaces the app's own options of the action at `index` ([`Action::options`]). Setting the options it holds + /// changes nothing, so the revision stays. + pub fn set_options(&mut self, index: usize, options: serde_json::Map) -> Result<(), ActionListError> { + let action = self.actions.get_mut(index).ok_or(ActionListError::NoSuchAction(index))?; + if action.options != options { + action.options = options; + self.touch(); + } + Ok(()) + } + /// Appends a whole action and returns its index; an empty or taken name is refused. pub fn push(&mut self, action: Action) -> Result { if action.name.trim().is_empty() { @@ -408,6 +428,9 @@ impl ActionList { if self.name_in_use(&action.name) { return Err(ActionListError::NameTaken(action.name)); } + if let Some(set) = &action.set { + self.record_set(set); + } self.actions.push(action); self.touch(); Ok(self.actions.len() - 1) @@ -457,17 +480,57 @@ impl ActionList { Ok(()) } + /// Renames the set `set` to `name` (trimmed) in the order and in every member's `set`: [`ActionListError::EmptyName`] + /// for an empty name, [`ActionListError::NameTaken`] for a name another set has, [`ActionListError::NoSuchSet`] for an + /// unknown set. The same name succeeds and changes nothing. + pub fn rename_set(&mut self, set: &str, name: &str) -> Result<(), ActionListError> { + let name = name.trim(); + if name.is_empty() { + return Err(ActionListError::EmptyName); + } + let order: Vec = self.sets().into_iter().map(str::to_owned).collect(); + let at = order.iter().position(|each| each == set).ok_or_else(|| ActionListError::NoSuchSet(set.to_owned()))?; + if name == set { + return Ok(()); + } + if order.iter().any(|each| each == name) { + return Err(ActionListError::NameTaken(name.to_owned())); + } + self.sets = order; + self.sets[at] = name.to_owned(); + for action in self.actions.iter_mut().filter(|action| action.set.as_deref() == Some(set)) { + action.set = Some(name.to_owned()); + } + self.touch(); + Ok(()) + } + + /// Removes the set `set` from the order and its actions from the list, and returns the actions in list order: + /// [`ActionListError::NoSuchSet`] for an unknown set. + pub fn delete_set(&mut self, set: &str) -> Result, ActionListError> { + if !self.sets().contains(&set) { + return Err(ActionListError::NoSuchSet(set.to_owned())); + } + let (removed, kept): (Vec, Vec) = + std::mem::take(&mut self.actions).into_iter().partition(|action| action.set.as_deref() == Some(set)); + self.actions = kept; + self.sets.retain(|each| each != set); + self.touch(); + Ok(removed) + } + /// Duplicates the set `set` under a unique name and returns that name; `shift` is as for - /// [`duplicate_action`](Self::duplicate_action). The copies of its actions go after its last - /// action; a set with none becomes an empty set after it. + /// [`duplicate_action`](Self::duplicate_action). The new set goes right after `set` in the order; + /// the copies of its actions go after its last action, and a set with none gives an empty set. pub fn duplicate_set(&mut self, set: &str, mut shift: impl FnMut(&mut ActionStep, usize, usize)) -> Result { + let mut order: Vec = self.sets().into_iter().map(str::to_owned).collect(); + let position = order.iter().position(|each| each == set).ok_or_else(|| ActionListError::NoSuchSet(set.to_owned()))?; + let name = Names::new(order.iter().cloned()).claim(&format!("{set} copy")); + order.insert(position + 1, name.clone()); + self.sets = order; let members: Vec = (0..self.actions.len()).filter(|&i| self.actions[i].set.as_deref() == Some(set)).collect(); - let name = Names::new(self.sets().into_iter().map(str::to_owned)).claim(&format!("{set} copy")); - if members.is_empty() { - let position = self.sets.iter().position(|each| each == set).ok_or_else(|| ActionListError::NoSuchSet(set.to_owned()))?; - self.sets.insert(position + 1, name.clone()); - } else { - let at = members[members.len() - 1] + 1; + if let Some(&last) = members.last() { + let at = last + 1; // Each copy's name is claimed before the next, so the copies never repeat one. let mut names = Names::of(&self.actions); for (offset, &source) in members.iter().enumerate() { @@ -513,12 +576,13 @@ impl ActionList { /// actions sharing a name, the file's shortcut owner keeps the name. The stored ids come back /// in [`MergedFile::ids`]. pub fn merge_file(&mut self, file: ActionsFile, replace: bool, mut calls: impl FnMut(&mut ActionStep, &[(String, String)])) -> MergedFile { - let ActionsFile { mut actions, sets, occurrences, .. } = file; + let ActionsFile { mut actions, sets, set_order, occurrences, .. } = file; if replace { let named: BTreeSet<&str> = actions .iter() .filter_map(|action| action.set.as_deref()) .chain(sets.iter().map(String::as_str)) + .chain(set_order.iter().map(String::as_str)) .chain(occurrences.set_rows.iter().map(String::as_str)) .collect(); self.actions.retain(|action| !action.set.as_deref().is_some_and(|set| named.contains(set))); @@ -533,6 +597,9 @@ impl ActionList { for (&i, name) in order.iter().zip(claimed) { given[i] = name; } + for set in &set_order { + self.record_set(set); + } let mut merged = MergedFile::default(); let ids = file_ids(&occurrences.actions); for (index, (mut action, name)) in actions.into_iter().zip(given).enumerate() { @@ -543,6 +610,9 @@ impl ActionList { merged.ids.push((id.clone(), name.clone())); } action.name = name; + if let Some(set) = &action.set { + self.record_set(set); + } self.actions.push(action); merged.added.push(self.actions.len() - 1); } @@ -552,9 +622,7 @@ impl ActionList { } } for set in empty_sets { - if !self.sets().contains(&set.as_str()) { - self.sets.push(set); - } + self.record_set(&set); } self.touch(); merged @@ -693,10 +761,27 @@ impl ActionList { self.touch(); } - /// The list as a file (version [`ActionsFile::VERSION`]; the empty sets in `sets`). + /// The list as a file (version [`ActionsFile::VERSION`]; the empty sets in `sets`, the set order in `set_order` when it is not the natural one). pub fn to_file(&self) -> ActionsFile { let empty = self.sets().into_iter().filter(|set| !self.actions.iter().any(|action| action.set.as_deref() == Some(*set))); - ActionsFile::new(self.actions.clone(), empty.map(str::to_owned).collect()) + let mut file = ActionsFile::new(self.actions.clone(), empty.map(str::to_owned).collect()); + let mut natural: Vec<&str> = Vec::new(); + for set in self.actions.iter().filter_map(|action| action.set.as_deref()).chain(file.sets.iter().map(String::as_str)) { + if !natural.contains(&set) { + natural.push(set); + } + } + if natural != self.sets() { + file.set_order = self.sets().into_iter().map(str::to_owned).collect(); + } + file + } + + /// Puts `set` at the end of the set order when the order lacks it. + fn record_set(&mut self, set: &str) { + if !self.sets.iter().any(|each| each == set) { + self.sets.push(set.to_owned()); + } } /// Whether an action has `name`. diff --git a/crates/automation/src/actions/model.rs b/crates/automation/src/actions/model.rs index 247d9f4d1a..09b3b6df1b 100644 --- a/crates/automation/src/actions/model.rs +++ b/crates/automation/src/actions/model.rs @@ -161,6 +161,10 @@ pub struct Action { /// Written by an automation client: playback keeps that client's gate. #[serde(default, skip_serializing_if = "std::ops::Not::not")] pub automation: bool, + /// The app's own options for the action. The framework never reads them; every edit, duplicate, move, merge and + /// the file keep them. + #[serde(default, skip_serializing_if = "serde_json::Map::is_empty")] + pub options: serde_json::Map, } fn is_no_color(color: &ActionColor) -> bool { diff --git a/crates/automation/src/actions/tests.rs b/crates/automation/src/actions/tests.rs index 9e5bfc1e90..2ae7845e9f 100644 --- a/crates/automation/src/actions/tests.rs +++ b/crates/automation/src/actions/tests.rs @@ -80,6 +80,22 @@ fn action_list_file_round_trip_keeps_pc_json() { assert_eq!(back.sets, ["Empty"]); assert_eq!(ActionList::from_file(back).sets(), ["S", "Empty"]); } +// An empty set made before filled ones keeps its place through a save; a file of the older layout +// (empty sets in `sets`, no `set_order`) loads with its filled sets first. +#[trial] +fn set_order_survives_the_file() { + let mut list = ActionList::new(); + list.new_set("A").unwrap(); + list.new_set("B").unwrap(); + list.new_set("C").unwrap(); + list.push(Action { set: Some("B".into()), ..action("X", &[]) }).unwrap(); + list.push(Action { set: Some("C".into()), ..action("Y", &[]) }).unwrap(); + let back = ActionList::from_file(ActionsFile::from_json(&list.to_file().to_json().unwrap()).unwrap()); + assert_eq!(back.sets(), ["A", "B", "C"]); + + let old = r#"{"version":1,"actions":[{"name":"X","steps":[],"set":"F"}],"sets":["E"]}"#; + assert_eq!(ActionList::from_file(ActionsFile::from_json(old).unwrap()).sets(), ["F", "E"]); +} // A file that repeats a name keeps a later action's own name: `Foo, Foo, Foo 2` renames the repeat // (`Foo 3`), never the real `Foo 2`; a merge does the same against the names already in the list. #[trial] @@ -271,3 +287,81 @@ fn action_player_charges_a_shared_budget_and_detects_loops() { } assert_eq!(deep.enter("more"), Err(PlaybackRefusal::TooDeep)); } + +// A set keeps its place as it gets its first action and loses its last; a duplicate goes right after its source; +// rename keeps the place and moves the members and refuses empty, taken and unknown names; delete returns the members +// in list order. +#[trial] +fn sets_keep_their_place_as_they_fill_empty_rename_and_go() { + let mut list = ActionList::new(); + for set in ["A", "B", "C"] { + list.new_set(set).unwrap(); + } + list.new_action("x", Some("B".into())).unwrap(); + assert_eq!(list.sets(), ["A", "B", "C"], "B keeps its place when it gets its first action"); + list.delete_action(0).unwrap(); + assert_eq!(list.sets(), ["A", "B", "C"], "B keeps its place when it loses its last"); + + assert_eq!(list.duplicate_set("A", |_, _, _| {}).unwrap(), "A copy"); + list.new_action("y", Some("B".into())).unwrap(); + assert_eq!(list.duplicate_set("B", |_, _, _| {}).unwrap(), "B copy"); + list.new_action("z", Some("B".into())).unwrap(); + assert_eq!(list.sets(), ["A", "A copy", "B", "B copy", "C"], "a copy follows its source, with or without actions"); + + let revision = list.revision(); + list.rename_set("B", "B").unwrap(); + assert_eq!(list.revision(), revision, "the same name changes nothing"); + assert_eq!(list.rename_set("B", " "), Err(ActionListError::EmptyName)); + assert_eq!(list.rename_set("B", "C"), Err(ActionListError::NameTaken("C".into()))); + assert_eq!(list.rename_set("Nope", "Z"), Err(ActionListError::NoSuchSet("Nope".into()))); + assert_eq!(list.revision(), revision, "a refused rename changes nothing"); + list.rename_set("B", " Beta ").unwrap(); + assert_eq!(list.sets(), ["A", "A copy", "Beta", "B copy", "C"]); + let members = list.actions().iter().filter(|action| action.set.as_deref() == Some("Beta")).count(); + assert_eq!(members, 2, "the members follow the rename"); + + let gone = list.delete_set("Beta").unwrap(); + assert_eq!(gone.iter().map(|action| action.name.as_str()).collect::>(), ["y", "z"]); + assert_eq!(list.sets(), ["A", "A copy", "B copy", "C"]); + assert_eq!(list.actions().len(), 1); + assert_eq!(list.delete_set("Beta"), Err(ActionListError::NoSuchSet("Beta".into()))); +} + +// An option of an action stays with it through a duplicate, a set duplicate, a step move, the file and a merge. +#[trial] +fn app_options_ride_with_an_action_through_edits_and_files() { + let mut base = action("A", &["a", "b"]); + base.set = Some("S".into()); + base.options.insert("key".into(), json!(3)); + let mut list = list_of(vec![base]); + list.duplicate_action(0, |_, _, _| {}).unwrap(); + list.duplicate_set("S", |_, _, _| {}).unwrap(); + list.move_step(0, 0, 0, 1).unwrap(); + assert_eq!(list.actions().len(), 4); + assert!(list.actions().iter().all(|action| action.options.get("key") == Some(&json!(3)))); + + let text = list.to_file().to_json().unwrap(); + assert!(text.contains("\"options\"")); + let loaded = ActionList::from_file(ActionsFile::from_json(&text).unwrap()); + assert!(loaded.actions().iter().all(|action| action.options.get("key") == Some(&json!(3)))); + let mut merged = ActionList::new(); + merged.merge_file(ActionsFile::from_json(&text).unwrap(), false, |_, _| {}); + assert!(merged.actions().iter().all(|action| action.options.get("key") == Some(&json!(3)))); +} + +// An action's options are set in the list, kept through a duplicate and the file, and the same options or an unknown +// action change nothing. +#[trial] +fn an_actions_options_are_set_and_kept_through_a_duplicate_and_the_file() { + let mut list = list_of(vec![action("a", &["one"])]); + let options = json!({"key": "F5", "automaticAlignTo": "artboard"}).as_object().cloned().unwrap(); + list.set_options(0, options.clone()).unwrap(); + assert_eq!(list.action(0).unwrap().options, options); + let revision = list.revision(); + list.set_options(0, options.clone()).unwrap(); + assert_eq!(list.revision(), revision, "the options it holds change nothing"); + assert_eq!(list.set_options(7, serde_json::Map::new()), Err(ActionListError::NoSuchAction(7))); + let copy = list.duplicate_action(0, |_, _, _| {}).unwrap(); + assert_eq!(list.action(copy).unwrap().options, options, "a duplicate keeps them"); + assert_eq!(ActionList::from_file(list.to_file()).action(0).unwrap().options, options, "the file keeps them"); +} diff --git a/crates/automation/src/client.rs b/crates/automation/src/client.rs index d84125f58a..7d6ca67e72 100644 --- a/crates/automation/src/client.rs +++ b/crates/automation/src/client.rs @@ -1,6 +1,6 @@ //! A JSON-lines client for integration tests and CLIs. -use std::io::{BufRead, BufReader, Write}; +use std::io::{BufRead, BufReader, Read, Write}; use std::net::SocketAddr; use serde_json::{Value, json}; @@ -12,6 +12,12 @@ use crate::security::{AUTH_METHOD, IO_TIMEOUT}; /// server's own timeout error arrives before the client gives up. pub const CALL_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(REPLY_DEADLINE.as_secs() + 5); +/// How long [`ControlClient::connect`] waits for the connection: 800 ms, as the server is on loopback only. +pub const CONNECT_TIMEOUT: std::time::Duration = std::time::Duration::from_millis(800); + +/// The longest reply line a client reads: 256 MiB. A longer one is an error and closes the connection. +pub const MAX_REPLY_BYTES: u64 = 256 << 20; + /// Why [`ControlClient::connect`] failed. #[derive(Clone, Debug, PartialEq, Eq)] #[non_exhaustive] @@ -47,20 +53,53 @@ impl ControlClient { self.broken } + /// Whether a call can be sent now: false when the connection is broken, the server closed it, + /// or it holds bytes no call asked for (a server that says why it closes), as no reply to the + /// next call could be read from it. Every call checks this before it sends and, when false, + /// closes the connection and fails with nothing sent; a caller reconnects instead. + pub fn is_usable(&self) -> bool { + if self.broken || !self.reader.buffer().is_empty() || self.stream.set_nonblocking(true).is_err() { + return false; + } + let probe = self.stream.peek(&mut [0]); + self.stream.set_nonblocking(false).is_ok() && probe.is_err_and(|e| e.kind() == std::io::ErrorKind::WouldBlock) + } + /// Connect (read timeout [`CALL_TIMEOUT`]), send /// `{"id": 1, "method": "auth", "params": {"token": token}}` and read one reply line; `Err` with /// the reply's `error` text as `Refused` when it isn't `ok`, or the I/O error's message as `Transport`. + /// A line the server wrote before the request (a refusal at accept) is the reply, and nothing is sent. pub fn connect(addr: SocketAddr, token: &str) -> Result { let io = |e: std::io::Error| ConnectError::Transport(e.to_string()); - let stream = std::net::TcpStream::connect(addr).map_err(io)?; - stream.set_read_timeout(Some(CALL_TIMEOUT)).map_err(io)?; - stream.set_write_timeout(Some(IO_TIMEOUT)).map_err(io)?; - let reader = BufReader::new(stream.try_clone().map_err(io)?); - let mut client = Self { stream, broken: false, reader, next_id: 2 }; - // `exchange` marks the client broken on a transport failure only, so an error reply is a refusal. - let auth = client.exchange(1, AUTH_METHOD, json!({"token": token})); - auth.map_err(|e| if client.broken { ConnectError::Transport(e) } else { ConnectError::Refused(e) })?; - Ok(client) + let stream = std::net::TcpStream::connect_timeout(&addr, CONNECT_TIMEOUT).map_err(io)?; + Self::over(stream).map_err(io)?.sign_in(token) + } + + /// A client over a connected `stream`, not yet signed in. + fn over(stream: std::net::TcpStream) -> std::io::Result { + stream.set_read_timeout(Some(CALL_TIMEOUT))?; + stream.set_write_timeout(Some(IO_TIMEOUT))?; + let reader = BufReader::new(stream.try_clone()?); + Ok(Self { stream, broken: false, reader, next_id: 2 }) + } + + /// Sends the sign-in and reads its answer. A server that refuses the connection at once (over its connection + /// limit) writes why before any request: that line answers the sign-in, which is then not sent, so only its + /// error counts. + fn sign_in(mut self, token: &str) -> Result { + let auth = if self.is_usable() { + self.round_trip(1, AUTH_METHOD, json!({"token": token}), None) + } else { + self.read_reply(1, None).and_then(|_| Err(Failure::Io("reply before the sign-in".into()))) + }; + match auth { + Ok(_) => Ok(self), + Err(Failure::Reply(why)) => Err(ConnectError::Refused(why)), + Err(Failure::Io(why)) => { + self.close(); + Err(ConnectError::Transport(why)) + } + } } /// Send `{"id": n, "method", "params"}` as one line (ids count up from 2) and read the reply @@ -68,36 +107,65 @@ impl ControlClient { /// `"ok": true`, `Err(error)` otherwise. After an I/O error or a timeout the connection is /// closed and every later call fails, so a late reply can't answer the wrong call. pub fn call(&mut self, method: &str, params: Value) -> Result { - let id = self.next_id; - self.next_id += 1; - self.exchange(id, method, params) + self.call_with(method, params, None) } - fn exchange(&mut self, id: u64, method: &str, params: Value) -> Result { - if self.broken { + /// As [`ControlClient::call`], but gives up with `Err("cancelled")` and closes the connection when `cancelled()` + /// turns true while it waits for the reply. + pub fn call_until(&mut self, method: &str, params: Value, cancelled: &dyn Fn() -> bool) -> Result { + self.call_with(method, params, Some(cancelled)) + } + + fn call_with(&mut self, method: &str, params: Value, cancelled: Option<&dyn Fn() -> bool>) -> Result { + let id = self.next_id; + self.next_id += 1; + self.exchange(id, method, params, cancelled) + } + + fn exchange(&mut self, id: u64, method: &str, params: Value, cancelled: Option<&dyn Fn() -> bool>) -> Result { + if !self.is_usable() { + self.close(); return Err("connection closed".into()); } - let result = self.round_trip(id, method, params); + let result = self.round_trip(id, method, params, cancelled); if matches!(result, Err(Failure::Io(_))) { - self.broken = true; - let _ = self.stream.shutdown(std::net::Shutdown::Both); + self.close(); } result.map_err(|f| match f { Failure::Io(e) | Failure::Reply(e) => e, }) } - fn round_trip(&mut self, id: u64, method: &str, params: Value) -> Result { + fn close(&mut self) { + self.broken = true; + let _ = self.stream.shutdown(std::net::Shutdown::Both); + } + + fn round_trip(&mut self, id: u64, method: &str, params: Value, cancelled: Option<&dyn Fn() -> bool>) -> Result { let io = |e: std::io::Error| Failure::Io(e.to_string()); writeln!(self.stream, "{}", json!({"id": id, "method": method, "params": params})).map_err(io)?; self.stream.flush().map_err(io)?; + self.read_reply(id, cancelled) + } + + /// Reads reply lines until the one with `id`, or with a null id (the server's answer to an unparseable line or a + /// refused connection). + fn read_reply(&mut self, id: u64, cancelled: Option<&dyn Fn() -> bool>) -> Result { + let io = |e: std::io::Error| Failure::Io(e.to_string()); loop { + if let Some(cancelled) = cancelled { + self.wait_for_reply(cancelled)?; + } let mut line = String::new(); - if self.reader.read_line(&mut line).map_err(io)? == 0 { + let read = (&mut self.reader).take(MAX_REPLY_BYTES + 1).read_line(&mut line).map_err(io)?; + if read == 0 { return Err(Failure::Io("connection closed".into())); } + if read as u64 > MAX_REPLY_BYTES { + return Err(Failure::Io(format!("reply longer than {MAX_REPLY_BYTES} bytes"))); + } let mut reply: Value = serde_json::from_str(&line).map_err(|e| Failure::Io(format!("bad reply: {e}")))?; - // A reply to an earlier request (a null id is the server's answer to an unparseable line). + // A reply to an earlier request. if reply.get("id").is_some_and(|got| !got.is_null() && got != &json!(id)) { continue; } @@ -108,6 +176,36 @@ impl ControlClient { }; } } + + /// Waits until a reply line starts to arrive, asking `cancelled` between short reads, for at most + /// [`CALL_TIMEOUT`]. A cancel is a transport failure, so the connection closes and a late reply can't answer the + /// next call. + fn wait_for_reply(&self, cancelled: &dyn Fn() -> bool) -> Result<(), Failure> { + const POLL: std::time::Duration = std::time::Duration::from_millis(100); + if !self.reader.buffer().is_empty() { + return Ok(()); + } + let io = |e: std::io::Error| Failure::Io(e.to_string()); + let start = std::time::Instant::now(); + self.stream.set_read_timeout(Some(POLL)).map_err(io)?; + let outcome = loop { + match self.stream.peek(&mut [0]) { + Ok(_) => break Ok(()), + Err(e) if matches!(e.kind(), std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut) => { + if cancelled() { + break Err(Failure::Io("cancelled".into())); + } + if start.elapsed() >= CALL_TIMEOUT { + break Err(io(e)); + } + } + Err(e) if e.kind() == std::io::ErrorKind::Interrupted => {} + Err(e) => break Err(io(e)), + } + }; + self.stream.set_read_timeout(Some(CALL_TIMEOUT)).map_err(io)?; + outcome + } } /// Why a round trip failed: the transport (the connection is then unusable) or an error reply. diff --git a/crates/automation/src/client_tests.rs b/crates/automation/src/client_tests.rs index 252841ea64..4718057ea8 100644 --- a/crates/automation/src/client_tests.rs +++ b/crates/automation/src/client_tests.rs @@ -37,3 +37,96 @@ fn replies_are_matched_by_id() { assert!(client.call("b", json!({})).is_err(), "the closed connection fails the call"); assert_eq!(client.call("c", json!({})), Err("connection closed".to_string()), "a failed client stays closed"); } + +// A cancelled wait gives up on a reply that never comes and closes the connection, so a late reply can't answer a +// later call. +#[trial] +fn a_cancelled_call_stops_waiting_and_closes_the_connection() { + use std::io::{BufRead, Write}; + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let (done, wait) = std::sync::mpsc::channel::<()>(); + let server = std::thread::spawn(move || { + let (stream, _) = listener.accept().unwrap(); + let mut reader = std::io::BufReader::new(stream.try_clone().unwrap()); + let mut out = stream; + let mut line = String::new(); + reader.read_line(&mut line).unwrap(); + writeln!(out, "{}", json!({"id": 1, "ok": true})).unwrap(); + // The call is read and never answered while the client waits. + line.clear(); + reader.read_line(&mut line).unwrap(); + wait.recv().unwrap(); + writeln!(out, "{}", json!({"id": 2, "ok": true, "result": "late"})).ok(); + }); + let mut client = ControlClient::connect(addr, TOKEN).unwrap(); + let asked = std::cell::Cell::new(0); + let cancelled = || { + asked.set(asked.get() + 1); + asked.get() > 1 + }; + assert_eq!(client.call_until("slow", json!({}), &cancelled), Err("cancelled".to_string())); + assert!(client.is_broken(), "a cancelled call closes the connection"); + done.send(()).unwrap(); + server.join().unwrap(); + assert_eq!(client.call("next", json!({})), Err("connection closed".to_string()), "the late reply answers nothing"); +} + +// A connection the server closed, or one holding a line no call asked for, is unusable: the next +// call sends nothing and fails, so the caller reconnects instead of reading the wrong answer. +#[trial] +fn an_unasked_line_makes_the_connection_unusable_before_sending() { + use std::io::{BufRead, Write}; + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let (said, wait) = std::sync::mpsc::channel::<()>(); + let server = std::thread::spawn(move || { + let (stream, _) = listener.accept().unwrap(); + let mut reader = std::io::BufReader::new(stream.try_clone().unwrap()); + let mut out = stream; + let mut line = String::new(); + reader.read_line(&mut line).unwrap(); + writeln!(out, "{}", json!({"id": 1, "ok": true})).unwrap(); + wait.recv().unwrap(); + writeln!(out, "{}", json!({"id": null, "ok": false, "error": "idle connection closed"})).unwrap(); + out.flush().unwrap(); + // The client's close shows as an end of input or, with the unread line, a reset. + line.clear(); + reader.read_line(&mut line).ok().filter(|&read| read > 0).map(|_| line) + }); + let mut client = ControlClient::connect(addr, TOKEN).unwrap(); + assert!(client.is_usable(), "an idle connection with nothing pending is usable"); + said.send(()).unwrap(); + let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5); + while client.is_usable() && std::time::Instant::now() < deadline { + std::thread::sleep(std::time::Duration::from_millis(5)); + } + assert!(!client.is_usable(), "the unasked line makes the connection unusable"); + assert_eq!(client.call("next", json!({})), Err("connection closed".to_string())); + assert!(client.is_broken(), "the unusable connection is closed"); + assert_eq!(server.join().unwrap(), None, "the call sent nothing"); +} + +// A server that refuses a connection at accept writes why and closes: the sign-in reads that waiting line as its +// answer, so the caller learns the reason, and sends nothing. +#[trial] +fn a_refusal_waiting_at_sign_in_is_the_reason_connect_gives() { + use std::io::{BufRead, Write}; + let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap(); + let addr = listener.local_addr().unwrap(); + let server = std::thread::spawn(move || { + let (stream, _) = listener.accept().unwrap(); + let mut reader = std::io::BufReader::new(stream.try_clone().unwrap()); + let mut out = stream; + writeln!(out, "{}", json!({"id": null, "ok": false, "error": "connection limit reached"})).unwrap(); + out.flush().unwrap(); + let mut line = String::new(); + reader.read_line(&mut line).ok().filter(|&read| read > 0).map(|_| line) + }); + let stream = std::net::TcpStream::connect(addr).unwrap(); + stream.set_read_timeout(Some(std::time::Duration::from_secs(5))).unwrap(); + assert!(stream.peek(&mut [0]).unwrap() > 0, "the refusal is waiting before the sign-in"); + let signed = ControlClient::over(stream).unwrap().sign_in(TOKEN); + assert_eq!(signed.err(), Some(ConnectError::Refused("connection limit reached".into()))); + assert_eq!(server.join().unwrap(), None, "the sign-in sent nothing"); +} diff --git a/crates/automation/src/control.rs b/crates/automation/src/control.rs index 2fedab3cd5..b1c005dadf 100644 --- a/crates/automation/src/control.rs +++ b/crates/automation/src/control.rs @@ -242,8 +242,10 @@ impl ControlChannel { /// `input cancelled` when the host withdrew queued input ([`TARGET_CHANGED`]), with success /// once nothing is queued or in flight. Call it once per pass, at the end of the pass (after its /// UI ran): the step that pass consumed counts as run, so the reply goes out with that pass - /// ([`WindowHost::injected_idle_at_pass_end`]). Called between passes, it waits for the pass. + /// ([`WindowHost::injected_idle_at_pass_end`]). Called between passes, it waits for the pass. It also has the host + /// keep its access trees, which `control` targets and `ui.find` read. pub fn poll_input(&mut self, host: &WindowHost) { + host.keep_access_trees(); if host.take_injected_withdrawn() { self.input_cancelled(TARGET_CHANGED); } else if host.injected_idle_at_pass_end() { @@ -259,7 +261,8 @@ impl ControlChannel { return; } // `ui.accessTree` takes no window: it reads the main window's tree. - let Some(update) = WindowHost::of(ctx).access_tree(egui::ViewportId::ROOT) else { return }; + let Some(tree) = WindowHost::of(ctx).access_tree(egui::ViewportId::ROOT) else { return }; + let update = tree.update(); let nodes: Vec = update .nodes .iter() diff --git a/crates/automation/src/dialogs.rs b/crates/automation/src/dialogs.rs index 62fc0b268b..398c917c57 100644 --- a/crates/automation/src/dialogs.rs +++ b/crates/automation/src/dialogs.rs @@ -12,6 +12,9 @@ use serde_json::{Value, json}; use crate::protocol::Params; +/// The most `fields` one `ui.dialog.set` call takes. +pub const MAX_DIALOG_FIELDS: usize = 256; + /// The open dialogs, the top one last: `{id, parent, key, fields}`, `null` for a missing parent, key or fields. Ids /// are 64-bit hashes, so they are listed as decimal strings, which every JSON reader keeps exact. pub fn inspect(host: &DialogHost) -> Value { @@ -30,14 +33,15 @@ pub fn inspect(host: &DialogHost) -> Value { /// Runs a `ui.dialog.*` method on `host`; `None` when `method` is not one of them. /// -/// - `ui.dialog.set {dialog, field, value}` sets one field ([`DialogHost::set_json_field`]). +/// - `ui.dialog.set {dialog, field, value}` sets one field ([`DialogHost::set_json_field`]); `{dialog, fields: [{field, +/// value?}]}` sets a list of at most [`MAX_DIALOG_FIELDS`], all or none ([`DialogHost::set_json_fields`]). /// - `ui.dialog.confirm {dialog, choice?}` answers OK, as the default button would, after setting the `choice` field /// when one is given (which button of a prompt). A dialog that holds its OK files it for the app, which answers it. /// - `ui.dialog.cancel {dialog}` closes the dialog as Escape would: a standard prompt with a button for its Escape /// answer gives that answer, with its tag; any other dialog closes with its children with Cancel. pub fn dialog_method(host: &mut DialogHost, ctx: &Context, method: &str, params: &Value) -> Option> { let fields: &[&str] = match method { - "ui.dialog.set" => &["dialog", "field", "value"], + "ui.dialog.set" => &["dialog", "field", "value", "fields"], "ui.dialog.confirm" => &["dialog", "choice"], "ui.dialog.cancel" => &["dialog"], _ => return None, @@ -50,10 +54,18 @@ fn run(host: &mut DialogHost, ctx: &Context, method: &str, params: &Value, field let read = Params(¶ms); let id = dialog_id(host, ¶ms)?; match method { - "ui.dialog.set" => { - let field = read.str_field("field")?.ok_or("missing `field`")?; - host.set_json_field(ctx, id, field, params.get("value").cloned().unwrap_or(Value::Null))?; - } + "ui.dialog.set" => match params.get("fields") { + Some(list) => { + if params.get("field").is_some() || params.get("value").is_some() { + return Err("`fields` takes the place of `field` and `value`".to_owned()); + } + host.set_json_fields(ctx, id, &field_list(list)?)?; + } + None => { + let field = read.str_field("field")?.ok_or("missing `field`")?; + host.set_json_field(ctx, id, field, params.get("value").cloned().unwrap_or(Value::Null))?; + } + }, "ui.dialog.confirm" => { if let Some(choice) = params.get("choice") { host.set_json_field(ctx, id, "choice", choice.clone())?; @@ -81,6 +93,21 @@ fn run(host: &mut DialogHost, ctx: &Context, method: &str, params: &Value, field Ok(Value::Null) } +/// The `(field, value)` pairs of a `fields` list, checked whole before anything is set; a missing `value` is `null`. +fn field_list(list: &Value) -> Result, String> { + let items = list.as_array().ok_or("`fields` is not a list")?; + if items.len() > MAX_DIALOG_FIELDS { + return Err(format!("`fields` holds {} items; at most {MAX_DIALOG_FIELDS}", items.len())); + } + items + .iter() + .map(|item| { + let field = item.get("field").and_then(Value::as_str).ok_or("an item of `fields` has no string `field`")?; + Ok((field.to_owned(), item.get("value").cloned().unwrap_or(Value::Null))) + }) + .collect() +} + /// The open dialog `params.dialog` names: the id `inspect` lists, as a decimal string or a number, or `"top"` for the /// top dialog of the stack. pub fn dialog_id(host: &DialogHost, params: &Value) -> Result { diff --git a/crates/automation/src/lib.rs b/crates/automation/src/lib.rs index 2c004e6dc7..97a14d3103 100644 --- a/crates/automation/src/lib.rs +++ b/crates/automation/src/lib.rs @@ -57,7 +57,6 @@ pub mod server; #[cfg(feature = "ui")] pub use control::{ControlChannel, ControlRequest, ControlResponse, Dispatch, Reply}; -#[cfg(not(target_arch = "wasm32"))] pub use protocol::REPLY_DEADLINE; #[cfg(feature = "ui")] pub use screenshot::Captures; diff --git a/crates/automation/src/server.rs b/crates/automation/src/server.rs index b2f9fdd1d0..c6808156d7 100644 --- a/crates/automation/src/server.rs +++ b/crates/automation/src/server.rs @@ -1,7 +1,7 @@ //! The loopback JSON-lines TCP transport: one request per line, one reply per line. -use std::io::{BufReader, Write}; -use std::net::{SocketAddr, TcpListener, TcpStream}; +use std::io::{BufReader, Read, Write}; +use std::net::{Shutdown, SocketAddr, TcpListener, TcpStream}; use std::sync::Arc; use std::sync::atomic::{AtomicBool, Ordering}; use std::sync::mpsc::{Receiver, Sender, channel}; @@ -89,6 +89,7 @@ pub fn serve_with_deadline( let Some(permit) = limiter.try_acquire() else { let _ = configure_stream(&stream); let _ = writeln!(stream, "{}", json!({"id": null, "ok": false, "error": "connection limit reached"})); + close_after_reply(&stream); continue; }; let tx = tx.clone(); @@ -179,4 +180,27 @@ fn serve_connection(stream: TcpStream, token: &str, tx: &Sender, break; } } + close_after_reply(&out); +} + +/// How long a closing connection's leftover input is read and dropped ([`close_after_reply`]). +const CLOSE_LINGER: Duration = Duration::from_millis(250); + +/// Closes `stream` after its last reply without resetting it: the write side ends first, so the client reads the +/// reply and then the end of the stream, and what the client still sends is read and dropped until it closes too, for +/// at most [`CLOSE_LINGER`]. A socket closed with input unread is reset instead, and the client loses the reply +/// (Linux) or reads the reset where the end of the stream should be (Windows). +fn close_after_reply(mut stream: &TcpStream) { + let _ = stream.shutdown(Shutdown::Write); + let deadline = motion::now() + CLOSE_LINGER; + let mut sink = [0; 1024]; + loop { + let left = deadline.saturating_duration_since(motion::now()); + if left.is_zero() || stream.set_read_timeout(Some(left)).is_err() { + return; + } + if matches!(stream.read(&mut sink), Ok(0) | Err(_)) { + return; + } + } } diff --git a/crates/automation/src/synthetic.rs b/crates/automation/src/synthetic.rs index 6e95677603..bea9c8d5a5 100644 --- a/crates/automation/src/synthetic.rs +++ b/crates/automation/src/synthetic.rs @@ -17,7 +17,8 @@ //! //! Points are screen points (egui points), or document points with `coordinates: "document"`, which the application //! 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. +//! 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 @@ -32,7 +33,7 @@ use craft_ui::runtime::windows::{Released, WindowHost}; use egui::{Pos2, Vec2, ViewportId, pos2, vec2}; use serde_json::Value; -use crate::access::{NodeTarget, inject_click, inject_context_menu, inject_focus}; +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`). @@ -62,22 +63,37 @@ pub const NOT_FINITE: &str = "the point must be finite"; /// when no canvas shows a document. Applications without documents pass `&|_, _| None`. pub type DocumentMap<'a> = &'a dyn Fn(usize, Pos2) -> Option; -/// A point of a request: screen points, or document points the application maps. -#[derive(Clone, Copy, Debug, PartialEq)] +/// A point of a request: screen points, document points the application maps, or an offset from a named control. +#[derive(Clone, Debug, PartialEq)] #[non_exhaustive] pub enum At { /// Screen points. Screen(Pos2), /// Document points on page `page` (0 when the request names none). Document(Pos2, usize), + /// An offset from the centre of the rect of the control `target` names. + #[non_exhaustive] + Control { + /// The control. + target: access::Target, + /// The offset from the rect's centre. + offset: Vec2, + }, } impl At { - /// `x` and `y`, each defaulting to 0, in the space `coordinates` names (`screen`, the default, or `document`). + /// `x` and `y`, each defaulting to 0, in the space `coordinates` names (`screen`, the default, or `document`); with + /// `control` they are an offset in points from the control's centre, and `coordinates` is refused. fn from_params(p: &Params<'_>) -> Result { let range = Some((-MAX_SCREEN_POINT, MAX_SCREEN_POINT)); let x = p.number_in("x", "x", range)?.unwrap_or(0.0) as f32; let y = p.number_in("y", "y", range)?.unwrap_or(0.0) as f32; + if let Some(control) = p.0.get("control") { + if p.0.get("coordinates").is_some() { + return Err("`coordinates` and `control` exclude each other".into()); + } + return Ok(Self::Control { target: access::Target::from_params(control)?, offset: vec2(x, y) }); + } Self::in_space(p, pos2(x, y)) } @@ -97,23 +113,30 @@ impl At { } /// The screen point, through `map` for a document point; [`NO_DOCUMENT`] when the map has none, and - /// [`OFF_SCREEN`] when it maps beyond [`MAX_SCREEN_POINT`]; a point that is not finite is [`NOT_FINITE`]. - pub fn resolve(self, map: DocumentMap<'_>) -> Result { + /// [`OFF_SCREEN`] when it maps beyond [`MAX_SCREEN_POINT`]; a point that is not finite is [`NOT_FINITE`]. A control + /// point is the centre of the rect `controls` gives it plus the offset, or the error `controls` gives. + pub fn resolve(&self, map: DocumentMap<'_>, controls: access::ControlMap<'_>) -> Result { match self { - Self::Screen(at) if at.x.is_finite() && at.y.is_finite() => Ok(at), + Self::Control { target, offset } => Ok(controls(target)?.center() + *offset), + Self::Screen(at) if at.x.is_finite() && at.y.is_finite() => Ok(*at), Self::Screen(_) => Err(NOT_FINITE.to_owned()), Self::Document(at, _) if !(at.x.is_finite() && at.y.is_finite()) => Err(NOT_FINITE.to_owned()), Self::Document(at, page) => { - let on_screen = map(page, at).ok_or_else(|| NO_DOCUMENT.to_owned())?; + let on_screen = map(*page, *at).ok_or_else(|| NO_DOCUMENT.to_owned())?; let within = |v: f32| v.is_finite() && f64::from(v.abs()) <= MAX_SCREEN_POINT; if within(on_screen.x) && within(on_screen.y) { Ok(on_screen) } else { Err(OFF_SCREEN.to_owned()) } } } } + + /// [`At::resolve`] against the controls of the access tree the host kept for `viewport`. + fn place(&self, host: &WindowHost, viewport: ViewportId, map: DocumentMap<'_>) -> Result { + self.resolve(map, &|target| target.rect(host, viewport)) + } } /// The point fields every pointer request takes. -const POINT: [&str; 4] = ["x", "y", "coordinates", "page"]; +const POINT: [&str; 5] = ["x", "y", "coordinates", "page", "control"]; /// The modifier fields ([`crate::protocol::KEY_MODIFIERS`], top-level or under `modifiers`). const MODIFIERS: [&str; 5] = ["modifiers", "shift", "alt", "command", "ctrl"]; @@ -233,7 +256,7 @@ impl Click { match &self.target { ClickTarget::At(at) => { let count = u32::try_from(self.count).unwrap_or(u32::MAX); - host.inject_click(viewport, at.resolve(map)?, self.button, count, self.mods, self.hold); + host.inject_click(viewport, at.place(host, viewport, map)?, self.button, count, self.mods, self.hold); Ok(()) } ClickTarget::Node(node) => { @@ -273,11 +296,15 @@ impl Move { /// Queues the move in `viewport`. pub fn inject(&self, host: &WindowHost, viewport: ViewportId, map: DocumentMap<'_>) -> Result<(), String> { - host.inject_move(viewport, self.at.resolve(map)?, self.mods, self.rest); + let at = self.at.place(host, viewport, map)?; + host.inject_move(viewport, at, self.mods, self.rest); Ok(()) } } +/// The most notches one `ui.wheel` turn in lines may ask for, either way. +pub const MAX_NOTCHES: f32 = 100.0; + /// A validated `ui.wheel`. #[derive(Clone, Debug, PartialEq)] #[non_exhaustive] @@ -286,23 +313,33 @@ pub struct Wheel { pub at: At, /// The scroll in points, as egui reports it (positive `y` scrolls towards the content's top). pub delta: Vec2, + /// Whether `delta` is in points or in whole notches of lines. + pub unit: egui::MouseWheelUnit, /// Modifiers held from the turn on. pub mods: Mods, } impl Wheel { - /// `{x?, y?, coordinates?, dx?, dy?, modifiers…}`, no other fields; `dx` and `dy` are points, default 0. + /// `{x?, y?, coordinates?, dx?, dy?, unit?, modifiers…}`, no other fields; `dx` and `dy` are default 0, in points + /// or, with `unit: "lines"`, in whole notches (rounded, at most [`MAX_NOTCHES`] either way). `unit` defaults to + /// `"points"`. pub fn from_params(params: &Value) -> Result { - let p = only(params, &["dx", "dy"])?; + let p = only(params, &["dx", "dy", "unit"])?; let p = Params(&p); let dx = p.number_in("dx", "dx", None)?.unwrap_or(0.0) as f32; let dy = p.number_in("dy", "dy", None)?.unwrap_or(0.0) as f32; - Ok(Self { at: At::from_params(&p)?, delta: vec2(dx, dy), mods: p.modifiers(&KEY_MODIFIERS)? }) + let notches = |turn: f32| turn.round().clamp(-MAX_NOTCHES, MAX_NOTCHES); + let (unit, delta) = match p.choice("unit", "unit", &["points", "lines"])?.unwrap_or("points") { + "lines" => (egui::MouseWheelUnit::Line, vec2(notches(dx), notches(dy))), + _ => (egui::MouseWheelUnit::Point, vec2(dx, dy)), + }; + Ok(Self { at: At::from_params(&p)?, delta, unit, mods: p.modifiers(&KEY_MODIFIERS)? }) } /// Queues the move and the turn in `viewport`. pub fn inject(&self, host: &WindowHost, viewport: ViewportId, map: DocumentMap<'_>) -> Result<(), String> { - host.inject_wheel(viewport, self.at.resolve(map)?, self.delta, self.mods); + let at = self.at.place(host, viewport, map)?; + host.inject_wheel(viewport, at, self.delta, self.unit, self.mods); Ok(()) } } @@ -336,7 +373,7 @@ impl KeyPress { } /// A validated `ui.release`. -#[derive(Clone, Copy, Debug, PartialEq)] +#[derive(Clone, Debug, PartialEq)] #[non_exhaustive] pub struct Release { /// Where the release happens; where the pointer is when absent. @@ -346,10 +383,10 @@ pub struct Release { } impl Release { - /// `{button?, key?, x?, y?, coordinates?}`, no other fields. With neither `button` nor `key` everything held is - /// released, the modifiers too; both is ``"`button` and `key` exclude each other"``. + /// `{button?, key?, x?, y?, coordinates?, page?, control?}`, no other fields. With neither `button` nor `key` everything + /// held is released, the modifiers too; both is ``"`button` and `key` exclude each other"``. pub fn from_params(params: &Value) -> Result { - let p = Params(params).only(None, &["button", "key", "x", "y", "coordinates", "page"])?; + let p = Params(params).only(None, &["button", "key", "x", "y", "coordinates", "page", "control"])?; let p = Params(&p); let released = match (button(&p)?, key(&p)?) { (Some(_), Some(_)) => return Err("`button` and `key` exclude each other".into()), @@ -357,13 +394,13 @@ impl Release { (None, Some(key)) => Released::Key(key), (None, None) => Released::All, }; - let at = (p.0.get("x").is_some() || p.0.get("y").is_some()).then(|| At::from_params(&p)).transpose()?; + let at = ["x", "y", "control"].iter().any(|field| p.0.get(*field).is_some()).then(|| At::from_params(&p)).transpose()?; Ok(Self { at, released }) } /// Queues the release in `viewport`. pub fn inject(&self, host: &WindowHost, viewport: ViewportId, map: DocumentMap<'_>) -> Result<(), String> { - let at = self.at.map(|at| at.resolve(map)).transpose()?; + let at = self.at.as_ref().map(|at| at.place(host, viewport, map)).transpose()?; host.inject_release(viewport, at, self.released); Ok(()) } @@ -422,8 +459,8 @@ fn drop_files(params: &Value, host: &WindowHost, viewport: ViewportId, map: Docu 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()).then(|| At::from_params(&p)).transpose()?; - let at = at.map(|at| at.resolve(map)).transpose()?; + 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(()) } diff --git a/crates/automation/src/ui/actions/body.rs b/crates/automation/src/ui/actions/body.rs index 19dcfca8a7..a38f637be5 100644 --- a/crates/automation/src/ui/actions/body.rs +++ b/crates/automation/src/ui/actions/body.rs @@ -17,7 +17,7 @@ use craft_ui::runtime::env::{Env, Label}; use egui::{Id, Response, Ui}; use super::menu::OpenMenu; -use super::panel::{ActionSelection, ActionsEvent, ActionsHost, ActionsPanelState, Session}; +use super::panel::{ActionSelection, ActionsEvent, ActionsHost, ActionsPanelState, Session, StepCells}; use super::rows::{ActionRows, DIALOG_COLUMN, INCLUDE_COLUMN, NAME_COLUMN, build_row, cells}; use super::words::ActionsWords; use crate::actions::{ActionList, moved_index}; @@ -32,6 +32,8 @@ pub(super) struct Body<'a> { pub(super) env: &'a Env, /// The id the tree's list shows under, which its drags carry as `ListDrag::list`. pub(super) list_id: Id, + /// Which step cells the rows show. + pub(super) step_cells: StepCells, } /// Where a moved row goes. @@ -82,8 +84,9 @@ pub struct ActionMove { pub(super) struct BodyOutput { pub(super) events: Vec, pub(super) response: Response, - /// The selection the list ended on, for the caller to store after the container; `None` when the body did not show the tree. - pub(super) selected: Option>, + /// The selected row and the range of sets the list ended on, for the caller to store after the container; `None` + /// when the body did not show the tree. + pub(super) selected: Option<(Option, Vec)>, } /// The part of the panel above the footer: the empty notice, Button Mode's buttons or the tree. @@ -149,19 +152,24 @@ fn show_tree(ui: &mut Ui, body: &Body<'_>, state: &mut ActionsPanelState, sessio let recording = host.and_then(|host| host.recording()); let rows = ActionRows::build(list, state, host); let order = rows.keys(); - let mut selection = Selection::new(state.selected.iter().cloned().collect(), state.selected.clone(), state.selected.clone()); + let items = if state.selected_sets.is_empty() { + state.selected.iter().cloned().collect() + } else { + state.selected_sets.iter().cloned().map(ActionSelection::Set).collect() + }; + let mut selection = Selection::new(items, state.selected.clone(), state.selected.clone()); if let Some(index) = rename.filter(|_| editable) { request_rename(ui.ctx(), list_id, &ActionSelection::Action(index)); } - let columns = vec![ - ColumnSpec::toggle(INCLUDE_COLUMN, Label::Empty, ToggleColumn::sweepable()), - ColumnSpec::toggle(DIALOG_COLUMN, Label::Empty, ToggleColumn::sweepable()).icon(IconId::new("note")), - ColumnSpec::new(NAME_COLUMN, Label::Empty, ColumnWidth::fill(1.0)), - ]; + let mut columns = vec![ColumnSpec::toggle(INCLUDE_COLUMN, Label::Empty, ToggleColumn::sweepable())]; + if body.step_cells == StepCells::IncludeAndDialog { + columns.push(ColumnSpec::toggle(DIALOG_COLUMN, Label::Empty, ToggleColumn::sweepable()).icon(IconId::new("note"))); + } + columns.push(ColumnSpec::new(NAME_COLUMN, Label::Empty, ColumnWidth::fill(1.0))); let mut widget = List::new(words.name.clone()) .id(list_id) .tree(true) - .select(SelectMode::Single) + .select(SelectMode::Multi) .allow_empty(true) .space(SpaceAction::ToggleCell) .deletable(true) @@ -224,17 +232,37 @@ fn show_tree(ui: &mut Ui, body: &Body<'_>, state: &mut ActionsPanelState, sessio } } CollectionEvent::Delete(keys) if editable => { - events.extend(keys.first().and_then(|key| delete_event(key, recording.is_some()))); + if state.selected_sets.is_empty() { + events.extend(keys.first().and_then(|key| delete_event(key, recording.is_some()))); + } else if recording.is_none() { + events.push(ActionsEvent::DeleteSets(state.selected_sets.clone())); + } } CollectionEvent::ContextMenu(request) => session.menu = OpenMenu::opened(request, list, host), _ => {} } } - let mut selected = selection.items.first().cloned(); + let (mut selected, sets) = kept(list, &selection); for (source, to) in &moves { selected = selected.map(|selected| remapped(selected, source, to)); } - BodyOutput { events, response: out.response, selected: Some(selected) } + BodyOutput { events, response: out.response, selected: Some((selected, sets)) } +} + +/// The selection the panel keeps after the list applied this pass's input: the lead row, and the range of sets in list +/// order when the lead and the range's other end (the anchor) are both set rows. The list's range runs over the shown +/// rows, so one across an expanded set holds that set's action rows too; only the set rows are kept. A lead that is an +/// action or step, or a set reached from one of those, is the whole selection. A range of fewer than two sets is none. +fn kept(list: &ActionList, selection: &Selection) -> (Option, Vec) { + let lead = selection.lead.clone().filter(|lead| selection.items.contains(lead)); + let range = matches!((&lead, &selection.anchor), (Some(ActionSelection::Set(_)), Some(ActionSelection::Set(_)))); + let sets: Vec = if range { + let chosen = |set: &str| selection.items.iter().any(|key| matches!(key, ActionSelection::Set(name) if name == set)); + list.sets().into_iter().filter(|set| chosen(set)).map(str::to_owned).collect() + } else { + Vec::new() + }; + (lead, if sets.len() > 1 { sets } else { Vec::new() }) } /// The `Delete` event for `selected`: a step always; a set or an action not while recording. diff --git a/crates/automation/src/ui/actions/menu.rs b/crates/automation/src/ui/actions/menu.rs index ed1e728371..74add10436 100644 --- a/crates/automation/src/ui/actions/menu.rs +++ b/crates/automation/src/ui/actions/menu.rs @@ -1,4 +1,4 @@ -//! The panel menu's commands and the row context menus (Keyboard Shortcuts, Color; Save Set…). +//! The panel menu's commands and the row context menus. use craft_keymap::Platform; use craft_ui::contract::{CommandSet, ContextMenuRequest, Props as _, Show as _, ShowContainer as _}; @@ -6,6 +6,7 @@ use craft_ui::display::Divider; use craft_ui::list::label_color_label; use craft_ui::menu::{Menu, MenuItem, PanelRow}; use craft_ui::runtime::commands::{CommandRef, CommandState}; +use craft_ui::runtime::env::Label; use egui::{Response, Ui}; use super::body::{Body, delete_event}; @@ -276,7 +277,7 @@ pub fn panel_rows(facts: ActionsMenuFacts, offered: &dyn Fn(ActionsPanelCommands /// The shortcut as the context menu has made it so far. #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub(super) struct PendingShortcut { - /// 0 for none, else 1..=12. + /// 0 for none, else 1..=15. key: u8, shift: bool, command: bool, @@ -291,7 +292,7 @@ impl PendingShortcut { /// The menu a context request opened, kept until the next request. #[derive(Clone, Debug)] pub(super) enum OpenMenu { - /// A set's menu: Save Set…. + /// A set's menu. Set(String), /// An action's menu, with the shortcut as the menu has made it from the host's. Action { index: usize, shortcut: PendingShortcut }, @@ -318,34 +319,58 @@ impl OpenMenu { } /// Shows the menu the last request chose, hanging from `opener` (the list), and reports what its -/// rows ran: -/// - On an action: Keyboard Shortcuts (a caption), None and F1 to F12 as radio rows, then Shift and -/// Command (Ctrl off macOS) check rows, enabled only with a key; the check rows keep the menu -/// open so both can be ticked, and each tick is reported as it is made with the shortcut as it -/// stands. A separator, then Color: a submenu of None, Red, Orange, Yellow, Green, Blue, Violet -/// and Gray with the current one marked. -/// - On a set: Save Set…. +/// rows ran. Rows that start or change something are off while an action plays or records, as the +/// footer's are; Delete follows the footer's Delete. +/// - On an action: Play and Record; Duplicate and Delete; Action Options… and Batch…. Then +/// Keyboard Shortcuts (a caption), None and F1 to F15 as radio rows, then Shift and Command (Ctrl +/// off macOS) check rows, enabled only with a key; the check rows keep the menu open so both can +/// be ticked, and each tick is reported as it is made with the shortcut as it stands. Last Color: +/// a submenu of None, Red, Orange, Yellow, Green, Blue, Violet and Gray with the current one +/// marked. +/// - On a set: New Action…, New Set…, Duplicate Set and Delete Set; Set Options…; Save Set…. pub(super) fn show_menu(ui: &mut Ui, body: &Body<'_>, opener: &Response, session: &mut Session) -> Vec { - let Body { list, words, list_words, .. } = *body; + let Body { list, host, words, list_words, .. } = *body; + let recording = host.is_some_and(|host| host.recording().is_some()); + let playing = host.is_some_and(|host| host.playing()); + let idle = !recording && !playing; + let hosted = host.is_some(); + let deletable = |row: &ActionSelection| delete_event(row, recording).filter(|_| !playing); let mut events = Vec::new(); match session.menu.as_mut() { None => {} Some(OpenMenu::Set(name)) => { + let set = ActionSelection::Set(name.clone()); Menu::context(words.row_menu.clone(), opener).show(ui, |ui, _| { - if MenuItem::new(words.save_set.clone()).show(ui).ran { - events.push(ActionsEvent::Save { set: Some(name.clone()) }); - } + let events = &mut events; + event_row(ui, events, &words.menu_new_action, (hosted && idle).then_some(ActionsEvent::NewAction)); + event_row(ui, events, &words.menu_new_set, idle.then_some(ActionsEvent::NewSet)); + event_row(ui, events, &words.duplicate_set, idle.then(|| ActionsEvent::Duplicate(set.clone()))); + event_row(ui, events, &words.delete_set, deletable(&set)); + Divider::horizontal().show(ui); + event_row(ui, events, &words.set_options, Some(ActionsEvent::SetOptions(name.clone()))); + Divider::horizontal().show(ui); + event_row(ui, events, &words.save_set, Some(ActionsEvent::save(Some(name.clone())))); }); } Some(OpenMenu::Action { index, shortcut }) => { let (action, current) = (*index, list.action(*index).map(|held| held.color).unwrap_or_default()); + let selection = ActionSelection::Action(action); Menu::context(words.row_menu.clone(), opener).show(ui, |ui, _| { + event_row(ui, &mut events, &words.menu_play, (hosted && idle).then(|| ActionsEvent::play(action, 0))); + event_row(ui, &mut events, &words.menu_record, (hosted && idle).then(|| ActionsEvent::begin_recording(Some(action)))); + Divider::horizontal().show(ui); + event_row(ui, &mut events, &words.duplicate, idle.then(|| ActionsEvent::Duplicate(selection.clone()))); + event_row(ui, &mut events, &words.delete, deletable(&selection)); + Divider::horizontal().show(ui); + event_row(ui, &mut events, &words.action_options, Some(ActionsEvent::ActionOptions(action))); + event_row(ui, &mut events, &words.batch, Some(ActionsEvent::Batch(action))); + Divider::horizontal().show(ui); MenuItem::new(words.keyboard_shortcuts.clone()).enabled(false).show(ui); if MenuItem::new(words.none.clone()).radio_mark(shortcut.key == 0).show(ui).ran { shortcut.key = 0; events.push(ActionsEvent::AssignShortcut { action, choice: shortcut.choice() }); } - for key in 1..=12u8 { + for key in 1..=15u8 { if MenuItem::new(format!("F{key}")).radio_mark(shortcut.key == key).show(ui).ran { shortcut.key = key; events.push(ActionsEvent::AssignShortcut { action, choice: shortcut.choice() }); @@ -375,3 +400,10 @@ pub(super) fn show_menu(ui: &mut Ui, body: &Body<'_>, opener: &Response, session } events } + +/// A row of a row menu, enabled while it has an event, which it reports when it runs. +fn event_row(ui: &mut Ui, events: &mut Vec, label: &Label, event: Option) { + if MenuItem::new(label.clone()).enabled(event.is_some()).show(ui).ran { + events.extend(event); + } +} diff --git a/crates/automation/src/ui/actions/mod.rs b/crates/automation/src/ui/actions/mod.rs index d8a30be9f9..1c9e113e08 100644 --- a/crates/automation/src/ui/actions/mod.rs +++ b/crates/automation/src/ui/actions/mod.rs @@ -23,7 +23,9 @@ mod words; pub use body::{ActionMove, ActionPlace}; pub use menu::{ActionsMenuAction, ActionsMenuFacts, ActionsPanelCommands, panel_rows}; -pub use panel::{ActionSelection, ActionsEvent, ActionsHost, ActionsPanel, ActionsPanelOutput, ActionsPanelState, ActionsSettings, ShortcutChoice}; +pub use panel::{ + ActionSelection, ActionsEvent, ActionsHost, ActionsPanel, ActionsPanelOutput, ActionsPanelState, ActionsSettings, ShortcutChoice, StepCells, +}; pub use prompt::LibraryPrompt; pub use rows::{DIALOG_COLUMN, INCLUDE_COLUMN}; pub use words::ActionsWords; diff --git a/crates/automation/src/ui/actions/panel.rs b/crates/automation/src/ui/actions/panel.rs index 179ff8a17b..ecdef774e6 100644 --- a/crates/automation/src/ui/actions/panel.rs +++ b/crates/automation/src/ui/actions/panel.rs @@ -100,13 +100,27 @@ pub struct ActionsPanelState { pub selected: Option, /// The expanded actions, by name (names are unique, so expansion survives moves). pub expanded: BTreeSet, + /// The sets a shift-click selected, from the current set to the clicked one, in the set order; empty when there is + /// no range. + pub selected_sets: Vec, +} + +/// Which step cells the rows show. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum StepCells { + /// The include cell and the dialog cell. + #[default] + IncludeAndDialog, + /// The include cell only: the dialog column is left out of the cells and the list's columns. + Include, } /// A function-key shortcut chosen in the context menu (Photoshop's Action Options). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)] #[non_exhaustive] pub struct ShortcutChoice { - /// F1 to F12: 1..=12. + /// F1 to F15: 1..=15. pub key: u8, /// Shift is part of the shortcut. pub shift: bool, @@ -115,7 +129,7 @@ pub struct ShortcutChoice { } impl ShortcutChoice { - /// Function key `key` (1 to 12) with the given modifiers. + /// Function key `key` (1 to 15) with the given modifiers. pub const fn new(key: u8, shift: bool, command: bool) -> Self { Self { key, shift, command } } @@ -126,7 +140,7 @@ impl ShortcutChoice { self.chord().display(Platform::current()) } - /// The shortcut as a keymap chord; a key above 12 is taken as F12. + /// The shortcut as a keymap chord; a key outside 1..=15 is taken as F12. fn chord(&self) -> Chord { let key = match self.key { 1 => Key::F1, @@ -140,6 +154,9 @@ impl ShortcutChoice { 9 => Key::F9, 10 => Key::F10, 11 => Key::F11, + 13 => Key::F13, + 14 => Key::F14, + 15 => Key::F15, _ => Key::F12, }; Chord::new(Mods { cmd: self.command, shift: self.shift, ..Mods::NONE }, key) @@ -217,6 +234,8 @@ pub enum ActionsEvent { InsertStop, /// Batch… with this action (the app's dialog). Batch(usize), + /// Action Options… from an action's menu: the app's dialog for this action's name, set, function key and colour. + ActionOptions(usize), /// Load Actions… (the app's file dialog). Load, /// Clear All Actions: the app asks with [`LibraryPrompt::ClearAll`](super::LibraryPrompt) and @@ -237,6 +256,8 @@ pub enum ActionsEvent { /// Duplicate this row ([`ActionList::duplicate_action`], [`ActionList::duplicate_step`], /// [`ActionList::duplicate_set`]): from the menu row or a row dropped on New Action. Duplicate(ActionSelection), + /// Delete with a range of sets selected: the range, in one event, so the app asks one question. + DeleteSets(Vec), /// Record Again: replace step `step` of `action` with a new recording /// ([`ActionList::replace_step`]). #[non_exhaustive] @@ -359,7 +380,9 @@ impl Default for Session { /// all); a double click on an action's name renames it, elsewhere on an action it plays it. The /// cells sweep down their column as one gesture. A drag moves an action (into or out of a set) /// or a step (within or between actions), or drops it on the footer's Delete. Right-click on an -/// action opens Keyboard Shortcuts and Color; on a set, Save Set…. +/// action or a set selects it and opens its menu: on an action Play, Record, Duplicate, Delete, +/// Action Options…, Batch…, Keyboard Shortcuts and Color; on a set New Action…, New Set…, +/// Duplicate Set, Delete Set, Set Options… and Save Set…. /// - **Keys**: the rows are one Tab stop: arrows move, Left and Right close and open, Enter plays /// an action or toggles a set, Space toggles the include cell, F2 renames, Delete deletes the /// selection (not an action while recording), Cmd/Ctrl+] and [ move the row, Shift to the ends. The footer @@ -376,12 +399,13 @@ pub struct ActionsPanel<'a> { host: Option<&'a dyn ActionsHost>, rename: Option, enabled: bool, + step_cells: StepCells, } impl<'a> ActionsPanel<'a> { /// A panel over `list` with `state`. pub fn new(state: &'a mut ActionsPanelState, list: &'a ActionList) -> Self { - Self { state, list, host: None, rename: None, enabled: true } + Self { state, list, host: None, rename: None, enabled: true, step_cells: StepCells::default() } } /// The app's side; without one, steps show their command ids and nothing records or plays. @@ -397,6 +421,12 @@ impl<'a> ActionsPanel<'a> { self } + /// Which step cells the rows show. + pub fn step_cells(mut self, cells: StepCells) -> Self { + self.step_cells = cells; + self + } + /// Whether the panel takes input (default true). pub fn enabled(mut self, enabled: bool) -> Self { self.enabled = enabled; @@ -406,7 +436,7 @@ impl<'a> ActionsPanel<'a> { /// Draws the tree (or the buttons) and the footer, and reports this pass's events in order: /// the list's, the cells', the context menu's, the footer's. pub fn show(self, ui: &mut Ui) -> ActionsPanelOutput { - let ActionsPanel { state, list, host, rename, enabled } = self; + let ActionsPanel { state, list, host, rename, enabled, step_cells } = self; let env = Env::of(ui); let words = env.words::(); let list_words = env.words::(); @@ -414,7 +444,7 @@ impl<'a> ActionsPanel<'a> { let settings_before = state.settings.clone(); let events = RefCell::new(Vec::new()); let state = RefCell::new(state); - let body = Body { list, host, words: &words, list_words: &list_words, env: &env, list_id }; + let body = Body { list, host, words: &words, list_words: &list_words, env: &env, list_id, step_cells }; let shown = Stack::new() .fill() @@ -436,8 +466,10 @@ impl<'a> ActionsPanel<'a> { let mut reported = Vec::new(); if let Some((body_events, selected)) = shown.inner { reported = body_events; - if let Some(selected) = selected { - state.borrow_mut().selected = selected; + if let Some((row, sets)) = selected { + let mut state = state.borrow_mut(); + state.selected = row; + state.selected_sets = sets; } } reported.extend(events.into_inner()); diff --git a/crates/automation/src/ui/actions/rows.rs b/crates/automation/src/ui/actions/rows.rs index 2319e3021d..41f1af45cc 100644 --- a/crates/automation/src/ui/actions/rows.rs +++ b/crates/automation/src/ui/actions/rows.rs @@ -11,7 +11,7 @@ use craft_ui::primitives::IconSpec; use craft_ui::runtime::env::Label; use super::body::Body; -use super::panel::{ActionSelection, ActionsHost, ActionsPanelState}; +use super::panel::{ActionSelection, ActionsHost, ActionsPanelState, StepCells}; use crate::actions::{ActionInclude, ActionList}; /// The include column: a toggle on action rows (every step) and step rows. @@ -145,6 +145,7 @@ impl ItemSource for ActionRows<'_> { (ActionSelection::Action(index), column) if *column == INCLUDE_COLUMN => { self.list.action(*index).is_some_and(|action| action.include() == ActionInclude::All) } + (ActionSelection::Set(name), column) if *column == INCLUDE_COLUMN => matches!(set_include(self.list, name), Some(ToggleState::On)), _ => match self.recorded_step(at) { Some((action, step)) if *column == INCLUDE_COLUMN => self.list.action(action).is_some_and(|held| held.step_enabled(step)), Some((action, step)) if *column == DIALOG_COLUMN => self.list.action(action).is_some_and(|held| held.dialogs.contains(&step)), @@ -158,11 +159,20 @@ impl ItemSource for ActionRows<'_> { match &row.key { ActionSelection::Action(index) => *column == INCLUDE_COLUMN && self.list.action(*index).is_some_and(|action| !action.steps.is_empty()), ActionSelection::Step(..) => self.recorded_step(at).is_some(), - ActionSelection::Set(_) => false, + ActionSelection::Set(name) => *column == INCLUDE_COLUMN && set_include(self.list, name).is_some(), } } } +/// The include mark of the set `name` over its actions that have steps: on when every one is fully included, off when +/// none is, mixed otherwise; `None` when no action of the set has a step. +fn set_include(list: &ActionList, name: &str) -> Option { + let mut marks = + list.actions().iter().filter(|action| action.set.as_deref() == Some(name) && !action.steps.is_empty()).map(|action| action.include()); + let first = marks.next()?; + Some(if marks.all(|mark| mark == first) { include_state(first) } else { ToggleState::Mixed }) +} + fn include_state(include: ActionInclude) -> ToggleState { match include { ActionInclude::All => ToggleState::On, @@ -224,10 +234,10 @@ pub(super) fn build_row(body: &Body<'_>, state: &ActionsPanelState, key: &Action } } -/// The toggle cells of a row: the include cell of an action with steps and of a recorded step, the -/// dialog cell of a recorded step. +/// The toggle cells of a row: the include cell of an action or set with steps and of a recorded step, the +/// dialog cell of a recorded step unless the panel leaves the dialog column out. pub(super) fn cells(body: &Body<'_>, key: &ActionSelection) -> Vec { - let Body { list, words, .. } = *body; + let Body { list, words, step_cells, .. } = *body; let include = |state: ToggleState| ToggleCell::check(INCLUDE_COLUMN, state, words.include.clone()).tooltip(words.include_tooltip.clone()); match key { ActionSelection::Action(index) => match list.action(*index) { @@ -245,10 +255,14 @@ pub(super) fn cells(body: &Body<'_>, key: &ActionSelection) -> Vec { ) .tooltip(words.dialog_tooltip.clone()); dialog.check_box = true; - vec![include(ToggleState::of(action.step_enabled(*step))), dialog] + let mut cells = vec![include(ToggleState::of(action.step_enabled(*step)))]; + if step_cells == StepCells::IncludeAndDialog { + cells.push(dialog); + } + cells } _ => Vec::new(), }, - ActionSelection::Set(_) => Vec::new(), + ActionSelection::Set(name) => set_include(list, name).map_or_else(Vec::new, |state| vec![include(state)]), } } diff --git a/crates/automation/src/ui/actions/stories.rs b/crates/automation/src/ui/actions/stories.rs index e2b754c6b0..b5f7ebd939 100644 --- a/crates/automation/src/ui/actions/stories.rs +++ b/crates/automation/src/ui/actions/stories.rs @@ -5,7 +5,7 @@ use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; use super::mock::{FakeActionsHost, action, list_of, sample_list, step}; -use super::{ActionSelection, ActionsPanel, ActionsPanelState, ShortcutChoice}; +use super::{ActionSelection, ActionsPanel, ActionsPanelState, ShortcutChoice, StepCells}; use crate::actions::{ActionColor, ActionList}; /// The sample list with Sharpen open and selected, one step off, and a shortcut on it. @@ -43,6 +43,33 @@ fn actions_panel_button_mode(ui: &mut Ui, _data: &mut StoryData) -> StoryOutput ActionsPanel::new(&mut state, &list).host(&FakeActionsHost::default()).show(ui).into() } +/// The include variant: step rows without the dialog cell, and set rows with an include cell, one of them mixed. +#[story(ActionsPanel<'static>, covers = [], drive = Drive::Never)] +fn actions_panel_include_cells(ui: &mut Ui, _data: &mut StoryData) -> StoryOutput { + let mut blur = action("Blur", Some("Effects"), &["blur", "mask"]); + blur.disabled.insert(1); + let list = list_of(vec![blur, action("Glow", Some("Effects"), &["glow"]), action("Levels", Some("Basics"), &["levels", "curves"])]); + let mut state = ActionsPanelState::default(); + state.expanded.insert("Blur".to_owned()); + ActionsPanel::new(&mut state, &list).host(&FakeActionsHost::default()).step_cells(StepCells::Include).show(ui).into() +} + +/// A range of three sets selected, as a Shift-click from the first to the last leaves it. +#[story(ActionsPanel<'static>, covers = [], drive = Drive::Never)] +fn actions_panel_set_range(ui: &mut Ui, _data: &mut StoryData) -> StoryOutput { + let list = list_of(vec![ + action("Blur", Some("Effects"), &["blur"]), + action("Levels", Some("Basics"), &["levels"]), + action("Glow", Some("Finish"), &["glow"]), + ]); + let mut state = ActionsPanelState { + selected: Some(ActionSelection::Set("Finish".to_owned())), + selected_sets: ["Effects", "Basics", "Finish"].map(str::to_owned).to_vec(), + ..ActionsPanelState::default() + }; + ActionsPanel::new(&mut state, &list).host(&FakeActionsHost::default()).show(ui).into() +} + #[story(ActionsPanel<'static>, covers = [], drive = Drive::Never)] fn actions_panel_empty(ui: &mut Ui, _data: &mut StoryData) -> StoryOutput { let mut state = ActionsPanelState::default(); diff --git a/crates/automation/src/ui/actions/words.rs b/crates/automation/src/ui/actions/words.rs index 745edf3746..c2f9ecc2ab 100644 --- a/crates/automation/src/ui/actions/words.rs +++ b/crates/automation/src/ui/actions/words.rs @@ -39,6 +39,16 @@ craft_ui::words! { /// The panel menu's submenu-free title of the row menu. row_menu: "actions.rowMenu" = "Action"; save_set: "actions.saveSet" = "Save Set…"; + menu_new_action: "actions.menuNewAction" = "New Action…"; + menu_new_set: "actions.menuNewSet" = "New Set…"; + duplicate_set: "actions.duplicateSet" = "Duplicate Set"; + delete_set: "actions.deleteSet" = "Delete Set"; + set_options: "actions.setOptions" = "Set Options…"; + menu_play: "actions.menuPlay" = "Play"; + menu_record: "actions.menuRecord" = "Record"; + duplicate: "actions.duplicate" = "Duplicate"; + action_options: "actions.actionOptions" = "Action Options…"; + batch: "actions.batch" = "Batch…"; keyboard_shortcuts: "actions.keyboardShortcuts" = "Keyboard Shortcuts"; /// The shortcut menu's "no shortcut" row. none: "actions.none" = "None"; diff --git a/crates/automation/tests/it/access.rs b/crates/automation/tests/it/access.rs index 1319f62299..96d050d5a3 100644 --- a/crates/automation/tests/it/access.rs +++ b/crates/automation/tests/it/access.rs @@ -1,14 +1,14 @@ -//! `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. +//! 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::{NodeTarget, inspect, resolve}; +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, Props as _, Show as _, ShowContainer as _}; +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; @@ -20,6 +20,105 @@ use craft_ui::text::TextField; use egui::{Pos2, ViewportId}; use serde_json::{Value, json}; +/// Two buttons and a text field named "Name", with the clicks each button got and where the pointer was. +struct Rig { + fx: Fixture, + host: WindowHost, + clicks: Rc<[Cell; 2]>, + pointer: Rc>>, +} + +impl Rig { + fn new(names: [&'static str; 2]) -> Self { + let clicks: Rc<[Cell; 2]> = Rc::default(); + let pointer = Rc::new(Cell::new(None)); + let text = RefCell::new(String::new()); + let (seen, at) = (clicks.clone(), pointer.clone()); + let fx = Fixture::new(move |ui| { + for (n, name) in names.iter().enumerate() { + if clicked(&Button::new(*name).show(ui)) { + seen[n].set(seen[n].get() + 1); + } + } + TextField::new("Name", Bind::bound(&mut *text.borrow_mut())).show(ui); + at.set(ui.input(|input| input.pointer.latest_pos())); + }); + let host = WindowHost::of(fx.ctx()); + Self { fx, host, clicks, pointer } + } + + /// The same, after the host kept its first access tree. + fn kept(names: [&'static str; 2]) -> Self { + let mut rig = Self::new(names); + rig.host.keep_access_trees(); + rig.fx.idle(2); + rig + } + + /// Sends `method`; when it is accepted, runs frames until the host has processed the input. + fn send(&mut self, method: &str, params: Value) -> Result<(), String> { + input_method(method, ¶ms, &self.host, ViewportId::ROOT, &|_, _| None).expect("an input method")?; + for _ in 0..32 { + self.fx.frame(Vec::new()); + if self.host.injected_idle() { + break; + } + } + assert!(self.host.injected_idle(), "{method} was processed"); + self.fx.frame(Vec::new()); + Ok(()) + } + + fn find(&self, params: Value) -> Result { + access_method("ui.find", ¶ms, &self.host, ViewportId::ROOT).expect("an access method") + } + + fn counts(&self) -> [u32; 2] { + [self.clicks[0].get(), self.clicks[1].get()] + } +} + +/// A click `{control: {name}}` presses that button and no other, also for a text field named by its label, and +/// `ui.find` reports where the control is. +#[trial] +fn a_click_on_a_named_control_lands_on_it() { + let mut rig = Rig::kept(["Save", "Cancel"]); + rig.send("ui.click", json!({"control": {"name": "Save"}})).expect("valid"); + assert_eq!(rig.counts(), [1, 0]); + rig.send("ui.click", json!({"control": {"name": "Cancel:"}})).expect("valid"); + assert_eq!(rig.counts(), [1, 1], "a trailing colon of the name is ignored"); + + let field = rig.find(json!({"name": "Name"})).expect("the field is found"); + assert_eq!(field["enabled"], json!(true)); + assert_eq!(field["focused"], json!(false)); + let rect: Vec = field["rect"].as_array().expect("a rect").iter().map(|v| v.as_f64().expect("a number")).collect(); + rig.send("ui.click", json!({"control": {"name": "Name"}})).expect("valid"); + let at = rig.pointer.get().expect("the pointer arrived"); + let (x, y) = (f64::from(at.x), f64::from(at.y)); + assert!(x >= rect[0] && x <= rect[0] + rect[2] && y >= rect[1] && y <= rect[1] + rect[3], "{at:?} lies in {rect:?}"); + assert_eq!(rig.find(json!({"name": "Name"})).expect("found")["focused"], json!(true), "the click focused the field"); +} + +/// A name two controls share needs an `index`; an unknown name matches none; neither queues anything. Before the +/// first kept pass there is no tree to look in. +#[trial] +fn an_ambiguous_or_missing_name_queues_nothing() { + let mut early = Rig::new(["Go", "Go"]); + assert_eq!(early.send("ui.click", json!({"control": {"name": "Go"}})), Err(NO_TREE.to_owned())); + assert_eq!(early.find(json!({"name": "Go"})), Err(NO_TREE.to_owned())); + + let mut rig = Rig::kept(["Go", "Go"]); + let ambiguous = rig.send("ui.click", json!({"control": {"name": "Go"}})).expect_err("two match"); + assert!(ambiguous.starts_with(AMBIGUOUS), "{ambiguous}"); + let missing = rig.send("ui.click", json!({"control": {"name": "Stop"}})).expect_err("none matches"); + assert!(missing.starts_with(NO_CONTROL), "{missing}"); + assert!(rig.host.injected_idle(), "nothing was queued"); + assert_eq!(rig.counts(), [0, 0]); + + 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") diff --git a/crates/automation/tests/it/actions.rs b/crates/automation/tests/it/actions.rs index f017fd4f9a..8046137005 100644 --- a/crates/automation/tests/it/actions.rs +++ b/crates/automation/tests/it/actions.rs @@ -5,7 +5,9 @@ use std::rc::Rc; use craft_automation::actions::ActionList; use craft_automation::ui::actions::mock::{FakeActionsHost, action, list_of}; -use craft_automation::ui::actions::{ActionMove, ActionPlace, ActionSelection, ActionsEvent, ActionsPanel, ActionsPanelState, INCLUDE_COLUMN}; +use craft_automation::ui::actions::{ + ActionMove, ActionPlace, ActionSelection, ActionsEvent, ActionsPanel, ActionsPanelState, INCLUDE_COLUMN, StepCells, +}; use craft_ui::testing::{Fixture, Target, pointer, trial}; use egui::{Key, Modifiers, Pos2, Ui, Vec2}; @@ -29,16 +31,20 @@ fn app(list: ActionList) -> App { App { state: ActionsPanelState::default(), list, host: FakeActionsHost::prefixed("Run "), events: Vec::new() } } -fn show(ui: &mut Ui, app: &mut App) { +fn show(ui: &mut Ui, app: &mut App, cells: StepCells) { let App { state, list, host, events } = app; - let out = ActionsPanel::new(state, list).host(&*host).show(ui); + let out = ActionsPanel::new(state, list).host(&*host).step_cells(cells).show(ui); events.extend(out.events); } fn rig(app: App) -> (Fixture, Shared) { + rig_cells(app, StepCells::default()) +} + +fn rig_cells(app: App, cells: StepCells) -> (Fixture, Shared) { let shared = Rc::new(RefCell::new(app)); let shown = Rc::clone(&shared); - let mut fixture = Fixture::new(move |ui| show(ui, &mut shown.borrow_mut())); + let mut fixture = Fixture::new(move |ui| show(ui, &mut shown.borrow_mut(), cells)); fixture.room(PANEL); fixture.settle(); (fixture, shared) @@ -248,3 +254,96 @@ fn actions_panel_menu_offers_the_library_commands() { let events: Vec<_> = [C::ClearAll, C::Reset, C::Replace].into_iter().map(|c| c.run(&mut panel, &list, idle)).collect(); assert_eq!(events, [ActionsEvent::ClearAll, ActionsEvent::Reset, ActionsEvent::Replace].map(|event| Some(ActionsMenuAction::Event(event)))); } + +/// A step row has an include and a dialog cell, or with `StepCells::Include` the include cell only; a set row with steps +/// has an include cell whose press reports a toggle of the set, and a set without steps has none. +#[trial] +fn a_set_row_has_an_include_cell_and_the_include_variant_has_no_dialog_column() { + let mut shown = app(two_sets()); + shown.state.expanded.insert("First".into()); + let (fixture, _) = rig(shown); + assert!(fixture.by_label("Include in playback: Run b").is_some(), "a step row has its include cell"); + assert!(fixture.by_label("Show dialog during playback: Run b").is_some(), "and its dialog cell"); + + let mut list = two_sets(); + list.new_set("Hollow").unwrap(); + let mut shown = app(list); + shown.state.expanded.insert("First".into()); + let (mut fixture, shared) = rig_cells(shown, StepCells::Include); + assert!(fixture.by_label("Include in playback: Run b").is_some(), "the include cell stays"); + assert!(fixture.by_label("Show dialog during playback: Run b").is_none(), "the dialog cell is left out"); + assert!(fixture.by_label("Include in playback: Hollow").is_none(), "a set with no steps has no include cell"); + + let cell = node(&fixture, "Include in playback: Alpha"); + click(&mut fixture, cell.center()); + let toggled = take(&shared).into_iter().any(|event| { + matches!(event, ActionsEvent::Toggle(craft_ui::contract::SweepStep::Flip(edit)) + if edit.key == ActionSelection::Set("Alpha".into()) && edit.column == INCLUDE_COLUMN) + }); + assert!(toggled, "a press on a set's include cell reports a toggle of the set"); +} + +/// Shift on a later set row selects the sets between, across an expanded set's action rows; Delete reports the range in +/// one event; a click on an action clears the range. +#[trial] +fn shift_clicking_a_set_selects_the_range_and_delete_reports_it_once() { + let list = list_of(vec![ + action("Loose", None, &["a"]), + action("First", Some("Alpha"), &["b"]), + action("Second", Some("Beta"), &["c"]), + action("Third", Some("Gamma"), &["d"]), + ]); + let (mut fixture, shared) = rig(app(list)); + let (first, last) = (node(&fixture, "Alpha").center(), node(&fixture, "Gamma").center()); + click(&mut fixture, first); + fixture.hold(Modifiers::SHIFT); + click(&mut fixture, last); + fixture.hold(Modifiers::NONE); + let names = ["Alpha", "Beta", "Gamma"].map(str::to_owned).to_vec(); + assert_eq!(shared.borrow().state.selected_sets, names, "the sets between, in list order, not the actions among them"); + + take(&shared); + fixture.key(Key::Delete, Modifiers::NONE).idle(2); + let events = take(&shared); + let deletes: Vec<_> = events.iter().filter(|event| matches!(event, ActionsEvent::Delete(_) | ActionsEvent::DeleteSets(_))).collect(); + assert_eq!(deletes, [&ActionsEvent::DeleteSets(names)], "one event for the range"); + + let row = node(&fixture, "First").center(); + click(&mut fixture, row); + assert!(shared.borrow().state.selected_sets.is_empty(), "a click on an action ends the range"); + assert_eq!(shared.borrow().state.selected, Some(ActionSelection::Action(1))); +} + +/// A right-click at `pos`, with the pointer moved there first. +fn right_click(fixture: &mut Fixture, pos: Pos2) { + fixture.frame(vec![pointer::moved(pos)]); + fixture.frame(vec![pointer::secondary(pos, true)]); + fixture.frame(vec![pointer::secondary(pos, false)]); + fixture.idle(2); +} + +/// What the row `item` of the menu a right-click on `row` opens reports. +fn menu_ran(fixture: &mut Fixture, shared: &Shared, row: &str, item: &str) -> Vec { + let at = node(fixture, row).center(); + right_click(fixture, at); + let at = node(fixture, item).center(); + click(fixture, at); + take(shared) +} + +/// A right-click on an action or a set selects it and opens its menu, whose rows report their event for that row; +/// Play reports nothing while an action plays. +#[trial] +fn a_rows_menu_selects_the_row_and_reports_its_rows_for_it() { + let (mut fixture, shared) = rig(app(two_sets())); + assert_eq!(menu_ran(&mut fixture, &shared, "First", "Action Options…"), [ActionsEvent::ActionOptions(1)]); + assert_eq!(shared.borrow().state.selected, Some(ActionSelection::Action(1)), "the right-click selects the action"); + assert_eq!(menu_ran(&mut fixture, &shared, "Second", "Duplicate"), [ActionsEvent::Duplicate(ActionSelection::Action(2))]); + assert_eq!(menu_ran(&mut fixture, &shared, "Alpha", "Delete Set"), [ActionsEvent::Delete(ActionSelection::Set("Alpha".into()))]); + assert_eq!(shared.borrow().state.selected, Some(ActionSelection::Set("Alpha".into())), "the right-click selects the set"); + + let mut playing = app(two_sets()); + playing.host.playing = true; + let (mut fixture, shared) = rig(playing); + assert_eq!(menu_ran(&mut fixture, &shared, "First", "Play"), [], "Play is off while an action plays"); +} diff --git a/crates/automation/tests/it/dialogs.rs b/crates/automation/tests/it/dialogs.rs index 1763a90f72..ad6986f096 100644 --- a/crates/automation/tests/it/dialogs.rs +++ b/crates/automation/tests/it/dialogs.rs @@ -1,6 +1,6 @@ //! `ui.dialog.*` on typed dialogs through one generic path. -use craft_automation::dialogs::{dialog_method, inspect}; +use craft_automation::dialogs::{MAX_DIALOG_FIELDS, dialog_method, inspect}; use craft_ui::contract::{Bind, SaveKey}; use craft_ui::dialog::{DialogHost, DialogResult, PromptChoice, PromptKind, StandardPrompt}; use craft_ui::patterns::form_dialogs::{DialogFields, HostedParamDialog, Param, ParamDialog, ParamKind}; @@ -124,6 +124,41 @@ fn param_dialog_automation_follows_its_rows() { assert_eq!((reopened.fields.number("radius"), reopened.fields.text("method")), (Some(7.0), Some("zoom"))); } +/// A `fields` list sets every field or none: a refused field in the middle leaves the dialog as it was and gives that +/// refusal; a list over the limit, an item without a string `field` and `field` beside `fields` are refused unread. +#[trial] +fn a_field_list_sets_every_field_or_none_and_has_a_limit() { + let ctx = Context::default(); + let mut host = DialogHost::new(); + host.open(HostedParamDialog::new(&ctx, "blur", DialogFields::new(), |fields| { + ParamDialog::new("blur", "Blur", Param::parse_list(r#"{"radius":0.1..1000=1,"method":"spin|zoom"}"#)).values(Bind::bound(fields)) + })); + let id = inspect(&host)[0]["id"].clone(); + let fields = |host: &DialogHost| inspect(host)[0]["fields"].clone(); + let set = |host: &mut DialogHost, params: Value| call(host, &ctx, "ui.dialog.set", params); + + let listed = json!([{"field": "radius", "value": 4.5}, {"field": "method", "value": "zoom"}]); + assert_eq!(set(&mut host, json!({"dialog": id, "fields": listed})), Ok(Value::Null)); + let settled = fields(&host); + assert_eq!((settled["radius"].as_f64(), &settled["method"]), (Some(4.5), &json!("zoom"))); + + let refused = json!([{"field": "radius", "value": 9}, {"field": "radius", "value": 5000}, {"field": "method", "value": "spin"}]); + assert!(set(&mut host, json!({"dialog": id, "fields": refused})).is_err_and(|e| e.contains("radius"))); + assert_eq!(fields(&host), settled, "a refusal in the middle sets nothing"); + + let too_many: Vec = (0..=MAX_DIALOG_FIELDS).map(|_| json!({"field": "radius", "value": 2})).collect(); + assert!(set(&mut host, json!({"dialog": id, "fields": too_many})).is_err()); + assert_eq!(fields(&host), settled, "a list over the limit sets nothing"); + + let unnamed = json!([{"field": "radius", "value": 9}, {"value": 1}]); + assert!(set(&mut host, json!({"dialog": id, "fields": unnamed})).is_err()); + assert_eq!(fields(&host), settled, "an item without a field sets nothing"); + + let both = json!({"dialog": id, "field": "radius", "value": 9, "fields": [{"field": "radius", "value": 8}]}); + assert!(set(&mut host, both).is_err()); + assert_eq!(fields(&host), settled, "`field` beside `fields` sets nothing"); +} + /// `"top"` names the top dialog of the stack: a child over its parent takes the field, the parent keeps its own; with /// nothing open the request says so. #[trial] diff --git a/crates/automation/tests/it/synthetic.rs b/crates/automation/tests/it/synthetic.rs index 520336154f..ee2c484f6c 100644 --- a/crates/automation/tests/it/synthetic.rs +++ b/crates/automation/tests/it/synthetic.rs @@ -5,6 +5,7 @@ use std::cell::{Cell, RefCell}; use std::rc::Rc; +use craft_automation::access::NO_TREE; 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; @@ -485,12 +486,37 @@ fn ui_ime_reaches_a_focused_text_field_as_a_preedit_then_a_commit_in_order() { /// A NaN or infinite point of a request is an error at the request, in either coordinate space, not a panic in the pass. #[trial] fn a_point_that_is_not_finite_is_refused() { + let no_controls = &|_: &_| Err(NO_TREE.to_owned()); for bad in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] { for at in [At::Screen(pos2(bad, 1.0)), At::Screen(pos2(1.0, bad)), At::Document(pos2(bad, 1.0), 0)] { - assert_eq!(at.resolve(&|_, p| Some(p)), Err(NOT_FINITE.to_owned()), "{at:?}"); + assert_eq!(at.resolve(&|_, p| Some(p), no_controls), Err(NOT_FINITE.to_owned()), "{at:?}"); } } - assert_eq!(At::Screen(pos2(3.0, 4.0)).resolve(&|_, _| None), Ok(pos2(3.0, 4.0))); + assert_eq!(At::Screen(pos2(3.0, 4.0)).resolve(&|_, _| None, no_controls), Ok(pos2(3.0, 4.0))); +} + +/// `ui.wheel` in lines queues whole notches in the line unit, clamped; without `unit` the turn is in points; an +/// unknown unit is refused. +#[trial] +fn a_wheel_in_lines_turns_by_notches() { + fn turn(rig: &mut Rig, params: Value) -> (egui::MouseWheelUnit, egui::Vec2) { + rig.send("ui.wheel", params); + rig.take() + .into_iter() + .flat_map(|pass| pass.events) + .find_map(|event| match event { + Event::MouseWheel { unit, delta, .. } => Some((unit, delta)), + _ => None, + }) + .expect("a pass saw the turn") + } + let mut rig = Rig::new(); + assert_eq!(turn(&mut rig, json!({"x": 30, "y": 20, "dy": 2.4, "unit": "lines"})), (egui::MouseWheelUnit::Line, egui::vec2(0.0, 2.0))); + assert_eq!(turn(&mut rig, json!({"dy": 500, "unit": "lines"})).1, egui::vec2(0.0, 100.0), "notches are clamped"); + assert_eq!(turn(&mut rig, json!({"dy": 2.4})), (egui::MouseWheelUnit::Point, egui::vec2(0.0, 2.4))); + let refused = input_method("ui.wheel", &json!({"dy": 1, "unit": "pages"}), &rig.host(), ViewportId::ROOT, &map); + 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 diff --git a/crates/behavior/src/canvas/mod.rs b/crates/behavior/src/canvas/mod.rs index 9ff5c9fb3b..0851e9509e 100644 --- a/crates/behavior/src/canvas/mod.rs +++ b/crates/behavior/src/canvas/mod.rs @@ -8,9 +8,9 @@ mod view; pub mod zoom; pub use history::{ViewHistory, ViewPlace}; -pub use units::{RulerUnits, Ticks}; +pub use units::{RulerUnits, TickLabels, Ticks}; pub use view::{CanvasView, resize_cursor}; -pub use zoom::ZoomLadder; +pub use zoom::{ZoomFloor, ZoomScheme}; /// A canvas body's mapping from canvas coordinates to its layer: `screen = canvas * scale + offset`. #[derive(Clone, Copy, Debug, PartialEq)] diff --git a/crates/behavior/src/canvas/units.rs b/crates/behavior/src/canvas/units.rs index a9ddbf6937..946e0d0aba 100644 --- a/crates/behavior/src/canvas/units.rs +++ b/crates/behavior/src/canvas/units.rs @@ -2,6 +2,8 @@ //! lives here; the text of a distance or a tick is written by craft-ui over `Env::units`, so no second number //! formatter exists. +use std::ops::RangeInclusive; + /// How a ruler divides its unit at a zoom. #[derive(Clone, Copy, Debug)] #[non_exhaustive] @@ -19,8 +21,20 @@ pub enum Ticks { Custom(fn(f64) -> (f64, u32)), } -/// The ruler unit of one document axis: its size and its ticks. Rulers label their ticks with it; guides use it for -/// the readout of a drag, their AccessKit values and Shift's snap to the ticks. +/// How a ruler writes the number at a labelled tick. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub enum TickLabels { + /// PhotoCraft's: the distance from the zero point with no minus sign, a step under 1 with at least two decimals + /// (`2.50`, `0.30`, `1.0000` on a sixteenth-inch ruler). + #[default] + Distance, + /// VectorCraft's: the signed position, with only the decimals the tick needs (`-2.5`, `0.3`, `1`). + Signed, +} + +/// The ruler unit of one document axis: its size, its ticks and how it labels them. Rulers label their ticks with it; +/// guides use it for the readout of a drag, their AccessKit values and Shift's snap to the ticks. #[derive(Clone, Copy, Debug)] #[non_exhaustive] pub struct RulerUnits { @@ -28,6 +42,8 @@ pub struct RulerUnits { pub per_doc: f64, /// How the ticks are spaced. pub ticks: Ticks, + /// How the labelled ticks are written. + pub labels: TickLabels, } impl Ticks { @@ -38,9 +54,16 @@ impl Ticks { } impl RulerUnits { - /// Ruler units of `per_doc` per document unit, spaced by `ticks`. + /// Ruler units of `per_doc` per document unit, spaced by `ticks`, labelled as [`TickLabels::Distance`]. pub const fn new(per_doc: f64, ticks: Ticks) -> Self { - Self { per_doc, ticks } + Self { per_doc, ticks, labels: TickLabels::Distance } + } + + /// The units with their ticks written as `labels`. + #[must_use] + pub const fn with_labels(mut self, labels: TickLabels) -> Self { + self.labels = labels; + self } /// Whole document pixels. @@ -78,22 +101,31 @@ impl RulerUnits { (position - zero) * self.per_doc } - /// The decimals a ruler writes a tick of labelled step `step` with. Whole ticks are whole numbers; a step of at - /// least 1 takes the decimals it has (none for 5, one for 2.5), a smaller one at least two (PhotoCraft's - /// `0.50`), more when it has them (0.025). - pub fn label_decimals(&self, step: f64) -> usize { - match self.ticks { + /// The least and most decimals a ruler writes a tick of labelled step `step` with. Whole ticks are whole numbers; + /// a step of at least 1 takes the decimals it has (none for 5, one for 2.5). Under [`TickLabels::Distance`] a + /// smaller step takes at least two (PhotoCraft's `0.50`), more when it has them (0.025), and every tick takes them + /// all; under [`TickLabels::Signed`] a tick drops the trailing zeros (`1` on a sixteenth-inch ruler). + pub fn label_decimals(&self, step: f64) -> RangeInclusive { + let most = match self.ticks { Ticks::Decimal { whole: true } => 0, - _ if step.abs() < 1.0 => step_decimals(step).max(2), + _ if step.abs() < 1.0 && self.labels == TickLabels::Distance => step_decimals(step).max(2), _ => step_decimals(step), + }; + match self.labels { + TickLabels::Distance => most..=most, + TickLabels::Signed => 0..=most, } } /// The number a ruler prints at the tick `value` (ruler units from the zero point) for a labelled step `step`: - /// the distance without a minus sign left of or above the zero point (PhotoCraft's `ruler_label`), rounded when - /// the ticks are whole. + /// under [`TickLabels::Distance`] the distance without a minus sign left of or above the zero point (PhotoCraft's + /// `ruler_label`), under [`TickLabels::Signed`] the value itself; rounded when the ticks are whole. pub fn label_value(&self, value: f64, step: f64) -> f64 { - if self.label_decimals(step) == 0 { value.abs().round() } else { value.abs() } + let value = match self.labels { + TickLabels::Distance => value.abs(), + TickLabels::Signed => value, + }; + if *self.label_decimals(step).end() == 0 { value.round() } else { value } } } diff --git a/crates/behavior/src/canvas/zoom.rs b/crates/behavior/src/canvas/zoom.rs index d4d7533303..00fca12994 100644 --- a/crates/behavior/src/canvas/zoom.rs +++ b/crates/behavior/src/canvas/zoom.rs @@ -1,4 +1,4 @@ -//! Zoom rules as pure functions on a [`CanvasView`]: Photoshop's zoom range and Zoom In / Zoom Out ladder, Fit on +//! Zoom rules as pure functions on a [`CanvasView`]: the zoom scheme's range and Zoom In / Zoom Out rungs, Fit on //! Screen and Fill Screen, a zoom about a point and the anchors of wheel zoom. //! //! Zoom levels here are **device zoom**: device pixels per document unit, so 1 is 100 % at any interface scale. @@ -7,7 +7,7 @@ //! `zoom` back into its own view type. //! //! Every way of setting the zoom (wheel, Zoom tool, menu, zoom field, navigator, automation) clamps through -//! [`ZoomLadder::clamp`], so no control can pull the zoom into a narrower range of its own. +//! [`ZoomScheme::clamp`], so no control can pull the zoom into a narrower range of its own. use super::view::CanvasView; use emath::{Pos2, Rect as ScreenRect, Vec2 as ScreenVec}; @@ -18,92 +18,145 @@ use std::ops::RangeInclusive; const RUNG_TOLERANCE_UP: f64 = 1.001; const RUNG_TOLERANCE_DOWN: f64 = 0.999; -/// Photoshop's zoom range and the Zoom In / Zoom Out ladder, measured on Photoshop 25.4: up to -/// 12800 %, down to where the document's shorter side is 2 px on screen (no lower than 0.1 % for -/// a ladder step). A ladder step goes from any zoom to the next rung (880 %: in to 1200 %, out to -/// 800 %). -pub struct ZoomLadder; +/// Photoshop's Zoom In / Zoom Out rungs (1 = 100 %), measured on Photoshop 25.4. +const PHOTOSHOP_RUNGS: [f64; 33] = [ + 0.001, + 0.002, + 0.003, + 0.004, + 0.005, + 0.007, + 0.01, + 0.015, + 0.02, + 0.03, + 0.04, + 0.05, + 0.0625, + 1.0 / 12.0, + 0.125, + 1.0 / 6.0, + 0.25, + 1.0 / 3.0, + 0.5, + 2.0 / 3.0, + 1.0, + 2.0, + 3.0, + 4.0, + 5.0, + 6.0, + 7.0, + 8.0, + 12.0, + 16.0, + 32.0, + 64.0, + 128.0, +]; -impl ZoomLadder { - /// 12800 %. - pub const MAX: f64 = 128.0; +/// The least zoom: the document's shorter side that many device pixels, or a fixed zoom in scheme units. +#[derive(Clone, Copy, Debug, PartialEq)] +#[non_exhaustive] +pub enum ZoomFloor { + /// The document's shorter side is this many device pixels. + ShorterSide(f64), + /// A fixed zoom in scheme units. + Fixed(f64), +} - /// Zoom In / Zoom Out rungs (1 = 100 %). - pub const STEPS: [f64; 33] = [ - 0.001, - 0.002, - 0.003, - 0.004, - 0.005, - 0.007, - 0.01, - 0.015, - 0.02, - 0.03, - 0.04, - 0.05, - 0.0625, - 1.0 / 12.0, - 0.125, - 1.0 / 6.0, - 0.25, - 1.0 / 3.0, - 0.5, - 2.0 / 3.0, - 1.0, - 2.0, - 3.0, - 4.0, - 5.0, - 6.0, - 7.0, - 8.0, - 12.0, - 16.0, - 32.0, - 64.0, - 128.0, - ]; +/// A zoom range and its Zoom In and Out rungs in scheme units (1 = its 100 %); `hundred` is the device zoom of +/// 100 %. A step goes from any zoom to the next rung (880 %: in to 1200 %, out to 800 %). +#[derive(Clone, Copy, Debug, PartialEq)] +#[non_exhaustive] +pub struct ZoomScheme { + /// The Zoom In and Out rungs, lowest first. + pub rungs: &'static [f64], + /// The greatest zoom. + pub max: f64, + /// The least zoom. + pub floor: ZoomFloor, + /// The device zoom of 100 %. + pub hundred: f64, +} - /// The lowest zoom for a document of `size` units: its shorter side 2 device pixels. An empty - /// size (a view before its first frame) gives the lowest rung. - pub fn min(size: Size) -> f64 { - match size.width.min(size.height) { - short if short.is_finite() && short > 0.0 => (2.0 / short).min(Self::MAX), - _ => Self::STEPS[0], +impl ZoomScheme { + /// Photoshop's: 33 rungs, up to 12800 %, the shorter side 2 px at the least. + pub const PHOTOSHOP: ZoomScheme = ZoomScheme { rungs: &PHOTOSHOP_RUNGS, max: 128.0, floor: ZoomFloor::ShorterSide(2.0), hundred: 1.0 }; + + /// Illustrator's: 26 stops from 3.13 % to 64000 %. + pub const ILLUSTRATOR: ZoomScheme = ZoomScheme { + rungs: &[ + 0.0313, 0.0417, 0.0625, 0.0833, 0.125, 0.1667, 0.25, 0.3333, 0.5, 0.6667, 1.0, 1.5, 2.0, 3.0, 4.0, 6.0, 8.0, 12.0, 16.0, 24.0, 32.0, + 48.0, 64.0, 128.0, 256.0, 640.0, + ], + max: 640.0, + floor: ZoomFloor::Fixed(0.0313), + hundred: 1.0, + }; + + /// The scheme with `device` as the device zoom of 100 %. + pub const fn with_hundred(self, device: f64) -> Self { + ZoomScheme { hundred: device, ..self } + } + + /// The least device zoom for a document of `size`. An empty size (a view before its first frame) gives the lowest + /// rung. + pub fn min(&self, size: Size) -> f64 { + match self.floor { + ZoomFloor::ShorterSide(pixels) => match size.width.min(size.height) { + short if short.is_finite() && short > 0.0 => (pixels / short).min(self.max_device()), + _ => self.rungs.first().map_or(self.hundred, |rung| rung * self.hundred), + }, + ZoomFloor::Fixed(zoom) => zoom * self.hundred, } } - /// `zoom` within the range for a document of `size`; a zoom that is not a finite number - /// becomes 100 %. - pub fn clamp(zoom: f64, size: Size) -> f64 { - if zoom.is_finite() { zoom.min(Self::MAX).max(Self::min(size)) } else { 1.0 } + /// The greatest device zoom. + pub fn max_device(&self) -> f64 { + self.max * self.hundred } - /// Zoom In (`dir` > 0) or Zoom Out (`dir` < 0) from `zoom`: the next rung past it (a zoom - /// within 0.1 % of a rung counts as on it), within the document's range. - pub fn step(zoom: f64, dir: i32, size: Size) -> f64 { - Self::step_in_range(zoom, dir, Self::min(size)..=Self::MAX) + /// `device` within the range for a document of `size`; a zoom that is not a finite number becomes 100 %. + pub fn clamp(&self, device: f64, size: Size) -> f64 { + if device.is_finite() { device.min(self.max_device()).max(self.min(size)) } else { self.hundred } } - /// [`step`](Self::step) within an explicit range (a navigator or a zoom field with bounds of - /// its own). - pub fn step_in_range(zoom: f64, dir: i32, range: RangeInclusive) -> f64 { + /// Zoom In (`dir` > 0) or Zoom Out (`dir` < 0) from `device`: the next rung past it (a zoom within 0.1 % of a rung + /// counts as on it), within the document's range. + pub fn step(&self, device: f64, dir: i32, size: Size) -> f64 { + self.step_in_range(device, dir, self.min(size)..=self.max_device()) + } + + /// [`step`](Self::step) within an explicit range of device zoom (a navigator or a zoom field with bounds of its + /// own). + pub fn step_in_range(&self, device: f64, dir: i32, range: RangeInclusive) -> f64 { let (lo, hi) = range.into_inner(); - let z = if zoom.is_finite() { zoom.min(hi).max(lo) } else { 1.0 }; + let z = if device.is_finite() { device.min(hi).max(lo) } else { self.hundred }; + let rungs = self.rungs.iter().map(|rung| rung * self.hundred); let next = if dir > 0 { - Self::STEPS.iter().copied().find(|s| *s > z * RUNG_TOLERANCE_UP).unwrap_or(hi) + rungs.clone().find(|s| *s > z * RUNG_TOLERANCE_UP).unwrap_or(hi) } else { - Self::STEPS.iter().rev().copied().find(|s| *s < z * RUNG_TOLERANCE_DOWN).unwrap_or(z) + rungs.rev().find(|s| *s < z * RUNG_TOLERANCE_DOWN).unwrap_or(z) }; if next.is_finite() { next.min(hi).max(lo) } else { z } } - /// A zoom field's range in percent: the document's range widened to include `zoom` itself. - /// A field narrower than the zoom would clamp it and write it back every pass. - pub fn percent_range(zoom: f64, size: Size) -> RangeInclusive { - let z = if zoom.is_finite() { zoom } else { 1.0 }; - (Self::min(size).min(z) * 100.0)..=(Self::MAX.max(z) * 100.0) + /// A zoom field's range in percent: the document's range widened to include `device` itself. A field narrower than + /// the zoom would clamp it and write it back every pass. + pub fn percent_range(&self, device: f64, size: Size) -> RangeInclusive { + let z = if device.is_finite() { device } else { self.hundred }; + self.percent(self.min(size).min(z))..=self.percent(self.max_device().max(z)) + } + + /// `device` zoom as percent of the scheme's 100 %. + pub fn percent(&self, device: f64) -> f64 { + device / self.hundred * 100.0 + } + + /// The device zoom of `percent` of the scheme's 100 %. + pub fn device(&self, percent: f64) -> f64 { + percent / 100.0 * self.hundred } } @@ -113,9 +166,9 @@ pub fn device(view: &CanvasView, pixels_per_point: f32) -> f64 { } /// `view` at `device` zoom (1 = 100 %), clamped to the zoom range of a document of `size`, with its centre kept. -pub fn with_device(view: &CanvasView, device: f64, size: Size, pixels_per_point: f32) -> CanvasView { +pub fn with_device(view: &CanvasView, device: f64, size: Size, pixels_per_point: f32, scheme: &ZoomScheme) -> CanvasView { let mut next = *view; - next.zoom = CanvasView::points_per_unit(ZoomLadder::clamp(device, size), pixels_per_point); + next.zoom = CanvasView::points_per_unit(scheme.clamp(device, size), pixels_per_point); next } @@ -132,30 +185,30 @@ fn shown_extent(view: &CanvasView, size: Size) -> (f64, f64, f64, f64) { /// each side, never past 100 % (one document pixel per device pixel, so a 150 % display does not open /// documents magnified). `size` is in document units; the view's [`aspect`](CanvasView::aspect) and rotation /// are taken into account. -pub fn fit(view: &mut CanvasView, size: Size, pixels_per_point: f32, margin: f64) { - fit_up_to(view, size, pixels_per_point, 1.0, margin); +pub fn fit(view: &mut CanvasView, size: Size, pixels_per_point: f32, margin: f64, scheme: &ZoomScheme) { + fit_up_to(view, size, pixels_per_point, scheme.hundred, margin, scheme); } /// [`fit`] with the device zoom allowed up to `max_device` (1 = 100 %) instead of 100 %: a small document is /// magnified to fill the canvas, as Photoshop's Fit on Screen does. -pub fn fit_up_to(view: &mut CanvasView, size: Size, pixels_per_point: f32, max_device: f64, margin: f64) { - fit_rect_up_to(view, Rect::from_origin_size(Point::ORIGIN, size), size, pixels_per_point, max_device, Vec2::new(margin, margin)); +pub fn fit_up_to(view: &mut CanvasView, size: Size, pixels_per_point: f32, max_device: f64, margin: f64, scheme: &ZoomScheme) { + fit_rect_up_to(view, Rect::from_origin_size(Point::ORIGIN, size), size, pixels_per_point, max_device, Vec2::new(margin, margin), scheme); } /// Fit a part of the document on screen (an artboard, the selected layers' bounds): centre `rect`, in document /// units, and zoom so all of it shows inside `view.rect` less `margin.x` points at the left and right and `margin.y` -/// at the top and bottom, up to the zoom ceiling. +/// at the top and bottom, up to the scheme's greatest zoom. /// The zoom stays inside the range of a document of `size`; an empty `rect` zooms to that ceiling about its centre. -pub fn fit_rect(view: &mut CanvasView, rect: Rect, size: Size, pixels_per_point: f32, margin: Vec2) { - fit_rect_up_to(view, rect, size, pixels_per_point, ZoomLadder::MAX, margin); +pub fn fit_rect(view: &mut CanvasView, rect: Rect, size: Size, pixels_per_point: f32, margin: Vec2, scheme: &ZoomScheme) { + fit_rect_up_to(view, rect, size, pixels_per_point, scheme.max_device(), margin, scheme); } -fn fit_rect_up_to(view: &mut CanvasView, rect: Rect, size: Size, pixels_per_point: f32, max_device: f64, margin: Vec2) { +fn fit_rect_up_to(view: &mut CanvasView, rect: Rect, size: Size, pixels_per_point: f32, max_device: f64, margin: Vec2, scheme: &ZoomScheme) { let rect = rect.abs(); let (shown_w, shown_h, sin, cos) = shown_extent(view, rect.size()); let (bw, bh) = (shown_w * cos + shown_h * sin, shown_w * sin + shown_h * cos); let scale = ((f64::from(view.rect.width()) - 2.0 * margin.x) / bw).min((f64::from(view.rect.height()) - 2.0 * margin.y) / bh); - let device = ZoomLadder::clamp((scale * f64::from(pixels_per_point)).min(max_device), size); + let device = scheme.clamp((scale * f64::from(pixels_per_point)).min(max_device), size); view.zoom = CanvasView::points_per_unit(device, pixels_per_point); view.center = rect.center(); } @@ -170,12 +223,12 @@ pub fn wrapped_canvas(view: &CanvasView, document: Size, canvas: ScreenRect) -> /// Fill Screen: centre the document and zoom until it covers `view.rect`; one axis may extend /// past the canvas. -pub fn fill(view: &mut CanvasView, size: Size, pixels_per_point: f32) { +pub fn fill(view: &mut CanvasView, size: Size, pixels_per_point: f32, scheme: &ZoomScheme) { let (shown_w, shown_h, sin, cos) = shown_extent(view, size); let (rw, rh) = (f64::from(view.rect.width()), f64::from(view.rect.height())); // The canvas rectangle's extent along the document's axes, which the document must cover. let (ex, ey) = (rw * cos + rh * sin, rw * sin + rh * cos); - let device = ZoomLadder::clamp((ex / shown_w).max(ey / shown_h) * f64::from(pixels_per_point), size); + let device = scheme.clamp((ex / shown_w).max(ey / shown_h) * f64::from(pixels_per_point), size); view.zoom = CanvasView::points_per_unit(device, pixels_per_point); view.center = Point::new(size.width / 2.0, size.height / 2.0); } @@ -213,12 +266,12 @@ pub fn wheel_anchor(view: &CanvasView, screen: Pos2, size: Size) -> Pos2 { if nearest == d { screen } else { view.to_screen(nearest) } } -/// View › Zoom In (`dir` > 0) or Zoom Out (`dir` < 0): the next ladder rung -/// ([`ZoomLadder::step`]), the view's centre unchanged. Returns whether the zoom changed (it does +/// View › Zoom In (`dir` > 0) or Zoom Out (`dir` < 0): the next rung of the scheme +/// ([`ZoomScheme::step`]), the view's centre unchanged. Returns whether the zoom changed (it does /// not at a limit). -pub fn step(view: &mut CanvasView, dir: i32, size: Size, pixels_per_point: f32) -> bool { +pub fn step(view: &mut CanvasView, dir: i32, size: Size, pixels_per_point: f32, scheme: &ZoomScheme) -> bool { let current = device(view, pixels_per_point); - let next = ZoomLadder::step(current, dir, size); + let next = scheme.step(current, dir, size); let changed = next.is_finite() && (next / current - 1.0).abs() > 1e-9; if changed { view.zoom = CanvasView::points_per_unit(next, pixels_per_point); diff --git a/crates/behavior/src/codec.rs b/crates/behavior/src/codec.rs index 0aa23ef1bf..cb45db81a6 100644 --- a/crates/behavior/src/codec.rs +++ b/crates/behavior/src/codec.rs @@ -62,6 +62,11 @@ pub trait Codec { true } + /// Whether a paste the codec reads whole replaces the field's text, wherever the caret is. + fn whole_paste(&self, _pasted: &str) -> bool { + false + } + /// The text the field shows after committing `v`, which was parsed from `text`. fn normalise(&self, _text: &str, v: &Self::Value) -> String { self.format(v) @@ -103,6 +108,10 @@ impl Codec for &C { (**self).filter(c) } + fn whole_paste(&self, pasted: &str) -> bool { + (**self).whole_paste(pasted) + } + fn normalise(&self, text: &str, v: &Self::Value) -> String { (**self).normalise(text, v) } @@ -158,6 +167,8 @@ pub struct NumberCodec { custom: Option, /// Typing rules of a zoom field ([`NumberCodec::zoom_typing`]). zoom: bool, + /// A lone percentage is that share of the start value ([`NumberCodec::share_of_start`]). + share: bool, signed_zoom: bool, } @@ -168,6 +179,7 @@ impl fmt::Debug for NumberCodec { .field("decimals", &self.decimals) .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() @@ -185,6 +197,7 @@ impl PartialEq for NumberCodec { && self.decimals == other.decimals && self.fixed == other.fixed && self.zoom == other.zoom + && self.share == other.share && self.signed_zoom == other.signed_zoom && same_custom } @@ -220,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, signed_zoom: 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 @@ -269,6 +282,14 @@ impl NumberCodec { Ok((number, ParseNote { cut, ..ParseNote::default() })) } + /// The same codec reading a lone percentage (`50%`, [`Reader::share`]) as that share of the value the edit + /// started from, as a size field does: every pass of the edit reads the same value. With no start value it is no + /// value, so it never applies as it is typed; it applies on commit. + pub fn share_of_start(mut self) -> Self { + self.share = true; + self + } + /// The same codec writing at most `decimals` decimal places. pub fn at_most(mut self, decimals: usize) -> Self { self.decimals = self.decimals.min(decimals); @@ -349,6 +370,11 @@ impl Codec for NumberCodec { if self.zoom { return self.read_zoom(trimmed).map(|(number, note)| (Some(number), note)); } + if self.share + && let Some(share) = self.reader.share(trimmed) + { + return start.map(|start| (Some(start * share), ParseNote::default())).ok_or(NotAValue); + } match self.reader.read_tagged(text, *start) { Ok((number, tag)) => Ok((Some(number), ParseNote { unit: tag, ..ParseNote::default() })), Err(rejected) => { diff --git a/crates/behavior/src/dock/arrange.rs b/crates/behavior/src/dock/arrange.rs index ec2bc27d85..7984ce4498 100644 --- a/crates/behavior/src/dock/arrange.rs +++ b/crates/behavior/src/dock/arrange.rs @@ -4,15 +4,16 @@ use emath::{Rect, vec2}; /// One Window › Arrange entry. The n-up entries split the document area into that many -/// cells and put one document group in each, and Tile one cell per document; the rest act on -/// windows and views. Saved under the command names (`"twoUpVertical"`, `"tile"`). +/// cells and put one document group in each, and Tile All and Tile one cell per document; the +/// rest act on windows and views. Saved under the command names (`"twoUpVertical"`, `"tile"`). #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] #[serde(rename_all = "camelCase")] #[non_exhaustive] pub enum Arrangement { - /// Tiles every document window across the document area, side by side. + /// One cell per document across the document area, side by side, floating windows docked + /// first. TileAllVertically, - /// Tiles every document window across the document area, stacked. + /// One cell per document across the document area, stacked, floating windows docked first. TileAllHorizontally, /// Two cells, side by side. TwoUpVertical, diff --git a/crates/behavior/src/dock/windows.rs b/crates/behavior/src/dock/windows.rs index 47246507bc..64d3a81b54 100644 --- a/crates/behavior/src/dock/windows.rs +++ b/crates/behavior/src/dock/windows.rs @@ -33,7 +33,7 @@ pub struct DocumentWindows { /// The floating groups, each with its window rect. #[serde(with = "floating_serde")] pub floating: Vec<(DocumentGroup, Rect)>, - /// The n-up or Tile arrangement the document area shows: set by Window › Arrange, cleared by + /// The n-up, Tile All or Tile arrangement the document area shows: set by Window › Arrange, cleared by /// Consolidate and by floating a document. #[serde(default)] pub arrangement: Option, diff --git a/crates/behavior/src/dock/workspace.rs b/crates/behavior/src/dock/workspace.rs index 6f18bf113f..14a752fe9e 100644 --- a/crates/behavior/src/dock/workspace.rs +++ b/crates/behavior/src/dock/workspace.rs @@ -162,6 +162,44 @@ impl

Workspace

{ } impl Workspace

{ + /// Renames a panel in `layout`, `hidden` and `floated` (keys and anchors), keeping its place; all or nothing. + /// An edit: it moves the revision and keeps the generation. `MissingPanel` when `from` is in none of them, `DuplicatePanel` when `to` is + /// already there. + pub fn rename(&mut self, from: &P, to: P) -> Result<(), DockError> { + if !self.holds(from) { + return Err(DockError::MissingPanel); + } + if self.holds(&to) { + return Err(DockError::DuplicatePanel); + } + let swap = |panel: &mut P| { + if *panel == *from { + *panel = to.clone(); + } + }; + let mut proposed = self.clone(); + if let Some(root) = proposed.layout.root.as_mut() { + rename_in_tree(root, &swap); + } + for window in &mut proposed.layout.floating { + rename_in_column(&mut window.column, &swap); + } + for (panel, location) in proposed.hidden.iter_mut().chain(&mut proposed.floated) { + swap(panel); + rename_in_location(location, &swap); + } + proposed.validate()?; + let Workspace { layout, hidden, floated, .. } = proposed; + (self.layout, self.hidden, self.floated) = (layout, hidden, floated); + self.touch(); + Ok(()) + } + + /// Whether `panel` is in the layout or is the key of a hidden or floated record. + fn holds(&self, panel: &P) -> bool { + self.layout.contains(panel) || self.hidden.iter().chain(&self.floated).any(|(held, _)| held == panel) + } + /// Check the version, the layout, that every hidden panel is hidden once and absent /// from the layout and its record is bounded, and that the floated records are bounded and one per panel. pub fn validate(&self) -> Result<(), DockError> { @@ -585,6 +623,37 @@ fn dock_columns_mut

(root: &mut Node

) -> Vec<&mut Column

> { out } +/// Applies `swap` to every panel of `root`, walking the tree with a stack: a loaded tree can be deeper than the call +/// stack. +fn rename_in_tree

(root: &mut Node

, swap: &impl Fn(&mut P)) { + let mut visit = vec![root]; + while let Some(node) = visit.pop() { + match node { + Node::Split { first, second, .. } => { + visit.push(second); + visit.push(first); + } + Node::Tabs { panels, .. } => panels.iter_mut().for_each(swap), + Node::Stack { entries } => entries.iter_mut().for_each(|entry| swap(&mut entry.panel)), + Node::Dock { columns, .. } => columns.iter_mut().for_each(|column| rename_in_column(column, swap)), + } + } +} + +/// Applies `swap` to every panel of the groups of `column`. +fn rename_in_column

(column: &mut Column

, swap: &impl Fn(&mut P)) { + column.groups.iter_mut().for_each(|group| group.panels.iter_mut().for_each(swap)); +} + +/// Applies `swap` to the panels a location names: its anchor, its siblings and the tab it goes before. +fn rename_in_location

(location: &mut Location

, swap: &impl Fn(&mut P)) { + location.anchor.iter_mut().for_each(swap); + location.sibling.iter_mut().for_each(swap); + if let DockPlacement::Tab { before: Some(panel) } = &mut location.placement { + swap(panel); + } +} + /// Whether `panel` is in a floating window of `layout`. fn floats(layout: &Layout

, panel: &P) -> bool { matches!(layout.place(panel), Some(PanelPlace::Floating { .. })) diff --git a/crates/behavior/src/edit_history.rs b/crates/behavior/src/edit_history.rs index c4484321d8..0b05d3c00c 100644 --- a/crates/behavior/src/edit_history.rs +++ b/crates/behavior/src/edit_history.rs @@ -6,6 +6,9 @@ use std::sync::Arc; /// Most steps a history keeps. const LIMIT: usize = 100; +/// How a value weighs under a history's budget. +type Weigh = fn(&T) -> usize; + /// Which way [`EditHistory::step`] goes. #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] @@ -21,6 +24,8 @@ pub enum Step { struct Entry { value: T, name: Arc, + /// The weight of `value` under the history's budget ([`EditHistory::with_budget`]). + weight: usize, } /// The gesture under way: its name, taken from its `Begin`. @@ -38,13 +43,39 @@ pub struct EditHistory { redo: Vec>, /// The value as of the latest step. settled: T, + /// The weight of `settled`; 0 without a budget. + settled_weight: usize, open: Option, + /// The most summed weight the undo steps keep, and how a value weighs. + budget: Option<(usize, Weigh)>, } impl EditHistory { /// A history that starts at `now`. pub fn new(now: &T) -> Self { - EditHistory { undo: Vec::new(), redo: Vec::new(), settled: now.clone(), open: None } + EditHistory { undo: Vec::new(), redo: Vec::new(), settled: now.clone(), settled_weight: 0, open: None, budget: None } + } + + /// The undo steps' summed weight stays at or under `max`: after each push the oldest go first, the newest always + /// stays; each weight is measured once at push. Without a budget nothing changes. + #[must_use] + pub fn with_budget(mut self, max: usize, weight: fn(&T) -> usize) -> Self { + self.settled_weight = weight(&self.settled); + self.budget = Some((max, weight)); + self.trim(); + self + } + + /// Drops the oldest undo steps while their summed weight passes the budget; the newest stays. + fn trim(&mut self) { + let Some((max, _)) = self.budget else { return }; + let mut total = self.undo.iter().fold(0usize, |sum, entry| sum.saturating_add(entry.weight)); + let mut gone = 0; + while total > max && gone + 1 < self.undo.len() { + total = total.saturating_sub(self.undo[gone].weight); + gone += 1; + } + self.undo.drain(..gone); } /// Takes in one event. Events of a gesture other than the open one are ignored. A concrete @@ -76,16 +107,22 @@ impl EditHistory { } 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); } - self.undo.push(Entry { value: before, name }); + self.undo.push(Entry { value: before, name, weight }); self.redo.clear(); + self.trim(); } /// Steps `now` back or forward. False when there is nowhere to go. An open gesture is abandoned. @@ -96,7 +133,8 @@ impl EditHistory { Step::Redo => (&mut self.redo, &mut self.undo), }; let Some(entry) = from.pop() else { return false }; - to.push(Entry { value: std::mem::replace(now, entry.value.clone()), name: entry.name }); + let weight = std::mem::replace(&mut self.settled_weight, entry.weight); + to.push(Entry { value: std::mem::replace(now, entry.value.clone()), name: entry.name, weight }); self.settled = entry.value; true } @@ -107,6 +145,7 @@ impl EditHistory { pub fn take_back(&mut self) -> Option { self.open = None; let entry = self.undo.pop()?; + self.settled_weight = entry.weight; self.settled = entry.value.clone(); Some(entry.value) } @@ -165,6 +204,52 @@ mod tests { assert_eq!(now, 0, "the undo takes the step before the one taken back"); } + fn weigh(value: &i32) -> usize { + usize::try_from(*value).unwrap_or(0) + } + + fn undo_weight(history: &EditHistory) -> usize { + history.undo.iter().map(|entry| entry.weight).sum() + } + + #[test] + fn a_weight_budget_drops_the_oldest_steps_and_keeps_the_newest() { + let mut history = EditHistory::new(&0).with_budget(10, weigh); + for (before, after) in [(0, 4), (4, 5), (5, 6)] { + history.record(&set(before, after)); + } + assert_eq!(history.undo.len(), 3, "weights 0, 4 and 5 fit"); + history.record(&set(6, 7)); + assert_eq!(history.undo.len(), 1, "the oldest went until the sum fit, the newest stayed"); + + let mut now = 7; + assert!(history.step(&mut now, Step::Undo)); + assert_eq!(now, 6); + assert!(!history.can_undo()); + assert!(history.step(&mut now, Step::Redo)); + assert_eq!((now, undo_weight(&history)), (7, 6), "the redo gave the step back with its own weight"); + + history.record(&set(7, 9)); + assert_eq!((history.undo.len(), undo_weight(&history)), (1, 7), "6 + 7 passes 10, the oldest went"); + + assert!(history.step(&mut now, Step::Undo)); + history.record(&set(7, 8)); + assert_eq!(history.redo_len(), 0, "a new step after an undo clears redo"); + assert_eq!(undo_weight(&history), 7); + + let mut long = EditHistory::new(&0).with_budget(usize::MAX, |_| 1); + for n in 0..120 { + long.record(&set(n, n + 1)); + } + assert_eq!(long.undo.len(), LIMIT, "the step limit still applies"); + + let mut free = EditHistory::new(&0); + for n in 0..3 { + free.record(&set(n, n + 1)); + } + assert_eq!((free.undo.len(), undo_weight(&free)), (3, 0), "without a budget nothing is trimmed or weighed"); + } + #[test] fn redo_len_counts_the_undone_steps_until_a_new_step() { let mut history = EditHistory::new(&0); diff --git a/crates/behavior/src/editor.rs b/crates/behavior/src/editor.rs index 7e9467f2c7..b15112b51e 100644 --- a/crates/behavior/src/editor.rs +++ b/crates/behavior/src/editor.rs @@ -87,7 +87,12 @@ pub enum EditorInput { /// An edit command from the command queue. Edit(EditCommand), /// Enter. - Newline, + #[non_exhaustive] + Newline { + /// Shift was held: an editor that gives Shift+Enter its own meaning (a line break within the paragraph) tells + /// it from a plain Enter. + shift: bool, + }, /// Tab. Tab, /// Shift+Tab, which reaches only a document canvas's editor part that keeps Tab. @@ -107,6 +112,11 @@ impl EditorInput { EditorInput::Delete { forward, by, shift } } + /// A `Newline`, with Shift held when `shift`. + pub const fn newline(shift: bool) -> Self { + EditorInput::Newline { shift } + } + /// A `DeleteSurrounding` of `before` and `after` characters. pub const fn delete_surrounding(before: usize, after: usize) -> Self { EditorInput::DeleteSurrounding { before, after, unit: SurroundingUnit::Chars } diff --git a/crates/behavior/src/focus.rs b/crates/behavior/src/focus.rs index e215a14fd8..e670e3b61a 100644 --- a/crates/behavior/src/focus.rs +++ b/crates/behavior/src/focus.rs @@ -1,5 +1,5 @@ -//! Pure focus rules (spec 9.3, 9.4, 8.3): key ownership, focus after removal, the Escape order and the -//! focus-on-press kinds. The runtime's focus service feeds them facts and applies the result. +//! Pure focus rules (spec 9.3, 9.4, 8.3): key ownership, the Escape order and the focus-on-press kinds. The runtime's +//! focus service feeds them facts and applies the result. use crate::sense::Sense; @@ -86,14 +86,6 @@ pub fn key_owner(blocked: bool, present: &[OwnerClass]) -> KeyOwner { .map_or(KeyOwner::Class(OwnerClass::App), |class| KeyOwner::Class(*class)) } -/// The stop that takes focus when `focused` is no longer registered: the one after it in last pass's order -/// that is still registered, else the one before. `None` leaves the scope's initial stop to decide. -pub fn after_removal<'a, T: PartialEq>(last_order: &'a [T], focused: &T, registered: impl Fn(&T) -> bool) -> Option<&'a T> { - let at = last_order.iter().position(|stop| stop == focused)?; - let after = last_order[at + 1..].iter().find(|stop| registered(stop)); - after.or_else(|| last_order[..at].iter().rev().find(|stop| registered(stop))) -} - /// What the Escape of one pass reaches first. #[derive(Clone, Copy, Debug, PartialEq, Eq)] #[non_exhaustive] diff --git a/crates/behavior/src/grid.rs b/crates/behavior/src/grid.rs index b9c1e5bfd2..bd782a0e9c 100644 --- a/crates/behavior/src/grid.rs +++ b/crates/behavior/src/grid.rs @@ -119,10 +119,11 @@ impl GridCursor { cursor } - /// A cursor for the sweep that asks each column for its least: every column but a `Fixed` one is placed as a - /// `Content` column whose cells measure in no bound along x, so each column measures its widest cell. + /// A cursor for the sweep that asks each column for its least: the cells of every `Content` and `Fill` column + /// measure in no bound along x, so each column measures its widest cell. A `Fill` column stays one, so a child + /// that fills its width measures its own width there, where a `Content` column would hold it and take none. pub fn unbounded(flow: Flow, columns: &[ColumnWidth], gap: Vec2) -> Self { - let mut cursor = Self::new(flow, &as_content(columns), gap, &GridMeasure::default()); + let mut cursor = Self::new(flow, columns, gap, &GridMeasure::default()); cursor.unbounded = true; cursor } @@ -185,7 +186,7 @@ impl GridCursor { let count = self.columns.len().max(1); let (column, _, _, top) = self.next_place(); let width = match self.columns.get(column) { - Some(ColumnWidth::Content) if self.unbounded => f32::INFINITY, + Some(ColumnWidth::Content | ColumnWidth::Fill { .. }) if self.unbounded => f32::INFINITY, Some(ColumnWidth::Content) => { // Every other column keeps at least its least: a column that fills keeps only that, and so does a // content column when each column measures alone. diff --git a/crates/behavior/src/hit.rs b/crates/behavior/src/hit.rs index 033d02fdfb..d2cd1f848b 100644 --- a/crates/behavior/src/hit.rs +++ b/crates/behavior/src/hit.rs @@ -51,6 +51,15 @@ pub enum HitShape { /// The corners of the polygon cut out of `within`. polygon: Vec, }, + /// A shape with discs cut out of it: a widget part over a bounding-box handle leaves the handle's disc to the + /// handle. + #[non_exhaustive] + Excluding { + /// The shape the discs are cut out of. + shape: Box, + /// The discs cut out, each a centre and a radius. + holes: Vec<(Pos2, f32)>, + }, } impl HitShape { @@ -81,10 +90,16 @@ impl HitShape { HitShape::OutsidePolygon { within, polygon } } + /// `shape` without the discs `holes` (a centre and a radius each). + pub fn excluding(shape: HitShape, holes: Vec<(Pos2, f32)>) -> HitShape { + HitShape::Excluding { shape: Box::new(shape), holes } + } + /// The smallest rectangle around the shape. pub fn bounds(&self) -> Rect { match self { HitShape::Rect(rect) | HitShape::OutsidePolygon { within: rect, .. } => *rect, + HitShape::Excluding { shape, .. } => shape.bounds(), HitShape::Circle { center, radius } => Rect::from_center_size(*center, Vec2::splat(radius * 2.0)), HitShape::Segment { a, b } => Rect::from_two_pos(*a, *b), HitShape::Polyline { points, .. } | HitShape::Polygon(points) => { @@ -104,6 +119,10 @@ impl HitShape { HitShape::Polyline { points: line, closed, reach } => HitShape::Polyline { points: points(line), closed: *closed, reach: *reach }, HitShape::Polygon(polygon) => HitShape::Polygon(points(polygon)), HitShape::OutsidePolygon { within, polygon } => HitShape::OutsidePolygon { within: within.translate(by), polygon: points(polygon) }, + HitShape::Excluding { shape, holes } => HitShape::Excluding { + shape: Box::new(shape.translated(by)), + holes: holes.iter().map(|(center, radius)| (*center + by, *radius)).collect(), + }, } } @@ -130,6 +149,18 @@ impl HitShape { (HitShape::OutsidePolygon { within: area, polygon }, HitShape::OutsidePolygon { within: to_area, polygon: to_polygon }) => { HitShape::OutsidePolygon { within: rect(*area, *to_area), polygon: points(polygon, to_polygon) } } + (HitShape::Excluding { shape, holes }, HitShape::Excluding { shape: to_shape, holes: to_holes }) => { + let holes = if holes.len() == to_holes.len() { + holes + .iter() + .zip(to_holes) + .map(|((center, radius), (to_center, to_radius))| (pos(*center, *to_center), near(*radius, *to_radius))) + .collect() + } else { + holes.clone() + }; + HitShape::Excluding { shape: Box::new(shape.snapped(to_shape, within)), holes } + } _ => self.clone(), } } @@ -152,6 +183,7 @@ impl HitShape { || closing.is_some_and(|(first, last)| segment_distance(point, *last, *first) <= reach) } HitShape::OutsidePolygon { within, polygon } => within.contains(point) && !inside_polygon(point, polygon), + HitShape::Excluding { shape, holes } => shape.hit_across(point, across) && !in_hole(holes, point), HitShape::Polygon(points) => { let bounds = self.bounds(); let small = bounds.width() < across || bounds.height() < across; @@ -174,10 +206,16 @@ impl HitShape { } HitShape::Polygon(points) => inside_polygon(point, points), HitShape::OutsidePolygon { within, polygon } => within.contains(point) && !inside_polygon(point, polygon), + HitShape::Excluding { shape, holes } => shape.hit(point) && !in_hole(holes, point), } } } +/// Whether `point` lies inside one of the discs `holes`. +fn in_hole(holes: &[(Pos2, f32)], point: Pos2) -> bool { + holes.iter().any(|(center, radius)| center.distance(point) <= *radius) +} + impl From for HitShape { fn from(rect: Rect) -> Self { HitShape::Rect(rect) diff --git a/crates/behavior/src/hold_repeat.rs b/crates/behavior/src/hold_repeat.rs new file mode 100644 index 0000000000..40fba66260 --- /dev/null +++ b/crates/behavior/src/hold_repeat.rs @@ -0,0 +1,39 @@ +//! Steps due while a press is held, as a spinner button repeats. + +/// A press held on a spinner button, known by the pass time it began. It keeps nothing between passes: a pass builds it +/// from the press's own start time and asks how many repeats the pass owes, so a rerun pass (no time elapsed) owes none. +/// A different concept from `HoldZoom`, which zooms continuously at a rate. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct HoldRepeat { + start: f64, +} + +impl HoldRepeat { + /// Seconds a press is held before the steps repeat. + pub const DELAY: f64 = 0.45; + + /// Seconds between repeated steps. + pub const INTERVAL: f64 = 0.06; + + /// A press that began at pass time `start`, in seconds. + pub const fn new(start: f64) -> Self { + HoldRepeat { start } + } + + /// How many repeat instants (`start + DELAY + k * INTERVAL`, `k >= 0`) lie at or before `at`. + fn reached(&self, at: f64) -> u32 { + let since = at - self.start - Self::DELAY; + if since < 0.0 { 0 } else { (since / Self::INTERVAL).floor() as u32 + 1 } + } + + /// The repeats due in the pass at `now` that follows another `elapsed` seconds after: the repeat instants in + /// `(now - elapsed, now]`. The step of the press itself is not counted. + pub fn due(&self, now: f64, elapsed: f64) -> u32 { + self.reached(now).saturating_sub(self.reached(now - elapsed)) + } + + /// The first repeat instant after `now`, the time to ask the next pass for while the press is held. + pub fn next_repeat(&self, now: f64) -> f64 { + self.start + Self::DELAY + f64::from(self.reached(now)) * Self::INTERVAL + } +} diff --git a/crates/behavior/src/item_layout.rs b/crates/behavior/src/item_layout.rs index 44bcafd99e..49bd039554 100644 --- a/crates/behavior/src/item_layout.rs +++ b/crates/behavior/src/item_layout.rs @@ -123,6 +123,10 @@ pub trait ItemLayout { /// The viewport and scroll offset the grid view describes. Layouts without a grid ignore it. fn set_view(&mut self, _viewport: Vec2, _offset: ScrollPos) {} + + /// Item `at` is as wide as it measured, `width` from the start edge, in a layout that gives every item one width; + /// `None` gives it that width again. Its rect and its hit test take the width. Layouts of other widths ignore it. + fn set_fit(&mut self, _at: usize, _width: Option) {} } /// Lines (rows or columns) with a default size, the lines whose size differs and their prefix sums, so the start @@ -349,12 +353,14 @@ pub struct SpanLayout { /// Whether the rows form a tree: arrows expand, collapse and step to the parent. pub tree: bool, rows: Option, + /// The rows as wide as they measured (`set_fit`), by position. + fits: BTreeMap, } impl SpanLayout { /// One row of `row_h` per entry of `source`, `width` wide, with no columns. pub fn new(source: &dyn DisplayOrder, width: f32, row_h: f32) -> Self { - Self { row_h, count: source.len(), width, columns: Vec::new(), tree: false, rows: None } + Self { row_h, count: source.len(), width, columns: Vec::new(), tree: false, rows: None, fits: BTreeMap::new() } } /// Rows as tall as `source` says: `Height` and `Rect` are the app's, `Aspect` follows the width, and `Auto` @@ -371,7 +377,12 @@ impl SpanLayout { row_h, ); let auto = hints.iter().map(|hint| matches!(hint, SizeHint::Auto)).collect(); - Self { row_h, count: hints.len(), width, columns: Vec::new(), tree: false, rows: Some(Sized { lines, auto }) } + Self { row_h, count: hints.len(), width, columns: Vec::new(), tree: false, rows: Some(Sized { lines, auto }), fits: BTreeMap::new() } + } + + /// The width of row `at`: the rows', or less where it is as wide as it measured. + fn width_of(&self, at: usize) -> f32 { + self.fits.get(&at).map_or(self.width, |fit| fit.min(self.width)) } fn top(&self, at: usize) -> f64 { @@ -423,16 +434,20 @@ impl ItemLayout for SpanLayout { fn rect(&self, at: usize, offset: ScrollPos) -> Rect { let top = (self.top(at) - offset.y) as f32; - Rect::from_min_size(Pos2::new(-(offset.x as f32), top), Vec2::new(self.width, self.height(at))) + Rect::from_min_size(Pos2::new(-(offset.x as f32), top), Vec2::new(self.width_of(at), self.height(at))) } fn hit(&self, point: Pos2, offset: ScrollPos) -> Option { let y = f64::from(point.y) + offset.y; - if let Some(rows) = &self.rows { - return (0.0..rows.lines.total()).contains(&y).then(|| rows.lines.at(y) as usize).filter(|&at| at < self.count); - } - let at = (y / f64::from(self.row_h)).floor(); - (at >= 0.0 && (at as usize) < self.count).then_some(at as usize) + let at = match &self.rows { + Some(rows) => (0.0..rows.lines.total()).contains(&y).then(|| rows.lines.at(y) as usize).filter(|&at| at < self.count), + None => { + let at = (y / f64::from(self.row_h)).floor(); + (at >= 0.0 && (at as usize) < self.count).then_some(at as usize) + } + }; + // A row as wide as it measured takes no point past its end. + at.filter(|&at| !self.fits.contains_key(&at) || f64::from(point.x) + offset.x < f64::from(self.width_of(at))) } fn column_count(&self) -> usize { @@ -467,6 +482,13 @@ impl ItemLayout for SpanLayout { } } + fn set_fit(&mut self, at: usize, width: Option) { + match width { + Some(width) => self.fits.insert(at, width), + None => self.fits.remove(&at), + }; + } + fn nav(&self) -> NavShape { if self.tree { NavShape::Tree } else { NavShape::Flat } } @@ -887,4 +909,19 @@ mod tests { assert!(!layout.shown(7) && layout.shown(6)); assert_eq!(layout.hit(Pos2::new(1.0, 5.0), ScrollPos { x: 0.0, y: 180.0 }), Some(8)); } + + /// A row as wide as it measured is that wide from the start edge and takes no point past its end; the rows around + /// it keep the layout's width, and `None` gives it that width again. + #[test] + fn a_fitted_span_row_is_as_wide_as_it_measured_and_hit_only_inside() { + let mut layout = SpanLayout::new(&crate::item_source::keyed(&[0_u8, 1, 2], |key| *key), 300.0, 20.0); + layout.set_fit(1, Some(60.0)); + let (row, other) = (layout.rect(1, ScrollPos::default()), layout.rect(2, ScrollPos::default())); + assert!(row.width() < other.width() && row.left() == other.left(), "the row is narrower from the start edge: {row:?} {other:?}"); + assert_eq!(layout.hit(Pos2::new(row.center().x, row.center().y), ScrollPos::default()), Some(1), "inside the row hits it"); + assert_eq!(layout.hit(Pos2::new(row.right() + 10.0, row.center().y), ScrollPos::default()), None, "past its end hits nothing"); + assert_eq!(layout.hit(Pos2::new(row.right() + 10.0, other.center().y), ScrollPos::default()), Some(2), "the next row keeps its width"); + layout.set_fit(1, None); + assert_eq!(layout.rect(1, ScrollPos::default()).width(), other.width(), "None gives the row the layout's width again"); + } } diff --git a/crates/behavior/src/lib.rs b/crates/behavior/src/lib.rs index 2ca15409c8..617f1f0347 100644 --- a/crates/behavior/src/lib.rs +++ b/crates/behavior/src/lib.rs @@ -26,6 +26,7 @@ pub mod focus; pub mod frame_step; pub mod grid; pub mod hit; +pub mod hold_repeat; pub mod input; pub mod intent; pub mod item_layout; @@ -66,7 +67,7 @@ pub use anchor::Anchor9; pub use arrangement::Arrangement; pub use canvas::CanvasTransform; -pub use canvas::{CanvasView, RulerUnits, Ticks, ViewHistory, ViewPlace, ZoomLadder, resize_cursor}; +pub use canvas::{CanvasView, RulerUnits, TickLabels, Ticks, ViewHistory, ViewPlace, ZoomFloor, ZoomScheme, resize_cursor}; /// The f64 geometry crate the canvas view and its callers share. pub use kurbo; @@ -100,9 +101,10 @@ pub use part::{PartKey, PartRef}; pub use pixel_size::PixelSize; +pub use hold_repeat::HoldRepeat; pub use press::{ - Buttons, MultiTouch, PassInput, PointerButton, PointerEvent, PointerKind, PointerSample, PressAside, PressCancel, PressMachine, PressPhase, - PressPick, 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}; diff --git a/crates/behavior/src/nav/step.rs b/crates/behavior/src/nav/step.rs index bb93f2df45..d25aff01a5 100644 --- a/crates/behavior/src/nav/step.rs +++ b/crates/behavior/src/nav/step.rs @@ -330,17 +330,17 @@ fn ragged_at(outline: &dyn NavOutline, row: usize, column: usize) -> Option NavStep { let Some((row, column, _)) = locate(outline, lead) else { return NavStep::Unhandled }; let rows = (0..).take_while(|&r| outline.row_len(r).is_some()).count(); - // A row without a position that takes the lead (a closed group's) is passed over in the move's direction. + // A row without a position that takes the lead (a closed group's, a divider's) is passed over in the move's + // direction. let shifted = |to: usize| column.saturating_add_signed(outline.column_shift(row, to)); let toward = |rows: Vec| moved(rows.into_iter().find_map(|to| ragged_at(outline, to, shifted(to)))); - let vertical = |to: Option| moved(to.and_then(|to| ragged_at(outline, to, shifted(to)))); match mv { NavMove::Back => moved(neighbour(outline, state, lead, false)), NavMove::Forward => moved(neighbour(outline, state, lead, true)), NavMove::Up => toward((0..row).rev().collect()), NavMove::Down => toward((row + 1..rows).collect()), - NavMove::PageUp => vertical(Some(row.saturating_sub(state.page))), - NavMove::PageDown => vertical(Some((row + state.page).min(rows - 1))), + NavMove::PageUp => toward((0..=row.saturating_sub(state.page)).rev().collect()), + NavMove::PageDown => toward(((row + state.page).min(rows - 1)..rows).collect()), NavMove::Start => moved(first_enabled(outline)), NavMove::End => moved(last_enabled(outline)), } diff --git a/crates/behavior/src/overlay.rs b/crates/behavior/src/overlay.rs index 0765e3d972..680c616ecb 100644 --- a/crates/behavior/src/overlay.rs +++ b/crates/behavior/src/overlay.rs @@ -101,6 +101,10 @@ pub struct PlaceRequest { /// over the anchor from the preferred side; only one taller than the bounds is capped. For a context menu, whose /// anchor is a point or a row. pub covers_anchor: bool, + /// After side, alignment and the bounds clamp, the overlay shifts by this and clamps again. + pub offset: Vec2, + /// When the shifted overlay would cover this rect, the unshifted one wins. + pub clear: Option, } impl PlaceRequest { @@ -118,6 +122,8 @@ impl PlaceRequest { kept: None, flips_across: false, covers_anchor: false, + offset: Vec2::ZERO, + clear: None, } } @@ -163,6 +169,18 @@ impl PlaceRequest { self } + /// Shifts the overlay by `by` after it is placed and clamped. + pub const fn offset(mut self, by: Vec2) -> Self { + self.offset = by; + self + } + + /// Keeps the unshifted place when the shifted overlay would cover `rect`. + pub const fn clear(mut self, rect: Option) -> Self { + self.clear = rect; + self + } + /// Lines up with the anchor's other end, beside it, when that fits and the aligned end does not. pub const fn flips_across(mut self, on: bool) -> Self { self.flips_across = on; @@ -214,7 +232,9 @@ fn room(anchor: Rect, bounds: Rect, side: Side, rtl: bool, gap: f32) -> f32 { /// stay inside the bounds, its height (or width, beside the anchor) capped to the room. Below or above the anchor, a /// request that covers its anchor and fits neither side keeps the preferred side and its height up to the bounds' and /// slides over the anchor. Beside the anchor, a request that flips across lines up with the anchor's other end when it -/// runs past the bounds from the aligned end and fits from the other. The rect is always finite and inside the bounds. +/// runs past the bounds from the aligned end and fits from the other. The rect is then shifted by the request's +/// `offset` and clamped again, unless the shifted rect would cover `clear`, in which case the unshifted one stays. The +/// rect is always finite and inside the bounds. pub fn place(request: &PlaceRequest) -> Placement { let anchor = clean(request.anchor); let bounds = clean(request.bounds); @@ -262,7 +282,11 @@ pub fn place(request: &PlaceRequest) -> Placement { (Side::Start, true) | (Side::End, false) => Pos2::new(anchor.right() + gap, across_y), }; let max_min = Pos2::new((bounds.right() - size.x).max(bounds.left()), (bounds.bottom() - size.y).max(bounds.top())); - let min = Pos2::new(min.x.clamp(bounds.left(), max_min.x), min.y.clamp(bounds.top(), max_min.y)); + let keep = |min: Pos2| Pos2::new(min.x.clamp(bounds.left(), max_min.x), min.y.clamp(bounds.top(), max_min.y)); + let min = keep(min); + let shifted = keep(min + Vec2::new(finite(request.offset.x), finite(request.offset.y))); + let hides_clear = request.clear.map(clean).is_some_and(|clear| clear.intersects(Rect::from_min_size(shifted, size))); + let min = if hides_clear { min } else { shifted }; Placement { rect: Rect::from_min_size(min, size), side } } @@ -326,6 +350,22 @@ mod tests { assert_eq!(place(&request.side(Side::End)).rect.width(), 120.0, "beside it: its own width"); } + #[test] + fn an_offset_overlay_moves_unless_it_would_cover_its_clear_rect() { + let request = PlaceRequest::new(rect(100.0, 100.0, 200.0, 24.0), Vec2::new(100.0, 40.0), BOUNDS); + let home = place(&request).rect; + assert_eq!(home.min, Pos2::new(100.0, 124.0), "below the anchor, aligned to its start"); + let by = Vec2::new(50.0, 30.0); + let moved = request.offset(by); + assert_eq!(place(&moved).rect.min, home.min + by, "shifted by the offset"); + let point = Rect::from_min_max(Pos2::new(160.0, 170.0), Pos2::new(160.0, 170.0)); + assert_eq!(place(&moved.clear(Some(point))).rect, home, "the shifted rect would cover the point: the unshifted one stays"); + let aside = rect(600.0, 500.0, 10.0, 10.0); + assert_eq!(place(&moved.clear(Some(aside))).rect.min, home.min + by, "a clear rect off to the side changes nothing"); + let far = place(&request.offset(Vec2::new(10_000.0, 0.0))).rect; + assert_eq!(far.right(), BOUNDS.right(), "the shifted rect is clamped inside the bounds"); + } + #[test] fn rect_is_finite_and_inside_the_bounds_for_any_request() { let sides = [Side::Below, Side::Above, Side::Start, Side::End]; @@ -342,7 +382,9 @@ mod tests { .align(align) .rtl(i % 2 == 0) .gap(if i == 1 { 4.0 } else { 0.0 }) - .covers_anchor(align != Align::Start); + .covers_anchor(align != Align::Start) + .offset(Vec2::new(w, y)) + .clear(Some(rect(h, x, w.abs(), y.abs()))); let placed = place(&request).rect; assert!(placed.min.is_finite() && placed.max.is_finite(), "{request:?}"); assert!(BOUNDS.contains_rect(placed), "{request:?} gave {placed:?}"); diff --git a/crates/behavior/src/press.rs b/crates/behavior/src/press.rs index 7daf3c078f..50269615ff 100644 --- a/crates/behavior/src/press.rs +++ b/crates/behavior/src/press.rs @@ -99,12 +99,14 @@ pub struct PointerSample { pub rotation: f32, /// The eraser end of a pen. pub eraser: bool, + /// An airbrush pen's finger wheel, 0 to 1; `None` when the pen has none. + pub wheel: Option, } impl PointerSample { /// A sample with no tilt or rotation. pub const fn new(pressure: f32) -> Self { - PointerSample { pressure, tilt: [0.0, 0.0], rotation: 0.0, eraser: false } + PointerSample { pressure, tilt: [0.0, 0.0], rotation: 0.0, eraser: false, wheel: None } } /// The sample with every field in range: pressure within 0 to 1, tilt and rotation finite radians, a stray value @@ -118,7 +120,8 @@ impl PointerSample { let quarter = std::f32::consts::FRAC_PI_2; let tilt = self.tilt.map(|tilt| if tilt.is_finite() { tilt.clamp(-quarter, quarter) } else { 0.0 }); let rotation = if self.rotation.is_finite() { self.rotation } else { 0.0 }; - PointerSample { pressure, tilt, rotation, eraser: self.eraser } + let wheel = self.wheel.filter(|wheel| wheel.is_finite()).map(|wheel| wheel.clamp(0.0, 1.0)); + PointerSample { pressure, tilt, rotation, eraser: self.eraser, wheel } } } @@ -157,6 +160,25 @@ pub enum PressCancel { Removed, /// The host ended what the press acted on (`primitives::cancel_press_of`). Host, + /// A second finger landed while a press was open. + Gesture, +} + +/// Two or more fingers came down and all lifted within [`MULTI_TAP_TIME`] without moving past [`MULTI_TAP_SLOP`]. +#[derive(Clone, Copy, Debug, PartialEq)] +#[non_exhaustive] +pub struct MultiTap { + /// How many fingers tapped. + pub fingers: u8, + /// The centre of the fingers. + pub at: Pos2, +} + +impl MultiTap { + /// A tap of `fingers` around `at`. + pub const fn new(fingers: u8, at: Pos2) -> Self { + MultiTap { fingers, at } + } } /// One part's press state in one pass. @@ -341,6 +363,13 @@ impl Default for PressState { /// The longest gap between presses that still count as one multi-click, in seconds. pub const MULTI_CLICK_TIME: f64 = 0.3; +/// The longest the fingers of a multi-finger tap may stay down, in seconds. +pub const MULTI_TAP_TIME: f64 = 0.5; + +/// How far a finger of a multi-finger tap may move from where it landed, in points: fingers drift more than a +/// pointer does while the others land. +pub const MULTI_TAP_SLOP: f32 = 16.0; + /// The click count of a press at `pos` and `time` with `mods` held, given the previous press `(pos, time, clicks, /// mods)`: one more when it follows within [`MULTI_CLICK_TIME`] and `slop` of the previous one with the same /// modifiers, else 1. @@ -594,6 +623,35 @@ impl PressMachine { self.open.is_some_and(|open| open.dragging) } + /// The press the open press began as. + pub fn start(&self) -> Option { + self.open.map(|open| open.start) + } + + /// Takes over a press whose button is down and went down elsewhere, as a drag of `target` from `start`: the next + /// pass reports `DragStart`, and later ones the press's own `Drag`, `Release` or `Cancel` from their input. A + /// press this machine holds already stays as it is. + // PLAN: the sheet's Files table has no row for this file; the handover of a held press (decision q346) needs the + // machine to open a press that did not begin on it, which only the machine can build. + pub fn take_over(&mut self, target: T, sense: Sense, start: PressStart) { + if self.open.is_some() { + return; + } + self.open = Some(Open { + target, + sense: sense - Sense::CLICK, + start, + dragging: true, + abandoned: false, + left: false, + reported: true, + drag_reported: false, + released_at: None, + passing: None, + silent: false, + }); + } + /// Whether the button went up and the release waits for a later pass, which the caller must ask for: no input may /// come to start it. pub fn release_held(&self) -> bool { @@ -924,6 +982,22 @@ mod tests { assert!(machine.target().is_none(), "the release ends the press"); } + /// A press taken over from another machine reports its drag's start first, then the held button's own drag and + /// release, which never clicks. + #[test] + fn a_press_taken_over_reports_its_drag_start_then_its_own_phases() { + let origin = pos2(10.0, 0.0); + let mut machine = PressMachine::new(); + machine.take_over(1u8, Sense::DRAG | Sense::CLICK, PressStart::new(origin, PointerButton::Primary, 1.0, 1)); + let first = pass(&mut machine, &[], Sense::DRAG); + assert!(matches!(first.phase, Some(PressPhase::DragStart { start, .. }) if start.origin == origin), "{:?}", first.phase); + let moved = pass(&mut machine, &[PointerEvent::moved(pos2(30.0, 0.0), None)], Sense::DRAG); + assert!(matches!(moved.phase, Some(PressPhase::Drag { pos, .. }) if pos == pos2(30.0, 0.0)), "{:?}", moved.phase); + let up = pass(&mut machine, &[PointerEvent::released(pos2(30.0, 0.0))], Sense::DRAG); + assert!(matches!(up.phase, Some(PressPhase::Release { click: false, .. })), "{:?}", up.phase); + assert_eq!(up.activated, None, "a taken-over press is no click"); + } + /// The pointer leaving the window (a press on a window's edge grip pulled outward) ends the press's click but not /// its drag: the window keeps getting the held button's moves from outside, and they start the drag once past slop. /// The resize from a window edge used to fail whenever the pointer left the window before it passed slop. diff --git a/crates/behavior/src/quantity.rs b/crates/behavior/src/quantity.rs index b424c342cb..0aae495027 100644 --- a/crates/behavior/src/quantity.rs +++ b/crates/behavior/src/quantity.rs @@ -11,9 +11,10 @@ fn digit(c: char) -> Option { DIGIT_BLOCKS.iter().find_map(|&zero| (zero..zero + 10).contains(&(c as u32)).then(|| c as u32 - zero)) } -/// Whether `c` can be part of a unit spelling: a letter or a symbol that stands for a unit (`%`, `°`, `×`). +/// Whether `c` can be part of a unit spelling: a letter or a symbol that stands for a unit (`%`, `°`). `×` is the +/// product sign, never part of a unit. fn is_unit_char(c: char) -> bool { - c.is_alphabetic() || matches!(c, '%' | '\u{2030}' | '°' | '×' | '′' | '″') + c.is_alphabetic() || matches!(c, '%' | '\u{2030}' | '°' | '′' | '″') } /// Whether `spelling` can be registered with [`Reader::unit`]: letters and unit symbols only, so the reader can @@ -29,23 +30,30 @@ struct Unit { factor: f64, /// What the caller named this unit by, handed back by [`Reader::read_tagged`]. tag: Option, + /// The factor of a number written right after the spelling ([`Reader::split_unit`]). + rest: Option, } /// Reads numbers, expressions and unit quantities written in one locale. /// -/// Grammar: `expr = term (('+' | '-') term)*`, `term = factor (('*' | '/') factor)*`, -/// `factor = ('-' | '+')? (number unit? | '(' expr ')')`. Text that starts with `+`, `*` or `/` is relative: it -/// applies to the start value (`+5` adds 5, `*2` doubles). A leading `-` is a negative number. +/// Grammar: `expr = term (('+' | '-') term)*`, `term = factor (('*' | '/' | 'x' | 'X' | '×') factor)*`, +/// `factor = ('-' | '+')? (number unit? | '(' expr ')')`. A factor after `*`, `/`, `x` or `×` may be a percentage +/// (`3cm*50%` is 1.5 cm), whatever `%` means elsewhere. Text that starts with `+`, `*` or `/` is relative: it +/// applies to the start value (`+5` adds 5, `*2` doubles). A leading `-` is a negative number. A unit is the longest +/// registered spelling at the start of the letters after a number, so `2inx3` is `2in` times 3 and `2px` stays a +/// quantity when `px` is registered. A group separator counts only before exactly three digits. #[derive(Clone, Debug, PartialEq)] pub struct Reader { decimal: char, group: Option, units: Vec, + /// The factor of a number with no unit ([`Reader::bare`]). + bare: f64, } impl Default for Reader { fn default() -> Self { - Reader { decimal: '.', group: None, units: Vec::new() } + Reader { decimal: '.', group: None, units: Vec::new(), bare: 1.0 } } } @@ -55,6 +63,15 @@ impl Reader { Self::default() } + /// A number with no unit counts as `factor` of the reader's base unit (a picas field reads bare numbers as + /// points: `1.0 / 12.0`). The factor applies to the first number of each term; a number after `*`, `/`, `x` or + /// `×` is a plain multiplier, so `12*2` is two factors of twelve points. + #[must_use] + pub fn bare(mut self, factor: f64) -> Self { + self.bare = factor; + self + } + /// The decimal separator. #[must_use] pub fn decimal(mut self, decimal: char) -> Self { @@ -69,18 +86,26 @@ impl Reader { self } - /// A unit spelling (case-insensitive; letters or the symbols `%`, `°`, `×`) and its factor to the base unit. + /// A unit spelling (case-insensitive; letters or the symbols `%`, `°`) and its factor to the base unit. /// Spaces between the number and the spelling are skipped, so "12 %" reads like "12%". #[must_use] pub fn unit(mut self, spelling: &str, factor: f64) -> Self { - self.units.push(Unit { spelling: spelling.to_lowercase(), factor, tag: None }); + self.units.push(Unit { spelling: spelling.to_lowercase(), factor, tag: None, rest: None }); self } /// Like [`Reader::unit`], with a `tag` that [`Reader::read_tagged`] returns when the text names this spelling. #[must_use] pub fn unit_tagged(mut self, spelling: &str, factor: f64, tag: u32) -> Self { - self.units.push(Unit { spelling: spelling.to_lowercase(), factor, tag: Some(tag) }); + self.units.push(Unit { spelling: spelling.to_lowercase(), factor, tag: Some(tag), rest: None }); + self + } + + /// Like [`Reader::unit_tagged`], where a number written right after the spelling adds that many of `rest`: picas + /// and points read as `2p6`, two picas and six points. + #[must_use] + pub fn split_unit(mut self, spelling: &str, factor: f64, rest: f64, tag: u32) -> Self { + self.units.push(Unit { spelling: spelling.to_lowercase(), factor, tag: Some(tag), rest: Some(rest) }); self } @@ -105,6 +130,16 @@ impl Reader { }; (parse.at == chars.len() && value.is_finite()).then_some((value, parse.tag)).ok_or(NotAValue) } + + /// The fraction a lone percentage writes (`50%` is 0.5): a number and `%`, with no sign, unit or operator; + /// `None` for any other text. + pub fn share(&self, text: &str) -> Option { + let chars: Vec = text.chars().filter(|c| !c.is_whitespace()).collect(); + let number = chars.strip_suffix(&['%'])?; + let mut parse = Parse { reader: self, chars: number, at: 0, tag: None }; + let value = parse.number().ok()?; + (parse.at == number.len()).then_some(value / 100.0) + } } struct Parse<'a> { @@ -141,29 +176,32 @@ impl Parse<'_> { } fn term(&mut self) -> Result { - let first = self.factor()?; + let first = self.factor(true)?; self.product(first) } fn product(&mut self, mut left: f64) -> Result { // A bare relative `+5` has no product to run; the sum loop takes it. - while let Some(op @ ('*' | '/')) = self.peek() { + while let Some(op @ ('*' | '/' | 'x' | 'X' | '×')) = self.peek() { self.at += 1; - let right = self.factor()?; - left = if op == '*' { left * right } else { left / right }; + // A multiplier is a plain number: the reader's bare factor does not scale it. + let right = self.factor(false)?; + left = if op == '/' { left / right } else { left * right }; } Ok(left) } - fn factor(&mut self) -> Result { + /// A factor; `scaled` says it starts a term, where a number with no unit counts as the reader's bare factor. + /// Otherwise it is a multiplier, which may be a percentage. + fn factor(&mut self, scaled: bool) -> Result { match self.peek() { Some('-') => { self.at += 1; - self.factor().map(|value| -value) + self.factor(scaled).map(|value| -value) } Some('+') => { self.at += 1; - self.factor() + self.factor(scaled) } Some('(') => { self.at += 1; @@ -171,22 +209,43 @@ impl Parse<'_> { (self.peek() == Some(')')).then(|| self.at += 1).ok_or(NotAValue)?; Ok(value) } - _ => self.quantity(), + _ => self.quantity(scaled), } } - fn quantity(&mut self) -> Result { + /// A number and the longest registered unit spelling at the start of the letters after it. Letters that start no + /// unit stay unread: a product sign (`2x3`) takes them, and anything else leaves the text unread, which refuses it. + fn quantity(&mut self, scaled: bool) -> Result { let number = self.number()?; self.tag = None; - let rest: String = self.chars[self.at..].iter().copied().take_while(|c| is_unit_char(*c)).collect(); - if rest.is_empty() { - return Ok(number); + if !scaled && self.peek() == Some('%') { + self.at += 1; + return Ok(number / 100.0); } - let lowered = rest.to_lowercase(); - let unit = self.reader.units.iter().find(|unit| unit.spelling == lowered).ok_or(NotAValue)?; - self.at += rest.chars().count(); - self.tag = unit.tag; - Ok(number * unit.factor) + let reader = self.reader; + let run: Vec = self.chars[self.at..].iter().copied().take_while(|c| is_unit_char(*c)).collect(); + let unit = (1..=run.len()).rev().find_map(|len| { + let lowered = run[..len].iter().collect::().to_lowercase(); + reader.units.iter().find(|unit| unit.spelling == lowered).map(|unit| (len, unit)) + }); + match unit { + Some((len, unit)) => { + self.at += len; + self.tag = unit.tag; + let rest = match unit.rest { + Some(rest) if self.peek().is_some_and(|c| digit(c).is_some() || c == reader.decimal) => rest * self.number()?, + _ => 0.0, + }; + Ok(number * unit.factor + rest) + } + None if scaled => Ok(number * reader.bare), + None => Ok(number), + } + } + + /// Whether the group separator at `at` is followed by exactly three digits. + fn three_digits_after(&self, at: usize) -> bool { + self.chars[at + 1..].iter().take_while(|c| digit(**c).is_some()).count() == 3 } fn number(&mut self) -> Result { @@ -198,7 +257,7 @@ impl Parse<'_> { } else if c == self.reader.decimal && !seen_decimal { seen_decimal = true; text.push('.'); - } else if Some(c) == self.reader.group && !seen_decimal && !text.is_empty() { + } else if Some(c) == self.reader.group && !seen_decimal && !text.is_empty() && self.three_digits_after(self.at) { } else { break; } @@ -226,13 +285,52 @@ mod tests { assert_eq!(reader.read("+5", Some(10.0)), Ok(15.0)); assert_eq!(reader.read("*2", Some(10.0)), Ok(20.0)); assert_eq!(reader.read("٣٤", None), Ok(34.0), "Arabic-Indic digits"); - let symbols = Reader::new().unit("%", 1.0).unit("°", 1.0).unit("×", 1.0); + let symbols = Reader::new().unit("%", 1.0).unit("°", 1.0); assert_eq!(symbols.read("12 %", None), Ok(12.0), "a symbol spelling after a space"); assert_eq!(symbols.read("12°", None), Ok(12.0)); - assert_eq!(symbols.read("1.5×", None), Ok(1.5)); + assert_eq!(symbols.read("1.5×2", None), Ok(3.0), "× is the product sign"); assert_eq!(symbols.read("10%+5%", None), Ok(15.0), "a symbol ends where the next operator starts"); for bad in ["", "abc", "1 +", "2px", "1/0", "(1"] { assert_eq!(reader.read(bad, Some(1.0)), Err(NotAValue), "{bad:?} is not a value"); } } + + #[test] + fn times_signs_and_bare_numbers_read_through_the_grammar() { + let near = |reader: &Reader, text: &str, want: f64| { + let got = reader.read(text, None).unwrap_or(f64::NAN); + assert!((got - want).abs() < 1e-9, "{text:?} read {got}, wanted {want}"); + }; + let lengths = Reader::new().unit("px", 1.0).unit("in", 72.0); + for sign in ["x", "X", "×", "*"] { + near(&lengths, &format!("2{sign}3"), 6.0); + } + near(&lengths, "2inx3", 432.0); + near(&lengths, "2px", 2.0); + near(&lengths, "2px×2", 4.0); + + let picas = Reader::new().bare(1.0 / 12.0).unit("pt", 1.0 / 12.0).unit("pc", 1.0); + near(&picas, "12", 1.0); + near(&picas, "1pt+12", 13.0 / 12.0); + near(&picas, "1pc+12", 2.0); + near(&picas, "12*2", 2.0); + + let split = Reader::new().bare(1.0 / 12.0).split_unit("p", 1.0, 1.0 / 12.0, 0); + near(&split, "2p6", 2.5); + near(&split, "-2p6", -2.5); + near(&split, "2p", 2.0); + + let percent = Reader::new().unit("cm", 1.0).unit("%", 7.0); + near(&percent, "3cm*50%", 1.5); + near(&percent, "3cm/50%", 6.0); + near(&percent, "2%", 14.0); + assert_eq!(percent.read("*50%", Some(4.0)), Ok(2.0), "a relative share"); + + let german = Reader::new().decimal(',').group('.'); + near(&german, "1.234,5", 1234.5); + near(&german, "1.234.567", 1_234_567.0); + for bad in ["1.2", "1.2345", "×3", "x3"] { + assert_eq!(german.read(bad, None), Err(NotAValue), "{bad:?} is not a value"); + } + } } diff --git a/crates/behavior/src/wheel.rs b/crates/behavior/src/wheel.rs index a5826e2826..1985e4bf9c 100644 --- a/crates/behavior/src/wheel.rs +++ b/crates/behavior/src/wheel.rs @@ -86,6 +86,8 @@ pub struct Wheel { pub rotation: f32, /// Rotation of a two-finger touch, in radians. 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`). @@ -231,6 +233,7 @@ impl Wheel { touch_zoom: 1.0, rotation: 0.0, touch_rotation: 0.0, + touch_pan: Vec2::ZERO, gathered: Vec2::ZERO, moved: false, } @@ -260,6 +263,13 @@ impl Wheel { self } + /// The same gesture with the two-finger touch movement `pan`, in points. + #[must_use] + pub const fn touch_pan(mut self, pan: Vec2) -> Self { + self.touch_pan = pan; + self + } + /// The same gesture from `source`. pub const fn source(mut self, source: WheelSource) -> Self { self.source = source; @@ -551,15 +561,15 @@ fn for_field(wheel: &Wheel) -> bool { !(mods.alt || mods.cmd || mods.ctrl) && (wheel.scroll.y != 0.0 || (mods.shift && wheel.scroll.x != 0.0)) } -/// Whether `wheel` carries a pinch, a touch zoom or a rotation: the zoom share's values. +/// Whether `wheel` carries a pinch, a touch zoom, a rotation or a two-finger pan: the zoom share's values. fn pinches(wheel: &Wheel) -> bool { - wheel.zoom != 1.0 || wheel.touch_zoom != 1.0 || wheel.rotation != 0.0 || wheel.touch_rotation != 0.0 + wheel.zoom != 1.0 || wheel.touch_zoom != 1.0 || wheel.rotation != 0.0 || wheel.touch_rotation != 0.0 || wheel.touch_pan != Vec2::ZERO } /// `wheel` without the zoom share's values: a scroll share carries no pinch or rotation, so a field or a scroll region /// never reads one. const fn scroll_only(wheel: Wheel) -> Wheel { - Wheel { zoom: 1.0, touch_zoom: 1.0, rotation: 0.0, touch_rotation: 0.0, zooms: false, ..wheel } + Wheel { zoom: 1.0, touch_zoom: 1.0, rotation: 0.0, touch_rotation: 0.0, touch_pan: Vec2::ZERO, zooms: false, ..wheel } } /// The split rule. A focused field (a `WheelTaker::field` taker that holds `focus`, or an app's own text field) takes @@ -708,6 +718,7 @@ fn split_at( share.touch_zoom *= part.touch_zoom; share.rotation += part.rotation; share.touch_rotation += part.touch_rotation; + share.touch_pan += part.touch_pan; share.zooms |= part.zooms; } None => shares.push((owner, part)), diff --git a/crates/behavior/tests/canvas_view.rs b/crates/behavior/tests/canvas_view.rs index 2da0b59c99..2b71090371 100644 --- a/crates/behavior/tests/canvas_view.rs +++ b/crates/behavior/tests/canvas_view.rs @@ -1,7 +1,7 @@ //! The canvas view's mapping between document and screen. use craft_behavior::CanvasView; -use craft_behavior::canvas::zoom; +use craft_behavior::canvas::{ZoomScheme, zoom}; use emath::{Rect as ScreenRect, pos2, vec2}; use kurbo::{Point, Rect, Size}; @@ -55,22 +55,44 @@ fn fit_and_fill_measure_the_stretched_document() { // Fit keeps 20 points of margin per side: 1000 points across for a 1000 px wide document, 2000 shown at aspect 2. let (mut square, mut wide) = (stage(1.0, rect(1040.0, 800.0)), stage(2.0, rect(1040.0, 800.0))); - zoom::fit(&mut square, size, 1.0, 20.0); - zoom::fit(&mut wide, size, 1.0, 20.0); + zoom::fit(&mut square, size, 1.0, 20.0, &ZoomScheme::PHOTOSHOP); + zoom::fit(&mut wide, size, 1.0, 20.0, &ZoomScheme::PHOTOSHOP); assert!(near(square.zoom, 1.0), "{}", square.zoom); assert!(near(wide.zoom, 0.5), "{}", wide.zoom); assert!(near(wide.center.x, 500.0) && near(wide.center.y, 250.0), "{:?}", wide.center); // On a square rect the height limits fill at both aspects; the 1000 by 400 rect below is where the stretched width decides. let (mut square, mut wide) = (stage(1.0, rect(1000.0, 1000.0)), stage(2.0, rect(1000.0, 1000.0))); - zoom::fill(&mut square, size, 1.0); - zoom::fill(&mut wide, size, 1.0); + zoom::fill(&mut square, size, 1.0, &ZoomScheme::PHOTOSHOP); + zoom::fill(&mut wide, size, 1.0, &ZoomScheme::PHOTOSHOP); assert!(near(square.zoom, 2.0) && near(wide.zoom, 2.0), "{} {}", square.zoom, wide.zoom); // A wide rect: the unstretched document is limited by its width, the stretched one by its height. let (mut square, mut wide) = (stage(1.0, rect(1000.0, 400.0)), stage(2.0, rect(1000.0, 400.0))); - zoom::fill(&mut square, size, 1.0); - zoom::fill(&mut wide, size, 1.0); + zoom::fill(&mut square, size, 1.0, &ZoomScheme::PHOTOSHOP); + zoom::fill(&mut wide, size, 1.0, &ZoomScheme::PHOTOSHOP); assert!(near(square.zoom, 1.0), "{}", square.zoom); assert!(near(wide.zoom, 0.8), "{}", wide.zoom); assert!(near(wide.center.x, 500.0) && near(wide.center.y, 250.0), "{:?}", wide.center); } + +#[test] +fn a_scheme_steps_and_clamps_in_its_own_units_about_its_hundred() { + let (small, big) = (Size::new(100.0, 100.0), Size::new(10_000.0, 10_000.0)); + + let illustrator = ZoomScheme::ILLUSTRATOR; + let up = illustrator.step(1.0, 1, big); + assert!(near(up, 1.5), "{up}"); + assert!(near(illustrator.step(up, -1, big), 1.0), "a step in then out returns to the rung"); + assert!(near(illustrator.min(small), 0.0313) && near(illustrator.min(big), 0.0313), "a fixed floor ignores the document"); + + let photoshop = ZoomScheme::PHOTOSHOP; + assert!(near(photoshop.min(small), 0.02), "{}", photoshop.min(small)); + assert!(photoshop.min(big) < photoshop.min(small), "the floor follows the shorter side"); + + let doubled = photoshop.with_hundred(2.0); + for device in [0.5, 3.0, 40.0] { + assert!(near(doubled.device(doubled.percent(device)), device), "{device}"); + } + assert!(near(doubled.step(2.0, 1, small), 4.0), "the rung after the scheme's 100 % is the next rung times it"); + assert!(near(photoshop.clamp(f64::NAN, small), 1.0) && near(doubled.clamp(f64::NAN, small), 2.0), "a non-finite zoom is 100 %"); +} diff --git a/crates/behavior/tests/dock_apply.rs b/crates/behavior/tests/dock_apply.rs index b3bad10d0e..1d25354fdc 100644 --- a/crates/behavior/tests/dock_apply.rs +++ b/crates/behavior/tests/dock_apply.rs @@ -439,6 +439,63 @@ fn a_panel_that_docks_only_in_columns_never_lands_in_a_frame() { assert_eq!(sorted(saved.layout()), [1, 2, 3, 4, 6]); } +/// A location whose anchor, sibling and tab-before name `anchor`. +fn recorded(layout: &Layout, anchor: u32) -> craft_behavior::dock::Location { + let mut location = layout.location(&5).unwrap(); + location.anchor = Some(anchor); + location.sibling = vec![anchor]; + location.placement = DockPlacement::tab(Some(anchor)); + location +} + +/// Every place of `workspace` that holds the panel `id`: the layout, the keys of the records and their locations. +fn mentions(workspace: &Workspace, id: u32) -> bool { + let records = workspace.hidden().iter().chain(workspace.floated()); + let named = records.clone().any(|(panel, location)| { + let before = matches!(&location.placement, DockPlacement::Tab { before: Some(p) } if *p == id); + *panel == id || location.anchor == Some(id) || location.sibling.contains(&id) || before + }); + named || workspace.layout().contains(&id) +} + +/// A rename keeps the panel's place wherever the id sits (tab group, dock column, floating window, records and the +/// anchors of other records), refuses a missing source and a taken name, and leaves the workspace as it was then. +#[test] +fn a_renamed_panel_keeps_its_place_and_a_taken_name_changes_nothing() { + for from in [11, 3, 7, 50, 51] { + let layout = docked(); + let mut base = Workspace::default(); + base.replace(Workspace::from_parts( + layout.clone(), + vec![(50, recorded(&layout, from)), (52, recorded(&layout, 5))], + vec![(51, recorded(&layout, from))], + )); + base.validate().unwrap(); + let swap = |panel: u32| if panel == from { 99 } else { panel }; + + let mut renamed = base.clone(); + let (revision, generation) = (renamed.revision(), renamed.generation()); + renamed.rename(&from, 99).unwrap_or_else(|e| panic!("{from}: {e:?}")); + let panels = |workspace: &Workspace| workspace.layout().panels().into_iter().copied().collect::>(); + assert_eq!(panels(&renamed), panels(&base).into_iter().map(swap).collect::>(), "{from}: the panel keeps its position"); + let keys = |records: &[(u32, _)]| records.iter().map(|(panel, _)| *panel).collect::>(); + assert_eq!(keys(renamed.hidden()), keys(base.hidden()).into_iter().map(swap).collect::>(), "{from}: hidden keys"); + assert_eq!(keys(renamed.floated()), keys(base.floated()).into_iter().map(swap).collect::>(), "{from}: floated keys"); + assert!(!mentions(&renamed, from) && mentions(&renamed, 99), "{from}: no field holds the old id"); + renamed.validate().unwrap(); + assert!(renamed.revision() != revision && renamed.generation() == generation, "{from}: a rename is an edit"); + + for (source, name, error) in [(40, 99, DockError::MissingPanel), (from, 4, DockError::DuplicatePanel), (from, 52, DockError::DuplicatePanel)] + { + let mut refused = base.clone(); + let revision = refused.revision(); + assert_eq!(refused.rename(&source, name), Err(error), "{from}: {source} to {name}"); + assert_eq!(refused, base, "{from}: a refused rename changes nothing"); + assert_eq!(refused.revision(), revision); + } + } +} + /// A stepped column (a toolbar's) keeps its step count docked, floating and through JSON, and its width moves only /// by steps. #[test] @@ -494,6 +551,7 @@ fn every_workspace_mutator_moves_the_revision() { moves("set_visible", &|workspace| workspace.set_visible(5, false, None, false, allow).unwrap()); moves("reconcile", &|workspace| workspace.reconcile(|panel| *panel != 5, allow, &Workspace::new(docked()))); moves("raise_window_floor", &|workspace| workspace.raise_window_floor(1000)); + moves("rename", &|workspace| workspace.rename(&5, 99).unwrap()); moves("forget_hidden", &|workspace| { workspace.apply(Action::close(5), false, allow).unwrap(); let revision = workspace.revision(); diff --git a/crates/behavior/tests/hit_excluding.rs b/crates/behavior/tests/hit_excluding.rs new file mode 100644 index 0000000000..aea0f1f910 --- /dev/null +++ b/crates/behavior/tests/hit_excluding.rs @@ -0,0 +1,16 @@ +//! A hit shape with discs cut out: a point in a hole misses where the shape alone hits. + +use craft_behavior::HitShape; +use emath::{Pos2, Rect, pos2}; + +#[test] +fn a_point_inside_a_hole_misses_and_one_beside_it_hits() { + let shape = HitShape::Rect(Rect::from_min_max(pos2(0.0, 0.0), pos2(100.0, 100.0))); + let hole = (pos2(10.0, 10.0), 5.0); + let cut = HitShape::excluding(shape.clone(), vec![hole]); + let (inside, beside): (Pos2, Pos2) = (pos2(12.0, 10.0), pos2(50.0, 50.0)); + assert!(shape.hit(inside), "the shape alone takes the point the hole covers"); + assert!(!cut.hit(inside), "a point in a hole misses"); + assert!(cut.hit(beside), "a point outside every hole still hits"); + assert_eq!(cut.bounds(), shape.bounds(), "the holes leave the bounds as they are"); +} diff --git a/crates/behavior/tests/main.rs b/crates/behavior/tests/main.rs index 905ddbbe0f..c52c1045ec 100644 --- a/crates/behavior/tests/main.rs +++ b/crates/behavior/tests/main.rs @@ -8,5 +8,6 @@ mod dock_apply; mod fit; #[path = "geometry/main.rs"] mod geometry; +mod hit_excluding; mod key_table; mod middle_scroll; diff --git a/crates/browse/src/ui/bin/free_view.rs b/crates/browse/src/ui/bin/free_view.rs index 9eddab3f5d..c8fdb826e7 100644 --- a/crates/browse/src/ui/bin/free_view.rs +++ b/crates/browse/src/ui/bin/free_view.rs @@ -67,7 +67,7 @@ where } for event in out.response.events { match event { - CollectionEvent::Selection(change) => events.push(BinEvent::Selection(change)), + CollectionEvent::Selection { change, .. } => events.push(BinEvent::Selection(change)), CollectionEvent::Activate(key) => events.push(open_event(model, key, mods.cmd, mods.shift || mods.alt)), CollectionEvent::ContextMenu(request) => events.push(BinEvent::ContextMenu(request)), CollectionEvent::Delete(keys) => events.push(BinEvent::Remove(keys)), diff --git a/crates/browse/src/ui/bin/icon.rs b/crates/browse/src/ui/bin/icon.rs index 178d007a65..118a11870d 100644 --- a/crates/browse/src/ui/bin/icon.rs +++ b/crates/browse/src/ui/bin/icon.rs @@ -189,7 +189,7 @@ where } for event in out.response.events { match event { - CollectionEvent::Selection(change) => events.push(BinEvent::Selection(change)), + CollectionEvent::Selection { change, .. } => events.push(BinEvent::Selection(change)), CollectionEvent::Activate(key) => events.push(open_event(model, key, mods.cmd, mods.shift || mods.alt)), CollectionEvent::ContextMenu(request) => events.push(BinEvent::ContextMenu(request)), CollectionEvent::Delete(keys) => events.push(BinEvent::Remove(keys)), diff --git a/crates/browse/src/ui/bin/list.rs b/crates/browse/src/ui/bin/list.rs index 78c587f304..e0c5c9a4d7 100644 --- a/crates/browse/src/ui/bin/list.rs +++ b/crates/browse/src/ui/bin/list.rs @@ -179,7 +179,7 @@ where } for event in out.events { match event { - CollectionEvent::Selection(change) => events.push(BinEvent::Selection(change)), + CollectionEvent::Selection { change, .. } => events.push(BinEvent::Selection(change)), CollectionEvent::Activate(key) => events.push(open_event(model, key, mods.cmd, mods.shift || mods.alt)), CollectionEvent::ContextMenu(request) => events.push(BinEvent::ContextMenu(request)), CollectionEvent::Delete(keys) => events.push(BinEvent::Remove(keys)), diff --git a/crates/browse/src/ui/relink/list.rs b/crates/browse/src/ui/relink/list.rs index fb046938d2..08b35fa15e 100644 --- a/crates/browse/src/ui/relink/list.rs +++ b/crates/browse/src/ui/relink/list.rs @@ -315,7 +315,7 @@ impl LinkList<'_, K> { .show_items(ui, &source, &mut |_, icx| link_row(&rows, source.shown[icx.at], icx.at)); for event in out.events { match event { - CollectionEvent::Selection(change) => events.borrow_mut().push(LinkListEvent::Selection(change)), + CollectionEvent::Selection { change, .. } => events.borrow_mut().push(LinkListEvent::Selection(change)), CollectionEvent::Activate(key) => events.borrow_mut().push(LinkListEvent::GoTo(key)), _ => {} } diff --git a/crates/color-ui/Cargo.toml b/crates/color-ui/Cargo.toml index d6cbb1c107..ca8ee89afe 100644 --- a/crates/color-ui/Cargo.toml +++ b/crates/color-ui/Cargo.toml @@ -42,6 +42,7 @@ serde_json = { workspace = true, optional = true } [dev-dependencies] craft-ui = { workspace = true, features = ["suite"] } egui = { workspace = true } +serde_json = { workspace = true } [target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies] egui_kittest = { version = "0.37", features = ["wgpu"] } diff --git a/crates/color-ui/src/display.rs b/crates/color-ui/src/display.rs index bf891985cb..aed937fe38 100644 --- a/crates/color-ui/src/display.rs +++ b/crates/color-ui/src/display.rs @@ -23,6 +23,9 @@ pub type DisplayId = Option; /// Bytes per conversion chunk of [`DisplayTransform::apply_rgba8`] (a whole number of pixels). const CHUNK_BYTES: usize = 4 * 65536; +/// Bytes of the stack scratch of [`DisplayTransform::apply_premultiplied_rgba8`] (4096 whole pixels). +const SCRATCH_BYTES: usize = 4 * 4096; + /// Most cached transforms before the cache is cleared. const MAX_TRANSFORMS: usize = 32; @@ -67,6 +70,11 @@ fn usable_monitor(profile: Profile) -> Result, MonitorProblem> { Ok(Arc::new(profile)) } +/// `icc` parsed and validated as a monitor profile. +fn parse_monitor(icc: &[u8]) -> Result, MonitorProblem> { + Profile::parse(icc).map_err(|e| MonitorProblem::Unreadable { reason: e.to_string() }).and_then(usable_monitor) +} + fn srgb_entry(status: MonitorStatus) -> MonitorEntry { MonitorEntry { profile: Arc::new(Builtin::Srgb.profile().clone()), status } } @@ -135,6 +143,52 @@ impl DisplayTransform { } } } + + /// Premultiplied RGBA8 pixels converted in place through a fixed scratch of whole pixels: + /// alpha 0 is skipped, partial alpha is divided out and multiplied back, a failed chunk is + /// left as it was; nothing happens for the identity. + // new: the canvas frames hold premultiplied pixels; `display_profile::usable` shares the + // monitor check through `check_monitor`. + pub fn apply_premultiplied_rgba8(&self, pixels: &mut [u8]) { + let Some(t) = &self.transform else { return }; + let mut scratch = [0u8; SCRATCH_BYTES]; + for chunk in pixels.chunks_mut(SCRATCH_BYTES).map(|c| { + let n = c.len() / 4 * 4; + &mut c[..n] + }) { + let Some(src) = scratch.get_mut(..chunk.len()) else { continue }; + src.copy_from_slice(chunk); + for px in src.as_chunks_mut::<4>().0 { + let a = u32::from(px[3]); + if a != 0 && a != 255 { + for c in &mut px[..3] { + *c = ((u32::from(*c) * 255 + a / 2) / a).min(255) as u8; + } + } + } + // A failed conversion writes nothing (the buffers are checked first): the chunk stays. + if t.convert_u8(src, 4, chunk, 4, true).is_err() { + continue; + } + for (d, s) in chunk.as_chunks_mut::<4>().0.iter_mut().zip(src.as_chunks::<4>().0) { + let a = u32::from(d[3]); + if a == 0 { + *d = *s; + } else if a != 255 { + for c in &mut d[..3] { + *c = ((u32::from(*c) * a + 127) / 255) as u8; + } + } + } + } + } +} + +/// Whether `icc` is usable as a monitor profile: [`Profile::parse`] plus the monitor checks, a +/// parse error giving [`MonitorProblem::Unreadable`]. +// new: `display_profile::usable` in the app tries each profile source until one passes. +pub fn check_monitor(icc: &[u8]) -> Result<(), MonitorProblem> { + parse_monitor(icc).map(drop) } /// Why the monitor profile is what it is. @@ -216,18 +270,16 @@ impl DisplayCaches { pub fn set_monitor(&self, display: DisplayId, icc: Option<&[u8]>) { let entry = match icc { None => srgb_entry(MonitorStatus::NoProfile), - Some(bytes) => match Profile::parse(bytes) { - Ok(p) => match usable_monitor(p) { - Ok(profile) => MonitorEntry { profile, status: MonitorStatus::Detected }, - Err(reason) => srgb_entry(MonitorStatus::Unusable(reason)), - }, - Err(e) => { + Some(bytes) => match parse_monitor(bytes) { + Ok(profile) => MonitorEntry { profile, status: MonitorStatus::Detected }, + Err(problem @ MonitorProblem::Unreadable { .. }) => { if let std::collections::hash_map::Entry::Vacant(v) = lock(&self.monitors).entry(display) { - v.insert(srgb_entry(MonitorStatus::Unusable(MonitorProblem::Unreadable { reason: e.to_string() }))); + v.insert(srgb_entry(MonitorStatus::Unusable(problem))); lock(&self.transforms).clear(); } return; } + Err(problem) => srgb_entry(MonitorStatus::Unusable(problem)), }, }; lock(&self.monitors).insert(display, entry); @@ -310,6 +362,39 @@ pub(crate) mod tests { Arc::new(Builtin::Srgb.profile().clone()) } + /// Premultiplied conversion agrees with the straight one, leaves alpha and empty pixels alone. + #[trial] + fn a_premultiplied_conversion_matches_the_straight_one() { + let t = DisplayTransform::new(srgb(), p3()).unwrap(); + assert!(!t.is_identity()); + let colours = [[255u8, 0, 0], [200, 120, 40], [10, 220, 90]]; + for c in colours { + let mut straight = [c[0], c[1], c[2], 255]; + t.apply_rgba8(&mut straight); + let mut opaque = [c[0], c[1], c[2], 255]; + t.apply_premultiplied_rgba8(&mut opaque); + assert_eq!(opaque, straight, "opaque pixels agree"); + + let a = 128u32; + let mut half = [0, 1, 2].map(|i| ((u32::from(c[i]) * a + 127) / 255) as u8).to_vec(); + half.push(a as u8); + t.apply_premultiplied_rgba8(&mut half); + assert_eq!(half[3], a as u8, "alpha stays"); + for i in 0..3 { + let want = (u32::from(straight[i]) * a + 127) / 255; + assert!(want.abs_diff(u32::from(half[i])) <= 1, "channel {i}: {} vs {want}", half[i]); + } + } + let mut empty = [9u8, 8, 7, 0]; + t.apply_premultiplied_rgba8(&mut empty); + assert_eq!(empty, [9, 8, 7, 0]); + + let same = DisplayTransform::new(srgb(), srgb()).unwrap(); + let mut px = [50u8, 60, 70, 100, 1, 2, 3, 255]; + same.apply_premultiplied_rgba8(&mut px); + assert_eq!(px, [50, 60, 70, 100, 1, 2, 3, 255]); + } + /// Choosing another monitor profile changes the signature and drops the cached transform. #[trial] fn choosing_a_monitor_profile_changes_the_signature() { diff --git a/crates/color-ui/src/gradient/stops.rs b/crates/color-ui/src/gradient/stops.rs index 25894faeac..fa791791b6 100644 --- a/crates/color-ui/src/gradient/stops.rs +++ b/crates/color-ui/src/gradient/stops.rs @@ -16,6 +16,17 @@ use super::value::{ColorStop, GradientStops, OpacityStop, StopRow, StopRows}; /// new stops; the default is [`default_sampler`]. pub type Sampler = dyn Fn(&GradientStops, f32) -> Srgba; +/// What an Alt-drag of a colour stop does when it is held over another colour stop. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +#[non_exhaustive] +pub enum AltDrop { + /// The drag copies the stop (the default). + #[default] + Copy, + /// The drag swaps the two stops' colours. + Swap, +} + /// What a host allows of the stops of one row. #[derive(Clone, Debug, PartialEq)] #[non_exhaustive] @@ -28,6 +39,8 @@ pub struct StopRules { pub max: usize, /// The range a midpoint may take (PhotoCraft 0.05..=0.95; InDesign and Illustrator 0.13..=0.87). pub midpoint: RangeInclusive, + /// What an Alt-drag of a colour stop over another colour stop does. + pub alt_drop: AltDrop, } impl StopRules { @@ -50,14 +63,36 @@ impl StopRules { self.midpoint = range; self } + + /// What an Alt-drag of a colour stop over another colour stop does. + #[must_use] + pub fn alt_drop(mut self, rule: AltDrop) -> Self { + self.alt_drop = rule; + self + } } impl Default for StopRules { fn default() -> Self { - Self { rows: StopRows::Split, min: 2, max: 1024, midpoint: 0.05..=0.95 } + Self { rows: StopRows::Split, min: 2, max: 1024, midpoint: 0.05..=0.95, alt_drop: AltDrop::Copy } } } +/// The stops with the colours of stops `i` and `j` exchanged (RGB and `tag`; locations, alpha and +/// midpoints stay), and the index of the stop `i`; `None` for `i == j` or an index out of range. +pub fn swap_colors(stops: &GradientStops, i: usize, j: usize) -> Option<(GradientStops, usize)> { + if i == j || i >= stops.color.len() || j >= stops.color.len() { + return None; + } + let (a, b) = (stops.color[i], stops.color[j]); + let mut out = stops.clone(); + out.color[i].color = Srgba { a: a.color.a, ..b.color }; + out.color[i].tag = b.tag; + out.color[j].color = Srgba { a: b.color.a, ..a.color }; + out.color[j].tag = a.tag; + Some((out, i)) +} + /// One Left or Right press moves a stop or midpoint by this share of the bar or line. pub const STOP_STEP: f32 = 0.01; /// One Shift press. @@ -113,6 +148,7 @@ impl Stop for OpacityStop { } /// The location of stop `i` of `row`. +#[cfg(feature = "ui")] pub(crate) fn location(stops: &GradientStops, row: StopRow, i: usize) -> f32 { match row { StopRow::Color => stops.color[i].location, @@ -121,6 +157,7 @@ pub(crate) fn location(stops: &GradientStops, row: StopRow, i: usize) -> f32 { } /// The midpoint after stop `i` of `row`. +#[cfg(feature = "ui")] pub(crate) fn midpoint(stops: &GradientStops, row: StopRow, i: usize) -> f32 { match row { StopRow::Color => stops.color[i].midpoint, @@ -129,6 +166,7 @@ pub(crate) fn midpoint(stops: &GradientStops, row: StopRow, i: usize) -> f32 { } /// The locations of `row`'s stops as the bar shows them. +#[cfg(feature = "ui")] pub(crate) fn locations(stops: &GradientStops, row: StopRow) -> Vec { match row { StopRow::Color => stops.color.iter().map(|s| s.location).collect(), @@ -137,6 +175,7 @@ pub(crate) fn locations(stops: &GradientStops, row: StopRow) -> Vec { } /// Where the midpoint after stop `i` of `row` is, 0..=1 of the bar. +#[cfg(feature = "ui")] pub(crate) fn midpoint_at(stops: &GradientStops, row: StopRow, i: usize) -> f32 { let at = locations(stops, row); at[i] + (at[i + 1] - at[i]) * midpoint(stops, row, i) diff --git a/crates/color-ui/src/harmony.rs b/crates/color-ui/src/harmony.rs index eb421af66c..7b03889bae 100644 --- a/crates/color-ui/src/harmony.rs +++ b/crates/color-ui/src/harmony.rs @@ -172,18 +172,36 @@ impl Harmony { // inv-vectorcraft: crates/color/src/harmony.rs:178 `apply`, with the `tones` table at :36–70 // (`t`, `soft`, `deep`, `hc`) and `contrast` at :72; `keep_model` is not needed (sRGB only). pub fn apply(self, base: Srgba) -> Vec { - let Hsb { h, s, b: v } = base.to_hsb(); - std::iter::once(base) - .chain(self.tones()[1..].iter().map(|tone| { + let Hsb { h, s, b } = base.to_hsb(); + let rest = self.apply_hsb([h, s, b]).into_iter().skip(1); + std::iter::once(base).chain(rest.map(|[h, s, b]| hsb(h, s, b).with_alpha(base.a))).collect() + } + + /// The rule's colours as HSB from the base's HSB, the base first: hue in degrees from 0 to + /// 360, saturation and brightness from 0 to 1. A grey base keeps its hue, so the colours keep + /// their places around a hue wheel. + // inv-vectorcraft: crates/color/src/harmony.rs:186 `apply_hsb`. + pub fn apply_hsb(self, [h, s, v]: [f32; 3]) -> Vec<[f32; 3]> { + self.tones() + .iter() + .map(|tone| { let b = match tone.bright { Bright::Times(f) => v * f, Bright::Contrast => contrast(v), }; - hsb(h + tone.turn, (s * tone.sat).clamp(0.0, 1.0), b.clamp(0.0, 1.0)).with_alpha(base.a) - })) + [(h + tone.turn).rem_euclid(360.0), (s * tone.sat).clamp(0.0, 1.0), b.clamp(0.0, 1.0)] + }) .collect() } + /// Whether every colour of the rule has a hue of its own (Triad, but not Triad 2 or + /// Monochromatic), so that each can sit on a hue ring apart from the others. + // inv-vectorcraft: crates/color/src/harmony.rs:201 `hues_differ`. + pub fn hues_differ(self) -> bool { + let turns: Vec = self.tones().iter().map(|t| t.turn.rem_euclid(360.0)).collect(); + turns.iter().enumerate().all(|(i, a)| turns[..i].iter().all(|b| a != b)) + } + fn tones(self) -> &'static [Tone] { match self { Harmony::Complementary => const { &[t(0.0), t(180.0)] }, @@ -383,3 +401,38 @@ impl Guide { self } } + +#[cfg(test)] +pub(crate) mod tests { + use super::*; + use craft_ui::testing::trial; + + /// A rule's HSB colours match the colours `apply` gives, and a grey base keeps its hue, so its + /// colours turn around the hue ring from it. + #[trial] + fn hsb_colours_match_and_keep_a_greys_hue() { + let base = Srgba::rgb(230.0 / 255.0, 120.0 / 255.0, 40.0 / 255.0); + let Hsb { h, s, b } = base.to_hsb(); + for rule in Harmony::ALL { + let hsb = rule.apply_hsb([h, s, b]); + let colors = rule.apply(base); + assert_eq!(hsb.len(), colors.len(), "{}", rule.id()); + for (a, c) in hsb.iter().zip(&colors).skip(1) { + assert_eq!(Srgba::from_hsb(Hsb { h: a[0], s: a[1], b: a[2] }), *c, "{}", rule.id()); + } + } + let grey = Harmony::Triad.apply_hsb([40.0, 0.0, 0.5]); + assert_eq!(grey.iter().map(|c| c[0]).collect::>(), [40.0, 160.0, 280.0]); + assert_eq!(Harmony::Analogous.apply_hsb([10.0, 1.0, 1.0])[2][0], 340.0, "hues wrap to 0..360"); + } + + /// Fifteen rules give every colour its own hue; the six that repeat a hue are left out. + #[trial] + fn rules_whose_colours_all_have_their_own_hue() { + let differ: Vec = Harmony::ALL.into_iter().filter(|h| h.hues_differ()).collect(); + assert_eq!(differ.len(), 15); + for h in [Harmony::Complementary2, Harmony::Monochromatic, Harmony::Shades, Harmony::Triad2, Harmony::Triad3, Harmony::HighContrast2] { + assert!(!h.hues_differ(), "{}", h.id()); + } + } +} diff --git a/crates/color-ui/src/palette.rs b/crates/color-ui/src/palette.rs index fb7b692308..4cffd10a35 100644 --- a/crates/color-ui/src/palette.rs +++ b/crates/color-ui/src/palette.rs @@ -147,7 +147,7 @@ impl SwatchColor { } } -/// How an `.ase` file marks a colour. +/// How a swatch is marked: its `.ase` kind, or the built-in Registration swatch. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))] #[serde(rename_all = "camelCase")] @@ -159,25 +159,102 @@ pub enum SwatchKind { Global, #[allow(missing_docs)] Spot, + /// The built-in Registration swatch: the global CMYK colour that prints on every plate. + Registration, +} + +/// What a swatch holds. +#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +#[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))] +#[non_exhaustive] +pub enum SwatchPaint { + /// A colour. + Color(SwatchColor), + /// A tint of a named base swatch, with the colour it resolves to. + Tint { + /// The base swatch's name. + base: String, + /// The tint, 0–1. + tint: f32, + /// The resolved colour. + color: SwatchColor, + }, + /// A gradient; its value is the host's, keyed by the entry's name. + Gradient, + /// A pattern; its value is the host's, keyed by the entry's name. + Pattern, + /// The None swatch. + None, +} + +impl From for SwatchPaint { + /// The colour as a [`SwatchPaint::Color`]. + fn from(color: SwatchColor) -> Self { + SwatchPaint::Color(color) + } } /// One named swatch. #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] #[cfg_attr(feature = "ui", derive(craft_ui::contract::MemoProps))] +#[serde(from = "SwatchEntryWire", into = "SwatchEntryWire")] pub struct SwatchEntry { /// The swatch's label. pub name: String, - /// The swatch's colour. - pub color: SwatchColor, - #[serde(default)] + /// What the swatch holds. + pub paint: SwatchPaint, /// How the file marks the colour; `Process` unless the file says otherwise. pub kind: SwatchKind, } +/// The stored form of a [`SwatchEntry`]. It still reads an entry stored as `{name, color, kind}`, which holds a +/// colour, and writes `paint` only. +#[derive(serde::Serialize, serde::Deserialize)] +struct SwatchEntryWire { + name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + color: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + paint: Option, + #[serde(default)] + kind: SwatchKind, +} + +impl From for SwatchEntry { + fn from(wire: SwatchEntryWire) -> Self { + let paint = wire.paint.or(wire.color.map(SwatchPaint::Color)).unwrap_or(SwatchPaint::None); + SwatchEntry { name: wire.name, paint, kind: wire.kind } + } +} + +impl From for SwatchEntryWire { + fn from(entry: SwatchEntry) -> Self { + SwatchEntryWire { name: entry.name, color: None, paint: Some(entry.paint), kind: entry.kind } + } +} + impl SwatchEntry { /// A process swatch. pub fn new(name: impl Into, color: SwatchColor) -> SwatchEntry { - SwatchEntry { name: name.into(), color, kind: SwatchKind::Process } + SwatchEntry { name: name.into(), paint: SwatchPaint::Color(color), kind: SwatchKind::Process } + } + + /// A process swatch holding `paint`. + pub fn with_paint(name: impl Into, paint: SwatchPaint) -> SwatchEntry { + SwatchEntry { name: name.into(), paint, kind: SwatchKind::Process } + } + + /// The swatch's colour: the colour of a `Color` or `Tint` paint, else `None`. + pub fn color(&self) -> Option<&SwatchColor> { + match &self.paint { + SwatchPaint::Color(color) | SwatchPaint::Tint { color, .. } => Some(color), + _ => None, + } + } + + /// Whether the swatch is reserved: a `None` paint or the Registration kind. + pub fn is_reserved(&self) -> bool { + self.kind == SwatchKind::Registration || matches!(self.paint, SwatchPaint::None) } } @@ -223,6 +300,9 @@ pub enum SwatchNote { /// An `.act` read whose trailer names a transparent index: the 1-based colour number, so a read reports what it /// could not keep. TransparentKept(usize), + /// The format holds colours only: gradient, pattern and None swatches were skipped, with their + /// count. + PaintsSkipped(usize), } /// Why a swatch file could not be read or written. @@ -291,7 +371,8 @@ pub fn read_swatches(bytes: &[u8], file_name: &str) -> Result<(Vec, let (mut n, mut skipped) = (0usize, 0usize); let mut convert = |s: &AseSwatch| { n += 1; - let entry = from_ase(&s.color).map(|color| SwatchEntry { name: entry_name(n - 1, &s.name), color, kind: s.kind }); + let entry = + from_ase(&s.color).map(|color| SwatchEntry { name: entry_name(n - 1, &s.name), paint: SwatchPaint::Color(color), kind: s.kind }); skipped += usize::from(entry.is_none()); entry }; @@ -330,20 +411,21 @@ pub fn write_swatches(groups: &[SwatchGroup], format: SwatchFormat) -> Result<(V } let mut report = SwatchReport::default(); let all = || groups.iter().flat_map(|g| g.entries.iter()); - let kinds = all().filter(|e| e.kind != SwatchKind::Process).count(); + let kinds = all().filter(|e| e.color().is_some() && e.kind != SwatchKind::Process).count(); + let skipped = all().filter(|e| e.color().is_none()).count(); let flattened = groups.len() > 1; - match format { + let bytes = match format { SwatchFormat::Aco => { if count_swatches(groups) > ACO_MAX_SWATCHES { return Err(malformed(format, "an .aco file holds at most 65535 swatches")); } - let entries: Vec<(String, AcoColor)> = all().map(|e| (e.name.clone(), to_aco(&e.color))).collect(); + let entries: Vec<(String, AcoColor)> = all().filter_map(|e| e.color().map(|c| (e.name.clone(), to_aco(c)))).collect(); if flattened { report.notes.push(SwatchNote::GroupsFlattened); } push_note(&mut report, kinds, SwatchNote::KindsDropped); push_note(&mut report, names_cut(groups, false), SwatchNote::NamesCut); - Ok((write_aco(&entries), report)) + write_aco(&entries) } SwatchFormat::Act => { let (colors, books, converted) = rgb_colors(groups); @@ -364,7 +446,7 @@ pub fn write_swatches(groups: &[SwatchGroup], format: SwatchFormat) -> Result<(V out.resize(ACT_PALETTE_LEN, 0); out.extend((triplets.len() as u16).to_be_bytes()); out.extend(0xFFFFu16.to_be_bytes()); - Ok((out, report)) + out } SwatchFormat::Ase => { if count_swatches(groups) > ASE_MAX_SWATCHES || groups.len() > ASE_MAX_GROUPS { @@ -377,8 +459,8 @@ pub fn write_swatches(groups: &[SwatchGroup], format: SwatchFormat) -> Result<(V put_ase_name(&mut name, &g.name); put_ase_block(&mut body, ASE_GROUP_START, &name); blocks += 2; - for e in &g.entries { - match to_ase(&e.color) { + for (e, color) in g.entries.iter().filter_map(|e| e.color().map(|c| (e, c))) { + match to_ase(color) { Some(color) => { put_ase_color(&mut body, &e.name, &color, e.kind); blocks += 1; @@ -396,7 +478,7 @@ pub fn write_swatches(groups: &[SwatchGroup], format: SwatchFormat) -> Result<(V out.extend(0u16.to_be_bytes()); out.extend(blocks.to_be_bytes()); out.extend(body); - Ok((out, report)) + out } SwatchFormat::Gpl | SwatchFormat::Css => { let (colors, books, converted) = rgb_colors(groups); @@ -409,9 +491,11 @@ pub fn write_swatches(groups: &[SwatchGroup], format: SwatchFormat) -> Result<(V } else { write_css(groups, &colors) }; - Ok((text.into_bytes(), report)) + text.into_bytes() } - } + }; + push_note(&mut report, skipped, SwatchNote::PaintsSkipped); + Ok((bytes, report)) } /// PhotoCraft's default swatches (46 RGB colours in five groups: Grays, the exact RGB primaries diff --git a/crates/color-ui/src/palette/ase.rs b/crates/color-ui/src/palette/ase.rs index 1155bf883d..ea3b36ca18 100644 --- a/crates/color-ui/src/palette/ase.rs +++ b/crates/color-ui/src/palette/ase.rs @@ -190,7 +190,7 @@ pub(super) fn put_ase_color(out: &mut Vec, name: &str, color: &AseColor, kin AseColor::Other => {} } let code: u16 = match kind { - SwatchKind::Global => 0, + SwatchKind::Global | SwatchKind::Registration => 0, SwatchKind::Spot => 1, SwatchKind::Process => 2, }; diff --git a/crates/color-ui/src/palette/reader.rs b/crates/color-ui/src/palette/reader.rs index 9662efdb9c..538075bc83 100644 --- a/crates/color-ui/src/palette/reader.rs +++ b/crates/color-ui/src/palette/reader.rs @@ -75,8 +75,10 @@ pub(super) fn stem_of(file_name: &str) -> String { if stem.is_empty() { "Imported Swatches".into() } else { stem } } +/// The swatches a file can carry: those with a colour. Gradient, pattern and None swatches are not counted, so a +/// library of them alone is empty to every writer. pub(super) fn count_swatches(groups: &[SwatchGroup]) -> usize { - groups.iter().map(|g| g.entries.len()).sum() + groups.iter().map(|g| g.entries.iter().filter(|e| e.color().is_some()).count()).sum() } /// Whole UTF-16 scalar values of `name` that fit in `max` units. @@ -94,7 +96,7 @@ pub(super) fn utf16_units(name: &str, max: usize) -> Vec { pub(super) fn names_cut(groups: &[SwatchGroup], include_groups: bool) -> usize { let cut = |name: &str| name.encode_utf16().count() > MAX_NAME_UNITS; - let swatches = groups.iter().flat_map(|g| g.entries.iter()).filter(|e| cut(&e.name)).count(); + let swatches = groups.iter().flat_map(|g| g.entries.iter()).filter(|e| e.color().is_some() && cut(&e.name)).count(); swatches + if include_groups { groups.iter().filter(|g| cut(&g.name)).count() } else { 0 } } @@ -167,7 +169,8 @@ pub(super) fn rgb_colors(groups: &[SwatchGroup]) -> (Vec>, usize, g.entries .iter() .filter_map(|e| { - match e.color { + let color = e.color()?; + match color { SwatchColor::Book { .. } => { books += 1; return None; @@ -175,7 +178,7 @@ pub(super) fn rgb_colors(groups: &[SwatchGroup]) -> (Vec>, usize, SwatchColor::Cmyk(_) | SwatchColor::Lab(_) | SwatchColor::Gray(_) => converted += 1, SwatchColor::Rgb(_) | SwatchColor::Hsb(_) => {} } - Some((e.name.clone(), rgb8(e.color.to_srgb(CmykConverter::coated()).to_rgb_array()), e.kind == SwatchKind::Spot)) + Some((e.name.clone(), rgb8(color.to_srgb(CmykConverter::coated()).to_rgb_array()), e.kind == SwatchKind::Spot)) }) .collect() }) diff --git a/crates/color-ui/src/palette/tests.rs b/crates/color-ui/src/palette/tests.rs index 47c223276e..498366b4e8 100644 --- a/crates/color-ui/src/palette/tests.rs +++ b/crates/color-ui/src/palette/tests.rs @@ -47,7 +47,7 @@ fn aco_round_trips_colours_in_their_own_model() { assert_eq!(groups[0].name, "Brand"); for ((name, color), entry) in colors.iter().zip(&groups[0].entries) { assert_eq!(entry.name, *name); - assert_same(color, &entry.color); + assert_same(color, entry.color().unwrap()); } // A version 1 section comes first, then version 2 with the names. assert_eq!(&bytes[..4], &[0, 1, 0, 6]); @@ -68,8 +68,8 @@ fn ase_keeps_groups_and_aco_reports_flattening() { let (back, _) = read_swatches(&ase, "x.ase").unwrap(); assert_eq!(back.iter().map(|g| g.name.as_str()).collect::>(), ["Brand", "Greys"]); assert_eq!(back[0].entries[1].kind, SwatchKind::Spot); - assert_same(&back[0].entries[1].color, &groups[0].entries[1].color); - assert_same(&back[1].entries[0].color, &SwatchColor::Gray(0.5)); + assert_same(back[0].entries[1].color().unwrap(), groups[0].entries[1].color().unwrap()); + assert_same(back[1].entries[0].color().unwrap(), &SwatchColor::Gray(0.5)); // A colour in a model this crate does not read is skipped and counted. let mut unknown = Vec::new(); @@ -90,3 +90,43 @@ fn ase_keeps_groups_and_aco_reports_flattening() { assert_eq!(flat.len(), 1); assert_eq!(flat[0].entries.len(), 3); } + +/// Every writer leaves out the swatches that have no colour and counts them once, after its other notes; colours, +/// tints and the Registration swatch are written. A library of paints alone is empty. An entry stored without a +/// paint reads as a colour. +#[trial] +fn writers_skip_paint_swatches_and_report_them() { + let mut registration = SwatchEntry::new("Registration", SwatchColor::Cmyk([1.0; 4])); + registration.kind = SwatchKind::Registration; + let paints = vec![ + SwatchEntry::with_paint("Sky", SwatchPaint::Gradient), + SwatchEntry::with_paint("Dots", SwatchPaint::Pattern), + SwatchEntry::with_paint("None", SwatchPaint::None), + ]; + let mut entries = vec![ + SwatchEntry::new("Red", SwatchColor::Rgb([1.0, 0.0, 0.0])), + SwatchEntry::with_paint("Pink", SwatchPaint::Tint { base: "Red".into(), tint: 0.5, color: SwatchColor::Rgb([1.0, 0.5, 0.5]) }), + registration, + ]; + entries.extend(paints.clone()); + let groups = vec![group("All", entries)]; + for format in SwatchFormat::ALL { + let (bytes, report) = write_swatches(&groups, format).unwrap(); + let counted = report.notes.iter().filter(|n| matches!(n, SwatchNote::PaintsSkipped(_))).count(); + assert_eq!(counted, 1, "{format:?}: {report:?}"); + assert_eq!(report.notes.last(), Some(&SwatchNote::PaintsSkipped(3)), "{format:?}: {report:?}"); + if format.can_read() { + let (back, _) = read_swatches(&bytes, &format!("x.{}", format.extension())).unwrap(); + assert_eq!(count_swatches(&back), 3, "{format:?}"); + } + assert_eq!(write_swatches(&[group("Paints", paints.clone())], format).unwrap_err(), SwatchError::Empty, "{format:?}"); + } + + let legacy: SwatchEntry = serde_json::from_str(r#"{"name":"Old","color":{"model":"rgb","values":[1.0,0.0,0.0]},"kind":"spot"}"#).unwrap(); + assert_eq!(legacy.paint, SwatchPaint::Color(SwatchColor::Rgb([1.0, 0.0, 0.0]))); + assert_eq!(legacy.kind, SwatchKind::Spot); + for entry in &groups[0].entries { + let json = serde_json::to_string(entry).unwrap(); + assert_eq!(serde_json::from_str::(&json).unwrap(), *entry, "{json}"); + } +} diff --git a/crates/color-ui/src/ui/area.rs b/crates/color-ui/src/ui/area.rs index 1ded48bc60..052cf0c97f 100644 --- a/crates/color-ui/src/ui/area.rs +++ b/crates/color-ui/src/ui/area.rs @@ -1,17 +1,18 @@ //! [`ColorArea`]: two components of a colour across and down a field, the others fixed. use super::channels::{QUANTIZE_CELLS, channel_range, channel_step, quantized, settled, snapped, spoken}; +use super::ramp::Gamut; use crate::AreaMode; use craft_behavior::{Metrics, Mixed, Proposal, Sense}; -use craft_theme::ModelValues; +use craft_theme::{ModelValues, Srgba}; use craft_ui::contract::{ Access, Bind, BindMut, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, MeasureCx, PaintUi, Props as _, Role, Sizing, WordSetCx as _, }; use craft_ui::primitives::ContentPainterCx; use craft_ui::runtime::env::Label; -use craft_ui::style::{ComponentStyle, StyleCx}; +use craft_ui::style::{ComponentStyle, MarkerLook, StyleColor, StyleCx}; use craft_ui::value_drag::{PointMark, PointPicker}; -use egui::{Mesh, Pos2, Rect, Vec2, pos2}; +use egui::{Color32, Mesh, Painter, Pos2, Rect, Stroke, Vec2, pos2}; #[cfg(feature = "suite")] pub(crate) mod stories; @@ -19,12 +20,19 @@ pub(crate) mod stories; /// Vertices along each side of the area's colour mesh (PhotoCraft's 32). const MESH: usize = 32; +/// Cells along each side of the gamut shading grid. +const GRID: usize = 16; + /// The style of a colour area: the field is a point picker, which brings its own look. #[derive(Clone, Debug, PartialEq, ComponentStyle)] #[non_exhaustive] pub struct ColorAreaStyle { #[style(metrics)] metrics: Metrics, + /// The fill of a cell the gamut moves (`surface.scrim`). + scrim: StyleColor, + /// The marker look: its halo is the dark edge line and its ring the light one. + marker: MarkerLook, } /// The 2D field of a colour picker: two components of the colour across and down, the others fixed, as an @@ -60,6 +68,10 @@ pub struct ColorArea<'a> { /// The size of an area that does not fill its room; plot proportions by default. #[prop] shape: AreaShape, + /// The host's gamut: a cell of the 16 × 16 grid whose centre colour it moves is shaded with `surface.scrim`, with + /// a dark line under a light one along the edges between shaded and unshaded cells; drawn under the marker. + #[prop] + gamut: Option>, } /// The size of a [`ColorArea`] that does not fill its room. @@ -77,7 +89,7 @@ pub enum AreaShape { impl<'a> ColorArea<'a> { /// An area named `label` ("Saturation and brightness") showing `values`, values of `mode`'s model. pub fn new(label: impl Into

Outcome for GradientEditorOutput

{ /// Pointer: a press on a marker or diamond selects and grabs it without a jump; a drag moves it (stops pass their /// neighbours and the selection follows) and is one gesture. A stop dragged more than the tear-off distance above or /// below the ramp is removed while its row is above the minimum, and comes back on re-entry within the drag. Alt held -/// at the press drags a copy, which can't be torn off. A click on empty space adds a stop there (under `Split`, above +/// at the press drags a copy, which can't be torn off; under `AltDrop::Swap` a colour stop held over another colour +/// stop swaps their colours instead (locations, opacities and midpoints stay). A click on empty space adds a stop there (under `Split`, above /// the ramp's centre an opacity stop) as one Set; a press and drag on empty space does nothing. A double click on a /// colour stop asks for its colour. /// @@ -315,10 +316,10 @@ impl<'a, P: Clone + Send + Sync + 'static> GradientEditor<'a, P> { stops.reborrow().write(cx, &event); edit.events.push(event); } - color_requested = color_requested.filter(|i| *i < now.color.len()); - if let Some(i) = color_requested { + color_requested = color_requested.filter(|(i, _)| *i < now.color.len()); + if let Some((i, rect)) = color_requested { let request = ColorRequest::new(REQUEST_KEY, stop_color(&now, rules.rows, i)).title(label.clone()); - output = Some(StopColor::new(i, now.color[i].tag, request)); + output = Some(StopColor::new(i, now.color[i].tag, request).at(rect)); } } if now_selected != held { diff --git a/crates/color-ui/src/ui/gradient/editor/bar.rs b/crates/color-ui/src/ui/gradient/editor/bar.rs index 74b67541d4..ba55ee2823 100644 --- a/crates/color-ui/src/ui/gradient/editor/bar.rs +++ b/crates/color-ui/src/ui/gradient/editor/bar.rs @@ -133,7 +133,8 @@ struct Drag { /// Where the press was and the marker's location then, so the marker doesn't jump. press: Pos2, grab: f32, - /// Alt was held at the press: the drag moves a copy of the stop. + /// Alt was held at the press: the drag moves a copy of the stop, or under `AltDrop::Swap` swaps its colours with + /// the colour stop it is held over. copy: bool, } @@ -145,8 +146,8 @@ pub struct GradientBarOutput

{ pub edit: EditResponse, /// The selection after this pass, when the bar changed it. pub select: Option>, - /// The colour stop whose colour is asked for: a double click on it, Enter or Space. - pub color_requested: Option, + /// The colour stop whose colour is asked for (a double click on it, Enter or Space) and its marker's square. + pub color_requested: Option<(usize, Rect)>, /// Enter or Space on an opacity stop or a midpoint: its first field takes the focus. pub field_requested: bool, /// A payload dropped on the bar: where it landed. @@ -190,7 +191,7 @@ pub struct GradientBar<'a, P: Clone + Send + Sync + 'static = ()> { #[prop] selected_marker: Option, select: Option>, - color_requested: Option, + color_requested: Option<(usize, Rect)>, field_requested: bool, dropped: Option<(StopDrop, P)>, payload: PhantomData P>, @@ -369,6 +370,11 @@ impl Geometry { Rect::from_min_size(pos2(self.x(at) - self.marker / 2.0, top), vec2(self.marker, self.marker)) } + /// The square of colour stop `i`. + fn color_square(&self, stops: &GradientStops, i: usize) -> Rect { + self.body(StopRow::Color, location(stops, StopRow::Color, i)) + } + /// What a press takes for marker `m`: a stop within `hit` across, from a diamond's radius away from the ramp's edge /// to the marker's far edge; a midpoint within `hit` of its diamond. fn hit_rect(&self, stops: &GradientStops, m: StopRef) -> Rect { @@ -387,17 +393,23 @@ impl Geometry { } } - /// The colour stop or location a payload dropped at `pos` lands on. - fn drop_place(&self, stops: &GradientStops, pos: Pos2) -> StopDrop { - let near = stops + /// The colour stop other than `except` nearest to `x` and within `hit` of it. + fn nearest_color(&self, stops: &GradientStops, x: f32, except: Option) -> Option { + stops .color .iter() .enumerate() - .map(|(i, s)| (i, (self.x(s.location) - pos.x).abs())) + .filter(|(i, _)| Some(*i) != except) + .map(|(i, s)| (i, (self.x(s.location) - x).abs())) .filter(|(_, d)| *d <= self.hit) - .min_by(|a, b| a.1.total_cmp(&b.1)); - match near { - Some((i, _)) => StopDrop::OnStop(i), + .min_by(|a, b| a.1.total_cmp(&b.1)) + .map(|(i, _)| i) + } + + /// The colour stop or location a payload dropped at `pos` lands on. + fn drop_place(&self, stops: &GradientStops, pos: Pos2) -> StopDrop { + match self.nearest_color(stops, pos.x, None) { + Some(i) => StopDrop::OnStop(i), None => StopDrop::At(stops::round_location(self.location(pos.x))), } } @@ -482,7 +494,7 @@ impl GradientBar<'_, P> { self.select = Some(marker); } - /// The drag's stops with the marker at the pointer: moved, copied, or torn off. + /// The drag's stops with the marker at the pointer: moved, copied, colour-swapped, or torn off. fn drag_to(&mut self, cx: &mut Cx<'_, Self>, geo: &Geometry, drag: &Drag, pos: Pos2) { let Drag { marker, ref base, press, grab, copy, .. } = *drag; let to = grab + geo.location(pos.x) - geo.location(press.x); @@ -500,9 +512,14 @@ impl GradientBar<'_, P> { } m => { let (row, i, at) = (m.row(), m.index(), stops::round_location(to)); + // Chosen from the stops at the press, so a pointer that leaves the other stop returns to the copy. + let swap = (moved && copy && row == StopRow::Color && rules.alt_drop == stops::AltDrop::Swap) + .then(|| geo.nearest_color(base, pos.x, Some(i)).and_then(|j| stops::swap_colors(base, i, j))) + .flatten() + .map(|(s, j)| (s, Some(StopRef::stop(row, j)))); // At the row's minimum a stop dragged off the bar stays and moves. let torn = (off && !copy).then(|| stops::remove(base, row, i, rules)).flatten().map(|(s, _)| (s, None)); - let edited = torn.or_else(|| match (moved, copy) { + let edited = swap.or(torn).or_else(|| match (moved, copy) { (false, _) => None, (true, true) => stops::copy(base, row, i, at, rules).map(|(s, j)| (s, Some(StopRef::stop(row, j)))), (true, false) => stops::move_to(base, row, i, at, rules).map(|(s, j)| (s, Some(StopRef::stop(row, j)))), @@ -526,7 +543,7 @@ impl GradientBar<'_, P> { if press.double_pressed() && let StopRef::Color(i) = marker { - self.color_requested = Some(i); + self.color_requested = Some((i, geo.color_square(stops, i))); } } PressPhase::DragStart { start, pos, .. } if start.button == PointerButton::Primary => { @@ -635,7 +652,7 @@ impl GradientBar<'_, P> { let activated = self.selected_marker.is_some_and(|m| matches!(cx.part_activated(part_of(m)), Some(FireSource::Key | FireSource::Access))); if activated { match self.selected_marker { - Some(StopRef::Color(i)) => self.color_requested = Some(i), + Some(StopRef::Color(i)) => self.color_requested = Some((i, geo.color_square(&stops, i))), Some(_) => self.field_requested = true, None => {} } diff --git a/crates/color-ui/src/ui/gradient/editor/fields.rs b/crates/color-ui/src/ui/gradient/editor/fields.rs index 4528965787..3444bb02e6 100644 --- a/crates/color-ui/src/ui/gradient/editor/fields.rs +++ b/crates/color-ui/src/ui/gradient/editor/fields.rs @@ -13,7 +13,7 @@ use craft_ui::contract::{Bind, BodyCx, Props as _, Remember as _, Show as _, Sho use craft_ui::form::{Field, FieldGroup}; use craft_ui::runtime::env::{Label, UnitKind}; use craft_ui::text::NumberField; -use egui::{Id, Ui}; +use egui::{Id, Rect, Ui}; use crate::gradient::stops::{self, StopRules, locations, midpoint}; use crate::gradient::{GradientStops, StopRow, StopRows}; @@ -62,8 +62,8 @@ pub(super) struct Report { pub events: Vec>, /// The selection the fields moved. pub select: Option>, - /// The colour stop whose colour the host is asked to edit. - pub color_requested: Option, + /// The colour stop whose colour the host is asked to edit, and the rect of what asked. + pub color_requested: Option<(usize, Rect)>, pub screen_pick: Option, } @@ -78,7 +78,7 @@ pub(super) struct Row<'r, 'a> { pub picker: &'r Option>, pub sampled: Option, /// The colour request of the bar, when the bar asked for one. - pub requested: Option, + pub requested: Option<(usize, Rect)>, } /// A 0..=1 value in percent, without the binary fraction an `f32` adds (0.3 is 30, not 30.0000012). @@ -222,7 +222,7 @@ impl Row<'_, '_> { } self.popover(ui, cx, now, i, &well.response, report); } else if well.clicked { - report.color_requested = Some(i); + report.color_requested = Some((i, well.response.rect)); } } if rows == StopRows::Combined { diff --git a/crates/color-ui/src/ui/gradient/editor/stories.rs b/crates/color-ui/src/ui/gradient/editor/stories.rs index 47f8b80dc4..8ca078ff57 100644 --- a/crates/color-ui/src/ui/gradient/editor/stories.rs +++ b/crates/color-ui/src/ui/gradient/editor/stories.rs @@ -1,6 +1,7 @@ //! Stories of `GradientEditor`. use super::{GradientEditor, GradientEditorOutput}; +use crate::gradient::stops::AltDrop; use crate::ui::gradient::{ColorStop, GradientStops, OpacityStop, StopRef, StopRows, StopRules}; use craft_theme::Srgba; use craft_ui::runtime::env::Env; @@ -67,6 +68,14 @@ fn gradient_editor_combined(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { hinted(ui, data, output) } +/// An Alt-drag of a colour stop onto another swaps their colours. +#[story(GradientEditor<'static, u8>, covers = [], drive = Drive::Never, title = "Alt-drop swaps")] +fn gradient_editor_alt_drop_swap(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let rules = StopRules::new(StopRows::Combined).alt_drop(AltDrop::Swap); + let output = GradientEditor::new("Gradient", data.bind("stops", combined())).rules(rules).show(ui); + hinted(ui, data, output) +} + #[story(GradientEditor<'static, u8>, covers = [], drive = Drive::Never)] fn gradient_editor_color_only(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let (stops, stops_at) = data.value_at("stops", GradientStops::new(vec![color(0.0, [0.0, 0.0, 0.0]), color(1.0, [1.0, 1.0, 1.0])])); diff --git a/crates/color-ui/src/ui/gradient/value.rs b/crates/color-ui/src/ui/gradient/value.rs index b16ef51160..efb765fc1e 100644 --- a/crates/color-ui/src/ui/gradient/value.rs +++ b/crates/color-ui/src/ui/gradient/value.rs @@ -1,6 +1,7 @@ //! The stop bar's marker vocabulary: [`StopRef`] and [`StopColor`]. use craft_ui::runtime::requests::ColorRequest; +use egui::Rect; use crate::gradient::StopRow; @@ -69,11 +70,21 @@ pub struct StopColor { pub tag: u64, /// The request, opened at the stop's colour. pub request: ColorRequest, + /// What asked for the colour (the stop's marker, or the Color well), where the host opens its picker; `None` + /// when the request carries no place. + pub rect: Option, } impl StopColor { /// A request to edit colour stop `index`, whose tag is `tag`. pub fn new(index: usize, tag: u64, request: ColorRequest) -> Self { - Self { index, tag, request } + Self { index, tag, request, rect: None } + } + + /// The request raised at `rect`. + #[must_use] + pub fn at(mut self, rect: Rect) -> Self { + self.rect = Some(rect); + self } } diff --git a/crates/color-ui/src/ui/harmony.rs b/crates/color-ui/src/ui/harmony.rs index 22abd4bbcc..a153276ada 100644 --- a/crates/color-ui/src/ui/harmony.rs +++ b/crates/color-ui/src/ui/harmony.rs @@ -13,11 +13,13 @@ use craft_ui::runtime::commands::{CommandRef, CommandState}; use craft_ui::runtime::env::{Env, Label}; use egui::{Response, Ui}; use std::hash::{DefaultHasher, Hash, Hasher}; +use std::marker::PhantomData; +use std::sync::Arc; -use super::ColorDisc; use super::picker::{ChannelRow, ChannelRule}; +use super::{ColorDisc, DiscHit, DiscLook, DiscRadius}; use crate::harmony::{Guide, GuideOptions, Harmony, Variation}; -use craft_ui::choice::{SwatchTable, SwatchTableOutput}; +use craft_ui::choice::{CellMarks, SwatchTable, SwatchTableOutput}; #[cfg(feature = "suite")] pub(crate) mod stories; @@ -28,6 +30,7 @@ craft_ui::words! { pub struct HarmonyWords { rule: "harmony.rule" = "Rule"; brightness: "harmony.brightness" = "Brightness"; + saturation: "harmony.saturation" = "Saturation"; set_base: "harmony.setBase" = "Set base color to the current color"; harmony: "harmony.harmony" = "Harmony colors"; variations: "harmony.variations" = "Variations"; @@ -99,6 +102,11 @@ pub struct HarmonyWheelOutput { pub response: Response, /// The colour whose marker was pressed; it becomes the selected one. pub pressed: Option, + /// A primary click on the wheel (no drag): the marker it grabbed and the point under the release. + pub clicked: Option, + /// A secondary click inside the wheel: the marker in grab reach, else the marker whose spoke is near, with the + /// point. + pub context: Option, /// The edits of the colours this pass, each with the colour's index: a marker dragged (new hue and saturation) or, /// for the selected colour, the Brightness slider (new brightness); the value is `[h degrees, s, b]` with `None` /// where the edit kept the value. The host applies each value with [`move_on_wheel`](crate::harmony::move_on_wheel), @@ -127,12 +135,17 @@ pub struct HarmonyWheel<'a> { label: Label, colors: &'a [Srgba], selected: Option, + /// `None` until [`base`](Self::base) sets it: the selected colour is the base. + base: Option>, + look: DiscLook, + radius: DiscRadius, + stored: Option<&'a dyn Fn(usize, Srgba) -> Srgba>, } impl<'a> HarmonyWheel<'a> { /// A wheel named `label` over `colors`. pub fn new(label: impl Into

= dyn Fn(&GuideCell) -> Option

+ Send + Sync; + +/// The host's payload map for cells, with the payload type it erases. +struct CellPayload

(Arc>, PhantomData P>); + +impl CellDrag for CellPayload

{ + fn attach<'t>(&self, table: SwatchTable<'t>, cells: Arc<[GuideCell]>) -> SwatchTable<'t> { + let map = Arc::clone(&self.0); + table.drag_payload(move |drag| cells.get(drag.grabbed).and_then(|cell| map(cell))) + } +} + +/// `table` with the host's drag payload, when it gave one. +fn dragging<'t>(table: SwatchTable<'t>, payload: Option<&Arc>, cells: &[GuideCell]) -> SwatchTable<'t> { + match payload { + Some(payload) => payload.attach(table, Arc::from(cells)), + None => table, + } +} + +/// The table items of `cells`: the colour each shows, named by its hex. +fn entries(cells: &[GuideCell]) -> Vec<(Label, Srgba)> { + cells.iter().map(|cell| (Label::from(cell.color.to_hex()), cell.color)).collect() +} + +/// Where flat index `index` of the variation grid, `columns` wide, lies. +fn grid_at(index: usize, columns: usize) -> GuideCellAt { + GuideCellAt::Grid { row: index / columns, column: index % columns } +} + /// What the guide is made from. #[derive(Clone, PartialEq)] struct GuideKey { @@ -280,6 +413,9 @@ impl GuideCache { } } +/// The host's colour of a guide cell (`HarmonyPanel::cell_color`). +type CellColorFn<'a> = Box Srgba + 'a>; + /// Color Guide: the base swatch (a click sets the base to the current colour) and the rule `Select`; the harmony strip /// (one cell per colour, tooltip the hex); the variation grid, one row per harmony colour from shades to tints (or /// cool to warm, muted to vivid), the harmony colour itself in the marked centre column; the grid's end labels. The @@ -292,12 +428,26 @@ pub struct HarmonyPanel<'a> { picked: Bind<'a, HarmonyPicked>, base: Srgba, limit: Option<&'a [Srgba]>, + cell_color: Option>, + payload: Option>, } impl<'a> HarmonyPanel<'a> { /// The guide for `base`. pub fn new(state: Bind<'a, HarmonyPanelState>, picked: Bind<'a, HarmonyPicked>, base: Srgba) -> Self { - HarmonyPanel { state, picked, base, limit: None } + HarmonyPanel { state, picked, base, limit: None, cell_color: None, payload: None } + } + + /// The colour the host shows in each cell (spot tints), drawn instead of the guide's. + pub fn cell_color(mut self, color: impl Fn(&GuideCell) -> Srgba + 'a) -> Self { + self.cell_color = Some(Box::new(color)); + self + } + + /// The payload a cell drags, through the swatch table's `drag_payload`. + pub fn drag_payload(mut self, map: impl Fn(&GuideCell) -> Option

+ Send + Sync + 'static) -> Self { + self.payload = Some(Arc::new(CellPayload(Arc::new(map), PhantomData))); + self } /// Limit to Library: every colour snaps to the nearest of `palette`. @@ -308,7 +458,7 @@ impl<'a> HarmonyPanel<'a> { /// Shows the panel. pub fn show(self, ui: &mut Ui) -> HarmonyPanelOutput { - let HarmonyPanel { state, picked, base, limit } = self; + let HarmonyPanel { state, picked, base, limit, cell_color, payload } = self; let words = Env::of(ui).words::(); let mut held_state = Held::new(state); let mut held_picked = Held::new(picked); @@ -329,38 +479,43 @@ impl<'a> HarmonyPanel<'a> { } }); - let strip: Vec<(Label, Srgba)> = guide.colors.iter().map(|c| (Label::from(c.to_hex()), *c)).collect(); + // The cell as the host colours it: its colour in place of the guide's. + let colored = |at: GuideCellAt, color: Srgba| { + let cell = GuideCell { at, color }; + cell_color.as_ref().map_or(cell, |color_of| GuideCell { color: color_of(&cell), ..cell }) + }; + let strip_cells: Vec = guide.colors.iter().enumerate().map(|(i, c)| colored(GuideCellAt::Strip(i), *c)).collect(); + let strip = entries(&strip_cells); let mut strip_selection = Selection::default(); - let out = SwatchTable::new(words.harmony.clone(), &strip) - .per_row(strip.len().max(1)) - .span(true) - .selection(Bind::bound(&mut strip_selection)) - .show_all(ui); + let table = + SwatchTable::new(words.harmony.clone(), &strip).per_row(strip.len().max(1)).span(true).selection(Bind::bound(&mut strip_selection)); + let out = dragging(table, payload.as_ref(), &strip_cells).show_all(ui); if let Some(i) = out.selected { - chosen = strip.get(i).map(|(_, c)| *c); + chosen = strip_cells.get(i).copied(); } let columns = guide.grid.first().map_or(1, Vec::len).max(1); let centre = guide.centre(); - let flat: Vec<(Label, Srgba)> = guide.grid.iter().flatten().map(|c| (Label::from(c.to_hex()), *c)).collect(); + let grid_cells: Vec = guide.grid.iter().flatten().enumerate().map(|(i, c)| colored(grid_at(i, columns), *c)).collect(); + let flat = entries(&grid_cells); let mut selection = if before_picked.guide == stamp { before_picked.selection.clone() } else { Selection::default() }; - let SwatchTableOutput { selected, chosen: cells, .. } = SwatchTable::new(words.variations.clone(), &flat) + let table = SwatchTable::new(words.variations.clone(), &flat) .multiple(true) .per_row(columns) .span(true) - .marked(move |&at| at % columns == centre) - .selection(Bind::bound(&mut selection)) - .show_all(ui); + .marks(move |&at| CellMarks::default().edge(at % columns == centre)) + .selection(Bind::bound(&mut selection)); + let SwatchTableOutput { selected, chosen: clicked, .. } = dragging(table, payload.as_ref(), &grid_cells).show_all(ui); if let Some(i) = selected - && cells.len() == 1 + && clicked.len() == 1 { - chosen = flat.get(i).map(|(_, c)| *c); + chosen = grid_cells.get(i).copied(); } - let mut cells = selection.items.clone(); - cells.sort_unstable(); - cells.dedup(); - let colors: Vec = cells.iter().filter_map(|&i| flat.get(i).map(|(_, c)| *c)).collect(); - let after_picked = HarmonyPicked { selection, guide: stamp, colors }; + let mut indexes = selection.items.clone(); + indexes.sort_unstable(); + indexes.dedup(); + let cells: Vec = indexes.iter().filter_map(|&i| grid_cells.get(i).copied()).collect(); + let after_picked = HarmonyPicked { selection, guide: stamp, cells }; let (left, right) = match before.options.variation { Variation::TintsShades => (&words.shades, &words.tints), @@ -437,7 +592,7 @@ impl HarmonyMenu { variation(HarmonyCommand::TintsShades, Variation::TintsShades), variation(HarmonyCommand::WarmCool, Variation::WarmCool), variation(HarmonyCommand::VividMuted, Variation::VividMuted), - (HarmonyCommand::SaveAsSwatches, CommandState::new().enabled(!picked.colors().is_empty())), + (HarmonyCommand::SaveAsSwatches, CommandState::new().enabled(!picked.cells().is_empty())), (HarmonyCommand::Options, CommandState::new()), ] } @@ -449,7 +604,8 @@ impl HarmonyMenu { HarmonyCommand::WarmCool => state.options.variation = Variation::WarmCool, HarmonyCommand::VividMuted => state.options.variation = Variation::VividMuted, HarmonyCommand::SaveAsSwatches => { - return (!picked.colors().is_empty()).then(|| HarmonyMenuAction::SaveAsSwatches(picked.colors().to_vec())); + return (!picked.cells().is_empty()) + .then(|| HarmonyMenuAction::SaveAsSwatches(picked.cells().iter().map(|cell| cell.color).collect())); } HarmonyCommand::Options => return Some(HarmonyMenuAction::Options), } diff --git a/crates/color-ui/src/ui/harmony/stories.rs b/crates/color-ui/src/ui/harmony/stories.rs index 9e201fce93..bb0426e931 100644 --- a/crates/color-ui/src/ui/harmony/stories.rs +++ b/crates/color-ui/src/ui/harmony/stories.rs @@ -1,6 +1,6 @@ //! Stories of `HarmonyWheel` and `HarmonyPanel`. -use super::{HarmonyPanel, HarmonyPanelState, HarmonyPicked, HarmonyWheel}; +use super::{DiscLook, GuideCellAt, HarmonyPanel, HarmonyPanelState, HarmonyPicked, HarmonyWheel}; use crate::harmony::Harmony; use craft_theme::Srgba; use craft_ui::contract::ShowContainer as _; @@ -24,11 +24,40 @@ fn harmony_panel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { .unwrap_or_default() } +/// The spot tint the host shows in the strip's cells. +const SPOT: Srgba = Srgba::rgb(0.95, 0.65, 0.1); + +#[story(HarmonyPanel<'static>, covers = [], drive = Drive::Never, title = "Host cell colors")] +fn harmony_panel_host_cells(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let ((state, state_at), (picked, picked_at)) = data.pair_at(("guide", triad()), ("picked", HarmonyPicked::default())); + HarmonyPanel::new(state_at.bind(state), picked_at.bind(picked), BASE) + .cell_color(|cell| match cell.at { + GuideCellAt::Strip(_) => SPOT, + GuideCellAt::Grid { .. } => cell.color, + }) + .drag_payload(|cell| Some(cell.color)) + .show(ui) + .into() +} + +#[story(HarmonyWheel<'static>, covers = [], drive = Drive::Never, title = "Segmented")] +fn harmony_wheel_segmented(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { + let colors = Harmony::Triad.apply(BASE); + HarmonyWheel::new("Harmony", &colors).look(DiscLook::Segmented).selected_marker(Some(1)).show(ui).into() +} + /// The panel set to a triad. fn triad() -> HarmonyPanelState { HarmonyPanelState { rule: Harmony::Triad, ..HarmonyPanelState::default() } } +/// Recolor's wheel: the base colour drawn large, the selected one ringed. +#[story(HarmonyWheel<'static>, covers = [], drive = Drive::Never, title = "Base")] +fn harmony_wheel_base(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { + let colors = Harmony::Triad.apply(BASE); + HarmonyWheel::new("Harmony", &colors).selected_marker(Some(1)).base(Some(0)).show(ui).into() +} + #[story(HarmonyWheel<'static>, covers = [], drive = Drive::Never)] fn harmony_wheel(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { let colors = Harmony::Triad.apply(BASE); diff --git a/crates/color-ui/src/ui/mod.rs b/crates/color-ui/src/ui/mod.rs index 7d3c18cc61..54fb837833 100644 --- a/crates/color-ui/src/ui/mod.rs +++ b/crates/color-ui/src/ui/mod.rs @@ -50,33 +50,40 @@ pub use area::{AreaShape, ColorArea, ColorAreaStyle, smooth_mesh}; pub use channels::finite_values; pub use choice::{ChosenColor, ColorChoice, ColorChoiceOutput, ColorChoiceWords, NamedColor}; pub use compare::{CompareSwatch, CompareSwatchOutput, CompareSwatchStyle}; -pub use disc::{ColorDisc, ColorDiscOutput, ColorDiscStyle, ColorDiscWords, DiscMove}; +pub use disc::{ColorDisc, ColorDiscOutput, ColorDiscStyle, ColorDiscWords, DiscHit, DiscLook, DiscMove, DiscRadius, patch_at}; pub use droppers::{DropperButton, DropperButtonOutput, DropperKind, DropperTool}; pub use eyedropper::{ EyedropperBar, EyedropperBarOutput, EyedropperOptions, EyedropperPick, EyedropperTool, EyedropperWords, SampleSize, SampleSource, }; pub use harmony::{ - HarmonyCommand, HarmonyMenu, HarmonyMenuAction, HarmonyPanel, HarmonyPanelOutput, HarmonyPanelState, HarmonyPicked, HarmonyWheel, - HarmonyWheelOutput, HarmonyWords, + GuideCell, GuideCellAt, HarmonyCommand, HarmonyMenu, HarmonyMenuAction, HarmonyPanel, HarmonyPanelOutput, HarmonyPanelState, HarmonyPicked, + HarmonyWheel, HarmonyWheelOutput, HarmonyWords, }; pub use hex::{HexPair, HexPairField, PairCodec}; pub use hud::{ColorHud, ColorHudOutput}; pub use info::{InfoColor, InfoMeasure, InfoPanel, InfoReadings, InfoWords}; pub use lut_picker::{LutChoice, LutPicker, LutPickerOutput, LutWords}; pub use paint_chip::{ - FillKind, GradientPreview, ImagePreview, Paint, PaintChip, PaintChipOutput, PaintEditor, PaintLink, PaintLinkKind, PaintList, PaintListEvent, - PaintListOptions, PaintListOutput, PaintRow, PaintWords, + FillKind, GradientPreview, ImagePreview, Paint, PaintChip, PaintChipOutput, PaintChipSize, PaintEditor, PaintLink, PaintLinkKind, PaintList, + PaintListEvent, PaintListOptions, PaintListOutput, PaintRow, PaintWords, }; -pub use pair::{PairWell, SwatchPair, SwatchPairOutput, Well}; +pub use pair::{DropAccepts, PairWell, SwatchPair, SwatchPairOutput, Well}; pub use palette::{SwatchPalette, SwatchPaletteOutput}; pub use panel::{ - ColorPanel, ColorPanelCommand, ColorPanelMenu, ColorPanelMode, ColorPanelOutput, ColorPanelRamp, ColorPanelState, ColorPanelWords, PanelTarget, + ColorPanel, ColorPanelAction, ColorPanelCommand, ColorPanelLayout, ColorPanelMenu, ColorPanelMode, ColorPanelOutput, ColorPanelRamp, + ColorPanelShown, ColorPanelState, ColorPanelWords, PanelTarget, TintRow, +}; +pub use picker::{ + ChannelRow, ChannelRule, ChannelUnit, ColorConstraint, ColorPicker, ColorPickerLayout, ColorPickerOutput, ColorPickerWords, PickedColor, + ScreenPickGesture, TrackRamp, +}; +pub use picker_dialog::{ + ColorPickerDialog, ColorPickerDialogLayout, ColorPickerDialogWords, ColorPickerMemory, ColorPickerResult, ColorPickerTab, PickerLibrary, + PickerSwatches, }; -pub use picker::{ColorConstraint, ColorPicker, ColorPickerLayout, ColorPickerOutput, ColorPickerWords, PickedColor, ScreenPickGesture}; -pub use picker_dialog::{ColorPickerDialog, ColorPickerDialogLayout, ColorPickerDialogWords, ColorPickerMemory, ColorPickerResult, ColorPickerTab}; pub use popover::{ColorPopover, ColorPopoverOutput}; pub use profile_prompts::{ProfileAction, ProfileAnswer, ProfileMismatchDialog, ProfileMode, ProfileQuestion, ProfileStatus, ProfileWords}; -pub use ramp::{ColorRamp, ColorRampOutput, ColorRampStyle, ColorRampWords, Gamut, RampKind, RampPick}; +pub use ramp::{ColorRamp, ColorRampOutput, ColorRampStyle, ColorRampWords, Gamut, RampKind, RampPick, RampRecolor}; pub use readout::{ChannelEdit, ColorReadout, ColorReadoutOutput, ColorReadoutWords, ReadoutChannel}; pub use sample_size::SampleSizeSelect; pub use samplers::{ @@ -91,5 +98,6 @@ pub use swatches::{ }; pub use warning::{ColorWarning, ColorWarningArrangement, ColorWarningChip, ColorWarningChipOutput, ColorWarningChipStyle}; pub use wheel::{ - ColorWheel, ColorWheelStyle, ColorWheelWords, WheelGeometry, WheelPart, hue_at, hue_direction, triangle_corners, triangle_point, triangle_sv, + ColorWheel, ColorWheelOutput, ColorWheelStyle, ColorWheelWords, WheelGeometry, WheelInner, WheelPart, hue_at, hue_direction, triangle_corners, + triangle_point, triangle_sv, }; diff --git a/crates/color-ui/src/ui/paint_chip.rs b/crates/color-ui/src/ui/paint_chip.rs index a26c70b454..28de7cc7b1 100644 --- a/crates/color-ui/src/ui/paint_chip.rs +++ b/crates/color-ui/src/ui/paint_chip.rs @@ -12,20 +12,22 @@ use std::collections::HashMap; use craft_behavior::Mixed; use craft_behavior::{Axis, EditEvent, EditEvents, Metrics, PartKey}; use craft_cms::convert::CmykConverter; +use craft_keymap::Mods; use craft_theme::Srgba; -use craft_ui::buttons::Button; -use craft_ui::choice::{ChoiceWords, Segmented, Swatch}; +use craft_ui::buttons::{Button, PopupMark}; +use craft_ui::choice::{ChoiceWords, RING_SHARE, Segmented, Swatch, SwatchStyle, paint_ring}; use craft_ui::contract::{ - Access, Activation, Bind, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Entry, Outcome, Overlay, OverlayUi, Overlays as _, Pages, - PaintUi, PartsCx, Pointer as _, PopupKind, Props as _, Remember as _, Role, Show as _, ShowContainer as _, WordSetCx as _, + 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::controls::disclosure::DisclosureGlyph; use craft_ui::layout_components::Row; -use craft_ui::patterns::presets::{DefaultOpen, PresetBrowser, PresetEvent, PresetState}; +use craft_ui::patterns::presets::{DefaultOpen, PresetBrowser, PresetEvent, PresetRowMenu, PresetState}; use craft_ui::primitives::textures::CachedTexture; -use craft_ui::primitives::{ContentPainterCx, PaintShape, StrokeWidth, WellFill}; +use craft_ui::primitives::{ContentPainterCx, FacePaint, PaintShape, StrokeWidth}; use craft_ui::runtime::env::{Env, Label}; use craft_ui::runtime::requests::ColorRequest; -use craft_ui::style::{ComponentStyle, DataColor, FocusLook, StyleColor, StyleCx}; +use craft_ui::style::{ComponentStyle, DataColor, Flags, FocusLook, State, StateMix, StateSet, StyleColor, StyleCx, SurfaceEdge, SurfaceStyle}; use egui::{Color32, Pos2, Rect, Response, Ui, pos2, vec2}; use super::popover::compact_picker; @@ -38,10 +40,14 @@ pub(crate) mod stories; pub use paint_list::{PaintLink, PaintLinkKind, PaintList, PaintListEvent, PaintListOptions, PaintListOutput, PaintRow}; -/// The chip is this many control heights wide. +/// A regular chip is this many control heights wide. const CHIP_WIDTH_IN_HEIGHTS: f32 = 1.5; +/// A swatch chip's side is a rail button's over this, so three to a row fill a one-column rail's cell. +const SWATCHES_PER_RAIL_BUTTON: f32 = 3.0; /// The most tiles a pattern chip draws; a tile so small that more would fit is drawn as one stretched image. const MAX_TILES: f32 = 4096.0; +/// The No Color diagonal stops this many control heights short of the chip's edges. +const DIAGONAL_INSET_IN_HEIGHTS: f32 = 0.15; /// The chip's face: a mixed paint shows the colour well's mixed look. const WELL: PartKey = PartKey::new("well"); /// The swatch list takes its content height up to this many small control heights, then scrolls, as the gradient @@ -91,12 +97,22 @@ pub struct GradientPreview { /// Whether the host's gradient runs end to start. The ramp keeps the stops as given; the flag is part of the /// preview's value so that a Reverse edit, which leaves the stops alone, still changes the paint the chip sets. pub reverse: bool, + /// The host's painter for the preview's face; it paints over the checker, and `stops` still give the accessible + /// value. + pub face: Option, } impl GradientPreview { + /// The preview shows `face` in the paint well. + #[must_use] + pub fn face(mut self, face: FacePaint) -> Self { + self.face = Some(face); + self + } + /// A preview through `stops`, not reversed. pub fn new(stops: Vec<(f32, Srgba)>) -> Self { - GradientPreview { stops, reverse: false } + GradientPreview { stops, reverse: false, face: None } } /// The preview with the gradient reversed or not. @@ -189,6 +205,21 @@ impl PaintEditor<'_, T> { } } +/// How large a [`PaintChip`] is; every size paints the same well. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum PaintChipSize { + /// A control high and 1.5 times as wide: a panel's or an options bar's chip. + #[default] + Regular, + /// A square well of `size.icon.md` in a slot a control high and `space.gap.item` wider than the well: a chip among + /// a bar's buttons, as a contextual task bar's Fill and Stroke. + Compact, + /// A square a third of `size.rail.button` on a side that opens no popover: a tool rail's Color, Gradient and None, + /// three to a row. + Swatch, +} + /// The style of a paint chip. #[derive(Clone, Debug, PartialEq, ComponentStyle)] #[non_exhaustive] @@ -197,14 +228,41 @@ pub struct PaintChipStyle { metrics: Metrics, #[style(focus)] focus: FocusLook, - /// The chip's height. - height: f32, + /// The well's size. + well: egui::Vec2, + /// The chip's size before the room of its mark: the well's, or for a compact chip the slot round it. + slot: egui::Vec2, /// The chip's corners. radius: egui::CornerRadius, /// The ring on the chip's outline. edge: StyleColor, /// The fill of a picture chip with no texture yet: the field's. none_fill: StyleColor, + /// The No Color diagonal. + none_mark: StyleColor, + /// The swatch look the ring is painted with. + swatch: SwatchStyle, + /// The side of the dropdown arrow a chip with [`PopupMark::Menu`] shows after its well. + arrow: f32, + /// The room the arrow takes after the well: the arrow with a tight gap on each side. + arrow_room: f32, + /// The arrow's colour. + arrow_color: StyleColor, +} + +impl PaintChipStyle { + /// The look of the chip's well, as a ring or filled. + pub(crate) fn well_look(&self, ring: bool) -> WellLook { + WellLook { + none_fill: self.none_fill, + none_mark: self.none_mark, + edge: self.edge, + height: self.well.y, + radius: self.radius, + ring, + swatch: self.swatch.clone(), + } + } } /// The last solid colour the chip held: a switch back to Solid starts from it. @@ -237,6 +295,8 @@ pub struct PaintChipOutput { /// The Color Picker… button was pressed: the popover closed and the host opens the full picker with this request /// for that pass. pub pick_color: Option, + /// A click, Enter or Space on a chip without a popover: the modifiers held. + pub clicked: Option, } impl Outcome for PaintChipOutput { @@ -252,7 +312,74 @@ impl Outcome for PaintChipOutput { } } -/// A paint chip, a control high and 1.5 times as wide. +/// The look of a paint well: the chip's own look fields. +pub(crate) struct WellLook { + pub(crate) none_fill: StyleColor, + pub(crate) none_mark: StyleColor, + pub(crate) edge: StyleColor, + pub(crate) height: f32, + /// The well's corners. + pub(crate) radius: egui::CornerRadius, + /// Whether the well shows its colour as a ring. + pub(crate) ring: bool, + /// The swatch look the ring is painted with. + pub(crate) swatch: SwatchStyle, +} + +/// One paint-well face for `PaintChip` and `SwatchPair`: none, solid, a gradient face or ramp, a pattern or a picture; +/// a face paints over the checker. +/// +/// A ring well shows a solid paint through [`paint_ring`]; any other paint fills the well and the hole inside the band +/// is filled with the surface the well sits on. +pub(crate) fn paint_well(ui: &mut PaintUi<'_>, cx: &Cx<'_, impl craft_ui::contract::ContentPainter>, well: Rect, paint: &Paint, style: &WellLook) { + if let (true, Paint::Solid(color)) = (style.ring, paint) { + let state = StateSet::new(State::Rest, Flags::empty(), StateMix::new(0.0, 0.0, 0.0)); + paint_ring(&ui.draw(), well, *color, &style.swatch, &state, style.radius); + return; + } + let shape = PaintShape::Rect(well, style.radius); + let painter = ui.content_painter(cx); + match paint { + Paint::Solid(color) => { + if color.a < 1.0 { + painter.checker(well); + } + ui.draw().data_fill(&shape, DataColor::new(Color32::from(*color))); + } + Paint::None => { + let draw = ui.draw(); + draw.fill(&shape, style.none_fill); + let inner = well.shrink(style.height * DIAGONAL_INSET_IN_HEIGHTS); + let (from, to) = if cx.flow.is_rtl() { (inner.right_bottom(), inner.left_top()) } else { (inner.left_bottom(), inner.right_top()) }; + draw.stroke(&PaintShape::Path(vec![from, to]), StrokeWidth::Medium, style.none_mark); + } + Paint::Gradient(preview) => { + painter.checker(well); + if let Some(face) = &preview.face { + face.paint(&painter, well); + } else if !preview.stops.is_empty() { + painter.ramp(well, egui::CornerRadius::ZERO, &ramp_stops(preview, cx.flow.is_rtl()), Axis::X); + } + } + Paint::Pattern(image) | Paint::Picture(image) => { + painter.checker(well); + match image.texture { + Some(texture) => paint_image(&painter, well, texture, matches!(paint, Paint::Pattern(_))), + None => ui.draw().fill(&shape, style.none_fill), + } + } + } + if style.ring { + let ground = + ui.with_style(cx.resolved.variant, |scope| SurfaceStyle { edge: SurfaceEdge::None, shadow: None, ..scope.surface(cx.env.surface()) }); + ui.draw().surface_styled(well.shrink(well.width() * RING_SHARE), &ground); + } else { + ui.draw().stroke(&shape, StrokeWidth::Thin, style.edge); + } +} + +/// A paint chip as large as its [`chip_size`](Self::chip_size) (by default a control high and 1.5 times as wide), with the +/// room of its [`popup_mark`](Self::popup_mark) after it. /// /// - Look: a solid paint fills the chip over the checkerboard (alpha shows); a gradient is a /// start-to-end ramp through its stops; No Color is the field fill with a `status.bad` diagonal @@ -293,8 +420,26 @@ pub struct PaintChip<'a> { /// A Color Picker… button at the end of the kind row opens the full picker. #[prop] full_picker: bool, + /// A click, Enter or Space opens the popover; on by default. Off, nothing opens and the chip reports the held + /// modifiers as [`clicked`](PaintChipOutput::clicked) (host-picker mode). + #[prop] + popover: bool, + /// The chip draws as a stroke ring through the one ring painter. + #[prop] + ring: bool, + /// The mark after the well that tells the chip opens more than it shows: [`PopupMark::Menu`] draws the shared + /// dropdown arrow, inside the chip's hit area. None by default; a chip has no tool group mark, so + /// [`PopupMark::ToolGroup`] draws none. + #[prop] + popup_mark: PopupMark, + /// How large the chip is; [`PaintChipSize::Regular`] by default. + #[style_key] + #[prop] + chip_size: PaintChipSize, /// The request of the Color Picker… button, for this pass. pick_color: Option, + /// The modifiers of this pass's click on a chip without a popover. + clicked: Option, } impl<'a> PaintChip<'a> { @@ -315,7 +460,12 @@ impl<'a> PaintChip<'a> { swatches: None, cmyk: None, full_picker: false, + popover: true, + ring: false, + popup_mark: PopupMark::None, + chip_size: PaintChipSize::Regular, pick_color: None, + clicked: None, } .label(label) } @@ -323,7 +473,7 @@ impl<'a> PaintChip<'a> { /// The [`ColorRequest::key`] of the full picker the Color Picker… button asks for. pub const COLOR_KEY: &'static str = "paintChip"; - /// The swatches the popover lists (rows from `swatch_rows`) beside the picker: the groups the Swatches panel takes, + /// The swatches the popover lists (from `swatch_source`) beside the picker: the groups the Swatches panel takes, /// so a host builds no library copy each pass. #[must_use] pub fn swatches(mut self, groups: &'a [SwatchGroup], state: Bind<'a, PresetState>) -> Self { @@ -373,6 +523,24 @@ impl<'a> PaintChip<'a> { self.gradient.as_ref().map(|(default, _)| default) } + /// The room after the well the mark takes: the arrow's for [`PopupMark::Menu`], none otherwise. + fn mark_room(&self, style: &PaintChipStyle) -> f32 { + if self.popup_mark == PopupMark::Menu { style.arrow_room } else { 0.0 } + } + + /// Whether a click opens the popover: on unless [`popover`](Self::popover) is off or the chip is a swatch. + fn opens(&self) -> bool { + self.popover && self.chip_size != PaintChipSize::Swatch + } + + /// The well and the mark's room in the chip's `rect`: a compact chip's well is centred in its slot, every other + /// fills it. + fn layout(&self, rect: Rect, style: &PaintChipStyle, rtl: bool) -> (Rect, Rect) { + let (slot, mark) = split_mark(rect, self.mark_room(style), rtl); + let well = if self.chip_size == PaintChipSize::Compact { Rect::from_center_size(slot.center(), style.well) } else { slot }; + (well, mark) + } + /// The paint a switch to `kind` sets. fn switched(&self, kind: FillKind, solid: Srgba) -> Paint { match kind { @@ -385,6 +553,13 @@ impl<'a> PaintChip<'a> { } } +/// `rect` split into the well and the mark's room, `room` wide at its end edge. +fn split_mark(rect: Rect, room: f32, rtl: bool) -> (Rect, Rect) { + let at = if rtl { rect.left() + room } else { rect.right() - room }; + let (left, right) = (Rect::from_min_max(rect.min, pos2(at, rect.max.y)), Rect::from_min_max(pos2(at, rect.min.y), rect.max)); + if rtl { (right, left) } else { (left, right) } +} + fn kind_label(words: &PaintWords, kind: FillKind) -> Label { match kind { FillKind::None => words.no_color.clone(), @@ -414,16 +589,37 @@ impl Component for PaintChip<'_> { type Style = PaintChipStyle; type Output = PaintChipOutput; - fn style(cx: &StyleCx<'_>, _: PaintChipStyleKey) -> PaintChipStyle { + fn style(cx: &StyleCx<'_>, key: PaintChipStyleKey) -> PaintChipStyle { let colors = &cx.tokens.color; let metrics = craft_ui::choice::SwatchMetrics::of(cx); + let arrow = cx.tokens.size.icon.glyph_sm; + let (well, slot) = match key.chip_size { + PaintChipSize::Regular => { + let well = vec2(metrics.side * CHIP_WIDTH_IN_HEIGHTS, metrics.side); + (well, well) + } + PaintChipSize::Compact => { + let well = egui::Vec2::splat(cx.tokens.size.icon.md); + (well, vec2(well.x + cx.tokens.space.gap.item, metrics.side)) + } + PaintChipSize::Swatch => { + let well = egui::Vec2::splat(cx.tokens.size.rail.button / SWATCHES_PER_RAIL_BUTTON); + (well, well) + } + }; PaintChipStyle { metrics: Metrics::new(), focus: cx.focus_look(), - height: metrics.side, + well, + slot, radius: metrics.radius, edge: cx.color(colors.line.control_edge), none_fill: cx.color(colors.surface.sunken), + none_mark: cx.color(colors.status.bad.solid), + swatch: Swatch::style(cx, Swatch::new(Label::default(), Srgba::BLACK).style_key()), + arrow, + arrow_room: arrow + 2.0 * cx.tokens.space.gap.tight, + arrow_color: cx.color(colors.text.muted), } } @@ -432,11 +628,15 @@ impl Component for PaintChip<'_> { } fn measure(&mut self, cx: &craft_ui::contract::MeasureCx<'_, Self>) -> egui::Vec2 { - vec2(cx.style.height * CHIP_WIDTH_IN_HEIGHTS, cx.style.height) + cx.style.slot + vec2(self.mark_room(cx.style), 0.0) } fn parts(&mut self, rect: egui::Rect, cx: &mut PartsCx<'_, Self>) { - let _ = cx.part(WELL, rect).toggles("picker"); + let (well, _) = self.layout(rect, cx.style, cx.flow.is_rtl()); + let part = cx.part(WELL, well); + if self.opens() { + let _ = part.toggles("picker"); + } } fn bind(&mut self) -> Option> { @@ -449,10 +649,14 @@ impl Component for PaintChip<'_> { let color = *color; cx.memory::().0 = Some(color); } + let activation = cx.activation().filter(|_: &Activation| cx.resolved.enabled); + if !self.opens() { + self.clicked = activation.map(|activation| activation.mods); + return; + } let popup = cx.popup("picker"); - let activated = cx.activation().filter(|_: &Activation| cx.resolved.enabled).is_some(); let open = popup.is_open(cx); - if activated { + if activation.is_some() { if open { popup.close(cx); } else { @@ -462,6 +666,9 @@ impl Component for PaintChip<'_> { } fn overlay(&mut self, ui: &mut OverlayUi<'_>, cx: &mut Cx<'_, Self>) { + if !self.opens() { + return; + } let popup = cx.popup("picker"); let words = cx.words::(); let name = cx.label(); @@ -510,10 +717,10 @@ impl Component for PaintChip<'_> { let groups: &[SwatchGroup] = groups; let source = swatch_source(groups, cmyk); let colors: HashMap<&str, &SwatchColor> = - groups.iter().flat_map(|g| g.entries.iter().map(|e| (e.name.as_str(), &e.color))).collect(); + groups.iter().flat_map(|g| g.entries.iter().filter_map(|e| e.color().map(|c| (e.name.as_str(), c)))).collect(); let out = PresetBrowser::new(words.swatches.clone(), state.reborrowed(), &source) .toolbar(false) - .row_menu(false) + .row_menu(PresetRowMenu::Off) .default_open(DefaultOpen::None) .room_height(Env::of(ui).tokens.size.control.sm * SWATCH_ROWS) .show(ui); @@ -570,45 +777,27 @@ impl Component for PaintChip<'_> { Some(paint) => access.value(value_text(&words, paint)), None => access.value(cx.words::().swatch_mixed.as_str()), }; - access.has_popup(PopupKind::Dialog); + if self.opens() { + access.has_popup(PopupKind::Dialog); + } } fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { - let style = cx.style; - let well = cx.rect; - let shape = PaintShape::Rect(well, style.radius); + let (well, mark) = self.layout(cx.rect, cx.style, cx.flow.is_rtl()); + if self.popup_mark == PopupMark::Menu { + let mut arrow = DisclosureGlyph::dropdown_of(cx.env.get()); + arrow.color = Some(cx.style.arrow_color); + ui.draw().icon(Rect::from_center_size(mark.center(), vec2(cx.style.arrow, cx.style.arrow)), &arrow); + } let Some(paint) = cx.value().cloned() else { ui.face(WELL, Swatch::new(cx.resolved.label.to_owned(), Mixed::::Mixed)); return; }; - let painter = ui.content_painter(cx); - match &paint { - Paint::Solid(color) => { - if color.a < 1.0 { - painter.checker(well); - } - ui.draw().data_fill(&shape, DataColor::new(Color32::from(*color))); - } - Paint::None => ui.draw().swatch_well(well, style.radius, WellFill::None), - Paint::Gradient(preview) => { - painter.checker(well); - if !preview.stops.is_empty() { - painter.ramp(well, egui::CornerRadius::ZERO, &ramp_stops(preview, cx.flow.is_rtl()), Axis::X); - } - } - Paint::Pattern(image) | Paint::Picture(image) => { - painter.checker(well); - match image.texture { - Some(texture) => paint_image(&painter, well, texture, matches!(paint, Paint::Pattern(_))), - None => ui.draw().fill(&shape, style.none_fill), - } - } - } - ui.draw().stroke(&shape, StrokeWidth::Thin, style.edge); + paint_well(ui, cx, well, &paint, &cx.style.well_look(self.ring)); } fn finish(self, cx: Cx<'_, Self>) -> PaintChipOutput { - PaintChipOutput { edit: cx.edit_response(), screen_pick: self.screen_pick, pick_color: self.pick_color } + PaintChipOutput { edit: cx.edit_response(), screen_pick: self.screen_pick, pick_color: self.pick_color, clicked: self.clicked } } } diff --git a/crates/color-ui/src/ui/paint_chip/paint_list.rs b/crates/color-ui/src/ui/paint_chip/paint_list.rs index 0d4d17752b..a6ca3ba2e5 100644 --- a/crates/color-ui/src/ui/paint_chip/paint_list.rs +++ b/crates/color-ui/src/ui/paint_chip/paint_list.rs @@ -374,8 +374,8 @@ impl<'a> PaintList<'a> { let mut events = acted.into_inner(); for event in list.events { match event { - CollectionEvent::Selection(SelectionChange::Set(keys)) => selected = keys.last().copied().or(selected), - CollectionEvent::Selection(SelectionChange::Toggle(row)) => selected = Some(row), + CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } => selected = keys.last().copied().or(selected), + CollectionEvent::Selection { change: SelectionChange::Toggle(row), .. } => selected = Some(row), CollectionEvent::Rename(event) if matches!(event, EditEvent::Commit { .. }) => { if let Some(Rename { key, name, .. }) = event.value() { events.push(PaintListEvent::Rename { row: *key, name: name.clone() }); diff --git a/crates/color-ui/src/ui/paint_chip/stories.rs b/crates/color-ui/src/ui/paint_chip/stories.rs index 576037f009..ca6748ed04 100644 --- a/crates/color-ui/src/ui/paint_chip/stories.rs +++ b/crates/color-ui/src/ui/paint_chip/stories.rs @@ -1,12 +1,15 @@ //! Stories of the paint chip and the paint list. -use super::{GradientPreview, ImagePreview, Paint, PaintChip, PaintLink, PaintLinkKind, PaintList, PaintListOptions, PaintRow}; +use super::{GradientPreview, ImagePreview, Paint, PaintChip, PaintChipSize, PaintLink, PaintLinkKind, PaintList, PaintListOptions, PaintRow}; use craft_behavior::Mixed; use craft_theme::Srgba; +use craft_ui::buttons::PopupMark; use craft_ui::contract::Role; use craft_ui::contract::{Bind, Props as _, Show as _, ShowContainer as _, Validity}; -use craft_ui::layout_components::Stack; +use craft_ui::display::{Shade, Text}; +use craft_ui::layout_components::{Row, Stack}; use craft_ui::patterns::presets::PresetState; +use craft_ui::primitives::FacePaint; use craft_ui::runtime::env::Message; use craft_ui::testing::{Drive, Fixture, StoryData, StoryOutput, story}; use egui::Ui; @@ -58,6 +61,94 @@ fn paint_chip(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { first.unwrap_or_default() } +/// Host-picker mode: a click opens nothing and reports the modifiers held. +#[story(PaintChip<'static>, covers = [], drive = Drive::Never)] +fn paint_chip_host_picker(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let (held, clicks) = data.value("state", (Paint::Solid(BLUE), 0u32)); + let shown = PaintChip::new("Fill", Bind::bound(held), BLUE).popover(false).show(ui); + if shown.clicked.is_some() { + *clicks += 1; + } + Text::new(format!("Clicks: {clicks}")).shade(Shade::Muted).show(ui); + shown.into() +} + +/// The chip as a ring round an open middle, for a solid and a gradient paint. +#[story(PaintChip<'static>, covers = [], drive = Drive::Never)] +fn paint_chip_ring(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let gradient = GradientPreview::new(vec![(0.0, BLUE), (1.0, Srgba::rgb(1.0, 1.0, 1.0))]); + let paints = data.value("paints", [Paint::Solid(BLUE), Paint::Gradient(gradient)]); + let mut first = None; + Stack::new().show(ui, |ui, _| { + for (index, (label, paint)) in ["Stroke", "Gradient stroke"].into_iter().zip(paints.iter_mut()).enumerate() { + let shown = PaintChip::new(label, Bind::bound(paint), BLUE).ring(true).show(ui); + if index == 0 { + first = Some(StoryOutput::from(shown)); + } + } + }); + first.unwrap_or_default() +} + +/// Fill and Stroke chips with the menu mark: the dropdown arrow after the well, inside the chip. +#[story(PaintChip<'static>, covers = [], drive = Drive::Never)] +fn paint_chip_menu_mark(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let paints = data.value("paints", [Paint::Solid(BLUE), Paint::Solid(Srgba::rgb(0.1, 0.1, 0.1))]); + let mut first = None; + Stack::new().show(ui, |ui, _| { + for (index, (label, paint)) in ["Fill", "Stroke"].into_iter().zip(paints.iter_mut()).enumerate() { + let shown = PaintChip::new(label, Bind::bound(paint), BLUE).ring(index == 1).popup_mark(PopupMark::Menu).show(ui); + if index == 0 { + first = Some(StoryOutput::from(shown)); + } + } + }); + first.unwrap_or_default() +} + +/// Compact Fill and Stroke chips in a row, as among a task bar's buttons: a small well in a control-high slot. +#[story(PaintChip<'static>, covers = [], drive = Drive::Never)] +fn paint_chip_compact(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let paints = data.value("paints", [Paint::Solid(BLUE), Paint::Solid(Srgba::rgb(0.1, 0.1, 0.1))]); + let mut first = None; + Row::new().show(ui, |ui, _| { + for (index, (label, paint)) in ["Fill", "Stroke"].into_iter().zip(paints.iter_mut()).enumerate() { + let shown = PaintChip::new(label, Bind::bound(paint), BLUE).ring(index == 1).chip_size(PaintChipSize::Compact).popover(false).show(ui); + if index == 0 { + first = Some(StoryOutput::from(shown)); + } + } + }); + first.unwrap_or_default() +} + +/// A tool rail's Color, Gradient and None as swatch chips, three in a row; a click opens nothing. +#[story(PaintChip<'static>, covers = [], drive = Drive::Never)] +fn paint_chip_swatches(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let gradient = GradientPreview::new(vec![(0.0, Srgba::rgb(1.0, 1.0, 1.0)), (1.0, Srgba::rgb(0.0, 0.0, 0.0))]); + let paints = data.value("paints", [Paint::Solid(BLUE), Paint::Gradient(gradient), Paint::None]); + let mut first = None; + Row::new().show(ui, |ui, _| { + for (index, (label, paint)) in ["Color", "Gradient", "None"].into_iter().zip(paints.iter_mut()).enumerate() { + let shown = PaintChip::new(label, Bind::bound(paint), BLUE).chip_size(PaintChipSize::Swatch).show(ui); + if index == 0 { + first = Some(StoryOutput::from(shown)); + } + } + }); + first.unwrap_or_default() +} + +/// A gradient whose face is the host's painter: one coloured rect over the checker. +#[story(PaintChip<'static>, covers = [], drive = Drive::Never)] +fn paint_chip_gradient_face(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let face = FacePaint::new(1, |painter, rect| { + painter.painter.rect_filled(rect.shrink2(egui::vec2(rect.width() / 4.0, 0.0)), 0.0, egui::Color32::from_rgb(230, 120, 30)); + }); + let preview = GradientPreview::new(vec![(0.0, BLUE), (1.0, Srgba::rgb(1.0, 1.0, 1.0))]).face(face); + chip(ui, data, Paint::Gradient(preview)) +} + #[story(PaintChip<'static>, covers = [Mixed], drive = Drive::Never)] fn paint_chip_mixed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let (held, held_at) = data.value_at("mixed", Mixed::::Mixed); diff --git a/crates/color-ui/src/ui/pair.rs b/crates/color-ui/src/ui/pair.rs index 5a91786b4e..8cb8cda739 100644 --- a/crates/color-ui/src/ui/pair.rs +++ b/crates/color-ui/src/ui/pair.rs @@ -5,18 +5,19 @@ use craft_theme::{Srgba, WellShape}; use craft_ui::buttons::IconButton; use craft_ui::choice::{ChoiceWords, Swatch, SwatchMetrics, SwatchStyle}; use craft_ui::contract::{ - Access, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Focus as _, MeasureCx, Meta as _, Outcome, Overlay, OverlayUi, - Overlays as _, PaintUi, PartsCx, Pointer as _, Props as _, Remember as _, Role, WordSetCx as _, + 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::{DataWidth, Draw, Glyph, IconSpec, PaintShape, StrokeWidth, WellFill}; +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, DataColor, Flags, FocusLook, GlyphRole, StyleColor, StyleCx, SurfaceEdge, SurfaceStyle, UiTokens}; +use craft_ui::style::{ComponentStyle, Flags, FocusLook, GlyphRole, StyleColor, StyleCx, SurfaceEdge, SurfaceStyle, UiTokens}; use egui::emath::GuiRounding as _; use egui::{Color32, CornerRadius, Painter, Pos2, Rect, Response, Shape, Stroke, StrokeKind, Vec2, pos2, vec2}; +use super::paint_chip::{WellLook, paint_well}; use super::popover::compact_picker; -use super::{ColorPicker, PickedColor, ScreenPickGesture}; +use super::{ColorPicker, Paint, PaintWords, PickedColor, ScreenPickGesture}; #[cfg(feature = "suite")] pub(crate) mod stories; @@ -27,8 +28,6 @@ const WELL: PartKey = PartKey::new("well"); const DEFAULT: PartKey = PartKey::new("default"); /// The Swap Colours button. const SWAP: PartKey = PartKey::new("swap"); -/// A ring well's band, as a share of the well's side. -const RING_SHARE: f32 = 0.3; /// One of a [`SwatchPair`]'s wells. The primary one is at the start, top, the secondary one is /// offset towards the end and down: foreground and background, or fill and stroke. @@ -68,7 +67,7 @@ impl Well { #[non_exhaustive] pub struct PairWell { label: Label, - color: Mixed, + paint: Mixed, ring: bool, } @@ -76,7 +75,17 @@ impl PairWell { /// A well named `label` (its accessible name and tooltip, translated: "Foreground colour") of the host's `color`; /// `Mixed::Mixed` for a selection whose fills differ, shown as the mixed well. pub fn new(label: impl Into

{ /// The pair's response. pub response: Response, /// The active well after this pass: the host's, or the one the user chose. @@ -163,9 +189,13 @@ pub struct SwatchPairOutput { pub open: Option, /// The edit of the active well: another well made active is one `Set`. pub choice: EditResponse, + /// A payload released on a well that accepts it: the well and the payload. + pub dropped: Option<(Well, P)>, + /// The well a dragged payload that it accepts is over. + pub over: Option, } -impl Outcome for SwatchPairOutput { +impl

Outcome for SwatchPairOutput

{ type Value = Well; fn response(&self) -> &Response { @@ -197,8 +227,8 @@ impl Outcome for SwatchPairOutput { /// - The wells are one roving group: Tab arrives at the active well; Left and Up go to the primary one, Right and /// Down to the secondary one (mirrored right to left). #[derive(craft_ui::contract::Component, craft_ui::contract::Props)] -#[component(overlay)] -pub struct SwatchPair<'a> { +#[component(overlay, content_painter, probe(SwatchPair<'static, u8>))] +pub struct SwatchPair<'a, P: Clone + Send + Sync + 'static = ()> { #[common] common: Common, wells: [PairWell; 2], @@ -225,6 +255,13 @@ pub struct SwatchPair<'a> { /// Sets up the popup's picker. #[prop(func = "Fn(ColorPicker<'a>) -> ColorPicker<'a>")] picker: Option>, + /// The payload each well drags past the slop (`None`: that well drags nothing). + drags: Option<[Option

; 2]>, + /// What each well accepts of a dragged payload: the well is a drop target for the payloads this allows. + #[prop(func = "Fn(Well, &P) -> bool")] + accepts: Option>, + dropped: Option<(Well, P)>, + over: Option, clicked: Option, double_clicked: Option, activated: bool, @@ -235,7 +272,7 @@ pub struct SwatchPair<'a> { screen_pick: Option, } -impl<'a> SwatchPair<'a> { +impl<'a> SwatchPair<'a, ()> { /// A pair named `label` of `wells`, primary first; `active` is the well in front. pub fn new(label: impl Into

; - fn style(cx: &StyleCx<'_>, _: SwatchPairStyleKey) -> SwatchPairStyle { + fn style(cx: &StyleCx<'_>, _: SwatchPairStyleKey

) -> SwatchPairStyle { let colors = &cx.tokens.color; let well = cx.tokens.size.icon.lg; let round = cx.tokens.shape.wells == WellShape::Round; @@ -324,6 +407,8 @@ impl Component for SwatchPair<'_> { outline: cx.tokens.stroke.thin, frame: cx.color(colors.text.muted), mark: cx.color(colors.text.normal), + none_fill: cx.color(colors.surface.sunken), + none_mark: cx.color(colors.status.bad.solid), swatch: Swatch::style(cx, Swatch::new(Label::default(), Srgba::BLACK).style_key()), } } @@ -344,23 +429,21 @@ impl Component for SwatchPair<'_> { fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) { let flow = Flow::new(rect, cx.flow.is_rtl()); - let rects = self.well_rects(cx.style, rect.size()); + let rects = self.placed(cx.style, rect, cx.flow.is_rtl()); let active = cx.value().copied().unwrap_or_default(); let on_top = self.front(active); - for (i, logical) in rects.into_iter().enumerate() { + for (i, at) in rects.into_iter().enumerate() { let well = Well::of(i as u64); let front = well == on_top; - let at = flow.to_physical(logical.translate(rect.min.to_vec2())); + let sense = if self.payload(i).is_some() { Sense::CLICK | Sense::FOCUS | Sense::DRAG } else { Sense::CLICK | Sense::FOCUS }; let mut flags = Flags::empty(); - flags.set(Flags::MIXED, self.wells[i].color.same().is_none()); + flags.set(Flags::MIXED, self.wells[i].paint.same().is_none()); flags.set(Flags::CHECKED, well == active); let shape = if cx.style.round { HitShape::circle(at.center(), at.width() / 2.0) } else { HitShape::Rect(at) }; - let part = cx - .part(WELL.at(i as u64), shape) - .sense(Sense::CLICK | Sense::FOCUS) - .priority(HitPriority::new(HitLevel::Body, u8::from(front))) - .flags(flags) - .focusable(); + let part = + cx.part(WELL.at(i as u64), shape).sense(sense).priority(HitPriority::new(HitLevel::Body, u8::from(front))).flags(flags).focusable(); + // Focus arrives at the active well, so arriving makes no other well active. + let part = if well == active { part.selected() } else { part }; if self.popover { part.pointer_only("Enter opens the picker"); } @@ -385,6 +468,11 @@ impl Component for SwatchPair<'_> { for i in 0..2u64 { let well = Well::of(i); let press = cx.part(WELL.at(i)).press; + if matches!(press.phase, PressPhase::DragStart { .. }) + && let Some(payload) = self.payload(i as usize) + { + cx.start_drag(payload.clone(), DragPreview::None); + } if let PressPhase::Release { start, click: true, .. } = press.phase { self.clicked = Some(well); if start.clicks >= 2 { @@ -420,9 +508,11 @@ impl Component for SwatchPair<'_> { } self.defaults |= cx.part_activated(DEFAULT).is_some(); self.swap |= cx.part_activated(SWAP).is_some(); + // Focus moving onto a well (an arrow, a click) makes it active; focus resting on a well leaves the host's + // choice of another one alone. if self.click_activates && cx.is_focused() - && let Some(part) = cx.active_part() + && let Some(part) = cx.focus_arrived() && part.key == WELL && let Some(well) = part.index.map(Well::of) && well != active @@ -430,6 +520,19 @@ impl Component for SwatchPair<'_> { cx.set(well); self.activated = true; } + if cx.resolved.enabled + && let Some(DropAccepts(accepts)) = &self.accepts + { + let target = WellsTarget { + rects: self.placed(cx.style, cx.rect, cx.flow.is_rtl()), + front: self.front(active), + round: cx.style.round, + mixed: [0, 1].map(|i| self.wells[i].paint.same().is_none()), + accepts: &**accepts, + }; + self.over = cx.dragging::

().and_then(|(payload, at)| target.takes(&payload, at)); + self.dropped = cx.drop_target(&target); + } } fn overlay(&mut self, ui: &mut OverlayUi<'_>, cx: &mut Cx<'_, Self>) { @@ -440,7 +543,7 @@ impl Component for SwatchPair<'_> { let popup = cx.popup("picker"); let opened = cx.memory::().0.map_or(Well::Primary, Well::of); let well = &self.wells[opened.index() as usize]; - let (color, name) = (*well.color.or(&Srgba::BLACK), well.label.clone()); + let (color, name) = (solid_of(&well.paint), well.label.clone()); let setup = self.picker.as_ref(); let sampled = self.sampled; let shown = ui.show(popup, Overlay::popover(), |ui, _| { @@ -459,8 +562,8 @@ impl Component for SwatchPair<'_> { fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) { for (i, well) in self.wells.iter().enumerate() { - let value = match well.color.same() { - Some(color) => color.to_hex(), + let value = match well.paint.same() { + Some(paint) => paint_value(&cx.words::(), paint), None => cx.words::().swatch_mixed.as_str().to_owned(), }; // The two wells are a choice of the active colour: radios, the front one checked, with the colour as value. @@ -470,10 +573,8 @@ impl Component for SwatchPair<'_> { fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) { let style = cx.style; - let flow = Flow::new(cx.rect, cx.flow.is_rtl()); - let rects = self.well_rects(style, cx.rect.size()); + let rects = self.placed(style, cx.rect, cx.flow.is_rtl()); let active = cx.value().copied().unwrap_or_default(); - let place = |logical: Rect| flow.to_physical(logical.translate(cx.rect.min.to_vec2())); // The back well first, then the front one with a gap round it: being in front, or the frame, shows the active well. // The gap is a patch of the surface the pair sits on (a panel, a tool rail's chrome), fill only. The back well's // frame is painted before the front well, which covers it where they overlap. @@ -485,24 +586,36 @@ impl Component for SwatchPair<'_> { shadow: None, ..scope.surface(cx.env.surface()) }); - let draw = ui.draw(); let front = self.front(active); for well in [front.other(), front] { - let at = place(rects[well.index() as usize]); + let at = rects[well.index() as usize]; let shown = &self.wells[well.index() as usize]; if well == front { - draw.surface_styled(at.expand(style.gap), &ground); + ui.draw().surface_styled(at.expand(style.gap), &ground); } - match shown.color.same() { - Some(color) if shown.ring => paint_ring(&draw, at, *color, style), - color => { - draw.swatch_well(at, style.radius, color.copied().map_or(WellFill::Mixed, WellFill::Color)); - draw.stroke(&PaintShape::Rect(at, style.radius), StrokeWidth::Thin, style.mark); - draw.stroke(&outline(at, style), StrokeWidth::Thin, style.edge); + match shown.paint.same() { + Some(paint) => { + let look = WellLook { + none_fill: style.none_fill, + none_mark: style.none_mark, + edge: style.edge, + height: style.well, + radius: style.radius, + ring: shown.ring, + swatch: style.swatch.clone(), + }; + paint_well(ui, cx, at, paint, &look); } + 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 { + let draw = ui.draw(); + draw.stroke(&PaintShape::Rect(at, style.radius), StrokeWidth::Thin, style.mark); + draw.stroke(&outline(at, style), StrokeWidth::Thin, style.edge); } if self.frame_active && well == active { - draw.stroke(&frame(at, style), StrokeWidth::Thin, style.frame); + ui.draw().stroke(&frame(at, style), StrokeWidth::Thin, style.frame); } } } @@ -515,7 +628,7 @@ impl Component for SwatchPair<'_> { } } - fn finish(self, cx: Cx<'_, Self>) -> SwatchPairOutput { + fn finish(self, cx: Cx<'_, Self>) -> SwatchPairOutput

{ let open = cx.recall::().0.map(Well::of).filter(|_| !self.edit.is_empty() || self.edited.is_some()); let (response, active) = (cx.response.clone(), cx.value().copied().unwrap_or_default()); SwatchPairOutput { @@ -531,24 +644,67 @@ impl Component for SwatchPair<'_> { screen_pick: self.screen_pick, open, choice: cx.edit_response(), + dropped: self.dropped, + over: self.over, } } } -/// A ring well: a band of the colour round the edge, the middle open to what is behind. Each side of the band has the -/// outline and, inside it, a line that stands out from the colour. -fn paint_ring(draw: &Draw<'_>, at: Rect, color: Srgba, style: &SwatchPairStyle) { - let band = at.width() * RING_SHARE; - let line = style.outline; - let contrast = style.swatch.inner_edge(Some(color)); - draw.stroke(&PaintShape::Rect(at, style.radius), DataWidth::points(band), DataColor::new(Color32::from(color))); - draw.stroke(&PaintShape::Rect(at, style.radius), StrokeWidth::Thin, contrast); - draw.stroke(&outline(at, style), StrokeWidth::Thin, style.edge); - let hole = at.shrink(band); - // The hole's corners are concentric with the well's: square for a square well, round for a round one. - let corner = |grow: f32| UiTokens::corner((f32::from(style.radius.nw) - band + grow).max(0.0)); - draw.stroke(&PaintShape::Rect(hole.expand(2.0 * line), corner(2.0 * line)), StrokeWidth::Thin, contrast); - draw.stroke(&PaintShape::Rect(hole.expand(line), corner(line)), StrokeWidth::Thin, style.edge); +/// The one drop target of a pair: it takes a payload on the well under the pointer, the front well first where they +/// overlap, unless that well is mixed or `accepts` refuses the payload. +struct WellsTarget<'t, P> { + rects: [Rect; 2], + front: Well, + round: bool, + mixed: [bool; 2], + accepts: &'t dyn Fn(Well, &P) -> bool, +} + +impl

WellsTarget<'_, P> { + fn well_at(&self, at: Pos2) -> Option { + [self.front, self.front.other()].into_iter().find(|well| { + let rect = self.rects[well.index() as usize]; + if self.round { at.distance(rect.center()) <= rect.width() / 2.0 } else { rect.contains(at) } + }) + } + + /// The well that takes `payload` dropped at `at`. + fn takes(&self, payload: &P, at: Pos2) -> Option { + let well = self.well_at(at)?; + (!self.mixed[well.index() as usize] && (self.accepts)(well, payload)).then_some(well) + } +} + +impl DropTarget

for WellsTarget<'_, P> { + type Drop = (Well, P); + + fn accept(&self, payload: &P, at: Pos2, _: DropOperation) -> Option<(Well, P)> { + self.takes(payload, at).map(|well| (well, payload.clone())) + } + + fn mark(&self, drop: &(Well, P)) -> DropMark { + DropMark::Into(self.rects[drop.0.index() as usize]) + } +} + +/// The colour a picker starts from for `paint`: a solid's colour, a gradient's first stop, else black. +fn solid_of(paint: &Mixed) -> Srgba { + match paint.same() { + Some(Paint::Solid(color)) => *color, + Some(Paint::Gradient(gradient)) => gradient.stops.first().map_or(Srgba::BLACK, |stop| stop.1), + _ => Srgba::BLACK, + } +} + +/// A well's value for a screen reader: the hex of a solid, else the kind of paint. +fn paint_value(words: &PaintWords, paint: &Paint) -> String { + match paint { + Paint::None => words.no_color.as_str().to_owned(), + Paint::Solid(color) => color.to_hex(), + Paint::Gradient(_) => words.gradient.as_str().to_owned(), + Paint::Pattern(_) => words.pattern.as_str().to_owned(), + Paint::Picture(_) => words.picture.as_str().to_owned(), + } } /// The frame round the active well `at`: a gap outside its outline, concentric with its corners. diff --git a/crates/color-ui/src/ui/pair/stories.rs b/crates/color-ui/src/ui/pair/stories.rs index c4c0279f7a..618cecddea 100644 --- a/crates/color-ui/src/ui/pair/stories.rs +++ b/crates/color-ui/src/ui/pair/stories.rs @@ -1,9 +1,11 @@ //! Stories of the swatch pair. use super::{PairWell, SwatchPair, Well}; +use crate::ui::{GradientPreview, Paint}; use craft_behavior::Mixed; use craft_theme::Srgba; -use craft_ui::contract::{Show as _, Tracked, Validity}; +use craft_ui::contract::{Bind, Role, Show as _, ShowContainer as _, Tracked, Validity}; +use craft_ui::layout_components::Row; use craft_ui::rails::{LastUsed, ToolRail, ToolSlot}; use craft_ui::runtime::env::Message; use craft_ui::testing::{Drive, Fixture, StoryData, StoryOutput, story}; @@ -36,8 +38,10 @@ fn editing(ui: &mut Ui, data: &mut StoryData, names: [&'static str; 2], start: [ let defaults = [Srgba::rgb(0.0, 0.0, 0.0), Srgba::rgb(1.0, 1.0, 1.0)]; let (state, state_at) = data.value_at("colors", Colors { active: Well::Primary, colors: start }); let wells = [PairWell::new(names[0], state.colors[0]), PairWell::new(names[1], state.colors[1]).ring(ring)]; - let shown = - SwatchPair::new("Colours", wells, state_at.bind(&mut state.active)).swap_button("Swap colours").default_button("Default colours").show(ui); + let shown = SwatchPair::<()>::new("Colours", wells, state_at.bind(&mut state.active)) + .swap_button("Swap colours") + .default_button("Default colours") + .show(ui); if shown.swap { state.colors.swap(0, 1); } @@ -56,26 +60,26 @@ fn editing(ui: &mut Ui, data: &mut StoryData, names: [&'static str; 2], start: [ StoryOutput::from(shown).readout(readout) } -#[story(SwatchPair<'static>, covers = [Default], drive = Drive::Custom(next_well))] +#[story(SwatchPair<'static, u8>, covers = [Default], drive = Drive::Custom(next_well))] fn swatch_pair(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let black_white = [Srgba::rgb(0.0, 0.0, 0.0), Srgba::rgb(1.0, 1.0, 1.0)]; editing(ui, data, ["Foreground colour", "Background colour"], black_white, false) } -#[story(SwatchPair<'static>, covers = [], drive = Drive::Never)] +#[story(SwatchPair<'static, u8>, covers = [], drive = Drive::Never)] fn swatch_pair_ring(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { editing(ui, data, ["Fill colour", "Stroke colour"], [Srgba::rgb(0.2, 0.55, 0.8), Srgba::rgb(0.9, 0.35, 0.2)], true) } -#[story(SwatchPair<'static>, covers = [], drive = Drive::Never)] +#[story(SwatchPair<'static, u8>, covers = [], drive = Drive::Never)] fn swatch_pair_host_picker(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - SwatchPair::new("Colours", wells(false), data.bind("active", Well::Primary)).popover(false).click_activates(false).show(ui).into() + SwatchPair::<()>::new("Colours", wells(false), data.bind("active", Well::Primary)).popover(false).click_activates(false).show(ui).into() } -#[story(SwatchPair<'static>, covers = [Mixed], drive = Drive::Never)] +#[story(SwatchPair<'static, u8>, covers = [Mixed], drive = Drive::Never)] fn swatch_pair_mixed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let wells = [PairWell::new("Fill", Mixed::::Mixed), PairWell::new("Stroke", Srgba::rgb(0.1, 0.3, 0.8)).ring(true)]; - SwatchPair::new("Fill and stroke", wells, data.bind("active", Well::Primary)).show(ui).into() + SwatchPair::<()>::new("Fill and stroke", wells, data.bind("active", Well::Primary)).show(ui).into() } /// Opens the picker of the focused well with Enter. @@ -85,20 +89,20 @@ fn open_picker(fixture: &mut Fixture) { fixture.idle(4); } -#[story(SwatchPair<'static>, covers = [Open], drive = Drive::Custom(open_picker))] +#[story(SwatchPair<'static, u8>, covers = [Open], drive = Drive::Custom(open_picker))] fn swatch_pair_open(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { - SwatchPair::new("Colours", wells(false), data.bind("active", Well::Primary)).show(ui).into() + SwatchPair::<()>::new("Colours", wells(false), data.bind("active", Well::Primary)).show(ui).into() } -#[story(SwatchPair<'static>, covers = [Invalid], drive = Drive::Never)] +#[story(SwatchPair<'static, u8>, covers = [Invalid], drive = Drive::Never)] fn swatch_pair_invalid(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let refuse_secondary = |well: &Well| if *well == Well::Secondary { Validity::Refuse(Message::new("Only the foreground can be edited")) } else { Validity::Ok }; - SwatchPair::new("Colours", wells(false), data.bind("active", Well::Secondary).check(refuse_secondary)).show(ui).into() + SwatchPair::<()>::new("Colours", wells(false), data.bind("active", Well::Secondary).check(refuse_secondary)).show(ui).into() } /// The pair in a tool rail's footer, as PhotoCraft's colour chips: the gap round the front well takes the rail's chrome. -#[story(SwatchPair<'static>, covers = [], drive = Drive::Never)] +#[story(SwatchPair<'static, u8>, covers = [], drive = Drive::Never)] fn swatch_pair_tool_rail(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let (active, active_at) = data.value_at("active", Well::Primary); let (slots, last): (Tracked>>, Tracked>) = (Tracked::default(), Tracked::default()); @@ -106,7 +110,7 @@ fn swatch_pair_tool_rail(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let mut shown = None; ToolRail::new("Tools", &slots, &0, &last).show_rail(ui, |ui, _| { shown = Some( - SwatchPair::new("Colours", wells.clone(), active_at.bind(&mut *active)) + SwatchPair::<()>::new("Colours", wells.clone(), active_at.bind(&mut *active)) .popover(false) .swap_button("Swap colours") .default_button("Default colours") @@ -115,3 +119,44 @@ fn swatch_pair_tool_rail(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { }); shown.map(StoryOutput::from).unwrap_or_default() } + +/// Wells that show a gradient and No Color, as squares and as rings. +#[story(SwatchPair<'static, u8>, covers = [], drive = Drive::Never)] +fn swatch_pair_paints(ui: &mut Ui, _: &mut StoryData) -> StoryOutput { + let ramp = || Paint::Gradient(GradientPreview::new(vec![(0.0, Srgba::rgb(0.9, 0.3, 0.2)), (1.0, Srgba::rgb(0.2, 0.4, 0.9))])); + Row::new().show(ui, |ui, _| { + for ring in [false, true] { + let wells = [PairWell::paint("Fill", ramp()).ring(ring), PairWell::paint("Stroke", Paint::None).ring(ring)]; + let name = if ring { "Ring paints" } else { "Paints" }; + let _ = SwatchPair::<()>::new(name, wells, Bind::given(Well::Primary)).show(ui); + } + }); + StoryOutput::default() +} + +/// Drags the first pair's primary well onto the second pair's. +fn drag_across(fixture: &mut Fixture) { + let wells = fixture.by_role(Role::RADIO_BUTTON); + let (from, to) = (wells[0].rect.center(), wells[2].rect.center()); + fixture.drag_at(from, to - from); +} + +/// Two pairs whose wells drag a payload and take the other pair's. +#[story(SwatchPair<'static, u8>, covers = [], drive = Drive::Custom(drag_across))] +fn swatch_pair_drags(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let dropped = data.note("dropped", String::new()); + Row::new().show(ui, |ui, _| { + for first in [1u8, 3] { + let wells = [PairWell::new("Source", Srgba::rgb(0.1, 0.3, 0.8)), PairWell::new("Target", Srgba::rgb(0.9, 0.35, 0.2))]; + let shown = SwatchPair::<()>::new(format!("Pair {first}"), wells, Bind::given(Well::Primary)) + .drags([Some(first), Some(first + 1)]) + .accepts(|_, _| true) + .show(ui); + if let Some((well, payload)) = shown.dropped { + *dropped = format!("{payload} on {well:?}"); + } + } + }); + let readout = format!("Dropped: {dropped}"); + StoryOutput::default().readout(readout) +} diff --git a/crates/color-ui/src/ui/palette.rs b/crates/color-ui/src/ui/palette.rs index 717b7fd81e..000e8ca818 100644 --- a/crates/color-ui/src/ui/palette.rs +++ b/crates/color-ui/src/ui/palette.rs @@ -3,8 +3,8 @@ use craft_behavior::{EditEvent, IconId, Mixed, Selection}; use craft_theme::Srgba; -use craft_ui::choice::SwatchTable; -use craft_ui::contract::{ActivateOn, Bind, Held, NoValue, Outcome, Pattern, Show as _, ShowContainer as _}; +use craft_ui::choice::{SwatchSpacing, SwatchTable}; +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; @@ -17,6 +17,9 @@ use std::sync::Arc; #[cfg(feature = "suite")] pub(crate) mod stories; +/// The table's drag mapper, type-erased so the palette needs no payload parameter. +type TableMap = Arc Fn(SwatchTable<'t>) -> SwatchTable<'t>>; + /// What a [`SwatchPalette`] reports. #[derive(Debug)] #[non_exhaustive] @@ -62,6 +65,8 @@ pub struct SwatchPalette<'a> { label: Label, 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. @@ -117,14 +122,46 @@ fn cell_of(swatches: &[(Label, Srgba)], color: Option) -> Selection 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

+ Send + Sync + 'static) -> Self { + let map = Arc::new(map); + self.drag = Some(Arc::new(move |table| { + let map = Arc::clone(&map); + table.drag_payload(move |drag| map(drag)) + })); + self } /// An Other… cell after the swatches, named `label`: activating it files a `ColorRequest` keyed `key` at the bound @@ -142,7 +179,7 @@ impl<'a> SwatchPalette<'a> { /// Shows the palette. pub fn show(self, ui: &mut Ui) -> SwatchPaletteOutput { - let SwatchPalette { label, mut color, swatches, other, recent } = self; + let SwatchPalette { label, mut color, swatches, spacing, drag, other, recent } = self; let recent = recent.filter(|(_, colors)| !colors.is_empty()); let recent_cells: Vec<(Label, Srgba)> = recent.iter().flat_map(|(_, colors)| colors.iter()).map(|color| (Label::from(color.to_hex()), *color)).collect(); @@ -155,8 +192,15 @@ impl<'a> SwatchPalette<'a> { let mut pick = None; if !swatches.is_empty() || other.is_some() { // Every click activates, so a click on the swatch already selected, which changes no selection, still picks. - let mut table = - SwatchTable::new(label.clone(), swatches).tips(true).wells(true).activate(ActivateOn::Click).selection(Bind::bound(&mut current)); + let mut table = SwatchTable::new(label.clone(), swatches) + .tips(true) + .wells(true) + .spacing(spacing) + .activate(ActivateOn::Click) + .selection(Bind::bound(&mut current)); + if let Some(map) = &drag { + table = map(table); + } if let Some((_, other_label)) = &other { table = table.trailing(other_label.clone(), IconId::new("plus")); } diff --git a/crates/color-ui/src/ui/palette/stories.rs b/crates/color-ui/src/ui/palette/stories.rs index f08d0ea194..6330b0d6ba 100644 --- a/crates/color-ui/src/ui/palette/stories.rs +++ b/crates/color-ui/src/ui/palette/stories.rs @@ -3,6 +3,7 @@ use super::SwatchPalette; use craft_behavior::Mixed; use craft_theme::Srgba; +use craft_ui::choice::SwatchSpacing; use craft_ui::runtime::env::Label; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; @@ -61,10 +62,10 @@ fn no_colour(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { StoryOutput::from(shown).readout(readout) } -#[story(SwatchPalette<'static>, covers = [], drive = Drive::Never)] -fn swatch_palette(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { +/// The palette of the twelve colours, set up by `options`, with the readout of its latest event. +fn shown_palette(ui: &mut Ui, data: &mut StoryData, options: impl for<'a> FnOnce(SwatchPalette<'a>) -> SwatchPalette<'a>) -> StoryOutput { let swatches = named(PALETTE.iter().map(|(name, color)| ((*name).to_owned(), *color))); - let shown = SwatchPalette::new("Swatches", data.bind("color", PALETTE[8].1), &swatches).show(ui); + let shown = options(SwatchPalette::new("Swatches", data.bind("color", PALETTE[8].1), &swatches)).show(ui); let last = data.note("last", String::new()); if let Some(event) = &shown.edit { *last = format!("{event:?}"); @@ -72,3 +73,18 @@ fn swatch_palette(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { let readout = format!("Last event: {last}"); StoryOutput::from(shown).readout(readout) } + +#[story(SwatchPalette<'static>, covers = [], drive = Drive::Never)] +fn swatch_palette(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + shown_palette(ui, data, |palette| palette) +} + +#[story(SwatchPalette<'static>, covers = [], drive = Drive::Never)] +fn swatch_palette_spaced(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + shown_palette(ui, data, |palette| palette.spacing(SwatchSpacing::Spaced)) +} + +#[story(SwatchPalette<'static>, covers = [], drive = Drive::Never)] +fn swatch_palette_spaced_draggable(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + shown_palette(ui, data, |palette| palette.spacing(SwatchSpacing::Spaced).drag_payload(|_| Some(String::from("swatch")))) +} diff --git a/crates/color-ui/src/ui/panel.rs b/crates/color-ui/src/ui/panel.rs index 1326059f60..90c92271b2 100644 --- a/crates/color-ui/src/ui/panel.rs +++ b/crates/color-ui/src/ui/panel.rs @@ -3,6 +3,7 @@ //! sliders; the panel menu chooses the view and the ramp and copies the colour. use std::hash::{DefaultHasher, Hash, Hasher}; +use std::sync::Arc; use craft_behavior::{EditEvent, GesturePhase, IconId, Mixed}; use craft_cms::convert::CmykConverter; @@ -25,10 +26,11 @@ use super::channels::finite_values; use super::picker::{ChannelRow, ChannelRule, ChannelUnit, channel_name}; use super::{ AreaMode, ColorArea, ColorPickerDialogWords, ColorRamp, ColorReadout, ColorStrip, ColorWarning, ColorWarningArrangement, ColorWarningChip, - ColorWheel, PairWell, PickedColor, RampKind, SwatchPair, Well, + ColorWheel, Gamut, PairWell, PickedColor, RampKind, RampPick, RampRecolor, SwatchPair, SwatchPairOutput, SwatchPalette, Well, }; use crate::{CmykModel, GrayModel, not_web_safe}; +mod fill_stroke; #[cfg(feature = "suite")] pub(crate) mod stories; @@ -57,6 +59,15 @@ craft_ui::words! { add_to_swatches: "colorPanel.addToSwatches" = "Add to Swatches"; create_swatch: "colorPanel.createSwatch" = "Create new swatch"; hex_color: "colorPanel.hexColor" = "Hex color"; + swap_colors: "colorPanel.swapColors" = "Swap fill and stroke"; + default_colors: "colorPanel.defaultColors" = "Default fill and stroke"; + none: "colorPanel.none" = "None"; + black: "colorPanel.black" = "Black"; + white: "colorPanel.white" = "White"; + recent_colors: "colorPanel.recentColors" = "Recent Colors"; + tint: "colorPanel.tint" = "Tint"; + global: "colorPanel.global" = "Global"; + spot: "colorPanel.spot" = "Spot"; } } @@ -100,6 +111,21 @@ pub enum ColorPanelMode { } impl ColorPanelMode { + /// The modes of the FillStroke layout's menu, in its order; the Shift-click on the spectrum cycles through them. + pub const FILL_STROKE: [ColorPanelMode; 5] = [ + ColorPanelMode::GrayscaleSlider, + ColorPanelMode::RgbSliders, + ColorPanelMode::HsbSliders, + ColorPanelMode::CmykSliders, + ColorPanelMode::WebColorSliders, + ]; + + /// The mode after this one in [`FILL_STROKE`](Self::FILL_STROKE); a mode outside the list goes to the first. + pub fn fill_stroke_next(self) -> ColorPanelMode { + let next = Self::FILL_STROKE.iter().position(|mode| *mode == self).and_then(|at| Self::FILL_STROKE.get(at + 1)); + next.copied().unwrap_or(ColorPanelMode::GrayscaleSlider) + } + /// Every mode, in the panel menu's order (one section, no separator). pub const ALL: [ColorPanelMode; 9] = [ ColorPanelMode::HueCube, @@ -203,9 +229,7 @@ impl ColorPanelRamp { } /// The Color panel's settings, kept across runs (settings section `color_panel`). -#[derive( - Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize, craft_ui::contract::MemoProps, craft_ui::contract::PlainData, -)] +#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize, craft_ui::contract::MemoProps, craft_ui::contract::PlainData)] #[serde(default, rename_all = "camelCase")] #[non_exhaustive] pub struct ColorPanelState { @@ -217,6 +241,91 @@ pub struct ColorPanelState { pub ramp: ColorPanelRamp, /// Make Ramp Web Safe: the ramp shows and picks web colours only. pub web_safe_ramp: bool, + /// Hide Options: the FillStroke layout keeps the proxy and the spectrum only. + pub hide_options: bool, + /// The FillStroke layout shows the Recent Colors slot. + pub recent_colors: bool, + /// The R, G and B rows count percents, 0 to 100, in place of 0 to 255. + pub rgb_percent: bool, +} + +impl Default for ColorPanelState { + fn default() -> Self { + ColorPanelState { + background: false, + mode: ColorPanelMode::default(), + ramp: ColorPanelRamp::default(), + web_safe_ramp: false, + hide_options: false, + recent_colors: true, + rgb_percent: false, + } + } +} + +/// How a [`ColorPanel`] arranges its body. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum ColorPanelLayout { + /// The foreground over the background wells with one view of the edited colour (Photoshop's panel). + #[default] + ForegroundBackground, + /// The fill and stroke proxy, the rows of the shown mode, the Spectrum ramp and the Recent Colors slot. + /// + /// The rows come from [`ColorPanel::shown`]. [`ColorPanelState::mode`] counts only when it is one of + /// [`ColorPanelMode::FILL_STROKE`]: any other value means no mode was picked, and the host's `shown` decides. + FillStroke, +} + +/// What rows a [`ColorPanel`] shows: the host's model rule. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub enum ColorPanelShown { + /// The channel rows of this mode. + Mode(ColorPanelMode), + /// The Tint row of a swatch-linked colour. + Tint(TintRow), + /// No rows. + Empty, +} + +/// The Tint row of a swatch-linked colour: a chip with the global corner and the spot dot, the name and the T row. +#[derive(Clone, Debug, PartialEq)] +#[non_exhaustive] +pub struct TintRow { + /// The swatch's name. + pub name: Label, + /// The swatch's colour at full strength. + pub base: Srgba, + /// The swatch is global: the chip has the global corner. + pub global: bool, + /// The swatch is a spot colour: the chip has the spot dot. + pub spot: bool, + /// The tint, 0 to 100. + pub tint: f32, +} + +impl TintRow { + /// A tint of `base` named `name`, neither global nor spot. + pub fn new(name: impl Into

+ Send + Sync + 'static) -> RecentSetup { + let map = Arc::new(map); + Box::new(move |palette| { + let map = Arc::clone(&map); + palette.drag_payload(move |drag| map(drag.grabbed)) + }) +} + +/// What the host gave the pass, borrowed from the panel. +#[derive(Clone, Copy)] +struct Inputs<'a> { + wells: Option<&'a [PairWell; 2]>, + edited: Option<&'a Option>, + shown: &'a ColorPanelShown, + recent: &'a [Srgba], + recent_setup: Option<&'a RecentSetup>, } impl<'a> ColorPanel<'a> { /// The panel on the app's `[foreground, background]`. pub fn new(state: Bind<'a, ColorPanelState>, colors: [Srgba; 2]) -> Self { - ColorPanel { state, colors, cmyk: None, dynamic: true } + ColorPanel { + state, + colors, + cmyk: None, + rgb: None, + dynamic: true, + layout: ColorPanelLayout::default(), + wells: None, + edited: None, + shown: None, + recent: &[], + recent_setup: None, + gamut: None, + } } /// The document's CMYK converter, for the CMYK sliders, the CMYK Spectrum ramp and the gamut warning; without it @@ -338,6 +501,13 @@ impl<'a> ColorPanel<'a> { self } + /// The host's working-RGB colour model, whose channels replace the built-in `rgb` rows (wide working spaces show + /// their own numbers). + pub fn working_rgb(mut self, model: &'a dyn ColorModel) -> Self { + self.rgb = Some(model); + self + } + /// Dynamic Color Sliders (PhotoCraft's interface preference, on by default): the slider tracks show the channel's /// colours with the other channels as they are. Off, the tracks keep the colours they had when a drag began. pub fn dynamic_tracks(mut self, on: bool) -> Self { @@ -345,45 +515,131 @@ impl<'a> ColorPanel<'a> { self } + /// How the panel arranges its body; the Photoshop foreground and background arrangement by default. + pub fn layout(mut self, layout: ColorPanelLayout) -> Self { + self.layout = layout; + self + } + + /// The host's wells (paints) and the active well; `active` replaces `ColorPanelState::background` as the edited + /// well. + pub fn wells(mut self, wells: [PairWell; 2], active: Bind<'a, Well>) -> Self { + self.wells = Some((wells, active)); + self + } + + /// The colour the rows edit, with its model values; `None` disables the rows (mixed, None, a pattern). The edited + /// well's colour by default. + pub fn edited(mut self, color: Option) -> Self { + self.edited = Some(color); + self + } + + /// Which rows show, by the host's model rule; `Mode(state.mode)` by default. + pub fn shown(mut self, shown: ColorPanelShown) -> Self { + self.shown = Some(shown); + self + } + + /// The Recent Colors, a spaced `SwatchPalette` that wraps and drags. + pub fn recent(mut self, colors: &'a [Srgba]) -> Self { + self.recent = colors; + self + } + + /// The payload a Recent Colors chip drags. + pub fn recent_payload(mut self, map: impl Fn(usize) -> Option

+ Send + Sync + 'static) -> Self { + self.recent_setup = Some(recent_setup(map)); + self + } + + /// The host's gamut for the out-of-gamut chip and the spectrum. + pub fn gamut(mut self, gamut: Gamut<'a>) -> Self { + self.gamut = Some(gamut); + self + } + /// Shows the panel and returns this pass's edits and requests. pub fn show(self, ui: &mut Ui) -> ColorPanelOutput { - let ColorPanel { state, colors, cmyk, dynamic } = self; + let ColorPanel { state, colors, cmyk, rgb, dynamic, layout, wells, edited, shown: rows, recent, recent_setup, gamut } = self; let env = Env::of(ui); let (words, dialog) = (env.words::(), env.words::()); let mut held = Held::new(state); + let (wells, active) = match wells { + Some((wells, active)) => (Some(wells), Some(Held::new(active))), + None => (None, None), + }; + let mut active = active; + let converter = cmyk.unwrap_or_else(|| CmykConverter::coated()); + let gamut = gamut.unwrap_or_else(|| Gamut::cmyk(converter.clone())); + let rgb: &dyn ColorModel = rgb.unwrap_or(&RgbModel); let (mut edits, mut pick_color, mut add_to_swatches) = (Vec::new(), None, None); + let (mut pair, mut tint, mut none, mut recolor) = (None, None, None, None); let mut shown = Stack::new().label(words.title.clone()).fill().show(ui, |ui, cx| { let before = held.read(cx)?; - let target = if before.background { PanelTarget::Background } else { PanelTarget::Foreground }; + let was = match active.as_mut() { + Some(active) => active.read(cx)?, + None if before.background => Well::Secondary, + None => Well::Primary, + }; + let target = if was == Well::Secondary { PanelTarget::Background } else { PanelTarget::Foreground }; + let default_rows = ColorPanelShown::Mode(before.mode); let body = Body { target, + active: was, + layout, colors, - converter: cmyk.unwrap_or_else(|| CmykConverter::coated()), + converter, + rgb, + gamut: &gamut, dynamic, words: &words, dialog: &dialog, + inputs: Inputs { + wells: wells.as_ref(), + edited: edited.as_ref(), + shown: rows.as_ref().unwrap_or(&default_rows), + recent, + recent_setup: recent_setup.as_ref(), + }, now: before, kept: cx.memory::().clone(), events: Vec::new(), pick_color: None, add_to_swatches: None, + pair: None, + tint: None, + none: None, + recolor: None, + }; + let mut body = match layout { + ColorPanelLayout::ForegroundBackground => body.show(ui), + ColorPanelLayout::FillStroke => body.fill_stroke(ui), }; - let mut body = body.show(ui); *cx.memory::() = std::mem::take(&mut body.kept); edits = body.events; pick_color = body.pick_color; add_to_swatches = body.add_to_swatches; - Some((before, body.now)) + pair = body.pair; + tint = body.tint; + none = body.none; + recolor = body.recolor; + Some((before, body.now, was, body.active)) }); - // Once per pass, after the real run: the edited state is stored. + // Once per pass, after the real run: the edited state and the host's active well are stored. shown.settle(|cx, state| { - if let Some((before, now)) = state.take() - && now != before - { - held.write(cx, &before, now, words.title.as_str()); + if let Some((before, now, was, now_active)) = state.take() { + if now != before { + held.write(cx, &before, now, words.title.as_str()); + } + if let Some(active) = active.as_mut() + && now_active != was + { + active.write(cx, &was, now_active, words.title.as_str()); + } } }); - ColorPanelOutput { response: shown.output, edits, pick_color, add_to_swatches } + ColorPanelOutput { response: shown.output, edits, pick_color, add_to_swatches, pair, tint, none, recolor } } } @@ -440,6 +696,21 @@ pub enum ColorPanelCommand { /// The ramp shows and picks web colours only. #[command(label = "Make Ramp Web Safe", kind = "toggle")] WebSafeRamp, + /// Hide or show the options of the FillStroke layout. + #[command(label = "Hide Options")] + ToggleOptions, + /// Show the Recent Colors slot. + #[command(label = "Show Recent Colors", kind = "toggle")] + ShowRecentColors, + /// Invert the edited colour. + #[command(label = "Invert")] + Invert, + /// Replace the edited colour by its complement. + #[command(label = "Complement")] + Complement, + /// Create a swatch of the edited colour. + #[command(label = "Create New Swatch…")] + NewSwatch, } impl ColorPanelMode { @@ -476,14 +747,49 @@ impl ColorPanelRamp { pub struct ColorPanelMenu; impl ColorPanelMenu { - /// The rows: the nine views, a separator, Copy Color as HTML and Copy Color's Hex Code, a separator, the four ramps, - /// a separator, Make Ramp Web Safe. - pub fn rows() -> Vec { + /// The rows. `ForegroundBackground`: the nine views, a separator, Copy Color as HTML and Copy Color's Hex Code, a + /// separator, the four ramps, a separator, Make Ramp Web Safe. `FillStroke`: Hide Options and Show Recent Colors, a + /// separator, the five modes, a separator, Invert, Complement and Create New Swatch…, a separator, Copy Color Value + /// (Hex). + pub fn rows(layout: ColorPanelLayout) -> Vec { let row = |command: ColorPanelCommand| PanelRow::Command(CommandRef::from(command)); - let mut rows: Vec = ColorPanelMode::ALL.iter().map(|mode| row(mode.command())).collect(); - rows.extend([PanelRow::Separator, row(ColorPanelCommand::CopyHtml), row(ColorPanelCommand::CopyHex), PanelRow::Separator]); - rows.extend(Self::ramp_rows()); - rows + match layout { + ColorPanelLayout::ForegroundBackground => { + let mut rows: Vec = ColorPanelMode::ALL.iter().map(|mode| row(mode.command())).collect(); + rows.extend([PanelRow::Separator, row(ColorPanelCommand::CopyHtml), row(ColorPanelCommand::CopyHex), PanelRow::Separator]); + rows.extend(Self::ramp_rows()); + rows + } + ColorPanelLayout::FillStroke => { + let mut rows = vec![row(ColorPanelCommand::ToggleOptions), row(ColorPanelCommand::ShowRecentColors), PanelRow::Separator]; + rows.extend(ColorPanelMode::FILL_STROKE.iter().map(|mode| row(mode.command()))); + rows.extend([ + PanelRow::Separator, + row(ColorPanelCommand::Invert), + row(ColorPanelCommand::Complement), + row(ColorPanelCommand::NewSwatch), + PanelRow::Separator, + row(ColorPanelCommand::CopyHex), + ]); + rows + } + } + } + + /// The commands of `layout`'s rows, in their order. + fn commands(layout: ColorPanelLayout) -> Vec { + match layout { + ColorPanelLayout::ForegroundBackground => { + let commands = ColorPanelMode::ALL.iter().map(|mode| mode.command()); + let commands = commands.chain([ColorPanelCommand::CopyHtml, ColorPanelCommand::CopyHex]); + commands.chain(ColorPanelRamp::ALL.iter().map(|ramp| ramp.command())).chain([ColorPanelCommand::WebSafeRamp]).collect() + } + ColorPanelLayout::FillStroke => [ColorPanelCommand::ToggleOptions, ColorPanelCommand::ShowRecentColors] + .into_iter() + .chain(ColorPanelMode::FILL_STROKE.iter().map(|mode| mode.command())) + .chain([ColorPanelCommand::Invert, ColorPanelCommand::Complement, ColorPanelCommand::NewSwatch, ColorPanelCommand::CopyHex]) + .collect(), + } } /// The ramps, a separator and Make Ramp Web Safe: the last rows of the menu and the ramp's context menu. @@ -494,47 +800,79 @@ impl ColorPanelMenu { rows } - /// The state of each command: the current view and ramp checked, Make Ramp Web Safe checked when on. - pub fn states(state: &ColorPanelState) -> Vec<(ColorPanelCommand, CommandState)> { - let commands = ColorPanelMode::ALL.iter().map(|mode| mode.command()); - let commands = commands.chain([ColorPanelCommand::CopyHtml, ColorPanelCommand::CopyHex]); - let commands = commands.chain(ColorPanelRamp::ALL.iter().map(|ramp| ramp.command())).chain([ColorPanelCommand::WebSafeRamp]); - commands + /// The state of each command of `layout`: the current view (under `FillStroke`, the one `shown` shows; a tint checks + /// none) and ramp checked, the toggles checked when on, and the commands that need a colour disabled without one. + /// Show Options is titled so while the options are hidden. + pub fn states( + layout: ColorPanelLayout, + state: &ColorPanelState, + shown: &ColorPanelShown, + has_color: bool, + ) -> Vec<(ColorPanelCommand, CommandState)> { + let needs_color = [ + ColorPanelCommand::CopyHtml, + ColorPanelCommand::CopyHex, + ColorPanelCommand::Invert, + ColorPanelCommand::Complement, + ColorPanelCommand::NewSwatch, + ]; + Self::commands(layout) + .into_iter() .map(|command| { - let checked = Self::checked(state, command); - (command, checked.map_or_else(CommandState::new, |on| CommandState::new().checked(on))) + let mut flag = Self::checked(layout, state, shown, command).map_or_else(CommandState::new, |on| CommandState::new().checked(on)); + if !has_color && needs_color.contains(&command) { + flag = flag.enabled(false); + } + if command == ColorPanelCommand::ToggleOptions && state.hide_options { + flag = flag.title("Show Options"); + } + (command, flag) }) .collect() } - /// Whether `command`'s row is checked: `Some` for the views, the ramps and Make Ramp Web Safe, `None` for the copy - /// commands, which have no check. - pub fn checked(state: &ColorPanelState, command: ColorPanelCommand) -> Option { + /// Whether `command`'s row is checked: `Some` for the views (by `state` under `ForegroundBackground`, by `shown` + /// under `FillStroke`), the ramps and the toggles, `None` for the other commands, which have no check. + pub fn checked(layout: ColorPanelLayout, state: &ColorPanelState, shown: &ColorPanelShown, command: ColorPanelCommand) -> Option { if let Some(mode) = ColorPanelMode::ALL.into_iter().find(|mode| mode.command() == command) { - return Some(state.mode == mode); + return Some(match layout { + ColorPanelLayout::ForegroundBackground => state.mode == mode, + ColorPanelLayout::FillStroke => matches!(shown, ColorPanelShown::Mode(shown) if *shown == mode), + }); } if let Some(ramp) = ColorPanelRamp::ALL.into_iter().find(|ramp| ramp.command() == command) { return Some(state.ramp == ramp); } - (command == ColorPanelCommand::WebSafeRamp).then_some(state.web_safe_ramp) + match command { + ColorPanelCommand::WebSafeRamp => Some(state.web_safe_ramp), + ColorPanelCommand::ShowRecentColors => Some(state.recent_colors), + _ => None, + } } - /// Carries out `command`: sets the view or the ramp, toggles Make Ramp Web Safe, or returns the text of `edited` - /// for the clipboard, as HTML (`color="#rrggbb"`) or as a hex code (`rrggbb`). - pub fn run_command(state: &mut ColorPanelState, command: ColorPanelCommand, edited: Srgba) -> Option { + /// Carries out `command`: sets the view or the ramp, toggles the options, Recent Colors or Make Ramp Web Safe, or + /// answers what the host does: show a mode, copy the text of `edited` (as HTML, `color="#rrggbb"`, or as a hex code, + /// `rrggbb`), invert, complement, create a swatch. + pub fn run_command(state: &mut ColorPanelState, command: ColorPanelCommand, edited: Srgba) -> Option { if let Some(mode) = ColorPanelMode::ALL.into_iter().find(|mode| mode.command() == command) { state.mode = mode; - } else if let Some(ramp) = ColorPanelRamp::ALL.into_iter().find(|ramp| ramp.command() == command) { + return Some(ColorPanelAction::Mode(mode)); + } + if let Some(ramp) = ColorPanelRamp::ALL.into_iter().find(|ramp| ramp.command() == command) { state.ramp = ramp; - } else { - match command { - ColorPanelCommand::WebSafeRamp => state.web_safe_ramp = !state.web_safe_ramp, - ColorPanelCommand::CopyHtml => return Some(format!("color=\"{}\"", Srgba::from_rgb_array([edited.r, edited.g, edited.b]).to_hex())), - ColorPanelCommand::CopyHex => { - return Some(Srgba::from_rgb_array([edited.r, edited.g, edited.b]).to_hex().trim_start_matches('#').to_owned()); - } - _ => {} - } + return None; + } + let hex = || Srgba::from_rgb_array([edited.r, edited.g, edited.b]).to_hex(); + match command { + ColorPanelCommand::WebSafeRamp => state.web_safe_ramp = !state.web_safe_ramp, + ColorPanelCommand::ToggleOptions => state.hide_options = !state.hide_options, + ColorPanelCommand::ShowRecentColors => state.recent_colors = !state.recent_colors, + ColorPanelCommand::CopyHtml => return Some(ColorPanelAction::Copy(format!("color=\"{}\"", hex()))), + ColorPanelCommand::CopyHex => return Some(ColorPanelAction::Copy(hex().trim_start_matches('#').to_owned())), + ColorPanelCommand::Invert => return Some(ColorPanelAction::Invert), + ColorPanelCommand::Complement => return Some(ColorPanelAction::Complement), + ColorPanelCommand::NewSwatch => return Some(ColorPanelAction::NewSwatch), + _ => {} } None } @@ -544,22 +882,44 @@ impl ColorPanelMenu { struct Body<'a> { /// The colour the panel edits. target: PanelTarget, + /// The well in front, which `target` follows. + active: Well, + layout: ColorPanelLayout, colors: [Srgba; 2], converter: &'a CmykConverter, + /// The model of the R, G and B rows: the host's working RGB, else sRGB. + rgb: &'a dyn ColorModel, + gamut: &'a Gamut<'a>, dynamic: bool, words: &'a ColorPanelWords, dialog: &'a ColorPickerDialogWords, /// The state as this pass leaves it. now: ColorPanelState, kept: Kept, + inputs: Inputs<'a>, events: Vec<(PanelTarget, EditEvent)>, pick_color: Option, add_to_swatches: Option, + pair: Option, + tint: Option>, + none: Option, + recolor: Option, } impl Body<'_> { + /// The colour the rows edit: the host's `edited` colour, else the edited well's. fn color(&self) -> Srgba { - self.colors[self.target.index()] + self.picked().map_or(self.colors[self.target.index()], |picked| picked.color) + } + + /// The host's colour with its model values, when it gave one. + fn picked(&self) -> Option<&PickedColor> { + self.inputs.edited.and_then(Option::as_ref) + } + + /// Whether the rows edit anything: the host gave no `edited(None)`. + fn enabled(&self) -> bool { + self.inputs.edited.is_none_or(Option::is_some) } fn push(&mut self, target: PanelTarget, event: EditEvent) { @@ -596,17 +956,7 @@ impl Body<'_> { match mode { ColorPanelMode::HueCube => self.cube(ui, AreaMode::Hue), ColorPanelMode::BrightnessCube => self.cube(ui, AreaMode::Brightness), - _ => { - // The channel rows stand as close as Photoshop's, their letters, fields and units in shared columns. - FieldGroup::new(mode.label(self.words)).labels(LabelScheme::Inspector).gap(Gap::Tight).show(ui, |ui, _| match mode { - ColorPanelMode::GrayscaleSlider => self.rows(ui, &GrayModel, false), - ColorPanelMode::RgbSliders => self.rows(ui, &RgbModel, false), - ColorPanelMode::CmykSliders => self.rows(ui, &CmykModel::new(self.converter.clone()), false), - ColorPanelMode::LabSliders => self.rows(ui, &LabModel, false), - ColorPanelMode::WebColorSliders => self.rows(ui, &RgbModel, true), - _ => self.rows(ui, &HsbModel, false), - }); - } + _ => self.mode_rows(ui, mode), } }); match mode { @@ -616,21 +966,46 @@ impl Body<'_> { } } - /// The foreground over the background: a click on the other well edits it, a click on the edited one asks for the - /// picker. + /// The channel rows of the slider `mode`. They stand as close as Photoshop's, their letters, fields and units in + /// shared columns. + fn mode_rows(&mut self, ui: &mut Ui, mode: ColorPanelMode) { + let rgb = self.rgb; + FieldGroup::new(mode.label(self.words)).labels(LabelScheme::Inspector).gap(Gap::Tight).show(ui, |ui, _| match mode { + ColorPanelMode::GrayscaleSlider => self.rows(ui, &GrayModel, false), + ColorPanelMode::RgbSliders => self.rows(ui, rgb, false), + ColorPanelMode::CmykSliders => self.rows(ui, &CmykModel::new(self.converter.clone()), false), + ColorPanelMode::LabSliders => self.rows(ui, &LabModel, false), + ColorPanelMode::WebColorSliders => self.rows(ui, rgb, true), + _ => self.rows(ui, &HsbModel, false), + }); + } + + /// The foreground over the background (the host's wells when it gave them): a click on the other well edits it, a + /// click on the edited one asks for the picker. `FillStroke` adds the pair's swap and default buttons. fn wells(&mut self, ui: &mut Ui) { - let was = if self.now.background { Well::Secondary } else { Well::Primary }; + let was = self.active; let mut active = was; - let wells = [PairWell::new(self.words.foreground.clone(), self.colors[0]), PairWell::new(self.words.background.clone(), self.colors[1])]; - let pair = SwatchPair::new(self.words.wells.clone(), wells, Bind::bound(&mut active)).popover(false).frame_active(true).show(ui); - self.now.background = active == Well::Secondary; - if pair.clicked.as_ref() == Some(&was) { + let wells = self.inputs.wells.cloned().unwrap_or_else(|| { + [PairWell::new(self.words.foreground.clone(), self.colors[0]), PairWell::new(self.words.background.clone(), self.colors[1])] + }); + let pair = SwatchPair::<()>::new(self.words.wells.clone(), wells, Bind::bound(&mut active)).popover(false).frame_active(true); + let pair = match self.layout { + ColorPanelLayout::ForegroundBackground => pair, + ColorPanelLayout::FillStroke => pair.swap_button(self.words.swap_colors.clone()).default_button(self.words.default_colors.clone()), + }; + let pair = pair.show(ui); + self.active = active; + if self.inputs.wells.is_none() { + self.now.background = active == Well::Secondary; + } + if pair.clicked == Some(was) { let title = match self.target { PanelTarget::Foreground => self.dialog.foreground_title.clone(), PanelTarget::Background => self.dialog.background_title.clone(), }; self.pick_color = Some(ColorRequest::new(self.target.key(), self.color()).title(title)); } + self.pair = Some(pair); } /// The out-of-gamut chip and, for Web Color, the web-colour chip under the wells, each its icon beside a small swatch. @@ -639,8 +1014,8 @@ impl Body<'_> { let rgb = [color.r, color.g, color.b]; let nearest = |near: [f32; 3]| Srgba::rgb(near[0], near[1], near[2]); let mut warnings = Vec::new(); - if let Some(near) = self.converter.nearest_in_gamut(rgb, CmykConverter::PICKER_GAMUT_DE) { - warnings.push(ColorWarning::new(self.dialog.out_of_gamut.clone(), nearest(near))); + if let Some(near) = self.gamut.nearest(color) { + warnings.push(ColorWarning::new(self.dialog.out_of_gamut.clone(), near)); } if web && let Some(near) = not_web_safe(rgb) { warnings.push(ColorWarning::web_colors(self.dialog.not_web_color.clone(), nearest(near))); @@ -656,16 +1031,16 @@ impl Body<'_> { }); } - /// The model's values for the edited colour, whole numbers as Photoshop's fields. + /// The model's values for the edited colour, unrounded: an edit of one channel leaves the others as they are. fn values(&self, model: &dyn ColorModel) -> ModelValues { let color = self.color(); - let kept = self.kept.values[self.target.index()].iter().find(|v| v.model == model.id() && model.to_srgb(&v.values).same_rgb8(color)); - let mut values = kept.copied().unwrap_or_else(|| self.read(model, color)); - for (slot, ch) in values.values.iter_mut().zip(model.channels()) { - let scale = 10f32.powi(i32::from(ch.decimals)); - *slot = if slot.is_finite() { (*slot * scale).round() / scale } else { 0.0 }; - } - values + // The host's own values of the colour (typed CMYK, a working space's numbers) stand when they give the colour. + let given = self.picked().and_then(|picked| picked.model); + let kept = self.kept.values[self.target.index()] + .iter() + .chain(given.as_ref()) + .find(|v| v.model == model.id() && model.to_srgb(&v.values).same_rgb8(color)); + finite_values(kept.copied().unwrap_or_else(|| self.read(model, color))) } /// `color` in `model`. HSB takes the hue of a grey, and the hue and saturation of black, from the last HSB values @@ -740,6 +1115,15 @@ impl Body<'_> { if web { rule.step = WEB_STEP; } + // The R, G and B rows count percents of the channel's range; an edit goes back through `scale`. + // PLAN: a double click on the units cell flips `rgb_percent` while the rows are enabled; `ChannelRow` + // (color-w2) reports no signal for its units cell, so the panel cannot read it. + let percent = self.now.rgb_percent && model.id() == self.rgb.id(); + let scale = if percent { 100.0 / *rule.range.end() } else { 1.0 }; + let unit = if percent { ChannelUnit::Percent } else { ChannelUnit::of(ch.unit) }; + if percent { + rule = ChannelRule { range: 0.0..=100.0, step: (rule.step * scale).max(1.0), decimals: 0 }; + } let mut track_values = basis; // The hue track is the whole spectrum, whatever the saturation and brightness. if model.id() == HsbModel.id() && i == 0 { @@ -747,13 +1131,12 @@ impl Body<'_> { track_values.values[2] = 100.0; } let track = model.track(i, &track_values); - let row = ChannelRow::new(channel_name(model, i, &[model]), Bind::given(f64::from(current.values[i])), rule) - .short(ch.label) - .unit(ChannelUnit::of(ch.unit)) - .track(track) - .show(ui); + // The field shows the channel's places, as Photoshop's; the edits start from the unrounded values. + let places = 10f64.powi(i32::from(rule.decimals)); + let shown = (f64::from(current.values[i]) * scale * places).round() / places; + let row = ChannelRow::new(channel_name(model, i, &[model]), Bind::given(shown), rule).short(ch.label).unit(unit).track(track).show(ui); for event in row.into_iter().flat_map(|row| row.events) { - self.channel_event(model, current, i, event); + self.channel_event(model, current, i, event.map(|x| x / scale)); } } } @@ -792,7 +1175,7 @@ impl Body<'_> { fn wheel(&mut self, ui: &mut Ui) { let values = self.values(&HsbModel); let wheel = ColorWheel::new(self.words.color_wheel.clone(), Bind::given(values)).show(ui); - for event in wheel.events { + for event in wheel.edit.events { self.model_event(&HsbModel, event); } let add = Row::new().align(RowAlign::End).show(ui, |ui, _| { @@ -803,26 +1186,20 @@ impl Body<'_> { } } - /// The ramp; Alt picks for the colour not edited, Shift-click cycles the kind, a secondary click opens the ramp - /// menu. - fn ramp(&mut self, ui: &mut Ui) { - let converter = self.converter; - let gamut = |c: Srgba| { - let back = converter.to_srgb(converter.from_srgb([c.r, c.g, c.b])); - Srgba::new(back[0], back[1], back[2], c.a) - }; + /// The ramp's map into the host's gamut, and the counter that recomputes the ramp's colours when the CMYK working + /// space changes. The map is the gamut's own `nearest`, so the warning chip and the ramp agree. + // PLAN: `Gamut` has no identity of its own; a host gamut that changes while the converter stays the same needs a + // revision on `Gamut` (color-w1). + fn ramp_gamut(&self) -> (Gamut<'_>, u64) { + let gamut = self.gamut; let mut hasher = DefaultHasher::new(); - std::sync::Arc::as_ptr(converter.profile()).hash(&mut hasher); - let ramp = ColorRamp::new(self.words.color_ramp.clone(), self.now.ramp.kind(), Bind::kept()) - .kind_name(self.now.ramp.label(self.words)) - .ends([self.colors[0], self.colors[1]]) - .gamut(gamut) - .gamut_revision(hasher.finish()) - .web_safe(self.now.web_safe_ramp) - .sizing(Sizing::Fill) - .show(ui); - // Alt is on every event of a gesture that has a value; the others go where it went. - for event in ramp.edit.events { + Arc::as_ptr(self.converter.profile()).hash(&mut hasher); + (Gamut::new(move |color| gamut.nearest(color).unwrap_or(color)), hasher.finish()) + } + + /// The picks of a ramp as edits. Alt is on every event of a gesture that has a value; the others go where it went. + fn ramp_events(&mut self, events: impl IntoIterator>) { + for event in events { if let Some(pick) = event.value() { self.kept.other = pick.other; } @@ -830,6 +1207,21 @@ impl Body<'_> { let alpha = self.colors[target.index()].a; self.push(target, event.map(|pick| PickedColor { color: pick.color.with_alpha(alpha), model: None })); } + } + + /// The ramp; Alt picks for the colour not edited, Shift-click cycles the kind, a secondary click opens the ramp + /// menu. + fn ramp(&mut self, ui: &mut Ui) { + let (gamut, revision) = self.ramp_gamut(); + let ramp = ColorRamp::new(self.words.color_ramp.clone(), self.now.ramp.kind(), Bind::kept()) + .kind_name(self.now.ramp.label(self.words)) + .ends([self.colors[0], self.colors[1]]) + .gamut(gamut) + .gamut_revision(revision) + .web_safe(self.now.web_safe_ramp) + .sizing(Sizing::Fill) + .show(ui); + self.ramp_events(ramp.edit.events); if ramp.cycle { self.now.ramp = self.now.ramp.next(); } @@ -852,22 +1244,37 @@ pub(crate) mod tests { use super::*; - /// The checks a host draws (`checked`) and the ones it publishes (`states`) agree: the view, the ramp and Make Ramp - /// Web Safe are checked as the state says, the copy commands carry no check. + /// The checks a host draws (`checked`) and the ones it publishes (`states`) agree in every layout: under + /// `ForegroundBackground` the state says which view is checked, under `FillStroke` the shown rows do (a tint checks + /// none), and the copy commands carry no check. #[trial] fn color_panel_menu_checks_follow_the_state() { let state = ColorPanelState { mode: ColorPanelMode::CmykSliders, ramp: ColorPanelRamp::GrayscaleRamp, web_safe_ramp: true, ..Default::default() }; - let checked: Vec = ColorPanelMenu::states(&state) - .into_iter() - .map(|(command, _)| command) - .filter(|c| ColorPanelMenu::checked(&state, *c) == Some(true)) - .collect(); - assert_eq!(checked, [ColorPanelCommand::CmykSliders, ColorPanelCommand::GrayscaleRamp, ColorPanelCommand::WebSafeRamp]); - assert_eq!(ColorPanelMenu::checked(&state, ColorPanelCommand::CopyHex), None); - for (command, published) in ColorPanelMenu::states(&state) { - let expected = ColorPanelMenu::checked(&state, command).map_or_else(CommandState::new, |on| CommandState::new().checked(on)); - assert_eq!(published, expected, "{command:?}"); + let shown = ColorPanelShown::Mode(ColorPanelMode::HsbSliders); + for layout in [ColorPanelLayout::ForegroundBackground, ColorPanelLayout::FillStroke] { + for (command, published) in ColorPanelMenu::states(layout, &state, &shown, true) { + let expected = + ColorPanelMenu::checked(layout, &state, &shown, command).map_or_else(CommandState::new, |on| CommandState::new().checked(on)); + assert_eq!(published, expected, "{layout:?} {command:?}"); + } + assert_eq!(ColorPanelMenu::checked(layout, &state, &shown, ColorPanelCommand::CopyHex), None, "{layout:?}"); } + let checked = |layout: ColorPanelLayout, shown: &ColorPanelShown| -> Vec { + ColorPanelMenu::states(layout, &state, shown, true) + .into_iter() + .map(|(command, _)| command) + .filter(|c| ColorPanelMenu::checked(layout, &state, shown, *c) == Some(true)) + .collect() + }; + assert_eq!( + checked(ColorPanelLayout::ForegroundBackground, &shown), + [ColorPanelCommand::CmykSliders, ColorPanelCommand::GrayscaleRamp, ColorPanelCommand::WebSafeRamp] + ); + assert_eq!(checked(ColorPanelLayout::FillStroke, &shown), [ColorPanelCommand::ShowRecentColors, ColorPanelCommand::HsbSliders]); + let tint = ColorPanelShown::Tint(TintRow::new("Brand", Srgba::rgb(1.0, 0.0, 0.0), 50.0)); + assert_eq!(checked(ColorPanelLayout::FillStroke, &tint), [ColorPanelCommand::ShowRecentColors]); + let without = ColorPanelMenu::states(ColorPanelLayout::FillStroke, &state, &shown, false); + assert!(without.contains(&(ColorPanelCommand::Invert, CommandState::new().enabled(false))), "no colour, nothing to invert"); } } diff --git a/crates/color-ui/src/ui/panel/fill_stroke.rs b/crates/color-ui/src/ui/panel/fill_stroke.rs new file mode 100644 index 0000000000..a3ff66c160 --- /dev/null +++ b/crates/color-ui/src/ui/panel/fill_stroke.rs @@ -0,0 +1,183 @@ +//! The FillStroke layout of the Color panel: the proxy wells with their warnings, the rows the host's model rule +//! shows, the None, Black and White wells with the hex field, the Spectrum ramp and the Recent Colors. It reads the +//! same `Body` as the Photoshop layout and shares its rows, wells, warnings and ramp helpers. + +use craft_behavior::{EditEvent, Mixed}; +use craft_theme::Srgba; +use craft_ui::choice::{Swatch, SwatchSpacing}; +use craft_ui::contract::{Bind, Gap, LabelScheme, Props as _, Scroll, Show as _, ShowContainer as _, Sizing}; +use craft_ui::display::Text; +use craft_ui::form::{Field, FieldGroup}; +use craft_ui::layout_components::{Row, Stack}; +use craft_ui::runtime::env::Label; +use craft_ui::text::{HexField, TextField}; +use egui::Ui; + +use super::{Body, ColorPanelMode, ColorPanelShown, PanelTarget, TintRow}; +use crate::ui::{ChannelRow, ChannelRule, ChannelUnit, ColorRamp, PickedColor, RampKind, SwatchPalette}; + +impl Body<'_> { + /// The layout. The options (rows, quick wells, recent colours) go when the state hides them; the proxy and the + /// spectrum stay. + pub(super) fn fill_stroke(mut self, ui: &mut Ui) -> Self { + let hidden = self.now.hide_options; + Stack::new().fill().scroll(Scroll::vertical()).show(ui, |ui, _| { + self.top(ui, hidden); + if !hidden { + self.quick_wells(ui); + } + self.spectrum(ui); + if !hidden && self.now.recent_colors { + self.recent(ui); + } + }); + self + } + + /// The mode whose rows show: the host's, else the state's. + fn shown_mode(&self) -> ColorPanelMode { + match self.inputs.shown { + ColorPanelShown::Mode(mode) => *mode, + _ => self.now.mode, + } + } + + /// The proxy with its warnings beside it, then the rows. The warnings sit in the proxy's own height, so the + /// layout under them holds still when one appears. + fn top(&mut self, ui: &mut Ui, hidden: bool) { + let enabled = self.enabled(); + let shown = self.inputs.shown; + let web = matches!(shown, ColorPanelShown::Mode(ColorPanelMode::WebColorSliders)); + Row::new().fill_width().gap(Gap::Item).show(ui, |ui, _| { + Row::new().gap(Gap::Tight).show(ui, |ui, _| { + self.wells(ui); + if enabled && !matches!(shown, ColorPanelShown::Empty) { + self.warnings(ui, web); + } + }); + if !hidden { + Stack::new().fill_width().enabled(enabled).show(ui, |ui, _| match shown { + ColorPanelShown::Mode(mode) if mode.is_sliders() => self.mode_rows(ui, *mode), + ColorPanelShown::Tint(tint) => self.tint_row(ui, tint), + _ => {} + }); + } + }); + } + + /// A swatch-linked colour: its chip (tinted, named with its kind), its name and the T row. + fn tint_row(&mut self, ui: &mut Ui, tint: &TintRow) { + let strength = tint.tint / 100.0; + let mix = |channel: f32| 1.0 + (channel - 1.0) * strength; + let shown = Srgba::new(mix(tint.base.r), mix(tint.base.g), mix(tint.base.b), tint.base.a); + let kinds: Vec<&str> = [(tint.global, self.words.global.as_str()), (tint.spot, self.words.spot.as_str())] + .into_iter() + .filter(|(on, _)| *on) + .map(|(_, word)| word) + .collect(); + let mut events = Vec::new(); + Stack::new().gap(Gap::Tight).show(ui, |ui, _| { + Row::new().gap(Gap::Item).show(ui, |ui, _| { + let _ = Swatch::new(tint.name.clone(), shown).well().description(kinds.join(", ")).show(ui); + Text::new(tint.name.clone()).show(ui); + }); + FieldGroup::new(self.words.tint.clone()).labels(LabelScheme::Inspector).gap(Gap::Tight).show(ui, |ui, _| { + let row = ChannelRow::new(self.words.tint.clone(), Bind::given(f64::from(tint.tint)), ChannelRule::ALPHA.clone()) + .short("T") + .unit(ChannelUnit::Percent) + .track(vec![Srgba::rgb(1.0, 1.0, 1.0), tint.base]) + .show(ui); + events.extend(row.into_iter().flat_map(|row| row.events)); + }); + }); + // A pass has one tint edit: the last of its events. + self.tint = events.into_iter().last().map(|event| event.map(|value| value as f32)); + } + + /// The None, Black and White wells and the hex field. Alt on a well sets the colour not edited. + fn quick_wells(&mut self, ui: &mut Ui) { + let (words, enabled) = (self.words, self.enabled()); + let wells = + [(&words.none, Srgba::new(0.0, 0.0, 0.0, 0.0)), (&words.black, Srgba::rgb(0.0, 0.0, 0.0)), (&words.white, Srgba::rgb(1.0, 1.0, 1.0))]; + let mut hit = None; + Row::new().fill_width().gap(Gap::Item).show(ui, |ui, _| { + for (at, (label, color)) in wells.iter().enumerate() { + let out = Swatch::new((*label).clone(), *color).well().show(ui); + if out.clicked { + hit = Some((at, out.activation.is_some_and(|activation| activation.mods.alt))); + } + } + Stack::new().fill_width().enabled(enabled).show(ui, |ui, _| self.hex(ui)); + }); + if let Some((at, other)) = hit { + let target = if other { self.target.other() } else { self.target }; + match wells.get(at) { + Some((_, color)) if at > 0 => self.set_color(target, *color), + _ => self.none = Some(target), + } + } + } + + /// The hex field: an entry sets the colour with the edited colour's alpha. + fn hex(&mut self, ui: &mut Ui) { + let color = self.color(); + let words = self.words; + let edit = Field::new(words.hex_color.clone()) + .side(HexField::hash_label()) + .show(ui, |ui, _| TextField::hex(words.hex_color.clone(), Bind::given(color.to_rgba())).show(ui)) + .inner; + for event in edit.into_iter().flat_map(|edit| edit.events) { + self.push(self.target, event.map(|rgba| PickedColor::rgb(Srgba::from(rgba).with_alpha(color.a)))); + } + } + + /// The Spectrum ramp (grey in Grayscale) with a tooltip naming the shown mode. A Cmd or Ctrl click recolours and + /// picks nothing; a Shift click moves to the next mode. + fn spectrum(&mut self, ui: &mut Ui) { + let mode = self.shown_mode(); + let kind = if mode == ColorPanelMode::GrayscaleSlider { RampKind::Grayscale } else { RampKind::Spectrum }; + let name = mode.label(self.words); + let (gamut, revision) = self.ramp_gamut(); + let ramp = ColorRamp::new(self.words.color_ramp.clone(), kind, Bind::kept()) + .kind_name(name.clone()) + .tooltip(name) + .recolor_clicks(true) + .gamut(gamut) + .gamut_revision(revision) + .web_safe(self.now.web_safe_ramp) + .sizing(Sizing::Fill) + .show(ui); + self.ramp_events(ramp.edit.events); + self.recolor = ramp.recolor; + if ramp.cycle { + self.now.mode = mode.fill_stroke_next(); + } + } + + /// The Recent Colors as a spaced palette; a pick sets the colour. + // PLAN: Alt on a recent colour or a warning chip should set the other colour; `SwatchPaletteOutput` and + // `ColorWarningChipOutput` report no modifiers (color-w1 for the palette, the owner of warning.rs for the chip). + fn recent(&mut self, ui: &mut Ui) { + if self.inputs.recent.is_empty() { + return; + } + let swatches: Vec<(Label, Srgba)> = self.inputs.recent.iter().map(|color| (Label::from(color.to_hex()), *color)).collect(); + let mut current = self.color(); + let mut palette = SwatchPalette::new(self.words.recent_colors.clone(), Bind::bound(&mut current), &swatches).spacing(SwatchSpacing::Spaced); + if let Some(setup) = self.inputs.recent_setup { + palette = setup(palette); + } + if let Some(event) = palette.show(ui).edit + && let Some(color) = event.value() + { + self.set_color(self.target, *color); + } + } + + /// Sets `target`'s colour to `color`, keeping its alpha. + fn set_color(&mut self, target: PanelTarget, color: Srgba) { + let before = self.colors[target.index()]; + let name = self.words.title.as_str(); + self.push(target, EditEvent::set(Mixed::Same(PickedColor::rgb(before)), PickedColor::rgb(color.with_alpha(before.a)), name.into(), None)); + } +} diff --git a/crates/color-ui/src/ui/panel/stories.rs b/crates/color-ui/src/ui/panel/stories.rs index 23e32da684..bb8867eea7 100644 --- a/crates/color-ui/src/ui/panel/stories.rs +++ b/crates/color-ui/src/ui/panel/stories.rs @@ -1,6 +1,7 @@ //! Stories of `ColorPanel`. -use super::{ColorPanel, ColorPanelMode, ColorPanelRamp, ColorPanelState}; +use super::{ColorPanel, ColorPanelLayout, ColorPanelMode, ColorPanelRamp, ColorPanelShown, ColorPanelState, TintRow}; +use crate::ui::Gamut; use craft_theme::Srgba; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; use egui::Ui; @@ -8,10 +9,40 @@ use egui::Ui; /// A foreground that is not a web colour and not printable, over a white background. const COLORS: [Srgba; 2] = [Srgba::rgb(0.07, 0.65, 0.58), Srgba::rgb(1.0, 1.0, 1.0)]; +/// Colours the Recent Colors slot shows. +static RECENT: [Srgba; 8] = [ + Srgba::rgb(0.90, 0.28, 0.30), + Srgba::rgb(0.97, 0.42, 0.08), + Srgba::rgb(0.19, 0.64, 0.42), + Srgba::rgb(0.07, 0.65, 0.58), + Srgba::rgb(0.24, 0.39, 0.87), + Srgba::rgb(0.56, 0.31, 0.78), + Srgba::rgb(0.0, 0.0, 0.0), + Srgba::rgb(1.0, 1.0, 1.0), +]; + fn panel(ui: &mut Ui, data: &mut StoryData, state: ColorPanelState) -> StoryOutput { ColorPanel::new(data.bind("state", state), COLORS).show(ui).into() } +/// The FillStroke panel on `state` showing `shown`, set up further by `tweak`. +fn fill_stroke( + ui: &mut Ui, + data: &mut StoryData, + state: ColorPanelState, + shown: ColorPanelShown, + tweak: impl FnOnce(ColorPanel<'_>) -> ColorPanel<'_>, +) -> StoryOutput { + let panel = ColorPanel::new(data.bind("state", state), COLORS).layout(ColorPanelLayout::FillStroke).shown(shown); + tweak(panel).show(ui).into() +} + +/// The FillStroke panel showing the rows of `mode`. +fn fill_stroke_mode(ui: &mut Ui, data: &mut StoryData, mode: ColorPanelMode) -> StoryOutput { + let state = ColorPanelState { mode, ..ColorPanelState::default() }; + fill_stroke(ui, data, state, ColorPanelShown::Mode(mode), |panel| panel) +} + #[story(ColorPanel<'static>, covers = [], drive = Drive::Never)] fn color_panel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { panel(ui, data, ColorPanelState::default()) @@ -27,3 +58,78 @@ fn color_panel_sliders(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { fn color_panel_wheel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { panel(ui, data, ColorPanelState { mode: ColorPanelMode::ColorWheel, ..ColorPanelState::default() }) } + +#[story(ColorPanel<'static>, covers = [], drive = Drive::Never)] +fn color_panel_fill_stroke_rgb(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + fill_stroke_mode(ui, data, ColorPanelMode::RgbSliders) +} + +#[story(ColorPanel<'static>, covers = [], drive = Drive::Never)] +fn color_panel_fill_stroke_hsb(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + fill_stroke_mode(ui, data, ColorPanelMode::HsbSliders) +} + +#[story(ColorPanel<'static>, covers = [], drive = Drive::Never)] +fn color_panel_fill_stroke_cmyk(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + fill_stroke_mode(ui, data, ColorPanelMode::CmykSliders) +} + +#[story(ColorPanel<'static>, covers = [], drive = Drive::Never)] +fn color_panel_fill_stroke_grayscale(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + fill_stroke_mode(ui, data, ColorPanelMode::GrayscaleSlider) +} + +#[story(ColorPanel<'static>, covers = [], drive = Drive::Never)] +fn color_panel_fill_stroke_web(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + fill_stroke_mode(ui, data, ColorPanelMode::WebColorSliders) +} + +#[story(ColorPanel<'static>, covers = [], drive = Drive::Never)] +fn color_panel_fill_stroke_lab(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + fill_stroke_mode(ui, data, ColorPanelMode::LabSliders) +} + +#[story(ColorPanel<'static>, covers = [], drive = Drive::Never)] +fn color_panel_fill_stroke_tint(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let mut tint = TintRow::new("Brand orange", Srgba::rgb(0.95, 0.45, 0.10), 60.0); + tint.global = true; + tint.spot = true; + fill_stroke(ui, data, ColorPanelState::default(), ColorPanelShown::Tint(tint), |panel| panel) +} + +#[story(ColorPanel<'static>, covers = [], drive = Drive::Never)] +fn color_panel_fill_stroke_none(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + fill_stroke(ui, data, ColorPanelState::default(), ColorPanelShown::Empty, |panel| panel.edited(None)) +} + +#[story(ColorPanel<'static>, covers = [], drive = Drive::Never)] +fn color_panel_fill_stroke_mixed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let state = ColorPanelState { mode: ColorPanelMode::RgbSliders, ..ColorPanelState::default() }; + fill_stroke(ui, data, state, ColorPanelShown::Mode(ColorPanelMode::RgbSliders), |panel| panel.edited(None)) +} + +#[story(ColorPanel<'static>, covers = [], drive = Drive::Never)] +fn color_panel_fill_stroke_hidden_options(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let state = ColorPanelState { hide_options: true, ..ColorPanelState::default() }; + fill_stroke(ui, data, state, ColorPanelShown::Mode(ColorPanelMode::RgbSliders), |panel| panel) +} + +#[story(ColorPanel<'static>, covers = [], drive = Drive::Never)] +fn color_panel_fill_stroke_out_of_gamut(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let shown = ColorPanelShown::Mode(ColorPanelMode::RgbSliders); + // A gamut that pulls green and blue in, so the foreground is outside it. + fill_stroke(ui, data, ColorPanelState::default(), shown, |panel| { + panel.gamut(Gamut::new(|color| Srgba::new(color.r, color.g * 0.8, color.b * 0.8, color.a))) + }) +} + +#[story(ColorPanel<'static>, covers = [], drive = Drive::Never)] +fn color_panel_fill_stroke_recent_colors(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + fill_stroke(ui, data, ColorPanelState::default(), ColorPanelShown::Mode(ColorPanelMode::RgbSliders), |panel| panel.recent(&RECENT)) +} + +#[story(ColorPanel<'static>, covers = [], drive = Drive::Never)] +fn color_panel_fill_stroke_rgb_percent(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let state = ColorPanelState { rgb_percent: true, ..ColorPanelState::default() }; + fill_stroke(ui, data, state, ColorPanelShown::Mode(ColorPanelMode::RgbSliders), |panel| panel) +} diff --git a/crates/color-ui/src/ui/picker/channel.rs b/crates/color-ui/src/ui/picker/channel.rs index a412ba1135..34807fb607 100644 --- a/crates/color-ui/src/ui/picker/channel.rs +++ b/crates/color-ui/src/ui/picker/channel.rs @@ -17,33 +17,43 @@ use egui::{Color32, CornerRadius, Ui, Vec2}; /// How a channel's value steps and settles: a channel's or the alpha's. #[derive(Clone, Debug, PartialEq)] -pub(crate) struct ChannelRule { +#[non_exhaustive] +pub struct ChannelRule { + /// The values the channel takes, from its least to its greatest. pub range: RangeInclusive, + /// One arrow key's step. pub step: f64, + /// The decimals the number field shows. pub decimals: u8, } impl ChannelRule { /// The alpha row's rule: 0 to 100 %, whole percents. - pub(crate) const ALPHA: ChannelRule = ChannelRule { range: RangeInclusive::new(0.0, 100.0), step: 1.0, decimals: 0 }; + pub const ALPHA: ChannelRule = ChannelRule { range: RangeInclusive::new(0.0, 100.0), step: 1.0, decimals: 0 }; - pub(crate) fn of(channel: &Channel) -> ChannelRule { + /// The rule of `channel`. + pub fn of(channel: &Channel) -> ChannelRule { ChannelRule { range: f64::from(channel.min)..=f64::from(channel.max), step: f64::from(channel.step), decimals: channel.decimals } } } /// What a channel's number counts. #[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum ChannelUnit { +#[non_exhaustive] +pub enum ChannelUnit { + /// No unit. None, + /// Percent. Percent, + /// Degrees. Degrees, /// Any other unit text a model declares. Text(&'static str), } impl ChannelUnit { - pub(crate) fn of(unit: &'static str) -> ChannelUnit { + /// The unit a model declares as text. + pub fn of(unit: &'static str) -> ChannelUnit { match unit { "" => ChannelUnit::None, "%" => ChannelUnit::Percent, @@ -77,7 +87,7 @@ pub struct TrackRampStyle { /// transparency checkerboard where `checker` is set. #[derive(Clone, craft_ui::contract::Component)] #[component(content_painter)] -pub(crate) struct TrackRamp { +pub struct TrackRamp { #[common] common: Common, stops: Vec, @@ -85,7 +95,8 @@ pub(crate) struct TrackRamp { } impl TrackRamp { - pub(crate) fn new(stops: Vec, checker: bool) -> Self { + /// A ramp through `stops`, over the checkerboard where `checker` is set. + pub fn new(stops: Vec, checker: bool) -> Self { TrackRamp { common: Common::new(), stops, checker } } } @@ -159,7 +170,7 @@ pub(crate) fn channel_slider<'a>( /// where one is given, "C"), which scrubs the value, the slider over the channel's colours with the pointer under its /// track, and the number field with its unit at the end, as wide as its widest value. #[derive(craft_ui::contract::Pattern)] -pub(crate) struct ChannelRow<'a> { +pub struct ChannelRow<'a> { label: Label, /// The text shown in place of the label: the channel's short label. short: Option<&'static str>, @@ -169,39 +180,50 @@ pub(crate) struct ChannelRow<'a> { /// Whether the track shows over the transparency checkerboard. checker: bool, unit: ChannelUnit, + marks: &'a [f64], } impl<'a> ChannelRow<'a> { - pub(crate) fn new(label: impl Into

(place, move |payload: &P, at: &DropAt| accepts(payload, at)) + })); + self + } + + /// A swatch drag carries `map` of the dragged swatches too, for the host's drop targets of type `P` (the app's + /// paint payload), as `PresetBrowser::drag_payload` does. + pub fn drag_payload(mut self, map: impl Fn(&ListDrag) -> Option

+ Send + Sync + 'static) -> Self { + let map = Arc::new(map); + self.payloads.push(Box::new(move |browser| { + let map = Arc::clone(&map); + browser.drag_payload(move |drag: &ListDrag| map(drag)) + })); + self + } + + /// The host's rows of the row menu for a swatch; the standard rows give way to them. + pub fn row_items(mut self, items: impl Fn(&SwatchKey) -> Vec> + 'a) -> Self { + self.row_items = Some(Box::new(items)); + self + } + /// Draws the panel and returns the user's actions this pass. pub fn show(self, ui: &mut Ui) -> SwatchesPanelOutput { - let SwatchesPanel { groups, state, cmyk, foreground } = self; + let SwatchesPanel { + groups, + state, + cmyk, + foreground, + thumb, + mut tools, + drop_zone, + footer, + reveal, + search, + row_icons, + select, + takes_drop, + payloads, + row_items, + } = self; let cmyk = cmyk.unwrap_or_else(|| CmykConverter::coated()); let words = Env::of(ui).words::(); let mut held_state = Held::new(state); let ctx = ui.ctx().clone(); - let rename_scope = ui.scope_id().with("browser-rows"); + let browser_id = ui.scope_id(); + let icons: BTreeMap<&str, Vec<(IconSpec<'static>, String)>> = match &row_icons { + Some(icons) => { + groups.iter().flat_map(|g| g.entries.iter()).map(|e| (e.name.as_str(), icons(&SwatchKey::Swatch(e.name.clone())))).collect() + } + None => BTreeMap::new(), + }; + // Built once: the body can run more than once a pass, and the host's painter is moved into the source. + let source = panel_source(groups, cmyk, icons, thumb); let mut shown = Stack::new().fill().show(ui, |ui, cx| { let before_state = held_state.read(cx)?; let mut st = before_state.clone(); - if st.selected.as_ref().is_some_and(|k| !has(groups, k)) { - st.selected = None; - } - let source = swatch_source(groups, cmyk); + let live = |key: &SwatchKey| has(groups, key); + st.selection.items.retain(live); + st.selection.lead = st.selection.lead.take().filter(live); + st.selection.anchor = st.selection.anchor.take().filter(live); + let footer_options = match &footer { + Some(host) => host.clone(), + None => Some(PresetFooterOptions::new().can_delete(!st.selection.items.is_empty())), + }; let out = { let mut browser = PresetBrowser::new(words.title.clone(), Bind::bound(&mut st.browser), &source) .thumb_range(SWATCH_ZOOM) .toolbar(true) + .search(search) + .select(select) .reorder(PresetReorder::items_and_groups()) - .footer(PresetFooterOptions::new().can_delete(st.selected.is_some())); - if let Some(key) = &st.selected { - browser = browser.selected(key.clone()); + .selection(Bind::bound(&mut st.selection)); + if let Some(options) = footer_options { + browser = browser.footer(options); + } + if let Some(zone) = drop_zone { + browser = browser.drop_zone(zone); + } + if let Some(key) = &reveal { + browser = browser.reveal(key.clone()); + } + if let Some(tools) = tools.as_mut() { + browser = browser.tools(|ui: &mut Ui| tools(ui)); + } + if let Some(items) = &row_items { + browser = browser.row_menu(PresetRowMenu::Host).row_items(|key: &SwatchKey| items(key)); + } + if let Some(make) = &takes_drop { + browser = browser.takes_drop(make()); + } + for add in &payloads { + browser = add(browser); } browser.show(ui) }; let mut used = None; let mut edits = Vec::new(); + let mut events = Vec::new(); for event in out.events { if let PresetEvent::Select { key: SwatchKey::Swatch(name), mods, .. } = &event && let Some(at) = find_swatch(groups, name) && let Some(entry) = groups.get(at.group).and_then(|g| g.entries.get(at.index)) { - used = Some((at, entry.color.to_srgb(cmyk), mods.alt || mods.cmd || mods.ctrl)); + used = Some((at, entry.color().map(|color| color.to_srgb(cmyk)), mods.alt || mods.cmd || mods.ctrl)); } + let forwarded = matches!( + event, + PresetEvent::Activate { .. } + | PresetEvent::Menu { .. } + | PresetEvent::DropAt { .. } + | PresetEvent::Dropped { .. } + | PresetEvent::Reorder { .. } + ) + .then(|| event.clone()); edits.extend(event_edits(groups, &mut st, event, foreground, &words)); + events.extend(forwarded); } - Some(Settled { before_state, st, used, edits }) + Some(Settled { before_state, st, used, edits, events }) }); // Once per pass, after the real run: the rename request and the edited state are stored, the edits reported. - let (used, edits) = shown + let (used, edits, events) = shown .settle(|cx, settled| { - let Settled { before_state, mut st, used, edits } = settled.take()?; + let Settled { before_state, mut st, used, edits, events } = settled.take()?; if let Some(key) = st.rename.take() { - request_rename(&ctx, rename_scope, &key); + PresetBrowser::request_rename(&ctx, browser_id, &key); } if st != before_state { held_state.write(cx, &before_state, st, words.title.as_str()); } - Some((used, edits)) + Some((used, edits, events)) }) .flatten() .unwrap_or_default(); - SwatchesPanelOutput { response: shown.output, used, edits } + SwatchesPanelOutput { response: shown.output, used, edits, events } } /// Carries out the host's answer to a file request of the panel menu: Import and Replace read the file into an @@ -191,6 +385,7 @@ impl<'a> SwatchesPanel<'a> { SwatchNote::Truncated(n) => count(&words.truncated, n), SwatchNote::NamesCut(n) => count(&words.names_cut, n), SwatchNote::TransparentKept(n) => count(&words.transparent_kept, n), + SwatchNote::PaintsSkipped(n) => count(&words.paints_skipped, n), }) .collect() } diff --git a/crates/color-ui/src/ui/swatches/stories.rs b/crates/color-ui/src/ui/swatches/stories.rs index b95cb079ff..d5c1063857 100644 --- a/crates/color-ui/src/ui/swatches/stories.rs +++ b/crates/color-ui/src/ui/swatches/stories.rs @@ -1,8 +1,15 @@ //! Stories of `SwatchesPanel`. -use super::{SwatchLibrary, SwatchesPanel, SwatchesState}; +use super::{SwatchKey, SwatchLibrary, SwatchesPanel, SwatchesState}; +use crate::palette::{SwatchColor, SwatchEntry, SwatchGroup, SwatchPaint}; +use craft_theme::Srgba; +use craft_ui::choice::SwatchFace; +use craft_ui::contract::Show as _; +use craft_ui::display::Text; +use craft_ui::patterns::presets::ThumbInfo; +use craft_ui::primitives::{ContentPainterCx, IconSpec}; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; -use egui::Ui; +use egui::{Rect, Ui}; /// The panel over a library and state kept in the story's data; the reported edits run on the library, so the story stays /// interactive. @@ -24,3 +31,44 @@ fn swatches_panel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { fn swatches_panel_empty(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { interactive(ui, data, "empty", SwatchLibrary { groups: Vec::new() }) } + +/// The host's thumbnail painter: a colour standing for each entry's paint. +fn host_thumb(_: &(), cx: &ContentPainterCx<'_>, rect: Rect, info: ThumbInfo<'_, SwatchKey>) { + if let SwatchKey::Swatch(name) = info.key { + let color = match name.as_str() { + "Sunset" => Srgba::rgb(0.95, 0.5, 0.2), + "Dots" => Srgba::rgb(0.4, 0.4, 0.45), + _ => Srgba::rgb(1.0, 0.0, 0.0), + }; + SwatchFace::new(color).selected(info.selected).paint(cx, rect); + } +} + +/// The host's own rows: its thumbnail painter on a gradient and a pattern entry, an icon trailing each of them, its tools, +/// and no footer. +#[story(SwatchesPanel<'static>, covers = [], drive = Drive::Never)] +fn swatches_panel_host_rows(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let entries = vec![ + SwatchEntry::new("Red", SwatchColor::Rgb([1.0, 0.0, 0.0])), + SwatchEntry::with_paint("Sunset", SwatchPaint::Gradient), + SwatchEntry::with_paint("Dots", SwatchPaint::Pattern), + ]; + let start = SwatchLibrary::new(vec![SwatchGroup { name: "Host".to_owned(), entries }]); + let ((library, state), library_state_at) = data.value_at("host-rows", (start, SwatchesState::default())); + let out = SwatchesPanel::new(&library.groups, library_state_at.bind(state), Srgba::rgb(0.2, 0.4, 0.6)) + .thumb((), host_thumb) + .row_icons(|key| match key { + SwatchKey::Swatch(name) if name == "Sunset" => vec![(IconSpec::initial("G"), "Gradient".to_owned())], + SwatchKey::Swatch(name) if name == "Dots" => vec![(IconSpec::initial("P"), "Pattern".to_owned())], + _ => Vec::new(), + }) + .tools(|ui| { + Text::new("Host tools").show(ui); + }) + .footer(None) + .show(ui); + for edit in &out.edits { + library.apply(edit); + } + out.into() +} diff --git a/crates/color-ui/src/ui/wheel.rs b/crates/color-ui/src/ui/wheel.rs index 7b0d6ade4f..24c6e5e331 100644 --- a/crates/color-ui/src/ui/wheel.rs +++ b/crates/color-ui/src/ui/wheel.rs @@ -1,27 +1,36 @@ //! [`ColorWheel`]: a hue ring round a saturation and brightness triangle that turns with the hue, as PhotoCraft's //! Color Wheel. +use super::area::{AreaShape, ColorArea}; use super::channels::{channel_step, finite, primary, settled, spoken}; -use craft_behavior::{HitLevel, HitPriority, HitShape, Metrics, NavMove, PartKey, PressPhase, Sense}; -use craft_theme::{ColorModel, HsbModel, ModelValues}; +use super::disc::nearest_within; +use super::ramp::Gamut; +use crate::AreaMode; +use craft_behavior::nav::{NavShape, Roving}; +use craft_behavior::{HitLevel, HitPriority, HitShape, Metrics, Mixed, NavMove, PartKey, PressPhase, Sense}; +use craft_theme::{ColorModel, HsbModel, ModelValues, Srgba}; use craft_ui::contract::{ - Access, Bind, BindMut, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Focus as _, Input, MeasureCx, Name, Numeric, PaintUi, - PartsCx, Pointer as _, Props as _, Role, WordSetCx as _, + Access, Bind, BindMut, Common, Component, Cx, DisabledLook, Edit as _, EditResponse, Focus as _, Input, MeasureCx, Name, Numeric, Outcome, + PaintUi, PartsCx, Pointer as _, Props as _, Remember as _, Role, WordSetCx as _, }; -use craft_ui::primitives::{Marker, PaintShape, StrokeWidth}; +use craft_ui::primitives::{Marker, MarkerSize, PaintShape, StrokeWidth}; +use craft_ui::runtime::commands::FireSource; use craft_ui::runtime::env::Label; use craft_ui::runtime::focus::{ActivateKeys, FocusShape, KeepKeys, KeyUse}; use craft_ui::style::{ComponentStyle, FocusLook, MarkerLook, StyleColor, StyleCx}; -use egui::{Mesh, Pos2, Rect, Vec2, vec2}; -use std::f32::consts::TAU; +use egui::{Color32, Mesh, Pos2, Rect, Response, Vec2, vec2}; +use std::f32::consts::{SQRT_2, TAU}; #[cfg(feature = "suite")] pub(crate) mod stories; /// The hue ring: a press on it sets the hue to the pointer's angle. const RING: PartKey = PartKey::new("ring"); -/// The triangle: a press on it sets saturation and brightness. +/// The triangle: a press on it sets saturation and brightness. With a square inside the ring it is the catch area +/// round the square: a press there sets the square's closest point. const TRIANGLE: PartKey = PartKey::new("triangle"); +/// A marker on the ring: `MARKER.at(i)`, a member of the markers' roving group. +const MARKER: PartKey = PartKey::new("marker"); /// Steps round the hue ring's mesh (PhotoCraft's 96). const RING_STEPS: u32 = 96; @@ -37,6 +46,8 @@ const BRIGHTNESS_PAGE: f32 = 10.0; const FAR: f32 = 10.0; /// The last hue a key reaches: the hue wraps at 360 and has no 360 of its own. const HUE_LAST: f32 = 359.0; +/// Degrees a ring drag with Shift snaps the hue to. +const HUE_SNAP: f32 = 45.0; craft_ui::words! { /// The words of colour wheels. @@ -58,6 +69,42 @@ pub enum WheelPart { Triangle, } +/// What a [`ColorWheel`] shows inside its ring. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[non_exhaustive] +pub enum WheelInner { + /// The saturation and brightness triangle. + #[default] + Triangle, + /// The largest square inside the ring, a `ColorArea` over the same values. + Square, +} + +/// What a [`ColorWheel`] returns. +#[derive(Debug)] +#[non_exhaustive] +pub struct ColorWheelOutput { + /// The edit of the values, carrying the ring's and the adopted square's edits. + pub edit: EditResponse, + /// The marker a click picked. + pub picked: Option, + /// The marker a press is holding. + pub held: Option, +} + +impl Outcome for ColorWheelOutput { + type Value = ModelValues; + + fn response(&self) -> &Response { + &self.edit.response + } + + #[cfg(feature = "screen-testing")] + fn story_facts(&self) -> craft_ui::testing::StoryOutput { + self.edit.story_facts() + } +} + /// Where a wheel lies in its area: pure numbers, shared with the colour disc. #[derive(Clone, Copy, Debug, PartialEq)] #[non_exhaustive] @@ -83,6 +130,12 @@ impl WheelGeometry { Self { center: area.center(), inner, outer, triangle: (inner - triangle_inset).max(0.0) } } + /// The largest square inside the ring, a `space.gap.tight` inside its inner edge: where `WheelInner::Square` lies. + /// The square's corners lie on the circle `triangle` is the radius of, which the style insets by that gap. + pub fn square(&self) -> Rect { + Rect::from_center_size(self.center, Vec2::splat(self.triangle * SQRT_2)) + } + /// The part a press at `pos` takes: nothing beyond the ring's outer edge plus `grab_outer`, /// the ring from `grab_inner` inside its inner edge, the triangle within. pub fn part_at(&self, pos: Pos2, grab_outer: f32, grab_inner: f32) -> Option { @@ -162,7 +215,7 @@ pub struct ColorWheelStyle { ring_max: f32, /// The gap between the area's edge and the ring. outer_inset: f32, - /// The gap between the ring's inner edge and the triangle's circle. + /// The gap between the ring's inner edge and the circle round the triangle's corners or the square's. triangle_inset: f32, /// A press this far outside the ring still takes it, and this far inside its inner edge. grab: f32, @@ -184,14 +237,19 @@ pub struct ColorWheelStyle { /// - Pointer (primary button): the part under the press is kept for the whole drag, so a drag that leaves the ring /// keeps turning the hue; a press further outside the ring than `size.hit.target` starts nothing. A press sets the /// value under the pointer (whole degrees, whole percents) and a drag follows it; Esc cancels. A press focuses the -/// part. +/// part. A ring drag with Shift snaps the hue to 45 degrees. /// - Keys on the focused ring: Left and Down lower the hue by 1 degree, Right and Up raise it, wrapping at 360; /// Shift steps ten; Page Up and Page Down 36 degrees; Home 0, End 359. On the triangle: Left and Right saturation, /// Up and Down brightness; Shift ten; Page keys a tenth of brightness; Home and End saturation 0 and 100. The /// directions are not screen directions: the triangle turns with the hue. -/// - Two Tab stops, the ring and then the triangle. +/// - Two Tab stops, the ring and then the triangle; then the markers, one roving stop, when there are any. +/// - [`WheelInner::Square`]: the largest square inside the ring is a `ColorArea` with its own stop, keys and node; a +/// press between the square and the ring sets the square's closest point. +/// - Markers: a click, Enter or Space on one reports [`picked`](ColorWheelOutput::picked); a press on one still drags +/// the ring and reports it as [`held`](ColorWheelOutput::held). /// - AccessKit: a `Group` named `label` holding a `Slider` for the hue (0 to 360, step 1, increment, decrement and -/// set value) and a `Slider` for saturation and brightness (value text, no numeric value). +/// set value; no numeric value while the value is mixed), a `Slider` for saturation and brightness (value text, no +/// numeric value) on the triangle, and a `Button` per marker. /// - Right to left nothing mirrors: red stays at 3 o'clock. #[derive(craft_ui::contract::Component, craft_ui::contract::Props)] #[component(content_painter)] @@ -199,18 +257,55 @@ pub struct ColorWheel<'a> { #[common] common: Common, values: Bind<'a, ModelValues>, + /// The host's gamut, passed to the square's `ColorArea`. + #[prop] + gamut: Option>, + /// What the ring holds: the triangle, or a square `ColorArea`. + #[prop] + #[style_key] + inner: WheelInner, + /// Markers on the ring, one roving Tab stop after it; a click, Enter or Space picks one. + #[prop] + markers: &'a [Srgba], + /// The markers' accessible names, in order. + #[prop(into)] + marker_names: Vec