mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-25 20:14:31 +01:00
Merge storytold next into next-host-input
Conflicts resolved so that next's changes and this branch's fixes both hold: - keys: next's unfocused-canvas state claims join the key stage's framework claims; the canvas's declared claims stay the host's (egui keeps their presses). - overlay: the app's own modal (`FrameInput::app_modal`) joins next's modal stack at the frame it first showed in. - docking: the tab-pick trial moves key focus into the group with Tab, since a click on a dock tab leaves key focus where it is.
This commit is contained in:
commit
2f8d73e7cf
1012 files changed
+55935
-8288
No files matched your search
@@ -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
|
||||
|
||||
Generated
+22
@@ -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]]
|
||||
|
||||
@@ -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" }
|
||||
|
||||
@@ -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"
|
||||
@@ -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<dyn Fn(bool) + Send + Sync>) {
|
||||
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<NSNotification>| 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);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -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.
|
||||
|
||||
@@ -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<Vec<u8>> {
|
||||
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(())
|
||||
}
|
||||
@@ -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 }
|
||||
|
||||
|
||||
@@ -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. |
|
||||
|
||||
@@ -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<Rect, String>;
|
||||
|
||||
/// 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<String>,
|
||||
/// The name of an ancestor the control is inside.
|
||||
pub within: Option<String>,
|
||||
/// Which match to take, in reading order.
|
||||
pub index: Option<usize>,
|
||||
}
|
||||
|
||||
/// `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<String> {
|
||||
}
|
||||
}
|
||||
|
||||
impl Target {
|
||||
/// The target `value` names: `{name, role?, within?, index?}` and no other field.
|
||||
pub fn from_params(value: &Value) -> Result<Self, String> {
|
||||
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<NodeKey, String> {
|
||||
let reported: HashSet<NodeKey> = tree.keys().into_iter().collect();
|
||||
let mut matches = Vec::new();
|
||||
let mut pending: Vec<NodeKey> = 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<Rect, String> {
|
||||
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<Result<Value, String>> {
|
||||
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<Value, String> {
|
||||
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
|
||||
|
||||
@@ -22,6 +22,12 @@ pub struct ActionsFile {
|
||||
/// Sets that hold no action.
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
pub sets: Vec<String>,
|
||||
/// 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<String>,
|
||||
/// 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<String>,
|
||||
#[serde(default)]
|
||||
set_order: Vec<String>,
|
||||
#[serde(default)]
|
||||
set_rows: Vec<String>,
|
||||
}
|
||||
|
||||
@@ -71,7 +79,7 @@ impl From<RawFile> for ActionsFile {
|
||||
let (actions, occurrences): (Vec<Action>, Vec<ActionOccurrence>) = 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<Action>, sets: Vec<String>) -> 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.
|
||||
|
||||
@@ -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<Action, ActionListError> {
|
||||
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<String>) -> 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<String, serde_json::Value>) -> 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<usize, ActionListError> {
|
||||
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<String> = 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<Vec<Action>, ActionListError> {
|
||||
if !self.sets().contains(&set) {
|
||||
return Err(ActionListError::NoSuchSet(set.to_owned()));
|
||||
}
|
||||
let (removed, kept): (Vec<Action>, Vec<Action>) =
|
||||
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<String, ActionListError> {
|
||||
let mut order: Vec<String> = 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<usize> = (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`.
|
||||
|
||||
@@ -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<String, serde_json::Value>,
|
||||
}
|
||||
|
||||
fn is_no_color(color: &ActionColor) -> bool {
|
||||
|
||||
@@ -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::<Vec<_>>(), ["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");
|
||||
}
|
||||
+119
-21
@@ -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<Self, ConnectError> {
|
||||
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<Self> {
|
||||
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<Self, ConnectError> {
|
||||
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<Value, String> {
|
||||
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<Value, String> {
|
||||
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<Value, String> {
|
||||
self.call_with(method, params, Some(cancelled))
|
||||
}
|
||||
|
||||
fn call_with(&mut self, method: &str, params: Value, cancelled: Option<&dyn Fn() -> bool>) -> Result<Value, String> {
|
||||
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<Value, String> {
|
||||
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<Value, Failure> {
|
||||
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<Value, Failure> {
|
||||
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<Value, Failure> {
|
||||
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.
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
@@ -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<Value> = update
|
||||
.nodes
|
||||
.iter()
|
||||
|
||||
@@ -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<Result<Value, String>> {
|
||||
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<Vec<(String, Value)>, 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<DialogId, String> {
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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<ControlRequest>,
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<Pos2>;
|
||||
|
||||
/// 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<Self, String> {
|
||||
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<Pos2, String> {
|
||||
/// [`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<Pos2, String> {
|
||||
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<Pos2, String> {
|
||||
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<Self, String> {
|
||||
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<Self, String> {
|
||||
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(())
|
||||
}
|
||||
|
||||
@@ -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<ActionsEvent>,
|
||||
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<Option<ActionSelection>>,
|
||||
/// 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<ActionSelection>, Vec<String>)>,
|
||||
}
|
||||
|
||||
/// 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<ActionSelection>) -> (Option<ActionSelection>, Vec<String>) {
|
||||
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<String> = 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.
|
||||
|
||||
@@ -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<ActionsEvent> {
|
||||
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<ActionsEvent>, label: &Label, event: Option<ActionsEvent>) {
|
||||
if MenuItem::new(label.clone()).enabled(event.is_some()).show(ui).ran {
|
||||
events.extend(event);
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
@@ -100,13 +100,27 @@ pub struct ActionsPanelState {
|
||||
pub selected: Option<ActionSelection>,
|
||||
/// The expanded actions, by name (names are unique, so expansion survives moves).
|
||||
pub expanded: BTreeSet<String>,
|
||||
/// 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<String>,
|
||||
}
|
||||
|
||||
/// 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<String>),
|
||||
/// 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<usize>,
|
||||
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::<ActionsWords>();
|
||||
let list_words = env.words::<ListWords>();
|
||||
@@ -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());
|
||||
|
||||
@@ -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<ActionSelection> 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<ActionSelection> 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<ToggleState> {
|
||||
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<ToggleCell> {
|
||||
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<ToggleCell> {
|
||||
)
|
||||
.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)]),
|
||||
}
|
||||
}
|
||||
@@ -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();
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -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<u32>; 2]>,
|
||||
pointer: Rc<Cell<Option<Pos2>>>,
|
||||
}
|
||||
|
||||
impl Rig {
|
||||
fn new(names: [&'static str; 2]) -> Self {
|
||||
let clicks: Rc<[Cell<u32>; 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<Value, String> {
|
||||
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<f64> = 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")
|
||||
|
||||
@@ -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<ActionsEvent> {
|
||||
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");
|
||||
}
|
||||
@@ -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<Value> = (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]
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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)]
|
||||
|
||||
@@ -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<usize> {
|
||||
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 }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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>) -> 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>) -> 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<f64> {
|
||||
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<f64> {
|
||||
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);
|
||||
|
||||
@@ -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<C: Codec + ?Sized> 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<Custom>,
|
||||
/// 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) => {
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -33,7 +33,7 @@ pub struct DocumentWindows<D> {
|
||||
/// The floating groups, each with its window rect.
|
||||
#[serde(with = "floating_serde")]
|
||||
pub floating: Vec<(DocumentGroup<D>, 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<Arrangement>,
|
||||
|
||||
@@ -162,6 +162,44 @@ impl<P> Workspace<P> {
|
||||
}
|
||||
|
||||
impl<P: Clone + Eq + Hash> Workspace<P> {
|
||||
/// 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<P>(root: &mut Node<P>) -> Vec<&mut Column<P>> {
|
||||
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<P>(root: &mut Node<P>, 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<P>(column: &mut Column<P>, 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<P>(location: &mut Location<P>, 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<P: Clone + Eq + Hash>(layout: &Layout<P>, panel: &P) -> bool {
|
||||
matches!(layout.place(panel), Some(PanelPlace::Floating { .. }))
|
||||
|
||||
@@ -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<T> = 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<T> {
|
||||
value: T,
|
||||
name: Arc<str>,
|
||||
/// 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<T> {
|
||||
redo: Vec<Entry<T>>,
|
||||
/// The value as of the latest step.
|
||||
settled: T,
|
||||
/// The weight of `settled`; 0 without a budget.
|
||||
settled_weight: usize,
|
||||
open: Option<Open>,
|
||||
/// The most summed weight the undo steps keep, and how a value weighs.
|
||||
budget: Option<(usize, Weigh<T>)>,
|
||||
}
|
||||
|
||||
impl<T: Value> EditHistory<T> {
|
||||
/// 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<T: Value> EditHistory<T> {
|
||||
}
|
||||
|
||||
fn push(&mut self, before: &Mixed<T>, after: &T, name: Arc<str>) {
|
||||
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<T: Value> EditHistory<T> {
|
||||
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<T: Value> EditHistory<T> {
|
||||
pub fn take_back(&mut self) -> Option<T> {
|
||||
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<i32>) -> 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);
|
||||
|
||||
@@ -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 }
|
||||
|
||||
@@ -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]
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -51,6 +51,15 @@ pub enum HitShape {
|
||||
/// The corners of the polygon cut out of `within`.
|
||||
polygon: Vec<Pos2>,
|
||||
},
|
||||
/// 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<HitShape>,
|
||||
/// 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<Rect> for HitShape {
|
||||
fn from(rect: Rect) -> Self {
|
||||
HitShape::Rect(rect)
|
||||
|
||||
@@ -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
|
||||
}
|
||||
}
|
||||
@@ -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<f32>) {}
|
||||
}
|
||||
|
||||
/// 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<Sized>,
|
||||
/// The rows as wide as they measured (`set_fit`), by position.
|
||||
fits: BTreeMap<usize, f32>,
|
||||
}
|
||||
|
||||
impl SpanLayout {
|
||||
/// One row of `row_h` per entry of `source`, `width` wide, with no columns.
|
||||
pub fn new<K>(source: &dyn DisplayOrder<K>, 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<usize> {
|
||||
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<f32>) {
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -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};
|
||||
|
||||
@@ -330,17 +330,17 @@ fn ragged_at(outline: &dyn NavOutline, row: usize, column: usize) -> Option<usiz
|
||||
fn ragged(outline: &dyn NavOutline, state: &NavState, lead: usize, mv: NavMove) -> 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<usize>| moved(rows.into_iter().find_map(|to| ragged_at(outline, to, shifted(to))));
|
||||
let vertical = |to: Option<usize>| 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)),
|
||||
}
|
||||
|
||||
@@ -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<Rect>,
|
||||
}
|
||||
|
||||
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<Rect>) -> 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:?}");
|
||||
|
||||
@@ -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<f32>,
|
||||
}
|
||||
|
||||
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<T: Copy> PressMachine<T> {
|
||||
self.open.is_some_and(|open| open.dragging)
|
||||
}
|
||||
|
||||
/// The press the open press began as.
|
||||
pub fn start(&self) -> Option<PressStart> {
|
||||
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.
|
||||
|
||||
+127
-29
@@ -11,9 +11,10 @@ fn digit(c: char) -> Option<u32> {
|
||||
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<u32>,
|
||||
/// The factor of a number written right after the spelling ([`Reader::split_unit`]).
|
||||
rest: Option<f64>,
|
||||
}
|
||||
|
||||
/// 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<char>,
|
||||
units: Vec<Unit>,
|
||||
/// 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<f64> {
|
||||
let chars: Vec<char> = 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<f64, NotAValue> {
|
||||
let first = self.factor()?;
|
||||
let first = self.factor(true)?;
|
||||
self.product(first)
|
||||
}
|
||||
|
||||
fn product(&mut self, mut left: f64) -> Result<f64, NotAValue> {
|
||||
// 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<f64, NotAValue> {
|
||||
/// 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<f64, NotAValue> {
|
||||
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<f64, NotAValue> {
|
||||
/// 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<f64, NotAValue> {
|
||||
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<char> = 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::<String>().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<f64, NotAValue> {
|
||||
@@ -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");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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<O: Copy + PartialEq>(
|
||||
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)),
|
||||
|
||||
@@ -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 %");
|
||||
}
|
||||
@@ -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<u32>, anchor: u32) -> craft_behavior::dock::Location<u32> {
|
||||
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<u32>, 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<u32>| workspace.layout().panels().into_iter().copied().collect::<Vec<_>>();
|
||||
assert_eq!(panels(&renamed), panels(&base).into_iter().map(swap).collect::<Vec<_>>(), "{from}: the panel keeps its position");
|
||||
let keys = |records: &[(u32, _)]| records.iter().map(|(panel, _)| *panel).collect::<Vec<_>>();
|
||||
assert_eq!(keys(renamed.hidden()), keys(base.hidden()).into_iter().map(swap).collect::<Vec<_>>(), "{from}: hidden keys");
|
||||
assert_eq!(keys(renamed.floated()), keys(base.floated()).into_iter().map(swap).collect::<Vec<_>>(), "{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();
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
@@ -8,5 +8,6 @@ mod dock_apply;
|
||||
mod fit;
|
||||
#[path = "geometry/main.rs"]
|
||||
mod geometry;
|
||||
mod hit_excluding;
|
||||
mod key_table;
|
||||
mod middle_scroll;
|
||||
@@ -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)),
|
||||
|
||||
@@ -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)),
|
||||
|
||||
@@ -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)),
|
||||
|
||||
@@ -315,7 +315,7 @@ impl<K: TextureKey + std::fmt::Debug> 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)),
|
||||
_ => {}
|
||||
}
|
||||
|
||||
@@ -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"] }
|
||||
@@ -23,6 +23,9 @@ pub type DisplayId = Option<u32>;
|
||||
/// 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<Arc<Profile>, MonitorProblem> {
|
||||
Ok(Arc::new(profile))
|
||||
}
|
||||
|
||||
/// `icc` parsed and validated as a monitor profile.
|
||||
fn parse_monitor(icc: &[u8]) -> Result<Arc<Profile>, 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() {
|
||||
|
||||
@@ -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<f32>,
|
||||
/// 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<f32> {
|
||||
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<f32> {
|
||||
}
|
||||
|
||||
/// 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)
|
||||
|
||||
@@ -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<Srgba> {
|
||||
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<f32> = 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::<Vec<_>>(), [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> = 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());
|
||||
}
|
||||
}
|
||||
}
|
||||
+100
-16
@@ -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<SwatchColor> 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<SwatchColor>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
paint: Option<SwatchPaint>,
|
||||
#[serde(default)]
|
||||
kind: SwatchKind,
|
||||
}
|
||||
|
||||
impl From<SwatchEntryWire> 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<SwatchEntry> 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<String>, 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<String>, 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<SwatchGroup>,
|
||||
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
|
||||
|
||||
@@ -190,7 +190,7 @@ pub(super) fn put_ase_color(out: &mut Vec<u8>, 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,
|
||||
};
|
||||
|
||||
@@ -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<u16> {
|
||||
|
||||
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<Vec<RgbSwatch>>, 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<Vec<RgbSwatch>>, 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()
|
||||
})
|
||||
|
||||
@@ -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::<Vec<_>>(), ["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::<SwatchEntry>(&json).unwrap(), *entry, "{json}");
|
||||
}
|
||||
}
|
||||
+110
-22
@@ -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<Gamut<'a>>,
|
||||
}
|
||||
|
||||
/// 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<Label>, mode: AreaMode, values: Bind<'a, ModelValues>) -> Self {
|
||||
ColorArea { common: Common::new(), mode, values, quantize: None, names: None, shape: AreaShape::Plot }.label(label).ltr_axis()
|
||||
ColorArea { common: Common::new(), mode, values, quantize: None, names: None, shape: AreaShape::Plot, gamut: None }.label(label).ltr_axis()
|
||||
}
|
||||
|
||||
/// The across and down channels of the mode's model.
|
||||
@@ -93,7 +105,7 @@ impl<'a> ColorArea<'a> {
|
||||
/// quantise steps. `ColorHud` drives it with the host's pointer.
|
||||
pub(crate) fn value_at(&self, rect: Rect, values: &ModelValues, at: Pos2) -> ModelValues {
|
||||
let mut mine = *values;
|
||||
if let Some(point) = self.picker(Some(values), false).value_at(rect, at) {
|
||||
if let Some(point) = self.picker(Some(values), false, None).value_at(rect, at) {
|
||||
self.settle_into(&mut mine, point.map(Some));
|
||||
}
|
||||
mine
|
||||
@@ -102,7 +114,7 @@ impl<'a> ColorArea<'a> {
|
||||
/// Where `values` stands in `rect`: the picker's own value-to-point mapping.
|
||||
pub(crate) fn point_in(&self, rect: Rect, values: &ModelValues) -> Pos2 {
|
||||
let [across, down] = self.channels();
|
||||
let picker = self.picker(Some(values), false);
|
||||
let picker = self.picker(Some(values), false, None);
|
||||
picker.position([values.values[across], values.values[down]].map(f64::from), picker.plot(rect))
|
||||
}
|
||||
|
||||
@@ -120,11 +132,36 @@ impl<'a> ColorArea<'a> {
|
||||
}
|
||||
}
|
||||
|
||||
/// The picker over `shown`, whose backdrop paints the field of `base`.
|
||||
fn picker<'c>(&self, shown: Option<&ModelValues>, field: bool) -> PointPicker<'c> {
|
||||
/// The values the field is painted around: `shown`, or the model's defaults.
|
||||
fn base(&self, shown: Option<&ModelValues>) -> ModelValues {
|
||||
shown.copied().unwrap_or_else(|| ModelValues::new(self.mode.model().id(), &[]))
|
||||
}
|
||||
|
||||
/// The shading of the cells the gamut moves, `None` without a gamut. The flags are computed here, in the pass, so the
|
||||
/// backdrop closure owns plain data: `Gamut` is not `Clone`.
|
||||
fn shading(&self, base: &ModelValues, style: &ColorAreaStyle) -> Option<Shading> {
|
||||
let gamut = self.gamut.as_ref()?;
|
||||
let at = field_at(self.mode, *base);
|
||||
let mut flags = [false; GRID * GRID];
|
||||
for (index, flag) in flags.iter_mut().enumerate() {
|
||||
let (col, row) = (index % GRID, index / GRID);
|
||||
let centre = |at: usize| (at as f32 + 0.5) / GRID as f32;
|
||||
*flag = gamut.nearest(at(centre(col), centre(row))).is_some();
|
||||
}
|
||||
let (dark, light) = (style.marker.halo, style.marker.ring);
|
||||
Some(Shading {
|
||||
flags,
|
||||
scrim: style.scrim.egui(),
|
||||
dark: Stroke::new(style.marker.ring_width, dark.egui()),
|
||||
light: Stroke::new(style.marker.halo_width, light.egui()),
|
||||
})
|
||||
}
|
||||
|
||||
/// The picker over `shown`; with `field` its backdrop paints the colours of the field (`shading` over them).
|
||||
fn picker<'c>(&self, shown: Option<&ModelValues>, field: bool, shading: Option<Shading>) -> PointPicker<'c> {
|
||||
let model = self.mode.model();
|
||||
let [across, down] = self.channels();
|
||||
let base = shown.copied().unwrap_or_else(|| ModelValues::new(model.id(), &[]));
|
||||
let base = self.base(shown);
|
||||
let point = match shown {
|
||||
Some(values) => Mixed::each([values.values[across], values.values[down]].map(f64::from)),
|
||||
None => [Mixed::Mixed; 2],
|
||||
@@ -143,7 +180,11 @@ impl<'a> ColorArea<'a> {
|
||||
};
|
||||
picker = picker.same(move |from, to| color(from) == color(to));
|
||||
}
|
||||
if field { picker.backdrop(move |painter: &ContentPainterCx, plot: Rect| paint_field(painter, plot, mode, &base, levels)) } else { picker }
|
||||
if field {
|
||||
picker.backdrop(move |painter: &ContentPainterCx, plot: Rect| paint_field(painter, plot, mode, &base, levels, shading))
|
||||
} else {
|
||||
picker
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -157,8 +198,8 @@ impl Component for ColorArea<'_> {
|
||||
type Style = ColorAreaStyle;
|
||||
type Output = EditResponse<ModelValues>;
|
||||
|
||||
fn style(_: &StyleCx<'_>, _: ColorAreaStyleKey) -> ColorAreaStyle {
|
||||
ColorAreaStyle { metrics: Metrics::new() }
|
||||
fn style(cx: &StyleCx<'_>, _: ColorAreaStyleKey) -> ColorAreaStyle {
|
||||
ColorAreaStyle { metrics: Metrics::new(), scrim: cx.color(cx.tokens.color.surface.scrim), marker: cx.marker() }
|
||||
}
|
||||
|
||||
fn sense(&self) -> Sense {
|
||||
@@ -199,7 +240,8 @@ impl Component for ColorArea<'_> {
|
||||
}
|
||||
|
||||
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
|
||||
let picker = self.picker(cx.value(), true).label(cx.label());
|
||||
let shading = self.shading(&self.base(cx.value()), cx.style);
|
||||
let picker = self.picker(cx.value(), true, shading).label(cx.label());
|
||||
let edit = ui.inner("picker", cx.rect, picker);
|
||||
let start = ModelValues::new(self.mode.model().id(), &[]);
|
||||
cx.adopt(&edit, &start, |point, mine| self.settle_into(mine, [0, 1].map(|axis| point[axis].same().copied())));
|
||||
@@ -210,29 +252,75 @@ impl Component for ColorArea<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Paints the colours of the field in `plot`: a mesh blending between 32 by 32 vertices, or with `levels` flat cells
|
||||
/// of the snapped colours.
|
||||
fn paint_field(painter: &ContentPainterCx, plot: Rect, mode: AreaMode, base: &ModelValues, levels: Option<usize>) {
|
||||
/// The cells of the gamut shading and how they are drawn. `flags[row * GRID + col]` is whether the cell is shaded, row 0
|
||||
/// at the top and col 0 at the left.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Shading {
|
||||
flags: [bool; GRID * GRID],
|
||||
scrim: Color32,
|
||||
dark: Stroke,
|
||||
light: Stroke,
|
||||
}
|
||||
|
||||
/// The colour at (`fx`, `fy`) of the field around `base`: across grows right and down grows from the top.
|
||||
fn field_at(mode: AreaMode, base: ModelValues) -> impl Fn(f32, f32) -> Srgba {
|
||||
let model = mode.model();
|
||||
let [across, down] = mode.area();
|
||||
let (x, y) = (channel_range(model, across), channel_range(model, down));
|
||||
let at = |fx: f32, fy: f32| {
|
||||
let mut values = *base;
|
||||
move |fx, fy| {
|
||||
let mut values = base;
|
||||
values.values[across] = egui::lerp(*x.start() as f32..=*x.end() as f32, fx);
|
||||
values.values[down] = egui::lerp(*y.end() as f32..=*y.start() as f32, fy);
|
||||
model.to_srgb(&values.values)
|
||||
};
|
||||
mode.model().to_srgb(&values.values)
|
||||
}
|
||||
}
|
||||
|
||||
/// Paints the colours of the field in `plot`: a mesh blending between 32 by 32 vertices, or with `levels` flat cells
|
||||
/// of the snapped colours; then the gamut `shading`.
|
||||
fn paint_field(painter: &ContentPainterCx, plot: Rect, mode: AreaMode, base: &ModelValues, levels: Option<usize>, shading: Option<Shading>) {
|
||||
let at = field_at(mode, *base);
|
||||
let mut mesh = Mesh::default();
|
||||
match levels {
|
||||
Some(levels) => flat_cells(&mut mesh, plot, &at, levels),
|
||||
None => smooth_mesh(&mut mesh, plot, MESH, &at),
|
||||
}
|
||||
painter.painter.add(mesh);
|
||||
if let Some(shading) = shading {
|
||||
paint_shading(&painter.painter, plot, &shading);
|
||||
}
|
||||
}
|
||||
|
||||
/// Fills the shaded cells and draws the lines between shaded and unshaded neighbours, the dark one first so the light
|
||||
/// one lies over it.
|
||||
fn paint_shading(painter: &Painter, plot: Rect, shading: &Shading) {
|
||||
let cell = plot.size() / GRID as f32;
|
||||
let point = |col: usize, row: usize| pos2(plot.left() + col as f32 * cell.x, plot.top() + row as f32 * cell.y);
|
||||
let shaded = |col: usize, row: usize| shading.flags[row * GRID + col];
|
||||
let mut edges = Vec::new();
|
||||
for row in 0..GRID {
|
||||
for col in 0..GRID {
|
||||
let here = shaded(col, row);
|
||||
if here {
|
||||
painter.rect_filled(Rect::from_min_size(point(col, row), cell), 0.0, shading.scrim);
|
||||
}
|
||||
if col + 1 < GRID && here != shaded(col + 1, row) {
|
||||
edges.push([point(col + 1, row), point(col + 1, row + 1)]);
|
||||
}
|
||||
if row + 1 < GRID && here != shaded(col, row + 1) {
|
||||
edges.push([point(col, row + 1), point(col + 1, row + 1)]);
|
||||
}
|
||||
}
|
||||
}
|
||||
for stroke in [shading.dark, shading.light] {
|
||||
for edge in &edges {
|
||||
painter.line_segment(*edge, stroke);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The colours as a mesh of `steps` by `steps` vertices over `plot`, blending between them; `at` gives the colour at a
|
||||
/// fraction across and down.
|
||||
pub fn smooth_mesh(mesh: &mut Mesh, plot: Rect, steps: usize, at: &dyn Fn(f32, f32) -> craft_theme::Srgba) {
|
||||
pub fn smooth_mesh(mesh: &mut Mesh, plot: Rect, steps: usize, at: &dyn Fn(f32, f32) -> Srgba) {
|
||||
let last = (steps - 1) as f32;
|
||||
for row in 0..steps {
|
||||
for col in 0..steps {
|
||||
@@ -251,7 +339,7 @@ pub fn smooth_mesh(mesh: &mut Mesh, plot: Rect, steps: usize, at: &dyn Fn(f32, f
|
||||
}
|
||||
|
||||
/// The colours as `QUANTIZE_CELLS` by `QUANTIZE_CELLS` flat cells, each the snapped colour at its centre.
|
||||
fn flat_cells(mesh: &mut Mesh, plot: Rect, at: &dyn Fn(f32, f32) -> craft_theme::Srgba, levels: usize) {
|
||||
fn flat_cells(mesh: &mut Mesh, plot: Rect, at: &dyn Fn(f32, f32) -> Srgba, levels: usize) {
|
||||
let n = QUANTIZE_CELLS;
|
||||
let (w, h) = (plot.width() / n as f32, plot.height() / n as f32);
|
||||
for row in 0..n {
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
use super::{AreaShape, ColorArea};
|
||||
use crate::AreaMode;
|
||||
use crate::ui::Gamut;
|
||||
use craft_theme::{ColorModel, HsbModel, Srgba};
|
||||
use craft_ui::contract::{Props as _, Show as _, Validity};
|
||||
use craft_ui::runtime::env::Message;
|
||||
@@ -43,3 +44,15 @@ fn color_area_disabled(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let (values, values_at) = data.value_at("values", HsbModel.from_srgb(Srgba::rgb(0.2, 0.5, 0.8)));
|
||||
ColorArea::new("Saturation and brightness", AreaMode::Hue, values_at.bind(values)).enabled(false).show(ui).into()
|
||||
}
|
||||
|
||||
/// A gamut that moves the pale colours (the top-left quarter of the hue field) to black: the cells it moves are shaded
|
||||
/// and edged.
|
||||
#[story(ColorArea<'static>, covers = [], drive = Drive::Never)]
|
||||
fn color_area_gamut(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let values = data.bind("values", HsbModel.from_srgb(Srgba::rgb(0.2, 0.5, 0.8)));
|
||||
let pale_to_black = Gamut::new(|color: Srgba| {
|
||||
let (high, low) = (color.r.max(color.g).max(color.b), color.r.min(color.g).min(color.b));
|
||||
if high > 0.5 && low > high / 2.0 { Srgba::rgb(0.0, 0.0, 0.0) } else { color }
|
||||
});
|
||||
ColorArea::new("Saturation and brightness", AreaMode::Hue, values).shape(AreaShape::Square).gamut(pale_to_black).show(ui).into()
|
||||
}
|
||||
+308
-71
@@ -4,7 +4,7 @@
|
||||
use super::channels::{finite, primary};
|
||||
use super::wheel::{hue_at, hue_direction, vertex};
|
||||
use craft_behavior::nav::{Arrows, NavShape, Roving};
|
||||
use craft_behavior::{CancelReason, HitShape, Metrics, NavMove, PartKey, PressPhase, Sense};
|
||||
use craft_behavior::{CancelReason, HitShape, Metrics, NavMove, PartKey, PointerButton, 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, Outcome,
|
||||
@@ -36,12 +36,20 @@ const CENTRE: f32 = 0.5;
|
||||
/// Degrees a hue key moves, and percents a saturation key moves; Shift moves ten times as far.
|
||||
const KEY_STEP: f32 = 1.0;
|
||||
const FAR: f32 = 10.0;
|
||||
/// The segmented look: hue sectors round the disc, rings out from its centre, and the degrees one sector spans.
|
||||
const SECTORS: u32 = 24;
|
||||
const PATCH_RINGS: u32 = 5;
|
||||
const SECTOR_DEGREES: f32 = 15.0;
|
||||
/// How far from where a drag put its marker, in radii, the host's colour may lie and still be the drag's: what an
|
||||
/// 8-bit round trip moves a colour by, two of the hundredths a drag reports its radial in.
|
||||
const ECHO_REACH: f32 = 0.02;
|
||||
|
||||
craft_ui::words! {
|
||||
/// The words of colour discs.
|
||||
pub struct ColorDiscWords {
|
||||
marker: template "colorDisc.marker" = "Color {n}";
|
||||
value: template "colorDisc.value" = "Hue {hue} degrees, saturation {saturation} %";
|
||||
value_brightness: template "colorDisc.valueBrightness" = "Hue {hue} degrees, brightness {brightness} %";
|
||||
}
|
||||
}
|
||||
|
||||
@@ -53,17 +61,68 @@ pub struct DiscMove {
|
||||
pub marker: usize,
|
||||
/// Degrees, 0 to 360, red at 0 and growing counter-clockwise.
|
||||
pub hue: f32,
|
||||
/// 0 (the centre) to 1 (the rim).
|
||||
pub saturation: f32,
|
||||
/// 0 (the centre) to 1 (the rim): the channel the radius shows.
|
||||
pub radial: f32,
|
||||
}
|
||||
|
||||
impl DiscMove {
|
||||
/// Marker `marker` at `hue` degrees and `saturation`.
|
||||
pub const fn new(marker: usize, hue: f32, saturation: f32) -> Self {
|
||||
DiscMove { marker, hue, saturation }
|
||||
/// Marker `marker` at `hue` degrees and `radial`.
|
||||
pub const fn new(marker: usize, hue: f32, radial: f32) -> Self {
|
||||
DiscMove { marker, hue, radial }
|
||||
}
|
||||
}
|
||||
|
||||
/// What a click on the disc reports: the marker it concerns and the point under the pointer.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct DiscHit {
|
||||
/// The marker grabbed (a primary click) or in grab reach (a secondary click).
|
||||
pub marker: Option<usize>,
|
||||
/// The marker whose spoke is within the spoke hit width (a secondary click).
|
||||
pub spoke: Option<usize>,
|
||||
/// Degrees, 0 to 360: the hue under the pointer.
|
||||
pub hue: f32,
|
||||
/// 0 to 1: the channel the radius shows, under the pointer.
|
||||
pub radial: f32,
|
||||
}
|
||||
|
||||
impl DiscHit {
|
||||
/// A hit on `marker` or `spoke` at `hue` and `radial`.
|
||||
pub const fn new(marker: Option<usize>, spoke: Option<usize>, hue: f32, radial: f32) -> Self {
|
||||
DiscHit { marker, spoke, hue, radial }
|
||||
}
|
||||
}
|
||||
|
||||
/// How a [`ColorDisc`] draws its colours.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
#[non_exhaustive]
|
||||
pub enum DiscLook {
|
||||
/// A smooth blend of hue around and the radial channel outwards.
|
||||
#[default]
|
||||
Smooth,
|
||||
/// 24 hue sectors by 5 rings of solid patches with thin edges.
|
||||
Segmented,
|
||||
}
|
||||
|
||||
/// The channel the radius of a [`ColorDisc`] shows.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
#[non_exhaustive]
|
||||
pub enum DiscRadius {
|
||||
/// Saturation outwards.
|
||||
#[default]
|
||||
Saturation,
|
||||
/// Brightness outwards.
|
||||
Brightness,
|
||||
}
|
||||
|
||||
/// The centre of the segmented patch at `hue` and `radial`, as `(hue, radial)`: sector `round(h/15) mod 24`, ring
|
||||
/// `floor(r*5).min(4)`.
|
||||
pub fn patch_at(hue: f32, radial: f32) -> (f32, f32) {
|
||||
let sector = (finite(hue).rem_euclid(360.0) / SECTOR_DEGREES).round() as u32 % SECTORS;
|
||||
let ring = ((finite(radial).clamp(0.0, 1.0) * PATCH_RINGS as f32).floor() as u32).min(PATCH_RINGS - 1);
|
||||
(sector as f32 * SECTOR_DEGREES, (ring as f32 + 0.5) / PATCH_RINGS as f32)
|
||||
}
|
||||
|
||||
/// The style of a colour disc.
|
||||
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
|
||||
#[non_exhaustive]
|
||||
@@ -98,6 +157,11 @@ pub struct ColorDiscOutput {
|
||||
pub pressed: Option<usize>,
|
||||
/// The marker a press grabbed and a drag is moving, also on the pass the drag ends.
|
||||
pub grabbed: Option<usize>,
|
||||
/// A primary click (no drag): the marker it grabbed and the point under the release.
|
||||
pub clicked: Option<DiscHit>,
|
||||
/// A secondary click inside the disc: the marker in grab reach, else the marker whose spoke is within the spoke
|
||||
/// hit width, with the point; `None` outside the circle.
|
||||
pub context: Option<DiscHit>,
|
||||
}
|
||||
|
||||
impl Outcome for ColorDiscOutput {
|
||||
@@ -127,7 +191,8 @@ struct Grab {
|
||||
/// ([`pressed`](ColorDiscOutput::pressed) reports it, for the host to select it); a press elsewhere grabs nothing.
|
||||
/// A drag moves the grabbed marker's hue (the pointer's angle, whole degrees) and saturation (its distance over the
|
||||
/// radius, whole percents, at most 1), one gesture; the marker's brightness stays, the host's slider sets it. A
|
||||
/// click is one `Set`. A colour of the host's that is not what the drag reported cancels the drag.
|
||||
/// click is one `Set`. A colour of the host's that is not what the drag reported, after the host's own round trip
|
||||
/// ([`stored_as`](ColorDisc::stored_as)), cancels the drag.
|
||||
/// - Keys: the markers are one Tab stop, which lands on the selected marker (the first without a selection); a press
|
||||
/// that grabs a marker focuses it. Left and Right change the focused marker's hue by 1 degree, Up and Down its
|
||||
/// saturation by 1 percent; Shift steps ten; each key is a `Set`. During a drag keys change nothing. Esc during a
|
||||
@@ -146,22 +211,59 @@ pub struct ColorDisc<'a> {
|
||||
/// The marker drawn larger and where Tab lands; the host owns it.
|
||||
#[prop]
|
||||
chosen: Option<usize>,
|
||||
/// The brightness the disc is drawn at, 0 to 1; never below a floor.
|
||||
#[prop(quantity = "brightness")]
|
||||
brightness: f32,
|
||||
/// The marker drawn large: the set's base colour; `chosen` keeps the Tab stop and, when it is not the base, gets
|
||||
/// the marker look's selection ring.
|
||||
#[prop]
|
||||
base: Option<usize>,
|
||||
/// The channel the radius does not show, 0 to 1; never below a floor (on a saturation disc).
|
||||
#[prop(quantity = "level")]
|
||||
level: f32,
|
||||
/// How the disc draws its colours.
|
||||
#[prop]
|
||||
#[style_key]
|
||||
look: DiscLook,
|
||||
/// The channel the radius shows.
|
||||
#[prop]
|
||||
radius: DiscRadius,
|
||||
/// The markers' accessible names, in order; a marker without one is "Color N".
|
||||
#[prop(into)]
|
||||
names: Vec<Label>,
|
||||
stored: Option<&'a dyn Fn(usize, Srgba) -> Srgba>,
|
||||
pressed: Option<usize>,
|
||||
grabbed: Option<usize>,
|
||||
clicked: Option<DiscHit>,
|
||||
context: Option<DiscHit>,
|
||||
}
|
||||
|
||||
impl<'a> ColorDisc<'a> {
|
||||
/// A disc named `label` ("Harmony") with a marker at each of `markers`, reporting moves through `drag`.
|
||||
pub fn new(label: impl Into<Label>, markers: &'a [Srgba], drag: Bind<'a, DiscMove>) -> Self {
|
||||
ColorDisc { common: Common::new(), markers, drag, chosen: None, brightness: 1.0, names: Vec::new(), pressed: None, grabbed: None }
|
||||
.label(label)
|
||||
.ltr_axis()
|
||||
ColorDisc {
|
||||
common: Common::new(),
|
||||
markers,
|
||||
drag,
|
||||
chosen: None,
|
||||
base: None,
|
||||
level: 1.0,
|
||||
look: DiscLook::Smooth,
|
||||
radius: DiscRadius::Saturation,
|
||||
names: Vec::new(),
|
||||
stored: None,
|
||||
pressed: None,
|
||||
grabbed: None,
|
||||
clicked: None,
|
||||
context: None,
|
||||
}
|
||||
.label(label)
|
||||
.ltr_axis()
|
||||
}
|
||||
|
||||
/// How the host stores marker `index`'s colours: `color` written in the host's own model (CMYK through a profile)
|
||||
/// and read back. A drag's colour that comes back moved by that round trip is still the drag's, not an outside
|
||||
/// change; without it the host is taken to keep the colour as given, to 8 bits.
|
||||
pub fn stored_as(mut self, stored: &'a dyn Fn(usize, Srgba) -> Srgba) -> Self {
|
||||
self.stored = Some(stored);
|
||||
self
|
||||
}
|
||||
|
||||
/// The disc's centre and radius in the area `rect`, `inset` inside its shorter side.
|
||||
@@ -179,20 +281,50 @@ impl<'a> ColorDisc<'a> {
|
||||
self.chosen.filter(|selected| *selected < self.markers.len()).unwrap_or(0)
|
||||
}
|
||||
|
||||
/// Marker `index` as the host's colour places it: hue, saturation (0 to 1) and brightness.
|
||||
/// Marker `index` as the host's colour places it: hue, saturation and brightness (0 to 1).
|
||||
fn hsb(&self, index: usize) -> [f32; 3] {
|
||||
let values = self.markers.get(index).map_or([0.0; 3], |color| {
|
||||
let v = HsbModel.from_srgb(*color).values;
|
||||
[finite(v[0]), finite(v[1]), finite(v[2])]
|
||||
});
|
||||
[values[0], values[1] / 100.0, values[2]]
|
||||
self.markers.get(index).map_or([0.0; 3], |color| hsb_of(*color))
|
||||
}
|
||||
|
||||
/// Marker `index` where the host has it.
|
||||
/// Marker `index` where the host has it: the radial channel is the one the radius shows.
|
||||
fn resting(&self, index: usize) -> DiscMove {
|
||||
let [hue, saturation, _] = self.hsb(index);
|
||||
DiscMove::new(index, hue, saturation)
|
||||
self.at(index, self.hsb(index))
|
||||
}
|
||||
|
||||
/// Marker `index` at the hue, saturation and brightness `hsb`: the radial channel is the one the radius shows.
|
||||
fn at(&self, index: usize, [hue, saturation, brightness]: [f32; 3]) -> DiscMove {
|
||||
let radial = match self.radius {
|
||||
DiscRadius::Saturation => saturation,
|
||||
DiscRadius::Brightness => brightness,
|
||||
};
|
||||
DiscMove::new(index, hue, radial)
|
||||
}
|
||||
|
||||
/// The HSB values (degrees, percents) `moved` makes of `color`: its radial channel on the radius's axis, the other
|
||||
/// channel `color`'s.
|
||||
fn values_on(&self, color: Srgba, moved: &DiscMove) -> [f32; 3] {
|
||||
let [_, saturation, brightness] = hsb_of(color);
|
||||
match self.radius {
|
||||
DiscRadius::Saturation => [moved.hue, moved.radial * 100.0, brightness * 100.0],
|
||||
DiscRadius::Brightness => [moved.hue, saturation * 100.0, moved.radial * 100.0],
|
||||
}
|
||||
}
|
||||
|
||||
/// Where marker `index` lies as the host has it.
|
||||
fn place(&self, index: usize, center: Pos2, radius: f32) -> Pos2 {
|
||||
let at = self.resting(index);
|
||||
Self::marker_pos(center, radius, at.hue, at.radial)
|
||||
}
|
||||
|
||||
/// The channel the radius does not show, 0 to 1; never below a floor on a saturation disc.
|
||||
fn shown_level(&self) -> f32 {
|
||||
let level = if self.level.is_finite() { self.level.clamp(0.0, 1.0) } else { 1.0 };
|
||||
match self.radius {
|
||||
DiscRadius::Saturation => level.max(DISC_FLOOR),
|
||||
DiscRadius::Brightness => level,
|
||||
}
|
||||
}
|
||||
|
||||
/// The marker focus is on.
|
||||
fn focused(&self, cx: &Cx<'_, Self>) -> Option<usize> {
|
||||
(0..self.markers.len()).find(|index| cx.active_part() == Some(MARKER.at(*index as u64)))
|
||||
@@ -237,7 +369,7 @@ impl Component for ColorDisc<'_> {
|
||||
fn parts(&mut self, rect: egui::Rect, cx: &mut PartsCx<'_, Self>) {
|
||||
let (center, radius) = Self::geometry(rect, cx.style.inset);
|
||||
cx.part(DISC, HitShape::circle(center, radius + cx.style.grab))
|
||||
.sense(Sense::DRAG | Sense::CLICK)
|
||||
.sense(Sense::DRAG | Sense::CLICK | Sense::CONTEXT_CLICK)
|
||||
.pointer_only("the arrow keys move the marker");
|
||||
let stop = self.stop();
|
||||
for index in 0..self.markers.len() {
|
||||
@@ -245,8 +377,8 @@ impl Component for ColorDisc<'_> {
|
||||
Some(moved) => *moved,
|
||||
None => self.resting(index),
|
||||
};
|
||||
let reach = Marker::reach(&cx.style.marker, marker_size(self.chosen == Some(index)));
|
||||
let part = cx.part(MARKER.at(index as u64), HitShape::circle(Self::marker_pos(center, radius, at.hue, at.saturation), reach));
|
||||
let reach = Marker::reach(&cx.style.marker, marker_size(self.base == Some(index)));
|
||||
let part = cx.part(MARKER.at(index as u64), HitShape::circle(Self::marker_pos(center, radius, at.hue, at.radial), reach));
|
||||
// A marker takes no press of its own: the disc grabs the nearest.
|
||||
let part = part.focusable().focus_shape(FocusShape::Circle);
|
||||
if index == stop {
|
||||
@@ -265,47 +397,44 @@ impl Component for ColorDisc<'_> {
|
||||
let (center, radius) = Self::geometry(cx.rect, cx.style.inset);
|
||||
let grab_reach = cx.style.grab;
|
||||
let press = cx.part(DISC).press;
|
||||
let secondary = press.phase.start().is_some_and(|start| start.button == PointerButton::Secondary);
|
||||
if primary(&press) && matches!(press.phase, PressPhase::Down { .. }) {
|
||||
let origin = press.phase.start().map(|start| start.origin);
|
||||
let near = origin.and_then(|origin| {
|
||||
let distance = |index: usize| {
|
||||
let at = self.resting(index);
|
||||
Self::marker_pos(center, radius, at.hue, at.saturation).distance(origin)
|
||||
};
|
||||
(0..self.markers.len()).map(|index| (index, distance(index))).filter(|(_, d)| *d <= grab_reach).min_by(|a, b| a.1.total_cmp(&b.1))
|
||||
let near = press.phase.start().and_then(|start| {
|
||||
nearest_within((0..self.markers.len()).map(|index| self.place(index, center, radius).distance(start.origin)), grab_reach)
|
||||
});
|
||||
cx.memory::<Grab>().marker = near.map(|(index, _)| index);
|
||||
self.pressed = near.map(|(index, _)| index);
|
||||
if let Some((index, _)) = near {
|
||||
cx.memory::<Grab>().marker = near;
|
||||
self.pressed = near;
|
||||
if let Some(index) = near {
|
||||
cx.focus_part(MARKER.at(index as u64));
|
||||
}
|
||||
}
|
||||
let grabbed = cx.memory::<Grab>().marker;
|
||||
self.grabbed = grabbed;
|
||||
let running = cx.gesture().is_some();
|
||||
// A colour of the host's that changed and is not what the drag reported is an outside change.
|
||||
// A colour of the host's that changed and does not lie where the drag put the marker is an outside change. Only
|
||||
// the hue and the radial count: the host keeps the channel the radius does not show as it likes (from the
|
||||
// colour before, or from the press against the drift of 8-bit colours) and stores the colour in its own
|
||||
// model, whose round trip the host gives. A colour whose 8 bits lose its hue (black on a saturation disc) is
|
||||
// the drag's when it is the 8-bit colour the drag made of the colour before.
|
||||
if running && let Some(marker) = grabbed.filter(|marker| *marker < self.markers.len()) {
|
||||
let last = cx.memory::<Grab>().last.replace(self.markers[marker]);
|
||||
if let Some(moved) = cx.value().filter(|moved| moved.marker == marker) {
|
||||
let echo = HsbModel.to_srgb(&ModelValues::new("hsb", &[moved.hue, moved.saturation * 100.0, self.hsb(marker)[2]]).values);
|
||||
if last.is_some_and(|last| last != self.markers[marker]) && !echo.same_rgb8(self.markers[marker]) {
|
||||
if let Some(moved) = cx.value().filter(|moved| moved.marker == marker)
|
||||
&& let Some(last) = last.filter(|last| *last != self.markers[marker])
|
||||
{
|
||||
let mut echo = HsbModel.to_srgb(&ModelValues::new("hsb", &self.values_on(last, moved)).values);
|
||||
let mut sent = *moved;
|
||||
if let Some(stored) = self.stored {
|
||||
echo = stored(marker, echo);
|
||||
sent = self.at(marker, hsb_of(echo));
|
||||
}
|
||||
if !lies_at(self.resting(marker), &sent) && !echo.same_rgb8(self.markers[marker]) {
|
||||
cx.cancel(CancelReason::HostChanged);
|
||||
}
|
||||
}
|
||||
}
|
||||
let value_at = |cx: &Cx<'_, Self>, marker: usize, pos: Pos2| {
|
||||
let base = cx.value().filter(|moved| moved.marker == marker && cx.gesture().is_some()).copied().unwrap_or_else(|| self.resting(marker));
|
||||
let offset = pos - center;
|
||||
let mut out = base;
|
||||
if offset.length().is_finite() {
|
||||
out.saturation = ((offset.length() / radius).clamp(0.0, 1.0) * 100.0).round() / 100.0;
|
||||
if offset.length() >= CENTRE
|
||||
&& let Some(hue) = hue_at(center, pos)
|
||||
{
|
||||
out.hue = hue;
|
||||
}
|
||||
}
|
||||
out
|
||||
moved_to(base, center, radius, pos)
|
||||
};
|
||||
if primary(&press)
|
||||
&& let Some(marker) = grabbed
|
||||
@@ -327,6 +456,20 @@ impl Component for ColorDisc<'_> {
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if let PressPhase::Release { pos, click: true, .. } = press.phase {
|
||||
let point = moved_to(DiscMove::new(0, 0.0, 0.0), center, radius, pos);
|
||||
if primary(&press) {
|
||||
self.clicked = Some(DiscHit::new(grabbed, None, point.hue, point.radial));
|
||||
} else if secondary && pos.distance(center) <= radius {
|
||||
let places: Vec<Pos2> = (0..self.markers.len()).map(|index| self.place(index, center, radius)).collect();
|
||||
let marker = nearest_within(places.iter().map(|place| place.distance(pos)), grab_reach);
|
||||
let spoke = match marker {
|
||||
Some(_) => None,
|
||||
None => nearest_within(places.iter().map(|place| segment_distance(center, *place, pos)), grab_reach),
|
||||
};
|
||||
self.context = Some(DiscHit::new(marker, spoke, point.hue, point.radial));
|
||||
}
|
||||
}
|
||||
if matches!(press.phase, PressPhase::Release { .. } | PressPhase::Cancel { .. }) {
|
||||
*cx.memory::<Grab>() = Grab::default();
|
||||
}
|
||||
@@ -343,12 +486,12 @@ impl Component for ColorDisc<'_> {
|
||||
match mv {
|
||||
NavMove::Forward => now.hue += by,
|
||||
NavMove::Back => now.hue -= by,
|
||||
NavMove::Up => now.saturation += by / 100.0,
|
||||
NavMove::Down => now.saturation -= by / 100.0,
|
||||
NavMove::Up => now.radial += by / 100.0,
|
||||
NavMove::Down => now.radial -= by / 100.0,
|
||||
_ => continue,
|
||||
}
|
||||
now.hue = now.hue.round().rem_euclid(360.0);
|
||||
now.saturation = (now.saturation * 100.0).round().clamp(0.0, 100.0) / 100.0;
|
||||
now.radial = (now.radial * 100.0).round().clamp(0.0, 100.0) / 100.0;
|
||||
cx.set(now);
|
||||
}
|
||||
for index in 0..self.markers.len() {
|
||||
@@ -369,54 +512,148 @@ impl Component for ColorDisc<'_> {
|
||||
None => words.marker.fill(&[("n", (index + 1).to_string().as_str())]),
|
||||
};
|
||||
let hue = format!("{:.0}", live.hue.rem_euclid(360.0));
|
||||
let saturation = format!("{:.0}", live.saturation * 100.0);
|
||||
let radial = format!("{:.0}", live.radial * 100.0);
|
||||
let node = access.node(MARKER.at(index as u64), Role::SLIDER);
|
||||
node.name = Name::Text(name);
|
||||
let text = words.value.fill(&[("hue", hue.as_str()), ("saturation", saturation.as_str())]);
|
||||
let text = match self.radius {
|
||||
DiscRadius::Saturation => words.value.fill(&[("hue", hue.as_str()), ("saturation", radial.as_str())]),
|
||||
DiscRadius::Brightness => words.value_brightness.fill(&[("hue", hue.as_str()), ("brightness", radial.as_str())]),
|
||||
};
|
||||
node.numeric = Some(Numeric::new(f64::from(live.hue.rem_euclid(360.0)), 0.0..=360.0).step(f64::from(KEY_STEP)).wraps(true).text(text));
|
||||
}
|
||||
}
|
||||
|
||||
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
|
||||
let (center, radius) = Self::geometry(cx.rect, cx.style.inset);
|
||||
let brightness = if self.brightness.is_finite() { self.brightness.clamp(0.0, 1.0).max(DISC_FLOOR) } else { 1.0 };
|
||||
let level = self.shown_level();
|
||||
let painter = ui.content_painter(cx);
|
||||
painter.painter.add(disc_mesh(center, radius, brightness));
|
||||
let patches = match self.look {
|
||||
DiscLook::Segmented => {
|
||||
let (mesh, edges) = patch_mesh(center, radius, level, self.radius);
|
||||
painter.painter.add(mesh);
|
||||
edges
|
||||
}
|
||||
_ => {
|
||||
painter.painter.add(disc_mesh(center, radius, level, self.radius));
|
||||
Vec::new()
|
||||
}
|
||||
};
|
||||
let draw = ui.draw();
|
||||
for edge in patches {
|
||||
draw.stroke(&PaintShape::Polygon(edge), StrokeWidth::Thin, cx.style.edge);
|
||||
}
|
||||
draw.stroke(&PaintShape::Circle(center, radius), StrokeWidth::Thin, cx.style.edge);
|
||||
let places: Vec<Pos2> = (0..self.markers.len())
|
||||
.map(|index| {
|
||||
let at = cx.value().filter(|moved| moved.marker == index).copied().unwrap_or_else(|| self.resting(index));
|
||||
Self::marker_pos(center, radius, at.hue, at.saturation)
|
||||
Self::marker_pos(center, radius, at.hue, at.radial)
|
||||
})
|
||||
.collect();
|
||||
for place in &places {
|
||||
draw.stroke(&PaintShape::Path(vec![center, *place]), StrokeWidth::Thin, cx.style.spoke);
|
||||
}
|
||||
let selected = self.chosen.filter(|selected| *selected < places.len());
|
||||
let order = (0..places.len()).filter(|index| Some(*index) != selected).chain(selected);
|
||||
let base = self.base.filter(|base| *base < places.len());
|
||||
let chosen = self.chosen.filter(|chosen| *chosen < places.len());
|
||||
// The base is drawn last, over the chosen marker, over the rest.
|
||||
let order = (0..places.len())
|
||||
.filter(|index| Some(*index) != chosen && Some(*index) != base)
|
||||
.chain(chosen.filter(|chosen| Some(*chosen) != base))
|
||||
.chain(base);
|
||||
for index in order {
|
||||
let marker = Marker::filled(places[index], Color32::from(self.markers[index])).size(marker_size(Some(index) == selected));
|
||||
let marker = Marker::filled(places[index], Color32::from(self.markers[index]))
|
||||
.size(marker_size(Some(index) == base))
|
||||
.selected(Some(index) == chosen && Some(index) != base);
|
||||
draw.marker(&cx.style.marker, &marker);
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> ColorDiscOutput {
|
||||
let (pressed, grabbed) = (self.pressed, self.grabbed);
|
||||
ColorDiscOutput { edit: cx.edit_response(), pressed, grabbed }
|
||||
let (pressed, grabbed, clicked, context) = (self.pressed, self.grabbed, self.clicked, self.context);
|
||||
ColorDiscOutput { edit: cx.edit_response(), pressed, grabbed, clicked, context }
|
||||
}
|
||||
}
|
||||
|
||||
/// The disc at `brightness`: a centre vertex and rings out to the rim, hue around.
|
||||
fn disc_mesh(center: Pos2, radius: f32, brightness: f32) -> Mesh {
|
||||
/// `base` moved to the pointer at `pos`: the hue is the pointer's angle (kept at the centre), the radial channel its
|
||||
/// distance over `radius`, in whole percents.
|
||||
fn moved_to(base: DiscMove, center: Pos2, radius: f32, pos: Pos2) -> DiscMove {
|
||||
let offset = pos - center;
|
||||
let mut out = base;
|
||||
if offset.length().is_finite() {
|
||||
out.radial = ((offset.length() / radius).clamp(0.0, 1.0) * 100.0).round() / 100.0;
|
||||
if offset.length() >= CENTRE
|
||||
&& let Some(hue) = hue_at(center, pos)
|
||||
{
|
||||
out.hue = hue;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether `at` lies within `ECHO_REACH` of `moved` on the disc.
|
||||
fn lies_at(at: DiscMove, moved: &DiscMove) -> bool {
|
||||
let point = |m: &DiscMove| Vec2::angled(m.hue.to_radians()) * m.radial;
|
||||
(point(&at) - point(moved)).length() <= ECHO_REACH
|
||||
}
|
||||
|
||||
/// Hue, saturation and brightness (0 to 1) of `color`.
|
||||
fn hsb_of(color: Srgba) -> [f32; 3] {
|
||||
let v = HsbModel.from_srgb(color).values;
|
||||
[finite(v[0]), finite(v[1]) / 100.0, finite(v[2]) / 100.0]
|
||||
}
|
||||
|
||||
/// The index of the least of `distances` that is within `reach`.
|
||||
pub(super) fn nearest_within(distances: impl Iterator<Item = f32>, reach: f32) -> Option<usize> {
|
||||
distances.enumerate().filter(|(_, distance)| *distance <= reach).min_by(|a, b| a.1.total_cmp(&b.1)).map(|(index, _)| index)
|
||||
}
|
||||
|
||||
/// The distance from `p` to the segment `a` to `b`.
|
||||
fn segment_distance(a: Pos2, b: Pos2, p: Pos2) -> f32 {
|
||||
let along = b - a;
|
||||
let length_sq = along.length_sq();
|
||||
let t = if length_sq > 0.0 { ((p - a).dot(along) / length_sq).clamp(0.0, 1.0) } else { 0.0 };
|
||||
p.distance(a + along * t)
|
||||
}
|
||||
|
||||
/// The colour at `hue` and `radial` on a disc whose radius shows `kind`, the other channel at `level`.
|
||||
fn disc_color(kind: DiscRadius, hue: f32, radial: f32, level: f32) -> Color32 {
|
||||
let (saturation, brightness) = match kind {
|
||||
DiscRadius::Saturation => (radial, level),
|
||||
DiscRadius::Brightness => (level, radial),
|
||||
};
|
||||
vertex(hue, saturation * 100.0, brightness * 100.0)
|
||||
}
|
||||
|
||||
/// The segmented disc: a solid patch per sector and ring, centred on `patch_at`'s colour, and each patch's outline.
|
||||
fn patch_mesh(center: Pos2, radius: f32, level: f32, kind: DiscRadius) -> (Mesh, Vec<Vec<Pos2>>) {
|
||||
let mut mesh = Mesh::default();
|
||||
let b = brightness * 100.0;
|
||||
mesh.colored_vertex(center, vertex(0.0, 0.0, b));
|
||||
let mut edges = Vec::new();
|
||||
for sector in 0..SECTORS {
|
||||
for ring in 0..PATCH_RINGS {
|
||||
let (hue, radial) = patch_at(sector as f32 * SECTOR_DEGREES, (ring as f32 + 0.5) / PATCH_RINGS as f32);
|
||||
let color = disc_color(kind, hue, radial, level);
|
||||
let corners = [(-1.0, ring), (1.0, ring), (1.0, ring + 1), (-1.0, ring + 1)]
|
||||
.map(|(side, edge)| ColorDisc::marker_pos(center, radius, hue + side * SECTOR_DEGREES / 2.0, edge as f32 / PATCH_RINGS as f32));
|
||||
let first = mesh.vertices.len() as u32;
|
||||
for corner in corners {
|
||||
mesh.colored_vertex(corner, color);
|
||||
}
|
||||
mesh.add_triangle(first, first + 1, first + 2);
|
||||
mesh.add_triangle(first, first + 2, first + 3);
|
||||
edges.push(corners.to_vec());
|
||||
}
|
||||
}
|
||||
(mesh, edges)
|
||||
}
|
||||
|
||||
/// The smooth disc at `level`: a centre vertex and rings out to the rim, hue around.
|
||||
fn disc_mesh(center: Pos2, radius: f32, level: f32, kind: DiscRadius) -> Mesh {
|
||||
let mut mesh = Mesh::default();
|
||||
mesh.colored_vertex(center, disc_color(kind, 0.0, 0.0, level));
|
||||
for ring in 1..=RINGS {
|
||||
let s = ring as f32 / RINGS as f32;
|
||||
for k in 0..SEGMENTS {
|
||||
let hue = k as f32 * 360.0 / SEGMENTS as f32;
|
||||
mesh.colored_vertex(ColorDisc::marker_pos(center, radius, hue, s), vertex(hue, s * 100.0, b));
|
||||
mesh.colored_vertex(ColorDisc::marker_pos(center, radius, hue, s), disc_color(kind, hue, s, level));
|
||||
}
|
||||
}
|
||||
let at = |ring: u32, k: u32| if ring == 0 { 0 } else { 1 + (ring - 1) * SEGMENTS + k % SEGMENTS };
|
||||
@@ -433,7 +670,7 @@ fn disc_mesh(center: Pos2, radius: f32, brightness: f32) -> Mesh {
|
||||
mesh
|
||||
}
|
||||
|
||||
/// The size of a marker: large while it is the selected one.
|
||||
fn marker_size(selected: bool) -> MarkerSize {
|
||||
if selected { MarkerSize::Large } else { MarkerSize::Regular }
|
||||
/// The size of a marker: large while it is the base.
|
||||
fn marker_size(base: bool) -> MarkerSize {
|
||||
if base { MarkerSize::Large } else { MarkerSize::Regular }
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
//! Stories of `ColorDisc`: three markers with one selected.
|
||||
|
||||
use super::{ColorDisc, DiscMove, MARKER};
|
||||
use super::{ColorDisc, DiscLook, DiscMove, DiscRadius, MARKER};
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::contract::{Props as _, Show as _, Validity};
|
||||
use craft_ui::runtime::env::Message;
|
||||
@@ -12,18 +12,37 @@ const MARKERS: [Srgba; 3] = [Srgba::rgb(0.9, 0.2, 0.2), Srgba::rgb(0.2, 0.7, 0.4
|
||||
#[story(ColorDisc<'static>, covers = [Default], drive = Drive::Drag(Grip::part(MARKER.at(1))))]
|
||||
fn color_disc(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let (moved, moved_at) = data.value_at("move", DiscMove::new(0, 0.0, 0.7));
|
||||
ColorDisc::new("Harmony", &MARKERS, moved_at.bind(moved)).chosen(1).show(ui).into()
|
||||
ColorDisc::new("Harmony", &MARKERS, moved_at.bind(moved)).base(1).chosen(1).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(ColorDisc<'static>, covers = [], drive = Drive::Never, title = "Segmented")]
|
||||
fn color_disc_segmented(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let moved = data.bind("move", DiscMove::new(0, 0.0, 0.7));
|
||||
ColorDisc::new("Harmony", &MARKERS, moved).look(DiscLook::Segmented).base(1).chosen(1).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(ColorDisc<'static>, covers = [], drive = Drive::Never, title = "Brightness radius")]
|
||||
fn color_disc_brightness(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let moved = data.bind("move", DiscMove::new(0, 0.0, 0.7));
|
||||
ColorDisc::new("Harmony", &MARKERS, moved).radius(DiscRadius::Brightness).level(0.8).base(1).chosen(1).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(ColorDisc<'static>, covers = [], drive = Drive::Never, title = "Base marker")]
|
||||
fn color_disc_base(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
// The base is large; the chosen marker, another one, wears the selection ring.
|
||||
let moved = data.bind("move", DiscMove::new(0, 0.0, 0.7));
|
||||
ColorDisc::new("Harmony", &MARKERS, moved).base(0).chosen(2).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(ColorDisc<'static>, covers = [Invalid], drive = Drive::Never)]
|
||||
fn color_disc_invalid(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let refuse_pale = |moved: &DiscMove| if moved.saturation < 0.5 { Validity::Refuse(Message::new("Too pale")) } else { Validity::Ok };
|
||||
let refuse_pale = |moved: &DiscMove| if moved.radial < 0.5 { Validity::Refuse(Message::new("Too pale")) } else { Validity::Ok };
|
||||
let moved = data.bind("pale", DiscMove::new(1, 0.0, 0.2)).check(refuse_pale);
|
||||
ColorDisc::new("Harmony", &MARKERS, moved).chosen(1).show(ui).into()
|
||||
ColorDisc::new("Harmony", &MARKERS, moved).base(1).chosen(1).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(ColorDisc<'static>, covers = [], drive = Drive::Never, title = "Disabled")]
|
||||
fn color_disc_disabled(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let (moved, moved_at) = data.value_at("move", DiscMove::new(0, 0.0, 0.7));
|
||||
ColorDisc::new("Harmony", &MARKERS, moved_at.bind(moved)).chosen(1).enabled(false).show(ui).into()
|
||||
ColorDisc::new("Harmony", &MARKERS, moved_at.bind(moved)).base(1).chosen(1).enabled(false).show(ui).into()
|
||||
}
|
||||
@@ -72,7 +72,8 @@ impl<P> Outcome for GradientEditorOutput<P> {
|
||||
/// 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 {
|
||||
|
||||
@@ -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<P = ()> {
|
||||
pub edit: EditResponse<GradientStops>,
|
||||
/// The selection after this pass, when the bar changed it.
|
||||
pub select: Option<Option<StopRef>>,
|
||||
/// The colour stop whose colour is asked for: a double click on it, Enter or Space.
|
||||
pub color_requested: Option<usize>,
|
||||
/// 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<StopRef>,
|
||||
select: Option<Option<StopRef>>,
|
||||
color_requested: Option<usize>,
|
||||
color_requested: Option<(usize, Rect)>,
|
||||
field_requested: bool,
|
||||
dropped: Option<(StopDrop, P)>,
|
||||
payload: PhantomData<fn() -> 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<usize>) -> Option<usize> {
|
||||
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<P: Clone + Send + Sync + 'static> 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<P: Clone + Send + Sync + 'static> 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<P: Clone + Send + Sync + 'static> 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<P: Clone + Send + Sync + 'static> 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 => {}
|
||||
}
|
||||
|
||||
@@ -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<EditEvent<GradientStops>>,
|
||||
/// The selection the fields moved.
|
||||
pub select: Option<Option<StopRef>>,
|
||||
/// The colour stop whose colour the host is asked to edit.
|
||||
pub color_requested: Option<usize>,
|
||||
/// 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<ScreenPickGesture>,
|
||||
}
|
||||
|
||||
@@ -78,7 +78,7 @@ pub(super) struct Row<'r, 'a> {
|
||||
pub picker: &'r Option<PickerSetup<'a>>,
|
||||
pub sampled: Option<Srgba>,
|
||||
/// The colour request of the bar, when the bar asked for one.
|
||||
pub requested: Option<usize>,
|
||||
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 {
|
||||
|
||||
@@ -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])]));
|
||||
|
||||
@@ -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<Rect>,
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
}
|
||||
@@ -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<usize>,
|
||||
/// A primary click on the wheel (no drag): the marker it grabbed and the point under the release.
|
||||
pub clicked: Option<DiscHit>,
|
||||
/// A secondary click inside the wheel: the marker in grab reach, else the marker whose spoke is near, with the
|
||||
/// point.
|
||||
pub context: Option<DiscHit>,
|
||||
/// 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<usize>,
|
||||
/// `None` until [`base`](Self::base) sets it: the selected colour is the base.
|
||||
base: Option<Option<usize>>,
|
||||
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<Label>, colors: &'a [Srgba]) -> Self {
|
||||
HarmonyWheel { label: label.into(), colors, selected: None }
|
||||
HarmonyWheel { label: label.into(), colors, selected: None, base: None, look: DiscLook::Smooth, radius: DiscRadius::Saturation, stored: None }
|
||||
}
|
||||
|
||||
/// Marks the colour at this index as selected; none by default.
|
||||
@@ -141,45 +154,101 @@ impl<'a> HarmonyWheel<'a> {
|
||||
self
|
||||
}
|
||||
|
||||
/// The colour drawn large, the set's base (`None`: none); the selected colour by default, as the Color Guide shows
|
||||
/// it. The selected colour, when it is not the base, gets the selection ring.
|
||||
pub fn base(mut self, base: Option<usize>) -> Self {
|
||||
self.base = Some(base);
|
||||
self
|
||||
}
|
||||
|
||||
/// How the wheel draws its colours; smooth by default.
|
||||
pub fn look(mut self, look: DiscLook) -> Self {
|
||||
self.look = look;
|
||||
self
|
||||
}
|
||||
|
||||
/// The channel the wheel's radius shows; its slider shows the other. Saturation by default.
|
||||
pub fn radius(mut self, radius: DiscRadius) -> Self {
|
||||
self.radius = radius;
|
||||
self
|
||||
}
|
||||
|
||||
/// How the host stores colour `index`: `color` written in its own model and read back, so a drag survives that
|
||||
/// round trip ([`ColorDisc::stored_as`]).
|
||||
pub fn stored_as(mut self, stored: &'a dyn Fn(usize, Srgba) -> Srgba) -> Self {
|
||||
self.stored = Some(stored);
|
||||
self
|
||||
}
|
||||
|
||||
/// Shows the wheel and the Brightness row.
|
||||
pub fn show(self, ui: &mut Ui) -> HarmonyWheelOutput {
|
||||
let HarmonyWheel { label, colors, selected } = self;
|
||||
let HarmonyWheel { label, colors, selected, base, look, radius, stored } = self;
|
||||
let words = Env::of(ui).words::<HarmonyWords>();
|
||||
let selected = selected.filter(|&i| i < colors.len());
|
||||
let base = base.unwrap_or(selected).filter(|&i| i < colors.len());
|
||||
let hsb = selected.map(|i| colors[i].to_hsb());
|
||||
let brightness = hsb.map_or(1.0, |c| c.b);
|
||||
// The disc shows one channel outwards; the selected colour's other channel is the disc's level and the slider's value.
|
||||
let (level, slider_name) = match radius {
|
||||
DiscRadius::Saturation => (hsb.map_or(1.0, |c| c.b), words.brightness.clone()),
|
||||
DiscRadius::Brightness => (hsb.map_or(1.0, |c| c.s), words.saturation.clone()),
|
||||
};
|
||||
let names: Vec<Label> = colors.iter().map(|c| Label::from(c.to_hex())).collect();
|
||||
let mut pressed = None;
|
||||
let (mut pressed, mut clicked, mut context) = (None, None, None);
|
||||
let mut edits = Vec::new();
|
||||
let shown = Stack::new().show(ui, |ui, _| {
|
||||
edits.clear();
|
||||
pressed = None;
|
||||
let mut disc = ColorDisc::new(label.clone(), colors, Bind::kept());
|
||||
if let Some(base) = base {
|
||||
disc = disc.base(base);
|
||||
}
|
||||
if let Some(selected) = selected {
|
||||
disc = disc.chosen(selected);
|
||||
}
|
||||
let disc = disc.brightness(brightness).names(names.clone()).show(ui);
|
||||
pressed = disc.pressed;
|
||||
if let Some(stored) = stored {
|
||||
disc = disc.stored_as(stored);
|
||||
}
|
||||
let disc = disc.look(look).radius(radius).level(level).names(names.clone()).show(ui);
|
||||
(pressed, clicked, context) = (disc.pressed, disc.clicked, disc.context);
|
||||
let grabbed = disc.grabbed;
|
||||
for event in disc.edit.events {
|
||||
let marker = event.value().map(|m| m.marker).or(grabbed).or(selected);
|
||||
if let Some(marker) = marker {
|
||||
edits.push((marker, event.map(|m| [Some(m.hue), Some(m.saturation), None])));
|
||||
edits.push((
|
||||
marker,
|
||||
event.map(|m| match radius {
|
||||
DiscRadius::Saturation => [Some(m.hue), Some(m.radial), None],
|
||||
DiscRadius::Brightness => [Some(m.hue), None, Some(m.radial)],
|
||||
}),
|
||||
));
|
||||
}
|
||||
}
|
||||
let track = hsb.map(|c| vec![Srgba::from_hsb(Hsb { b: 0.0, ..c }), Srgba::from_hsb(Hsb { b: 1.0, ..c })]).unwrap_or_default();
|
||||
let value = (f64::from(brightness) * 100.0).round();
|
||||
let track = hsb
|
||||
.map(|c| match radius {
|
||||
DiscRadius::Saturation => vec![Srgba::from_hsb(Hsb { b: 0.0, ..c }), Srgba::from_hsb(Hsb { b: 1.0, ..c })],
|
||||
DiscRadius::Brightness => vec![Srgba::from_hsb(Hsb { s: 0.0, ..c }), Srgba::from_hsb(Hsb { s: 1.0, ..c })],
|
||||
})
|
||||
.unwrap_or_default();
|
||||
let value = (f64::from(level) * 100.0).round();
|
||||
let rule = ChannelRule { range: 0.0..=100.0, step: 1.0, decimals: 0 };
|
||||
Stack::new().enabled(selected.is_some()).show(ui, |ui, _| {
|
||||
let row = ChannelRow::new(words.brightness.clone(), Bind::given(value), rule.clone()).track(track.clone()).show(ui);
|
||||
let row = ChannelRow::new(slider_name.clone(), Bind::given(value), rule.clone()).track(track.clone()).show(ui);
|
||||
if let (Some(i), Some(row)) = (selected, row) {
|
||||
for event in row.events {
|
||||
edits.push((i, event.map(|v| [None, None, Some((v / 100.0) as f32)])));
|
||||
edits.push((
|
||||
i,
|
||||
event.map(|v| {
|
||||
let level = Some((v / 100.0) as f32);
|
||||
match radius {
|
||||
DiscRadius::Saturation => [None, None, level],
|
||||
DiscRadius::Brightness => [None, level, None],
|
||||
}
|
||||
}),
|
||||
));
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
HarmonyWheelOutput { response: shown.output, pressed, edits }
|
||||
HarmonyWheelOutput { response: shown.output, pressed, clicked, context, edits }
|
||||
}
|
||||
}
|
||||
|
||||
@@ -205,19 +274,45 @@ pub enum HarmonyMenuAction {
|
||||
Options,
|
||||
}
|
||||
|
||||
/// Where a Color Guide cell lies.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
#[non_exhaustive]
|
||||
pub enum GuideCellAt {
|
||||
/// The harmony strip's cell at this index.
|
||||
Strip(usize),
|
||||
/// The variation grid's cell at this row and column.
|
||||
#[non_exhaustive]
|
||||
Grid {
|
||||
/// The grid row.
|
||||
row: usize,
|
||||
/// The grid column.
|
||||
column: usize,
|
||||
},
|
||||
}
|
||||
|
||||
/// A Color Guide cell: where it lies and the colour it shows.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct GuideCell {
|
||||
/// Where the cell lies.
|
||||
pub at: GuideCellAt,
|
||||
/// The colour the cell shows: the host's, when it gave one.
|
||||
pub color: Srgba,
|
||||
}
|
||||
|
||||
/// The cells of the variation grid chosen for Save Colors as Swatches. The host owns it and hands it to the panel and
|
||||
/// to the panel menu; the cells belong to the guide they were picked from.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct HarmonyPicked {
|
||||
selection: Selection<usize>,
|
||||
guide: u64,
|
||||
colors: Vec<Srgba>,
|
||||
cells: Vec<GuideCell>,
|
||||
}
|
||||
|
||||
impl HarmonyPicked {
|
||||
/// The chosen colours, in grid order.
|
||||
pub fn colors(&self) -> &[Srgba] {
|
||||
&self.colors
|
||||
/// The chosen cells, in grid order.
|
||||
pub fn cells(&self) -> &[GuideCell] {
|
||||
&self.cells
|
||||
}
|
||||
}
|
||||
|
||||
@@ -228,8 +323,9 @@ impl HarmonyPicked {
|
||||
pub struct HarmonyPanelOutput {
|
||||
/// The panel's response.
|
||||
pub response: Response,
|
||||
/// A colour of the strip or the grid was clicked: the app applies it to the selection or the current colour.
|
||||
pub chosen: Option<Srgba>,
|
||||
/// A cell of the strip or the grid was clicked, with the colour the host gave it: the app applies it to the
|
||||
/// selection or the current colour. One output per click.
|
||||
pub chosen: Option<GuideCell>,
|
||||
/// The base swatch was clicked: the app sets the base to its current colour.
|
||||
pub set_base: bool,
|
||||
}
|
||||
@@ -242,6 +338,43 @@ impl Outcome for HarmonyPanelOutput {
|
||||
}
|
||||
}
|
||||
|
||||
/// Gives a swatch table the host's drag payload for the cells it shows.
|
||||
trait CellDrag: Send + Sync {
|
||||
/// `table` dragging the payload of the cell it grabbed, `cells` indexed as the table's items.
|
||||
fn attach<'t>(&self, table: SwatchTable<'t>, cells: Arc<[GuideCell]>) -> SwatchTable<'t>;
|
||||
}
|
||||
|
||||
/// The host's map from a cell to its payload.
|
||||
type CellMap<P> = dyn Fn(&GuideCell) -> Option<P> + Send + Sync;
|
||||
|
||||
/// The host's payload map for cells, with the payload type it erases.
|
||||
struct CellPayload<P>(Arc<CellMap<P>>, PhantomData<fn() -> P>);
|
||||
|
||||
impl<P: Send + Sync + 'static> CellDrag for CellPayload<P> {
|
||||
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<dyn CellDrag>>, 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<dyn Fn(&GuideCell) -> 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<CellColorFn<'a>>,
|
||||
payload: Option<Arc<dyn CellDrag>>,
|
||||
}
|
||||
|
||||
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<P: Send + Sync + 'static>(mut self, map: impl Fn(&GuideCell) -> Option<P> + 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::<HarmonyWords>();
|
||||
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<GuideCell> = 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<GuideCell> = 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<Srgba> = 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<GuideCell> = 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),
|
||||
}
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
@@ -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<FacePaint>,
|
||||
}
|
||||
|
||||
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<T> 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<ColorRequest>,
|
||||
/// A click, Enter or Space on a chip without a popover: the modifiers held.
|
||||
pub clicked: Option<Mods>,
|
||||
}
|
||||
|
||||
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<ColorRequest>,
|
||||
/// The modifiers of this pass's click on a chip without a popover.
|
||||
clicked: Option<Mods>,
|
||||
}
|
||||
|
||||
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<SwatchKey>>) -> 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<craft_ui::contract::BindMut<'_, Paint>> {
|
||||
@@ -449,10 +649,14 @@ impl Component for PaintChip<'_> {
|
||||
let color = *color;
|
||||
cx.memory::<LastSolid>().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::<PaintWords>();
|
||||
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::<ChoiceWords>().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::<Srgba>::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 }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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() });
|
||||
|
||||
@@ -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::<Paint>::Mixed);
|
||||
|
||||
+215
-59
@@ -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<Srgba>,
|
||||
paint: Mixed<Paint>,
|
||||
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<Label>, color: impl Into<Mixed<Srgba>>) -> Self {
|
||||
Self { label: label.into(), color: color.into(), ring: false }
|
||||
let paint = match color.into() {
|
||||
Mixed::Same(color) => Mixed::Same(Paint::Solid(color)),
|
||||
Mixed::Mixed => Mixed::Mixed,
|
||||
};
|
||||
Self { label: label.into(), paint, ring: false }
|
||||
}
|
||||
|
||||
/// A well named `label` showing any paint through `paint_well`; `Mixed::Mixed` for a selection whose paints differ.
|
||||
/// A ring well clips the face to its band; the popover picker starts from the solid colour or the first stop.
|
||||
pub fn paint(label: impl Into<Label>, paint: impl Into<Mixed<Paint>>) -> Self {
|
||||
Self { label: label.into(), paint: paint.into(), ring: false }
|
||||
}
|
||||
|
||||
/// Draws the well as a ring (a stroke, as DesignCraft's stroke well) instead of a filled square. The middle shows
|
||||
@@ -118,6 +127,23 @@ pub struct SwatchPairStyle {
|
||||
mark: StyleColor,
|
||||
/// A swatch's look, for the lines that stand out from a ring well's colour.
|
||||
swatch: SwatchStyle,
|
||||
/// The No Color well's fill: the paint chip's.
|
||||
none_fill: StyleColor,
|
||||
/// The No Color well's diagonal: the paint chip's.
|
||||
none_mark: StyleColor,
|
||||
}
|
||||
|
||||
/// What a [`SwatchPair`]'s wells take of a dragged payload: `SwatchPair::accepts`.
|
||||
pub struct DropAccepts<'a, P>(Box<AcceptsFn<'a, P>>);
|
||||
|
||||
/// The host's test of a payload over a well.
|
||||
type AcceptsFn<'a, P> = dyn Fn(Well, &P) -> bool + 'a;
|
||||
|
||||
impl<'a, P> DropAccepts<'a, P> {
|
||||
/// A test that runs `accepts` on the well and the payload.
|
||||
pub fn new(accepts: impl Fn(Well, &P) -> bool + 'a) -> Self {
|
||||
DropAccepts(Box::new(accepts))
|
||||
}
|
||||
}
|
||||
|
||||
/// A closure that sets up the picker of the popup.
|
||||
@@ -137,7 +163,7 @@ struct Opened(Option<u64>);
|
||||
/// What a swatch pair reports.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
pub struct SwatchPairOutput {
|
||||
pub struct SwatchPairOutput<P = ()> {
|
||||
/// 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<Well>,
|
||||
/// The edit of the active well: another well made active is one `Set`.
|
||||
pub choice: EditResponse<Well>,
|
||||
/// 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<Well>,
|
||||
}
|
||||
|
||||
impl Outcome for SwatchPairOutput {
|
||||
impl<P> Outcome for SwatchPairOutput<P> {
|
||||
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<PickerSetup<'a>>,
|
||||
/// The payload each well drags past the slop (`None`: that well drags nothing).
|
||||
drags: Option<[Option<P>; 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<DropAccepts<'a, P>>,
|
||||
dropped: Option<(Well, P)>,
|
||||
over: Option<Well>,
|
||||
clicked: Option<Well>,
|
||||
double_clicked: Option<Well>,
|
||||
activated: bool,
|
||||
@@ -235,7 +272,7 @@ pub struct SwatchPair<'a> {
|
||||
screen_pick: Option<ScreenPickGesture>,
|
||||
}
|
||||
|
||||
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<Label>, wells: [PairWell; 2], active: Bind<'a, Well>) -> Self {
|
||||
SwatchPair {
|
||||
@@ -249,6 +286,10 @@ impl<'a> SwatchPair<'a> {
|
||||
frame_active: false,
|
||||
sampled: None,
|
||||
picker: None,
|
||||
drags: None,
|
||||
accepts: None,
|
||||
dropped: None,
|
||||
over: None,
|
||||
clicked: None,
|
||||
double_clicked: None,
|
||||
activated: false,
|
||||
@@ -261,6 +302,42 @@ impl<'a> SwatchPair<'a> {
|
||||
.label(label)
|
||||
}
|
||||
|
||||
/// The payload each well drags past the slop, primary first (`None`: that well drags nothing); a mixed well drags
|
||||
/// nothing whatever it is given. Set before `accepts`, which is typed by the payload.
|
||||
pub fn drags<Q: Clone + Send + Sync + 'static>(self, payloads: [Option<Q>; 2]) -> SwatchPair<'a, Q> {
|
||||
SwatchPair {
|
||||
common: self.common,
|
||||
wells: self.wells,
|
||||
active: self.active,
|
||||
swap_button: self.swap_button,
|
||||
default_button: self.default_button,
|
||||
popover: self.popover,
|
||||
click_activates: self.click_activates,
|
||||
frame_active: self.frame_active,
|
||||
sampled: self.sampled,
|
||||
picker: self.picker,
|
||||
drags: Some(payloads),
|
||||
accepts: None,
|
||||
dropped: None,
|
||||
over: None,
|
||||
clicked: self.clicked,
|
||||
double_clicked: self.double_clicked,
|
||||
activated: self.activated,
|
||||
swap: self.swap,
|
||||
defaults: self.defaults,
|
||||
edit: self.edit,
|
||||
edited: self.edited,
|
||||
screen_pick: self.screen_pick,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a, P: Clone + Send + Sync + 'static> SwatchPair<'a, P> {
|
||||
/// The payload well `i` drags: none for a well without one or a mixed one.
|
||||
fn payload(&self, i: usize) -> Option<&P> {
|
||||
self.drags.as_ref()?[i].as_ref().filter(|_| self.wells[i].paint.same().is_some())
|
||||
}
|
||||
|
||||
fn has_buttons(&self) -> bool {
|
||||
self.swap_button.is_some() || self.default_button.is_some()
|
||||
}
|
||||
@@ -298,15 +375,21 @@ impl<'a> SwatchPair<'a> {
|
||||
let secondary = Rect::from_min_size(pos2(end - style.well, top + style.step), square);
|
||||
[primary, secondary]
|
||||
}
|
||||
|
||||
/// The wells' rects inside `rect` on screen, primary first.
|
||||
fn placed(&self, style: &SwatchPairStyle, rect: Rect, rtl: bool) -> [Rect; 2] {
|
||||
let flow = Flow::new(rect, rtl);
|
||||
self.well_rects(style, rect.size()).map(|logical| flow.to_physical(logical.translate(rect.min.to_vec2())))
|
||||
}
|
||||
}
|
||||
|
||||
impl Component for SwatchPair<'_> {
|
||||
impl<P: Clone + Send + Sync + 'static> Component for SwatchPair<'_, P> {
|
||||
const ROLE: Role = Role::GROUP;
|
||||
|
||||
type Style = SwatchPairStyle;
|
||||
type Output = SwatchPairOutput;
|
||||
type Output = SwatchPairOutput<P>;
|
||||
|
||||
fn style(cx: &StyleCx<'_>, _: SwatchPairStyleKey) -> SwatchPairStyle {
|
||||
fn style(cx: &StyleCx<'_>, _: SwatchPairStyleKey<P>) -> 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::<P>().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::<Opened>().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::<PaintWords>(), paint),
|
||||
None => cx.words::<ChoiceWords>().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<P> {
|
||||
let open = cx.recall::<Opened>().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<P> WellsTarget<'_, P> {
|
||||
fn well_at(&self, at: Pos2) -> Option<Well> {
|
||||
[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<Well> {
|
||||
let well = self.well_at(at)?;
|
||||
(!self.mixed[well.index() as usize] && (self.accepts)(well, payload)).then_some(well)
|
||||
}
|
||||
}
|
||||
|
||||
impl<P: Clone + Send + Sync + 'static> DropTarget<P> 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<Paint>) -> 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.
|
||||
|
||||
@@ -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::<Srgba>::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<Vec<ToolSlot<u8>>>, Tracked<LastUsed<u8>>) = (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)
|
||||
}
|
||||
@@ -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<dyn for<'t> 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<TableMap>,
|
||||
/// 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<Srgba>) -> Selection<usize
|
||||
impl<'a> SwatchPalette<'a> {
|
||||
/// A palette named `label` of `swatches`, each a name and a colour, choosing the colour bound to `color`.
|
||||
pub fn new(label: impl Into<Label>, color: Bind<'a, Srgba>, swatches: &'a [(Label, Srgba)]) -> Self {
|
||||
SwatchPalette { label: label.into(), color: PaletteColor::Color(Held::new(color)), swatches, other: None, recent: None }
|
||||
SwatchPalette {
|
||||
label: label.into(),
|
||||
color: PaletteColor::Color(Held::new(color)),
|
||||
swatches,
|
||||
spacing: SwatchSpacing::Touching,
|
||||
drag: None,
|
||||
other: None,
|
||||
recent: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// A palette over a colour that may be none: a host binds its `Mixed<Option<Srgba>>` with `Bind::bound_mixed`.
|
||||
/// No swatch is selected for `Same(None)` or `Mixed`, and a pick writes `Mixed::Same(Some(colour))` and reports
|
||||
/// the same `edit` as [`new`](Self::new), its `before` the colour or `Mixed` when there was none.
|
||||
pub fn optional(label: impl Into<Label>, color: Bind<'a, Option<Srgba>>, swatches: &'a [(Label, Srgba)]) -> Self {
|
||||
SwatchPalette { label: label.into(), color: PaletteColor::Optional(color), swatches, other: None, recent: None }
|
||||
SwatchPalette {
|
||||
label: label.into(),
|
||||
color: PaletteColor::Optional(color),
|
||||
swatches,
|
||||
spacing: SwatchSpacing::Touching,
|
||||
drag: None,
|
||||
other: None,
|
||||
recent: None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The gap between the cells, passed on to its `SwatchTable`.
|
||||
pub fn spacing(mut self, spacing: SwatchSpacing) -> Self {
|
||||
self.spacing = spacing;
|
||||
self
|
||||
}
|
||||
|
||||
/// The payload a cell drags, passed on to its `SwatchTable`.
|
||||
pub fn drag_payload<P: Send + Sync + 'static>(mut self, map: impl Fn(&ListDrag<usize>) -> Option<P> + 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"));
|
||||
}
|
||||
|
||||
@@ -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"))))
|
||||
}
|
||||
+523
-116
@@ -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<Label>, base: Srgba, tint: f32) -> Self {
|
||||
TintRow { name: name.into(), base, global: false, spot: false, tint }
|
||||
}
|
||||
}
|
||||
|
||||
/// What a [`ColorPanelMenu`] command asks the host to do.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub enum ColorPanelAction {
|
||||
/// Show this mode.
|
||||
Mode(ColorPanelMode),
|
||||
/// Put this text on the clipboard.
|
||||
Copy(String),
|
||||
/// Invert the edited colour.
|
||||
Invert,
|
||||
/// Replace the edited colour by its complement.
|
||||
Complement,
|
||||
/// Create a swatch of the edited colour.
|
||||
NewSwatch,
|
||||
}
|
||||
|
||||
impl craft_host::Section for ColorPanelState {
|
||||
@@ -279,6 +388,14 @@ pub struct ColorPanelOutput {
|
||||
/// The Add to Swatches button under the Color Wheel was pressed: the app adds the colour of this well to the
|
||||
/// swatches.
|
||||
pub add_to_swatches: Option<PanelTarget>,
|
||||
/// The output of the proxy wells (the swap and default buttons, the clicks), for the host to read.
|
||||
pub pair: Option<SwatchPairOutput>,
|
||||
/// The edit of the Tint row.
|
||||
pub tint: Option<EditEvent<f32>>,
|
||||
/// The None well was pressed: the target to set to no paint.
|
||||
pub none: Option<PanelTarget>,
|
||||
/// A recolour click on the Spectrum ramp, with nothing picked.
|
||||
pub recolor: Option<RampRecolor>,
|
||||
}
|
||||
|
||||
impl Outcome for ColorPanelOutput {
|
||||
@@ -315,6 +432,9 @@ struct Kept {
|
||||
/// - Ramp: in the slider modes, a `ColorRamp` of the chosen kind; a press picks for the edited well, Alt picks for the
|
||||
/// other; Shift-click cycles the kind. A drag keeps the Current Colors ends it began with. A secondary click opens
|
||||
/// the ramp rows as a context menu.
|
||||
/// - Layouts: [`ColorPanelLayout::FillStroke`] shows the host's wells, the rows the host's model rule picks, the
|
||||
/// Spectrum ramp and the Recent Colors instead. In both layouts [`PanelTarget::Foreground`] is the edited well
|
||||
/// (`Well::Primary`) and [`PanelTarget::Background`] the other.
|
||||
/// - Focus: the panel never takes the focus when shown.
|
||||
#[must_use = "show the panel with `show`"]
|
||||
#[derive(Pattern)]
|
||||
@@ -322,13 +442,56 @@ pub struct ColorPanel<'a> {
|
||||
state: Bind<'a, ColorPanelState>,
|
||||
colors: [Srgba; 2],
|
||||
cmyk: Option<&'a CmykConverter>,
|
||||
rgb: Option<&'a dyn ColorModel>,
|
||||
dynamic: bool,
|
||||
layout: ColorPanelLayout,
|
||||
wells: Option<([PairWell; 2], Bind<'a, Well>)>,
|
||||
edited: Option<Option<PickedColor>>,
|
||||
shown: Option<ColorPanelShown>,
|
||||
recent: &'a [Srgba],
|
||||
recent_setup: Option<RecentSetup>,
|
||||
gamut: Option<Gamut<'a>>,
|
||||
}
|
||||
|
||||
/// Sets up the Recent Colors palette: the payload its chips drag.
|
||||
type RecentSetup = Box<dyn for<'p> Fn(SwatchPalette<'p>) -> SwatchPalette<'p>>;
|
||||
|
||||
/// The palette setup that drags `map`'s payload for the chip under the pointer.
|
||||
fn recent_setup<P: Send + Sync + 'static>(map: impl Fn(usize) -> Option<P> + 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<PickedColor>>,
|
||||
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<PickedColor>) -> 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<P: Send + Sync + 'static>(mut self, map: impl Fn(usize) -> Option<P> + 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::<ColorPanelWords>(), env.words::<ColorPickerDialogWords>());
|
||||
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::<Kept>().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::<Kept>() = 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<PanelRow> {
|
||||
/// 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<PanelRow> {
|
||||
let row = |command: ColorPanelCommand| PanelRow::Command(CommandRef::from(command));
|
||||
let mut rows: Vec<PanelRow> = 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<PanelRow> = 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<ColorPanelCommand> {
|
||||
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<bool> {
|
||||
/// 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<bool> {
|
||||
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<String> {
|
||||
/// 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<ColorPanelAction> {
|
||||
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<PickedColor>)>,
|
||||
pick_color: Option<ColorRequest>,
|
||||
add_to_swatches: Option<PanelTarget>,
|
||||
pair: Option<SwatchPairOutput>,
|
||||
tint: Option<EditEvent<f32>>,
|
||||
none: Option<PanelTarget>,
|
||||
recolor: Option<RampRecolor>,
|
||||
}
|
||||
|
||||
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<PickedColor>) {
|
||||
@@ -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<Item = EditEvent<RampPick>>) {
|
||||
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<ColorPanelCommand> = 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<ColorPanelCommand> {
|
||||
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");
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
@@ -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)
|
||||
}
|
||||
@@ -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<f64>,
|
||||
/// 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<Srgba>,
|
||||
@@ -85,7 +95,8 @@ pub(crate) struct TrackRamp {
|
||||
}
|
||||
|
||||
impl TrackRamp {
|
||||
pub(crate) fn new(stops: Vec<Srgba>, checker: bool) -> Self {
|
||||
/// A ramp through `stops`, over the checkerboard where `checker` is set.
|
||||
pub fn new(stops: Vec<Srgba>, 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<Label>, value: Bind<'a, f64>, rule: ChannelRule) -> Self {
|
||||
ChannelRow { label: label.into(), short: None, value, rule, track: None, checker: false, unit: ChannelUnit::None }
|
||||
/// A row named `label` over `value`, ruled by `rule`.
|
||||
pub fn new(label: impl Into<Label>, value: Bind<'a, f64>, rule: ChannelRule) -> Self {
|
||||
ChannelRow { label: label.into(), short: None, value, rule, track: None, checker: false, unit: ChannelUnit::None, marks: &[] }
|
||||
}
|
||||
|
||||
/// Shows `short` at the line's start in place of the label, which stays the row's name.
|
||||
pub(crate) fn short(mut self, short: &'static str) -> Self {
|
||||
pub fn short(mut self, short: &'static str) -> Self {
|
||||
self.short = Some(short).filter(|short| !short.is_empty());
|
||||
self
|
||||
}
|
||||
|
||||
/// The colours of the track, from the channel's start to its end.
|
||||
pub(crate) fn track(mut self, stops: Vec<Srgba>) -> Self {
|
||||
pub fn track(mut self, stops: Vec<Srgba>) -> Self {
|
||||
self.track = Some(stops);
|
||||
self
|
||||
}
|
||||
|
||||
/// The track over the transparency checkerboard, for the colours that carry alpha.
|
||||
pub(crate) fn checker(mut self, on: bool) -> Self {
|
||||
pub fn checker(mut self, on: bool) -> Self {
|
||||
self.checker = on;
|
||||
self
|
||||
}
|
||||
|
||||
pub(crate) fn unit(mut self, unit: ChannelUnit) -> Self {
|
||||
/// What the number counts.
|
||||
pub fn unit(mut self, unit: ChannelUnit) -> Self {
|
||||
self.unit = unit;
|
||||
self
|
||||
}
|
||||
|
||||
/// The ticks under the track, passed to `SliderField::marks`; not the labelled form, whose caption line has no room
|
||||
/// in a channel row.
|
||||
#[must_use]
|
||||
pub fn marks(mut self, marks: &'a [f64]) -> Self {
|
||||
self.marks = marks;
|
||||
self
|
||||
}
|
||||
|
||||
/// Shows the row; the edit of the slider or the field, `None` when the row did not run.
|
||||
pub(crate) fn show(self, ui: &mut Ui) -> Option<EditResponse<f64>> {
|
||||
let ChannelRow { label, short, mut value, rule, track, checker, unit } = self;
|
||||
pub fn show(self, ui: &mut Ui) -> Option<EditResponse<f64>> {
|
||||
let ChannelRow { label, short, mut value, rule, track, checker, unit, marks } = self;
|
||||
let side = match short {
|
||||
Some(short) => SideLabel::new().kind(LabelKind::Glyph(GlyphLabel::text(Label::from(short)))),
|
||||
None => SideLabel::new(),
|
||||
@@ -210,6 +232,7 @@ impl<'a> ChannelRow<'a> {
|
||||
.side(side.scrub(true))
|
||||
.show(ui, |ui, _| {
|
||||
channel_slider(label.clone(), value.reborrowed(), &rule, unit, track.clone().map(|stops| (stops, checker)))
|
||||
.marks(marks)
|
||||
.layout(SliderFieldLayout::Inline)
|
||||
.field_sizing(Sizing::Content)
|
||||
.thumb(SliderThumb::Triangle)
|
||||
|
||||
@@ -18,8 +18,9 @@ use super::{Collected, ColorPicker, ColorPickerWords, Pass, PickedColor};
|
||||
use crate::ui::{AreaMode, AreaShape, CompareSwatch};
|
||||
|
||||
/// Two columns that never stack: the two halves of the picker, the right half (compare block and actions over the two
|
||||
/// field groups), and each field group (the radio cell, then the channel's letter, field and unit).
|
||||
const TWO_COLUMNS: &[ColumnWidth] = &[ColumnWidth::Content, ColumnWidth::Content];
|
||||
/// field groups), each field group (the radio cell, then the channel's letter, field and unit), and the dialog's Color
|
||||
/// Swatches view (the swatches, then the buttons' cell).
|
||||
pub(crate) const TWO_COLUMNS: &[ColumnWidth] = &[ColumnWidth::Content, ColumnWidth::Content];
|
||||
|
||||
/// The models the picker shows and the area modes it offers.
|
||||
#[derive(Clone, Copy)]
|
||||
|
||||
@@ -20,7 +20,9 @@ use craft_ui::runtime::env::Label;
|
||||
use egui::{Pos2, Response, Ui};
|
||||
|
||||
use super::{AreaMode, ColorWarning};
|
||||
pub(crate) use channel::{ChannelRow, ChannelRule, ChannelUnit, channel_name};
|
||||
pub(crate) use channel::channel_name;
|
||||
pub use channel::{ChannelRow, ChannelRule, ChannelUnit, TrackRamp};
|
||||
pub(crate) use full::TWO_COLUMNS;
|
||||
pub use value::ColorConstraint;
|
||||
use value::Rules;
|
||||
|
||||
|
||||
@@ -1,17 +1,19 @@
|
||||
//! Stories of `ColorPicker` and `ColorPickerDialog`: Compact, Compact with opacity, Compact with Only Web Colors, Full
|
||||
//! with Photoshop's models and both warnings, Full with an InDesign-like model set, and the dialog behind its button.
|
||||
|
||||
use craft_behavior::Mixed;
|
||||
use craft_theme::{Channel, ColorModel, DefaultOn, HsbModel, LabModel, MAX_CHANNELS, ModelValues, OklchModel, RgbModel, Srgba};
|
||||
use craft_ui::contract::{Bind, Props as _, Show as _};
|
||||
use craft_ui::contract::{Bind, EditResponse, Props as _, Show as _, ShowContainer as _};
|
||||
use craft_ui::dialog::stories::hosted;
|
||||
use craft_ui::layout_components::Stack;
|
||||
use craft_ui::runtime::env::Label;
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use egui::Ui;
|
||||
|
||||
use super::channel::{ChannelRow, ChannelRule, TrackRamp};
|
||||
use super::channel::{ChannelRow, ChannelRule, ChannelUnit, TrackRamp};
|
||||
use super::screen_pick::ScreenPickButton;
|
||||
use super::{ColorPicker, ColorPickerLayout, ColorPickerOutput, PickedColor};
|
||||
use crate::ui::{AreaMode, ColorPickerDialog, ColorPickerDialogLayout, ColorPickerTab, ColorWarning};
|
||||
use crate::ui::{AreaMode, ColorPickerDialog, ColorPickerDialogLayout, ColorPickerTab, ColorWarning, PickerLibrary, PickerSwatches};
|
||||
|
||||
type StandardColors = (Vec<(Label, Srgba)>, Vec<(Label, Srgba)>);
|
||||
|
||||
@@ -175,6 +177,35 @@ fn color_picker_dialog(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
hosted(ui, data, (), || ColorPickerDialog::foreground(Srgba::rgb(0.2, 0.5, 0.8)))
|
||||
}
|
||||
|
||||
/// The dialog with the Color Swatches button after Cancel: two libraries, the first of eight colours.
|
||||
#[story(ColorPickerDialog, covers = [], drive = Drive::Never)]
|
||||
fn color_picker_dialog_with_swatches(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
hosted(ui, data, (), || {
|
||||
let eight = [
|
||||
("Red", Srgba::rgb(0.9, 0.1, 0.1)),
|
||||
("Orange", Srgba::rgb(0.95, 0.5, 0.1)),
|
||||
("Yellow", Srgba::rgb(0.95, 0.85, 0.1)),
|
||||
("Green", Srgba::rgb(0.1, 0.65, 0.2)),
|
||||
("Cyan", Srgba::rgb(0.1, 0.75, 0.85)),
|
||||
("Blue", Srgba::rgb(0.1, 0.3, 0.9)),
|
||||
("Violet", Srgba::rgb(0.5, 0.2, 0.8)),
|
||||
("Magenta", Srgba::rgb(0.9, 0.1, 0.6)),
|
||||
];
|
||||
let basic = PickerLibrary::new("Basic", eight.into_iter().map(|(name, color)| (Label::from(name), color)).collect());
|
||||
let grays = PickerLibrary::new("Grays", vec![(Label::from("Black"), Srgba::BLACK), (Label::from("White"), Srgba::rgb(1.0, 1.0, 1.0))]);
|
||||
ColorPickerDialog::foreground(Srgba::rgb(0.1, 0.3, 0.9)).swatch_view(PickerSwatches::new(vec![basic, grays], Label::from("No swatches")))
|
||||
})
|
||||
}
|
||||
|
||||
/// The dialog whose only library is empty: the Color Swatches view shows the notice.
|
||||
#[story(ColorPickerDialog, covers = [], drive = Drive::Never)]
|
||||
fn color_picker_dialog_with_an_empty_library(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
hosted(ui, data, (), || {
|
||||
let libraries = vec![PickerLibrary::new("Empty", Vec::new())];
|
||||
ColorPickerDialog::foreground(Srgba::rgb(0.2, 0.5, 0.8)).swatch_view(PickerSwatches::new(libraries, Label::from("No swatches")))
|
||||
})
|
||||
}
|
||||
|
||||
#[story(ScreenPickButton, covers = [Default], drive = Drive::Never)]
|
||||
fn screen_pick_button(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
ScreenPickButton::new().label("Sample color from the screen").show(ui).into()
|
||||
@@ -185,14 +216,50 @@ fn track_ramp(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
TrackRamp::new(vec![Srgba::rgb(0.0, 0.0, 0.0), Srgba::rgb(1.0, 1.0, 1.0)], false).show(ui).into()
|
||||
}
|
||||
|
||||
/// The saturation row the channel-row stories share: HSB's rule over a white-to-red track.
|
||||
fn saturation_row(value: Bind<'_, f64>) -> ChannelRow<'_> {
|
||||
let channel = HsbModel.channels()[1];
|
||||
ChannelRow::new("Saturation", value, ChannelRule::of(&channel)).track(vec![Srgba::rgb(1.0, 1.0, 1.0), Srgba::rgb(1.0, 0.0, 0.0)])
|
||||
}
|
||||
|
||||
fn row_output(edit: Option<EditResponse<f64>>) -> StoryOutput {
|
||||
edit.map_or_else(StoryOutput::default, StoryOutput::from)
|
||||
}
|
||||
|
||||
#[story(ChannelRow<'static>, covers = [], drive = Drive::Never)]
|
||||
fn channel_row(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let (value, value_at) = data.value_at("value", 40.0_f64);
|
||||
let channel = HsbModel.channels()[1];
|
||||
let row = ChannelRow::new("Saturation", value_at.bind(value), ChannelRule::of(&channel))
|
||||
.track(vec![Srgba::rgb(1.0, 1.0, 1.0), Srgba::rgb(1.0, 0.0, 0.0)]);
|
||||
match row.show(ui) {
|
||||
Some(edit) => StoryOutput::from(edit),
|
||||
None => StoryOutput::default(),
|
||||
row_output(saturation_row(value_at.bind(value)).show(ui))
|
||||
}
|
||||
|
||||
/// Rows whose number counts percent, degrees and a model's own unit text.
|
||||
#[story(ChannelRow<'static>, covers = [], drive = Drive::Never)]
|
||||
fn channel_row_units(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let (value, value_at) = data.value_at("value", 40.0_f64);
|
||||
let mut edit = None;
|
||||
for unit in [ChannelUnit::Percent, ChannelUnit::Degrees, ChannelUnit::Text("pt")] {
|
||||
edit = edit.or(saturation_row(value_at.bind(&mut *value)).unit(unit).show(ui));
|
||||
}
|
||||
row_output(edit)
|
||||
}
|
||||
|
||||
/// A row over a mixed value: the field shows the mixed readout until an edit makes it concrete.
|
||||
#[story(ChannelRow<'static>, covers = [], drive = Drive::Never)]
|
||||
fn channel_row_mixed(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
row_output(saturation_row(Bind::given(Mixed::<f64>::Mixed)).show(ui))
|
||||
}
|
||||
|
||||
/// A row in a disabled container.
|
||||
#[story(ChannelRow<'static>, covers = [], drive = Drive::Never)]
|
||||
fn channel_row_disabled(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let (value, value_at) = data.value_at("value", 40.0_f64);
|
||||
let shown = Stack::new().enabled(false).show(ui, |ui, _| saturation_row(value_at.bind(value)).show(ui));
|
||||
row_output(shown.inner.flatten())
|
||||
}
|
||||
|
||||
/// A row with ticks at 0, 50 and 100 under the track.
|
||||
#[story(ChannelRow<'static>, covers = [], drive = Drive::Never)]
|
||||
fn channel_row_marks(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let marks = [0.0, 50.0, 100.0];
|
||||
row_output(saturation_row(data.bind("value", 40.0_f64)).marks(&marks).show(ui))
|
||||
}
|
||||
@@ -14,14 +14,20 @@ use craft_cms::convert::CmykConverter;
|
||||
use craft_host::Host;
|
||||
use craft_host::target::Caps;
|
||||
use craft_settings::Remembered;
|
||||
use craft_theme::{ColorModel, Srgba, builtin_models};
|
||||
use craft_ui::choice::{SwatchArrangement, SwatchTable};
|
||||
use craft_ui::contract::{Bind, CanvasGesture, CollectionEvent, Sampler as _, ShowCollection as _, ShowContainer as _};
|
||||
use craft_theme::variant::Tone;
|
||||
use craft_theme::{ColorModel, DefaultOn, RgbModel, Srgba, builtin_models};
|
||||
use craft_ui::choice::{SwatchArrangement, SwatchSpacing, SwatchTable};
|
||||
use craft_ui::contract::{
|
||||
Bind, CanvasGesture, CollectionEvent, Entry, FooterSlot, Gap, Sampler as _, Show as _, ShowCollection as _, ShowContainer as _,
|
||||
};
|
||||
use craft_ui::dialog::{
|
||||
ButtonPlace, Dialog, DialogId, DialogResult, DialogStack, FieldRefusal, StackDialog, dialog_id, serde_fields, set_serde_field,
|
||||
};
|
||||
use craft_ui::layout_components::Stack;
|
||||
use craft_ui::layout::{CellAlign, GridFit};
|
||||
use craft_ui::layout_components::{Grid, Stack};
|
||||
use craft_ui::notices::{Notice, NoticeLayout};
|
||||
use craft_ui::patterns::form_dialogs::{HostRequests, ResetFooter};
|
||||
use craft_ui::pickers::Select;
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
use craft_ui::runtime::focus::Initial;
|
||||
use craft_ui::runtime::overlay::CloseReason;
|
||||
@@ -34,7 +40,8 @@ use serde::{Deserialize, Serialize};
|
||||
use std::borrow::Cow;
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::{ColorPicker, ColorPickerLayout, ColorWarning, PickedColor, ScreenPickGesture};
|
||||
use super::picker::TWO_COLUMNS;
|
||||
use super::{ColorPicker, ColorPickerLayout, ColorWarning, Gamut, PickedColor, ScreenPickGesture, SwatchPalette};
|
||||
use crate::{AreaMode, CmykModel, not_web_safe, web_safe};
|
||||
|
||||
type StandardColors = (Vec<(Label, Srgba)>, Vec<(Label, Srgba)>);
|
||||
@@ -51,6 +58,9 @@ craft_ui::words! {
|
||||
add_to_swatches: "colorPickerDialog.addToSwatches" = "Add to Swatches";
|
||||
out_of_gamut: "colorPickerDialog.outOfGamut" = "Out of gamut for printing: click for the nearest printable color";
|
||||
not_web_color: "colorPickerDialog.notWebColor" = "Not a web color: click for the nearest web color";
|
||||
color_swatches: "colorPickerDialog.colorSwatches" = "Color Swatches";
|
||||
color_models: "colorPickerDialog.colorModels" = "Color Models";
|
||||
library: "colorPickerDialog.library" = "Swatch library";
|
||||
standard_tab: "colorPickerDialog.standardTab" = "Standard";
|
||||
custom_tab: "colorPickerDialog.customTab" = "Custom";
|
||||
standard_colors: "colorPickerDialog.standardColors" = "Standard colors";
|
||||
@@ -68,12 +78,85 @@ pub struct ColorPickerMemory {
|
||||
pub mode: AreaMode,
|
||||
/// Only Web Colors: snap to the 216 web-safe colours.
|
||||
pub web_colors: bool,
|
||||
/// The Color Swatches view is shown in place of the Color Models.
|
||||
pub swatches: bool,
|
||||
/// The index of the swatch library the Color Swatches view shows.
|
||||
pub library: usize,
|
||||
/// The tab a tabbed dialog showed last.
|
||||
pub tab: ColorPickerTab,
|
||||
/// The id of the model the Custom tab's model switch showed last; `None` while no switch shows.
|
||||
pub model: Option<String>,
|
||||
}
|
||||
|
||||
/// A named library of colours the Color Swatches view of a [`ColorPickerDialog`] shows.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct PickerLibrary {
|
||||
/// The library's name in the library `Select`.
|
||||
pub name: Label,
|
||||
/// The library's swatches, each a name and a colour.
|
||||
pub swatches: Vec<(Label, Srgba)>,
|
||||
}
|
||||
|
||||
impl PickerLibrary {
|
||||
/// A library named `name` of `swatches`.
|
||||
pub fn new(name: impl Into<Label>, swatches: Vec<(Label, Srgba)>) -> Self {
|
||||
PickerLibrary { name: name.into(), swatches }
|
||||
}
|
||||
}
|
||||
|
||||
/// What the Color Swatches view of a [`ColorPickerDialog`] shows: the libraries to choose from, and the notice for an
|
||||
/// empty library.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct PickerSwatches {
|
||||
/// The libraries, in the order of the library `Select`.
|
||||
pub libraries: Vec<PickerLibrary>,
|
||||
/// The notice shown for an empty library.
|
||||
pub empty: Label,
|
||||
}
|
||||
|
||||
impl PickerSwatches {
|
||||
/// Swatch libraries `libraries`, with `empty` as the notice for an empty one.
|
||||
pub fn new(libraries: Vec<PickerLibrary>, empty: impl Into<Label>) -> Self {
|
||||
PickerSwatches { libraries, empty: empty.into() }
|
||||
}
|
||||
}
|
||||
|
||||
/// The Color Swatches view: the library `Select` over the chosen library's spaced palette, whose cell equal to the colour
|
||||
/// in `held` is marked and whose pick replaces `held`; the notice for a library without swatches. `library` is the
|
||||
/// remembered index, which may lie past the end; it is written only when the user chooses another. The dialog's buttons
|
||||
/// stand in the cell after it, as they head the Full picker's second column.
|
||||
fn show_swatches(ui: &mut Ui, view: &PickerSwatches, library: &mut usize, held: &mut Mixed<PickedColor>, library_label: &Label) {
|
||||
let mut chosen = (*library).min(view.libraries.len().saturating_sub(1));
|
||||
Grid::new(TWO_COLUMNS).fit(GridFit::Fixed).cells(CellAlign::Top).gap(Gap::Section).show(ui, |ui, _| {
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
if !view.libraries.is_empty() {
|
||||
let entries: Vec<Entry<usize>> = view.libraries.iter().enumerate().map(|(i, lib)| Entry::new(i, lib.name.clone())).collect();
|
||||
let shown = Select::new(library_label.clone(), Bind::given(chosen), &entries).show(ui);
|
||||
if let Some(next) = shown.value().copied() {
|
||||
chosen = next;
|
||||
*library = next;
|
||||
}
|
||||
}
|
||||
match view.libraries.get(chosen).filter(|lib| !lib.swatches.is_empty()) {
|
||||
Some(lib) => {
|
||||
// A colour that is not set marks no cell of a library without it; black stands for "none yet".
|
||||
let color = held.same().map_or(Srgba::BLACK, |picked| picked.color);
|
||||
let shown = SwatchPalette::new(lib.name.clone(), Bind::given(color), &lib.swatches).spacing(SwatchSpacing::Spaced).show(ui);
|
||||
if let Some(picked) = shown.edit.as_ref().and_then(|edit| edit.value()).copied() {
|
||||
*held = Mixed::Same(PickedColor::rgb(picked));
|
||||
}
|
||||
}
|
||||
None => {
|
||||
Notice::new(Tone::Neutral, view.empty.clone()).layout(NoticeLayout::Centred).show(ui);
|
||||
}
|
||||
}
|
||||
});
|
||||
let _ = FooterSlot::new().show(ui);
|
||||
});
|
||||
}
|
||||
|
||||
/// The remembered scope of [`ColorPickerMemory`].
|
||||
const MEMORY_SCOPE: &str = "colorPicker.memory";
|
||||
|
||||
@@ -125,12 +208,12 @@ enum Title {
|
||||
/// dialog takes the picker's size: one arrangement in every room.
|
||||
///
|
||||
/// - **Opening:** the hex field has the focus with its text selected, so typing replaces it. The field shows the
|
||||
/// component it showed last time and Only Web Colors is as it was left ([`ColorPickerMemory`]); with Only Web Colors
|
||||
/// component and view it showed last time and Only Web Colors is as it was left ([`ColorPickerMemory`]); with Only Web Colors
|
||||
/// on, the opening colour is snapped to the nearest web colour and the compare swatch's "current" half shows the
|
||||
/// snapped colour, so OK without an edit changes nothing (storytold/photocraft#4995).
|
||||
/// - **Warnings:** the out-of-gamut chip shows when the colour leaves the CMYK gamut of the [`cmyk`](Self::cmyk)
|
||||
/// converter (ΔE over 3); with Only Web Colors off, the web-colour chip shows for a colour that is not one. A click
|
||||
/// on a chip takes its nearest colour.
|
||||
/// - **Warnings:** the out-of-gamut chip shows when the colour leaves the [`gamut`](Self::gamut) (the CMYK gamut of the
|
||||
/// [`cmyk`](Self::cmyk) converter when none is given); with Only Web Colors off, the web-colour chip shows for a colour
|
||||
/// that is not one. A click on a chip takes its nearest colour.
|
||||
/// - **Eyedroppers:** while the dialog is the top dialog it files an `EyedropperRequest` through
|
||||
/// [`requests`](Self::requests); the host runs its canvas dropper, which samples under the dialog (the dialog
|
||||
/// registers [`canvas`](Self::canvas) with the sampler) and answers with `HostRequests::answer_eyedropper`. The
|
||||
@@ -157,6 +240,9 @@ pub struct ColorPickerDialog {
|
||||
remember: bool,
|
||||
add_to_swatches: bool,
|
||||
cmyk: Option<CmykConverter>,
|
||||
working_rgb: Option<Box<dyn ColorModel + Send + Sync>>,
|
||||
gamut: Option<Gamut<'static>>,
|
||||
swatches: Option<PickerSwatches>,
|
||||
eyedropper: bool,
|
||||
canvas_samples: bool,
|
||||
canvas: Option<Id>,
|
||||
@@ -175,16 +261,26 @@ pub struct ColorPickerDialog {
|
||||
standard: Option<StandardColors>,
|
||||
/// The tab the app asked to open on; it wins over the remembered one, once.
|
||||
tab: Option<ColorPickerTab>,
|
||||
/// The request asked to open on the Color Swatches view ([`ColorRequest::on_swatches`]); it wins over the
|
||||
/// remembered view, once.
|
||||
on_swatches: bool,
|
||||
}
|
||||
|
||||
/// What the tabbed body shows besides the memory and the colour it edits.
|
||||
struct TabbedBody<'a> {
|
||||
title: &'a Label,
|
||||
working_rgb: Option<&'a dyn ColorModel>,
|
||||
words: &'a ColorPickerDialogWords,
|
||||
standard: Option<&'a StandardColors>,
|
||||
compare: Option<Mixed<PickedColor>>,
|
||||
}
|
||||
|
||||
/// The built-in models `on` takes, the host's working RGB in place of the built-in RGB.
|
||||
fn models_with(working_rgb: Option<&dyn ColorModel>, on: impl Fn(DefaultOn) -> bool) -> Vec<&dyn ColorModel> {
|
||||
let models = builtin_models().into_iter().filter(|model| on(model.default_on()));
|
||||
models.map(|model| working_rgb.filter(|_| model.id() == RgbModel.id()).unwrap_or(model)).collect()
|
||||
}
|
||||
|
||||
/// The selection of the entry whose colour is exactly `current`.
|
||||
fn chosen(entries: &[(Label, Srgba)], current: Option<Srgba>) -> Selection<usize> {
|
||||
current.and_then(|color| entries.iter().position(|(_, entry)| *entry == color)).map_or_else(Selection::default, Selection::single)
|
||||
@@ -204,7 +300,7 @@ impl TabbedBody<'_> {
|
||||
&mut |key, _| Tab::new(tabs.iter().find(|tab| tab.0 == *key).map_or_else(Label::default, |tab| tab.1.clone())),
|
||||
);
|
||||
for event in out.response.events {
|
||||
if let CollectionEvent::Selection(SelectionChange::Set(keys)) = event
|
||||
if let CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } = event
|
||||
&& let Some(picked) = keys.last()
|
||||
{
|
||||
memory.tab = *picked;
|
||||
@@ -247,10 +343,12 @@ impl TabbedBody<'_> {
|
||||
|
||||
/// The compact picker over the colour, the compare swatch beside its area; the model switch is the memory's.
|
||||
fn custom_page(&self, ui: &mut Ui, memory: &mut ColorPickerMemory, held: &mut Mixed<PickedColor>) {
|
||||
let models: Vec<&dyn ColorModel> = builtin_models().into_iter().filter(|model| model.default_on().compact).collect();
|
||||
let models = models_with(self.working_rgb, |on| on.compact);
|
||||
let mut model: Option<&'static str> = memory.model.as_deref().and_then(|id| models.iter().map(|known| known.id()).find(|known| *known == id));
|
||||
let mut picker =
|
||||
ColorPicker::new(self.title.clone(), Bind::bound_mixed(held)).layout(ColorPickerLayout::Compact).shown_model(Bind::bound(&mut model));
|
||||
let mut picker = ColorPicker::new(self.title.clone(), Bind::bound_mixed(held))
|
||||
.layout(ColorPickerLayout::Compact)
|
||||
.models(models)
|
||||
.shown_model(Bind::bound(&mut model));
|
||||
if let Some(compare) = self.compare {
|
||||
picker = picker.compare(compare);
|
||||
}
|
||||
@@ -264,9 +362,9 @@ impl ColorPickerDialog {
|
||||
/// and its colour. The app opens it on its `DialogHost` and answers the component with the result's `key` and
|
||||
/// `picked.color`.
|
||||
pub fn from_request(request: ColorRequest) -> ColorPickerDialog {
|
||||
let ColorRequest { key, title, color, .. } = request;
|
||||
let ColorRequest { key, title, color, on_swatches, .. } = request;
|
||||
let title = title.map_or(Title::Default, Title::Given);
|
||||
ColorPickerDialog::with_title(key, title, color)
|
||||
ColorPickerDialog { on_swatches, ..ColorPickerDialog::with_title(key, title, color) }
|
||||
}
|
||||
|
||||
/// A picker for the colour `key` names, titled `title`, opening on `color`.
|
||||
@@ -298,6 +396,9 @@ impl ColorPickerDialog {
|
||||
remember: true,
|
||||
add_to_swatches: true,
|
||||
cmyk: None,
|
||||
working_rgb: None,
|
||||
gamut: None,
|
||||
swatches: None,
|
||||
eyedropper: true,
|
||||
canvas_samples: true,
|
||||
canvas: None,
|
||||
@@ -314,9 +415,26 @@ impl ColorPickerDialog {
|
||||
layout: ColorPickerDialogLayout::default(),
|
||||
standard: None,
|
||||
tab: None,
|
||||
on_swatches: false,
|
||||
}
|
||||
}
|
||||
|
||||
/// In the Full layout, a body button after Cancel switches between Color Models and Color Swatches: a library `Select` over a spaced
|
||||
/// `SwatchPalette` with the current colour's cell marked, a pick being an edit. Without it there is no button.
|
||||
#[must_use]
|
||||
pub fn swatch_view(mut self, swatches: PickerSwatches) -> ColorPickerDialog {
|
||||
self.swatches = Some(swatches);
|
||||
self
|
||||
}
|
||||
|
||||
/// The gamut the out-of-gamut chip tests with `Gamut::nearest`; without it the `cmyk` converter gives
|
||||
/// `Gamut::cmyk`.
|
||||
#[must_use]
|
||||
pub fn gamut(mut self, gamut: Gamut<'static>) -> ColorPickerDialog {
|
||||
self.gamut = Some(gamut);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets the dialog's layout: Full (Photoshop) or Tabbed (Word's Colors dialog).
|
||||
#[must_use]
|
||||
pub fn layout(mut self, l: ColorPickerDialogLayout) -> ColorPickerDialog {
|
||||
@@ -379,15 +497,23 @@ impl ColorPickerDialog {
|
||||
self
|
||||
}
|
||||
|
||||
/// The document's CMYK converter: the C, M, Y, K fields convert through it and the out-of-gamut chip tests against
|
||||
/// it. Without it the dialog uses the built-in coated converter, as PhotoCraft does for a document without a CMYK
|
||||
/// profile.
|
||||
/// The document's CMYK converter: the C, M, Y, K fields convert through it, and it is the out-of-gamut chip's gamut
|
||||
/// when [`gamut`](Self::gamut) gives none. Without it the dialog uses the built-in coated converter, as PhotoCraft
|
||||
/// does for a document without a CMYK profile.
|
||||
#[must_use]
|
||||
pub fn cmyk(mut self, converter: &CmykConverter) -> ColorPickerDialog {
|
||||
self.cmyk = Some(converter.clone());
|
||||
self
|
||||
}
|
||||
|
||||
/// The host's working-RGB colour model, whose channels replace the built-in RGB fields in both layouts: a wide
|
||||
/// working space shows its own numbers, and [`kept`](Self::kept) values in it stay as given.
|
||||
#[must_use]
|
||||
pub fn working_rgb(mut self, model: impl ColorModel + Send + Sync + 'static) -> ColorPickerDialog {
|
||||
self.working_rgb = Some(Box::new(model));
|
||||
self
|
||||
}
|
||||
|
||||
/// The screen eyedropper button; on by default, and shown only where the platform can capture the screen.
|
||||
#[must_use]
|
||||
pub fn eyedropper(mut self, on: bool) -> ColorPickerDialog {
|
||||
@@ -496,6 +622,7 @@ impl ColorPickerDialog {
|
||||
if let Some(tab) = self.tab.take() {
|
||||
self.memory.tab = tab;
|
||||
}
|
||||
self.memory.swatches |= self.on_swatches;
|
||||
if self.memory.web_colors
|
||||
&& self.layout == ColorPickerDialogLayout::Full
|
||||
&& let Some(opening) = self.opening
|
||||
@@ -540,7 +667,8 @@ impl StackDialog for ColorPickerDialog {
|
||||
self.instance
|
||||
}
|
||||
|
||||
/// `color` (`#rrggbb`, null when there is none yet), and the memory's own `mode`, `webColors`, `tab` and `model`.
|
||||
/// `color` (`#rrggbb`, null when there is none yet), and the memory's own `mode`, `webColors`, `swatches`, `library`, `tab`
|
||||
/// and `model`.
|
||||
fn json_fields(&self) -> Option<serde_json::Value> {
|
||||
let mut fields = serde_fields(&self.memory)?;
|
||||
let color = self.current.map_or(serde_json::Value::Null, |picked| picked.color.to_hex().into());
|
||||
@@ -594,20 +722,41 @@ impl StackDialog for ColorPickerDialog {
|
||||
}
|
||||
};
|
||||
let cmyk = CmykModel::new(self.cmyk.clone().unwrap_or_else(|| CmykConverter::coated().clone()));
|
||||
let fallback;
|
||||
let gamut = match &self.gamut {
|
||||
Some(gamut) => gamut,
|
||||
None => {
|
||||
fallback = Gamut::cmyk(cmyk.converter().clone());
|
||||
&fallback
|
||||
}
|
||||
};
|
||||
let footer = ResetFooter::new(ui, None, true);
|
||||
let changed = self.current != self.opening;
|
||||
let mut buttons = footer.buttons(FooterButton::new(common.ok.clone(), DialogRole::Accept).enabled(self.current.is_some()), changed).to_vec();
|
||||
if self.add_to_swatches && self.layout == ColorPickerDialogLayout::Full {
|
||||
let full = self.layout == ColorPickerDialogLayout::Full;
|
||||
// The buttons after OK and Cancel are placed by position; their indices are read back from the list.
|
||||
let mut toggle_at = None;
|
||||
if self.swatches.is_some() && full {
|
||||
toggle_at = Some(buttons.len());
|
||||
let label = if self.memory.swatches { words.color_models.clone() } else { words.color_swatches.clone() };
|
||||
buttons.push(FooterButton::new(label, DialogRole::Other).stays_open(true));
|
||||
}
|
||||
let mut add_at = None;
|
||||
if self.add_to_swatches && full {
|
||||
add_at = Some(buttons.len());
|
||||
buttons.push(FooterButton::new(words.add_to_swatches.clone(), DialogRole::Other).stays_open(true));
|
||||
}
|
||||
|
||||
let arm = self.sampling.then_some(self.canvas).flatten();
|
||||
let keep_open = self.canvas;
|
||||
let screen = self.eyedropper && self.layout == ColorPickerDialogLayout::Full && env.view().shell().caps.contains(Caps::SCREEN_CAPTURE);
|
||||
let screen = self.eyedropper && full && env.view().shell().caps.contains(Caps::SCREEN_CAPTURE);
|
||||
// The Full picker keeps a cell for the buttons; the tabbed body has none, so they stand in the side column, as in
|
||||
// Word's Colors dialog.
|
||||
let place = if self.layout == ColorPickerDialogLayout::Full { ButtonPlace::Body } else { ButtonPlace::Side };
|
||||
let Self { current, opening, compare, memory, screen_busy, sample, pending_screen, open, layout, standard, .. } = self;
|
||||
let place = if full { ButtonPlace::Body } else { ButtonPlace::Side };
|
||||
let Self {
|
||||
current, opening, compare, memory, screen_busy, sample, pending_screen, open, layout, standard, swatches: view, working_rgb, ..
|
||||
} = self;
|
||||
let working_rgb = working_rgb.as_deref().map(|model| model as &dyn ColorModel);
|
||||
let mut held: Mixed<PickedColor> = current.map_or(Mixed::Mixed, Mixed::Same);
|
||||
let (sampled, busy, compare_with) = (sample.take(), *screen_busy, compare.then(|| opening.map_or(Mixed::Mixed, Mixed::Same)));
|
||||
let color = current.map(|current| current.color);
|
||||
@@ -627,18 +776,23 @@ impl StackDialog for ColorPickerDialog {
|
||||
cx.pass_canvas_gesture(canvas, CanvasGesture::PRIMARY);
|
||||
}
|
||||
if *layout == ColorPickerDialogLayout::Tabbed {
|
||||
let body = TabbedBody { title: &title, words: &words, standard: standard.as_ref(), compare: compare_with };
|
||||
let body = TabbedBody { title: &title, working_rgb, words: &words, standard: standard.as_ref(), compare: compare_with };
|
||||
body.show(ui, &mut *memory, &mut held);
|
||||
return;
|
||||
}
|
||||
let mut models: Vec<&dyn ColorModel> = builtin_models().into_iter().filter(|model| model.default_on().full).collect();
|
||||
// PLAN: the swatch view should keep the value fields and replace only the area and strip, which the picker body
|
||||
// (picker/mod.rs, not in this set) lays out; here it replaces the whole picker body.
|
||||
if let Some(view) = view.as_ref().filter(|_| memory.swatches) {
|
||||
show_swatches(ui, view, &mut memory.library, &mut held, &words.library);
|
||||
return;
|
||||
}
|
||||
let mut models = models_with(working_rgb, |on| on.full);
|
||||
models.push(&cmyk);
|
||||
let mut warnings = Vec::new();
|
||||
if let Some(color) = color {
|
||||
let rgb = [color.r, color.g, color.b];
|
||||
if let Some(nearest) = cmyk.converter().nearest_in_gamut(rgb, CmykConverter::PICKER_GAMUT_DE) {
|
||||
warnings
|
||||
.push(ColorWarning::new(words.out_of_gamut.clone(), Srgba { r: nearest[0], g: nearest[1], b: nearest[2], a: color.a }));
|
||||
if let Some(nearest) = gamut.nearest(color) {
|
||||
warnings.push(ColorWarning::new(words.out_of_gamut.clone(), Srgba { a: color.a, ..nearest }));
|
||||
}
|
||||
if !web_only && let Some(nearest) = not_web_safe(rgb) {
|
||||
warnings.push(ColorWarning::web_colors(
|
||||
@@ -668,12 +822,16 @@ impl StackDialog for ColorPickerDialog {
|
||||
self.current = held.same().copied();
|
||||
|
||||
let (picked, closed) = (shown.output.picked, shown.output.closed);
|
||||
if picked.is_some() && picked == toggle_at {
|
||||
self.memory.swatches = !self.memory.swatches;
|
||||
return None;
|
||||
}
|
||||
let ok = (picked == Some(0) || closed == Some(CloseReason::Enter)) && self.current.is_some();
|
||||
if !ok && picked == Some(1) && footer.resetting() {
|
||||
self.current = self.opening;
|
||||
return None;
|
||||
}
|
||||
if picked == Some(2) {
|
||||
if picked.is_some() && picked == add_at {
|
||||
self.pending_swatch = self.current;
|
||||
return None;
|
||||
}
|
||||
|
||||
@@ -8,8 +8,9 @@
|
||||
use craft_cms::ColorSpace;
|
||||
use craft_cms::profile::Profile;
|
||||
use craft_ui::choice::{Checkbox, Radio, RadioGroup};
|
||||
use craft_ui::contract::{Bind, Props as _, Show as _, ShowContainer as _};
|
||||
use craft_ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _};
|
||||
use craft_ui::dialog::{DialogId, DialogResult, DialogStack, FieldRefusal, Prompt, StackDialog, dialog_id};
|
||||
use craft_ui::pickers::Select;
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
use craft_ui::runtime::words::CommonWords;
|
||||
use craft_ui::sections::{DialogRole, FooterButton};
|
||||
@@ -39,6 +40,7 @@ craft_ui::words! {
|
||||
discard: "profile.discard" = "Discard the embedded profile (don't color manage)";
|
||||
leave: "profile.leave" = "Leave as is (don't color manage)";
|
||||
assign_working: "profile.assignWorking" = "Assign working space";
|
||||
assign_profile: "profile.assignProfile" = "Assign profile:";
|
||||
remember: "profile.remember" = "Remember this choice for future images";
|
||||
remember_tip: "profile.rememberTip" = "Turn the prompt back on with Ask On Mismatch in Edit \u{203a} Color Settings.";
|
||||
rgb: "profile.rgb" = "RGB";
|
||||
@@ -181,15 +183,19 @@ pub enum ProfileAction {
|
||||
LeaveAsIs,
|
||||
/// Missing: tag it with the working space.
|
||||
AssignWorking,
|
||||
/// Missing: tag it with the profile picked from the list the dialog was given.
|
||||
AssignProfile,
|
||||
}
|
||||
|
||||
/// The answer to a [`ProfileMismatchDialog`]: the action, and whether to remember it for this
|
||||
/// mode (the app sets its policy and turns Ask On Mismatch off).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub struct ProfileAnswer {
|
||||
/// What the user chose.
|
||||
pub action: ProfileAction,
|
||||
/// The profile's name for `AssignProfile`, else `None`.
|
||||
pub profile: Option<String>,
|
||||
/// Whether to apply the choice to later files of the same mode without asking.
|
||||
pub remember: bool,
|
||||
}
|
||||
@@ -216,6 +222,8 @@ pub struct ProfileMismatchDialog {
|
||||
action: ProfileAction,
|
||||
rememberable: bool,
|
||||
remember: bool,
|
||||
profiles: Vec<String>,
|
||||
chosen: usize,
|
||||
open: bool,
|
||||
}
|
||||
|
||||
@@ -234,6 +242,8 @@ impl ProfileMismatchDialog {
|
||||
action,
|
||||
rememberable: false,
|
||||
remember: false,
|
||||
profiles: Vec::new(),
|
||||
chosen: 0,
|
||||
open: true,
|
||||
}
|
||||
}
|
||||
@@ -245,6 +255,15 @@ impl ProfileMismatchDialog {
|
||||
self
|
||||
}
|
||||
|
||||
/// The profiles the Assign profile `Select` lists under its radio row, a Missing Profile prompt only; it starts on
|
||||
/// the first name.
|
||||
#[must_use]
|
||||
pub fn profiles(mut self, names: Vec<String>) -> ProfileMismatchDialog {
|
||||
self.profiles = names;
|
||||
self.chosen = 0;
|
||||
self
|
||||
}
|
||||
|
||||
/// Offers "Remember this choice"; only for a mismatch (ignored for a missing profile).
|
||||
#[must_use]
|
||||
pub fn rememberable(mut self, on: bool) -> ProfileMismatchDialog {
|
||||
@@ -252,14 +271,31 @@ impl ProfileMismatchDialog {
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether Assign profile is offered: a missing profile and a list of profiles to assign.
|
||||
fn offers_profile(&self) -> bool {
|
||||
!self.profiles.is_empty() && matches!(self.question, ProfileQuestion::Missing { .. })
|
||||
}
|
||||
|
||||
/// The actions the question offers, in radio order.
|
||||
fn offered(&self) -> &'static [ProfileAction] {
|
||||
fn offered(&self) -> Vec<ProfileAction> {
|
||||
match self.question {
|
||||
ProfileQuestion::Mismatch { .. } => &[ProfileAction::UseEmbedded, ProfileAction::ConvertToWorking, ProfileAction::Discard],
|
||||
ProfileQuestion::Missing { .. } => &[ProfileAction::LeaveAsIs, ProfileAction::AssignWorking],
|
||||
ProfileQuestion::Mismatch { .. } => vec![ProfileAction::UseEmbedded, ProfileAction::ConvertToWorking, ProfileAction::Discard],
|
||||
ProfileQuestion::Missing { .. } => {
|
||||
let mut offered = vec![ProfileAction::LeaveAsIs, ProfileAction::AssignWorking];
|
||||
if self.offers_profile() {
|
||||
offered.push(ProfileAction::AssignProfile);
|
||||
}
|
||||
offered
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The answer the dialog's state gives: the profile's name only for Assign profile.
|
||||
fn answer(&self) -> ProfileAnswer {
|
||||
let profile = if self.action == ProfileAction::AssignProfile { self.profiles.get(self.chosen).cloned() } else { None };
|
||||
ProfileAnswer { action: self.action, profile, remember: self.remember && self.can_remember() }
|
||||
}
|
||||
|
||||
/// Whether "Remember this choice" shows: a mismatch the app made rememberable.
|
||||
fn can_remember(&self) -> bool {
|
||||
self.rememberable && matches!(self.question, ProfileQuestion::Mismatch { .. })
|
||||
@@ -274,6 +310,7 @@ fn action_name(action: ProfileAction) -> &'static str {
|
||||
ProfileAction::Discard => "discard",
|
||||
ProfileAction::LeaveAsIs => "leaveAsIs",
|
||||
ProfileAction::AssignWorking => "assignWorking",
|
||||
ProfileAction::AssignProfile => "assignProfile",
|
||||
}
|
||||
}
|
||||
|
||||
@@ -286,12 +323,16 @@ impl StackDialog for ProfileMismatchDialog {
|
||||
|
||||
/// The chosen action, as OK gives it; `None` for an action the question does not offer.
|
||||
fn confirm(&mut self, _: &Context) -> Option<ProfileAnswer> {
|
||||
self.offered().contains(&self.action).then(|| ProfileAnswer { action: self.action, remember: self.remember && self.can_remember() })
|
||||
self.offered().contains(&self.action).then(|| self.answer())
|
||||
}
|
||||
|
||||
/// `action`, the chosen one of the question's actions, and `remember` while the box shows.
|
||||
/// `action`, the chosen one of the question's actions, `profile` while Assign profile is offered, and `remember`
|
||||
/// while the box shows.
|
||||
fn json_fields(&self) -> Option<serde_json::Value> {
|
||||
let mut fields = json!({ "action": action_name(self.action) });
|
||||
if self.offers_profile() {
|
||||
fields["profile"] = Value::String(self.profiles.get(self.chosen).cloned().unwrap_or_default());
|
||||
}
|
||||
if self.can_remember() {
|
||||
fields["remember"] = Value::Bool(self.remember);
|
||||
}
|
||||
@@ -305,6 +346,11 @@ impl StackDialog for ProfileMismatchDialog {
|
||||
let Some(picked) = picked else { return Err(FieldRefusal::Rejects(&value).message(field)) };
|
||||
self.action = picked;
|
||||
}
|
||||
"profile" if self.offers_profile() => {
|
||||
let at = value.as_str().and_then(|name| self.profiles.iter().position(|profile| profile == name));
|
||||
let Some(at) = at else { return Err(FieldRefusal::Rejects(&value).message(field)) };
|
||||
self.chosen = at;
|
||||
}
|
||||
"remember" if self.can_remember() => match value.as_bool() {
|
||||
Some(on) => self.remember = on,
|
||||
None => return Err(FieldRefusal::Rejects(&value).message(field)),
|
||||
@@ -317,8 +363,10 @@ impl StackDialog for ProfileMismatchDialog {
|
||||
fn show(&mut self, ui: &mut Ui, _: &DialogStack) -> Option<DialogResult<ProfileAnswer>> {
|
||||
let env = Env::of(ui);
|
||||
let (words, common) = (env.words::<ProfileWords>(), env.words::<CommonWords>());
|
||||
let (offered, can_remember) = (self.offered(), self.can_remember());
|
||||
let Self { file_name, mode, question, action, remember, open, .. } = self;
|
||||
let (offered, can_remember, offers_profile) = (self.offered(), self.can_remember(), self.offers_profile());
|
||||
let entries: Vec<Entry<usize>> =
|
||||
if offers_profile { self.profiles.iter().enumerate().map(|(at, name)| Entry::new(at, name.clone())).collect() } else { Vec::new() };
|
||||
let Self { file_name, mode, question, action, remember, chosen, open, .. } = self;
|
||||
let mode_word = mode.word(&words);
|
||||
let name = file_name.as_str();
|
||||
let (title, message, embedded, working) = match &*question {
|
||||
@@ -341,15 +389,18 @@ impl StackDialog for ProfileMismatchDialog {
|
||||
ProfileAction::Discard => words.discard.clone(),
|
||||
ProfileAction::LeaveAsIs => words.leave.clone(),
|
||||
ProfileAction::AssignWorking => words.assign_working.clone(),
|
||||
ProfileAction::AssignProfile => words.assign_profile.clone(),
|
||||
};
|
||||
(choice, text)
|
||||
})
|
||||
.collect();
|
||||
let group_label = title.clone();
|
||||
let select_label = words.assign_profile.clone();
|
||||
let (remember_label, remember_tip) = (words.remember.clone(), words.remember_tip.clone());
|
||||
let answers = [FooterButton::new(common.ok.clone(), DialogRole::Accept), FooterButton::new(common.cancel.clone(), DialogRole::Cancel)];
|
||||
let held = &mut *action;
|
||||
let ticked = &mut *remember;
|
||||
let picked_profile = &mut *chosen;
|
||||
let shown = Prompt::new(title, message)
|
||||
.answers(answers)
|
||||
.extras(move |ui| {
|
||||
@@ -358,6 +409,11 @@ impl StackDialog for ProfileMismatchDialog {
|
||||
Radio::new(value).label(text).show(ui);
|
||||
}
|
||||
});
|
||||
if offers_profile {
|
||||
Select::new(select_label.clone(), Bind::bound(&mut *picked_profile), &entries)
|
||||
.enabled(*held == ProfileAction::AssignProfile)
|
||||
.show(ui);
|
||||
}
|
||||
if can_remember {
|
||||
Checkbox::new(Bind::bound(&mut *ticked)).label(remember_label.clone()).tooltip(remember_tip.clone()).show(ui);
|
||||
}
|
||||
@@ -365,7 +421,7 @@ impl StackDialog for ProfileMismatchDialog {
|
||||
.opened(Bind::bound(open))
|
||||
.show(ui);
|
||||
match shown.picked {
|
||||
Some(0) => Some(DialogResult::Ok(ProfileAnswer { action: *action, remember: *remember && can_remember })),
|
||||
Some(0) => Some(DialogResult::Ok(self.answer())),
|
||||
Some(_) => Some(DialogResult::Cancel),
|
||||
None => None,
|
||||
}
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Stories of the profile prompts.
|
||||
|
||||
use super::{ProfileMismatchDialog, ProfileMode, ProfileQuestion};
|
||||
use craft_ui::dialog::stories::hosted;
|
||||
use craft_ui::dialog::{DialogStack, StackDialog as _};
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use egui::Ui;
|
||||
@@ -18,6 +19,27 @@ fn profile_mismatch(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
shown(ui, ProfileMismatchDialog::new("photo.psd", ProfileMode::Rgb, question).rememberable(true))
|
||||
}
|
||||
|
||||
/// A Missing Profile prompt for a scan that offers `names` to assign.
|
||||
fn missing_with(names: &[&str]) -> ProfileMismatchDialog {
|
||||
let question = ProfileQuestion::Missing { working: "sRGB IEC61966-2.1".into() };
|
||||
ProfileMismatchDialog::new("photo.psd", ProfileMode::Rgb, question).profiles(names.iter().map(|name| (*name).to_owned()).collect())
|
||||
}
|
||||
|
||||
#[story(ProfileMismatchDialog, covers = [], drive = Drive::Never)]
|
||||
fn profile_missing_with_profiles(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
hosted(ui, data, (), || missing_with(&["Adobe RGB (1998)", "Display P3", "ProPhoto RGB"]))
|
||||
}
|
||||
|
||||
#[story(ProfileMismatchDialog, covers = [], drive = Drive::Never)]
|
||||
fn profile_missing_with_long_profile_names(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
hosted(ui, data, (), || {
|
||||
missing_with(&[
|
||||
"Coated FOGRA39 (ISO 12647-2:2004) with a perceptual rendering intent and black point compensation",
|
||||
"Japan Color 2001 Coated",
|
||||
])
|
||||
})
|
||||
}
|
||||
|
||||
#[story(ProfileMismatchDialog, covers = [], drive = Drive::Never)]
|
||||
fn profile_missing(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
let question = ProfileQuestion::Missing { working: "sRGB IEC61966-2.1".into() };
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
|
||||
use super::channels::primary;
|
||||
use craft_behavior::{Axis, Metrics, NavMove, PartKey, PressPhase, Sense};
|
||||
use craft_cms::convert::CmykConverter;
|
||||
use craft_theme::{Hsb, Srgba};
|
||||
use craft_ui::canvas::context_click;
|
||||
use craft_ui::contract::{
|
||||
@@ -94,14 +95,50 @@ impl RampPick {
|
||||
}
|
||||
}
|
||||
|
||||
/// Maps a spectrum colour to the host's gamut: `ColorRamp::gamut`.
|
||||
pub struct Gamut<'a>(Box<dyn Fn(Srgba) -> Srgba + 'a>);
|
||||
/// Maps a spectrum colour to the host's gamut: `ColorRamp::gamut`. The one gamut mechanism of the picker, the panel,
|
||||
/// the ramp and `ColorArea`; it is `Send + Sync`, so a stored dialog can hold one.
|
||||
pub struct Gamut<'a>(Box<dyn Fn(Srgba) -> Srgba + Send + Sync + 'a>);
|
||||
|
||||
impl<'a> Gamut<'a> {
|
||||
/// The gamut that runs `map`.
|
||||
pub fn new(map: impl Fn(Srgba) -> Srgba + 'a) -> Self {
|
||||
pub fn new(map: impl Fn(Srgba) -> Srgba + Send + Sync + 'a) -> Self {
|
||||
Gamut(Box::new(map))
|
||||
}
|
||||
|
||||
/// The gamut of a CMYK working space: the nearest in-gamut colour by [`CmykConverter::nearest_in_gamut`] with
|
||||
/// [`CmykConverter::PICKER_GAMUT_DE`], the colour itself inside.
|
||||
pub fn cmyk(converter: CmykConverter) -> Gamut<'static> {
|
||||
Gamut::new(move |c| match converter.nearest_in_gamut([c.r, c.g, c.b], CmykConverter::PICKER_GAMUT_DE) {
|
||||
Some([r, g, b]) => Srgba::new(r, g, b, c.a),
|
||||
None => c,
|
||||
})
|
||||
}
|
||||
|
||||
/// The mapped colour when it differs from `color` by more than one 8-bit step, else `None`: the one out-of-gamut
|
||||
/// test every warning chip and `ColorArea`'s shading use.
|
||||
pub fn nearest(&self, color: Srgba) -> Option<Srgba> {
|
||||
let mapped = (self.0)(color);
|
||||
let step = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as i32;
|
||||
let (a, b) = ([color.r, color.g, color.b, color.a].map(step), [mapped.r, mapped.g, mapped.b, mapped.a].map(step));
|
||||
a.iter().zip(&b).any(|(x, y)| (x - y).abs() > 1).then_some(mapped)
|
||||
}
|
||||
}
|
||||
|
||||
/// What a click on the ramp with Cmd or Ctrl asks the host to recolour: Shift sets `invert`, Alt sets `other`.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub struct RampRecolor {
|
||||
/// Shift was held.
|
||||
pub invert: bool,
|
||||
/// Alt was held.
|
||||
pub other: bool,
|
||||
}
|
||||
|
||||
impl RampRecolor {
|
||||
/// A recolour request with `invert` when Shift was held and `other` when Alt was.
|
||||
pub const fn new(invert: bool, other: bool) -> Self {
|
||||
RampRecolor { invert, other }
|
||||
}
|
||||
}
|
||||
|
||||
/// What [`ColorRamp`] returns.
|
||||
@@ -115,6 +152,8 @@ pub struct ColorRampOutput {
|
||||
pub cycle: bool,
|
||||
/// A secondary click that began and ended on the bar: where the host opens its menu.
|
||||
pub menu_at: Option<Pos2>,
|
||||
/// A primary click with Cmd or Ctrl on a ramp with `recolor_clicks`: nothing was picked.
|
||||
pub recolor: Option<RampRecolor>,
|
||||
}
|
||||
|
||||
impl Outcome for ColorRampOutput {
|
||||
@@ -135,6 +174,7 @@ impl Outcome for ColorRampOutput {
|
||||
struct Held {
|
||||
shift: bool,
|
||||
alt: bool,
|
||||
cmd: bool,
|
||||
/// The ends of a Between ramp at the press.
|
||||
ends: Option<[Srgba; 2]>,
|
||||
}
|
||||
@@ -162,7 +202,8 @@ struct Cache {
|
||||
/// moves, also outside the bar, where the pick stays at the edge, and commits at the release. A
|
||||
/// [`Between`](RampKind::Between) ramp keeps the ends it had at the press for the whole gesture. Alt at the press
|
||||
/// sets [`other`](RampPick::other) on every event. A click with Shift starts no gesture and sets
|
||||
/// [`cycle`](ColorRampOutput::cycle). A secondary click on the bar is reported as
|
||||
/// [`cycle`](ColorRampOutput::cycle). With [`recolor_clicks`](ColorRamp::recolor_clicks), a click with Cmd or Ctrl
|
||||
/// starts no gesture, picks nothing and sets [`recolor`](ColorRampOutput::recolor). A secondary click on the bar is reported as
|
||||
/// [`menu_at`](ColorRampOutput::menu_at).
|
||||
/// - Boxes: a click on the white or the black box (also by keyboard) is a `Set` of that colour, with
|
||||
/// [`other`](RampPick::other) when Alt is held; they are Tab stops of their own.
|
||||
@@ -184,7 +225,7 @@ pub struct ColorRamp<'a> {
|
||||
ends: Option<[Srgba; 2]>,
|
||||
/// Maps each colour of a spectrum ramp to the host's gamut (a CMYK round trip). It runs for the cached colours
|
||||
/// only, and again for a pick.
|
||||
#[prop(func = "Fn(Srgba) -> Srgba")]
|
||||
#[prop]
|
||||
gamut: Option<Gamut<'a>>,
|
||||
/// The host's counter for the working space `gamut` maps into; a change recomputes the colours.
|
||||
#[prop]
|
||||
@@ -192,6 +233,10 @@ pub struct ColorRamp<'a> {
|
||||
/// Whether every channel is rounded to the nearest of 0, 0.2, ... 1 and the ramp is flat cells.
|
||||
#[prop]
|
||||
web_safe: bool,
|
||||
/// Whether a primary click with Cmd or Ctrl picks nothing and reports a [`RampRecolor`] (Shift sets `invert`, Alt
|
||||
/// sets `other`); off by default, where Cmd clicks pick as they do.
|
||||
#[prop]
|
||||
recolor_clicks: bool,
|
||||
/// Whether the white and black boxes follow the bar; on by default.
|
||||
#[prop]
|
||||
boxes: bool,
|
||||
@@ -203,6 +248,7 @@ pub struct ColorRamp<'a> {
|
||||
cursor: (usize, usize),
|
||||
cycle: bool,
|
||||
menu_at: Option<Pos2>,
|
||||
recolor: Option<RampRecolor>,
|
||||
}
|
||||
|
||||
impl<'a> ColorRamp<'a> {
|
||||
@@ -217,6 +263,7 @@ impl<'a> ColorRamp<'a> {
|
||||
gamut: None,
|
||||
gamut_revision: 0,
|
||||
web_safe: false,
|
||||
recolor_clicks: false,
|
||||
boxes: true,
|
||||
kind_name: None,
|
||||
colors: Arc::default(),
|
||||
@@ -224,6 +271,7 @@ impl<'a> ColorRamp<'a> {
|
||||
cursor: (0, CELLS_Y / 2),
|
||||
cycle: false,
|
||||
menu_at: None,
|
||||
recolor: None,
|
||||
}
|
||||
.label(label)
|
||||
.ltr_axis()
|
||||
@@ -258,7 +306,7 @@ impl<'a> ColorRamp<'a> {
|
||||
}
|
||||
|
||||
fn gamut_fn(&self) -> Option<&dyn Fn(Srgba) -> Srgba> {
|
||||
self.gamut.as_ref().map(|gamut| &*gamut.0)
|
||||
self.gamut.as_ref().map(|gamut| &*gamut.0 as &dyn Fn(Srgba) -> Srgba)
|
||||
}
|
||||
|
||||
/// The pick at the fractions (`fx`, `fy`) of the bar.
|
||||
@@ -391,14 +439,18 @@ impl Component for ColorRamp<'_> {
|
||||
let configured = self.ends.unwrap_or_else(Self::default_ends);
|
||||
let press = cx.part(BAR).press;
|
||||
if primary(&press) && matches!(press.phase, PressPhase::Down { .. }) {
|
||||
*cx.memory::<Held>() = Held { shift: press.mods.shift, alt: press.mods.alt, ends: Some(configured) };
|
||||
*cx.memory::<Held>() = Held { shift: press.mods.shift, alt: press.mods.alt, cmd: press.mods.cmd, ends: Some(configured) };
|
||||
}
|
||||
let held = *cx.memory::<Held>();
|
||||
let running = cx.gesture().is_some();
|
||||
let ends = if running || press.phase.is_press() { held.ends.unwrap_or(configured) } else { configured };
|
||||
self.shown_ends = ends;
|
||||
let mut cursor = cx.memory::<Cursor>().0.unwrap_or((0, CELLS_Y / 2));
|
||||
if primary(&press) && !held.shift {
|
||||
if primary(&press) && self.recolor_clicks && held.cmd {
|
||||
if matches!(press.phase, PressPhase::Release { click: true, .. }) {
|
||||
self.recolor = Some(RampRecolor::new(held.shift, held.alt));
|
||||
}
|
||||
} else if primary(&press) && !held.shift {
|
||||
let mut picked = None;
|
||||
cx.follow_press(BAR, |pos| {
|
||||
let (fx, fy) = fractions(bar, pos);
|
||||
@@ -477,8 +529,8 @@ impl Component for ColorRamp<'_> {
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> ColorRampOutput {
|
||||
let (cycle, menu_at) = (self.cycle, self.menu_at);
|
||||
ColorRampOutput { edit: cx.edit_response(), cycle, menu_at }
|
||||
let (cycle, menu_at, recolor) = (self.cycle, self.menu_at, self.recolor);
|
||||
ColorRampOutput { edit: cx.edit_response(), cycle, menu_at, recolor }
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -35,6 +35,17 @@ fn color_ramp_web_safe(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
ColorRamp::new("Color ramp", RampKind::Spectrum, data.bind("pick", pick())).web_safe(true).kind_name("Web colors").show(ui).into()
|
||||
}
|
||||
|
||||
#[story(ColorRamp<'static>, covers = [], drive = Drive::Never)]
|
||||
fn color_ramp_recolor_clicks(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let shown = ColorRamp::new("Color ramp", RampKind::Spectrum, data.bind("pick", pick())).recolor_clicks(true).kind_name("RGB Spectrum").show(ui);
|
||||
let last = data.note("last", String::new());
|
||||
if let Some(recolor) = shown.recolor {
|
||||
*last = format!("{recolor:?}");
|
||||
}
|
||||
let readout = format!("Last recolor: {last}");
|
||||
StoryOutput::from(shown).readout(readout)
|
||||
}
|
||||
|
||||
#[story(ColorRamp<'static>, covers = [Invalid], drive = Drive::Never)]
|
||||
fn color_ramp_invalid(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let refuse_dark = |pick: &RampPick| if pick.color.b < 0.5 { Validity::Refuse(Message::new("Too dark")) } else { Validity::Ok };
|
||||
|
||||
@@ -50,6 +50,7 @@ craft_ui::words! {
|
||||
skipped: count "swatches.skipped" = "{n} color in a model that cannot be read was skipped." | "{n} colors in a model that cannot be read were skipped.";
|
||||
converted: count "swatches.converted" = "{n} color was converted to RGB." | "{n} colors were converted to RGB.";
|
||||
kinds_dropped: count "swatches.kindsDropped" = "{n} spot or global color was written as a process color." | "{n} spot or global colors were written as process colors.";
|
||||
paints_skipped: count "swatches.paintsSkipped" = "{n} gradient, pattern or None swatch was not written." | "{n} gradient, pattern or None swatches were not written.";
|
||||
truncated: count "swatches.truncated" = "{n} color past the 256 the format holds was left out." | "{n} colors past the 256 the format holds were left out.";
|
||||
transparent_kept: count "swatches.transparentKept" = "{n} color was kept transparent." | "{n} colors were kept transparent.";
|
||||
names_cut: count "swatches.namesCut" = "{n} name was cut to the length the format holds." | "{n} names were cut to the length the format holds.";
|
||||
|
||||
Loaded 100 of 1012 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user