mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-17 00:34:25 +00:00
Picture crates on the framework: imaging, draw, colour, layers
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
[package]
|
||||
name = "craft-color"
|
||||
description = "Colour for Craft apps: the colour picker, wells, swatch tables, ramps and the hex field."
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
repository.workspace = true
|
||||
autotests = false
|
||||
|
||||
[lib]
|
||||
# The lib's test target is the crate's one test executable: its trials and, with `screen-testing`, the
|
||||
# screen tests in tests/it.
|
||||
harness = false
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[features]
|
||||
default = []
|
||||
# The colour widgets (`craft_color::ui`).
|
||||
ui = ["dep:craft-behavior", "dep:craft-keymap", "dep:craft-ui", "dep:egui", "dep:craft-settings", "dep:craft-window", "craft-platform/screen"]
|
||||
# Screenshot and input tests of the widgets with egui_kittest (desktop only).
|
||||
screen-testing = ["ui", "craft-ui/testing"]
|
||||
|
||||
[dependencies]
|
||||
craft-behavior = { workspace = true, optional = true }
|
||||
craft-cms = { workspace = true }
|
||||
craft-host = { workspace = true }
|
||||
craft-i18n = { workspace = true }
|
||||
craft-keymap = { workspace = true, optional = true }
|
||||
craft-platform = { workspace = true }
|
||||
craft-settings = { workspace = true, optional = true }
|
||||
craft-theme = { workspace = true }
|
||||
craft-ui = { workspace = true, optional = true }
|
||||
craft-window = { workspace = true, optional = true }
|
||||
egui = { workspace = true, optional = true }
|
||||
serde = { workspace = true }
|
||||
|
||||
[dev-dependencies]
|
||||
craft-ui = { workspace = true, features = ["testing"] }
|
||||
egui = { workspace = true }
|
||||
|
||||
[target.'cfg(not(target_arch = "wasm32"))'.dev-dependencies]
|
||||
egui_kittest = { version = "0.37", features = ["wgpu"] }
|
||||
@@ -0,0 +1,9 @@
|
||||
# craft-color
|
||||
|
||||
Colour for Craft apps. With the `ui` feature, `craft_color::ui` has the colour picker (`ColorPicker`, `ColorPopover`, `ColorArea`, `ColorStrip`, `ColorWheel`, `ColorDisc`, `ColorRamp`), the wells (`SwatchPair`, `Well`), `SwatchPalette` tables and the `HexField`. It also has the colour features built on them: the Color Picker dialog (`ColorPickerDialog`), dialog droppers (`DropperButton`, `DropperState`), the Eyedropper's options and ring, Color Sampler points, the screen colour picker (`ScreenColorPicker`), `ColorChoice`, `PaintChip` and `PaintList` (with their `PaintKindLabels` and `PaintListLabels`), the Color and Swatches panels (`ColorPanel`, `SwatchesPanel`), the profile mismatch prompt, the harmony wheel and Color Guide panel, and the `LutPicker`.
|
||||
|
||||
Stories: `patterns/color/{picker-dialog, panel, swatches, eyedropper-bar, samplers, paint-chip, choice, harmony, lut-picker, profile-mismatch}` show each of those features in its states. The two dialogs run on a `DialogHost` (a "Show dialog" button in an Overview tile). The screen eyedropper is off in the stories, so none starts a screen capture.
|
||||
|
||||
Without `ui`: `CmykModel` (CMYK through a craft-cms profile), swatch files (`palette`: `.aco`, `.act`, `.ase`, `.gpl`, `.css`), the display transform and its caches (`display`), and colour harmonies (`harmony`).
|
||||
|
||||
The colour model and conversions are in `craft-theme`; profiles and transforms in `craft-cms`.
|
||||
@@ -0,0 +1,73 @@
|
||||
//! [`CmykModel`]: a colour as the inks of one CMYK profile.
|
||||
|
||||
use craft_cms::convert::CmykConverter;
|
||||
use craft_theme::{Channel, ColorModel, DefaultOn, MAX_CHANNELS, ModelValues, Srgba};
|
||||
|
||||
/// CMYK through a CMYK profile, as Photoshop's and PhotoCraft's Color Picker show it: four
|
||||
/// channels C, M, Y and K, ink in percent (0 no ink, 100 full). It converts through the
|
||||
/// [`CmykConverter`] it holds (the document's CMYK profile, or the built-in coated CMYK), so the
|
||||
/// same sRGB colour reads as different inks in different documents.
|
||||
///
|
||||
/// A host offers it by passing it to the picker
|
||||
/// (`ColorPicker::models`, feature `ui`); the
|
||||
/// `ColorPickerDialog` adds it when it is given a
|
||||
/// `ColorPickerDialog::gamut`. Inks the user typed stay as typed while they
|
||||
/// still give the colour (`PickedColor::model`): a CMYK document
|
||||
/// fills with them, not with what its sRGB stand-in converts back to (storytold/photocraft#4196).
|
||||
#[derive(Clone)]
|
||||
pub struct CmykModel {
|
||||
converter: CmykConverter,
|
||||
}
|
||||
|
||||
const CMYK_CHANNELS: [Channel; 4] = [
|
||||
Channel { name: "Cyan", qualified: "CMYK cyan", label: "C", min: 0.0, max: 100.0, unit: "%", decimals: 0, step: 1.0, track_stops: 9 },
|
||||
Channel { name: "Magenta", qualified: "CMYK magenta", label: "M", min: 0.0, max: 100.0, unit: "%", decimals: 0, step: 1.0, track_stops: 9 },
|
||||
Channel { name: "Yellow", qualified: "CMYK yellow", label: "Y", min: 0.0, max: 100.0, unit: "%", decimals: 0, step: 1.0, track_stops: 9 },
|
||||
Channel { name: "Black", qualified: "CMYK black", label: "K", min: 0.0, max: 100.0, unit: "%", decimals: 0, step: 1.0, track_stops: 9 },
|
||||
];
|
||||
|
||||
impl CmykModel {
|
||||
/// The model on `converter` (cheap: the transforms are shared).
|
||||
pub fn new(converter: CmykConverter) -> CmykModel {
|
||||
CmykModel { converter }
|
||||
}
|
||||
|
||||
/// The converter the model converts through.
|
||||
pub fn converter(&self) -> &CmykConverter {
|
||||
&self.converter
|
||||
}
|
||||
}
|
||||
|
||||
impl std::fmt::Debug for CmykModel {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
f.debug_struct("CmykModel").field("profile", &self.converter.profile().description).finish()
|
||||
}
|
||||
}
|
||||
|
||||
impl ColorModel for CmykModel {
|
||||
fn id(&self) -> &'static str {
|
||||
"cmyk"
|
||||
}
|
||||
fn name(&self) -> &'static str {
|
||||
"CMYK"
|
||||
}
|
||||
fn channels(&self) -> &[Channel] {
|
||||
&CMYK_CHANNELS
|
||||
}
|
||||
// pc: crates/ui-egui/src/dialogs/color_picker_ui.rs:298 `Components` (cmyk from
|
||||
// `photocraft_color::convert::rgb_to_cmyk`); `self.converter.from_srgb([r, g, b])` scaled to
|
||||
// percent.
|
||||
fn from_srgb(&self, color: Srgba) -> ModelValues {
|
||||
let inks = self.converter.from_srgb([color.r, color.g, color.b]);
|
||||
ModelValues::new("cmyk", &inks.map(|v| v * 100.0))
|
||||
}
|
||||
// pc: crates/ui-egui/src/dialogs/color_picker_ui.rs:722 (typed inks to sRGB through
|
||||
// `cmyk_to_rgb`); `self.converter.to_srgb(values / 100)`, opaque.
|
||||
fn to_srgb(&self, values: &[f32; MAX_CHANNELS]) -> Srgba {
|
||||
let rgb = self.converter.to_srgb([values[0] / 100.0, values[1] / 100.0, values[2] / 100.0, values[3] / 100.0]);
|
||||
Srgba { r: rgb[0].clamp(0.0, 1.0), g: rgb[1].clamp(0.0, 1.0), b: rgb[2].clamp(0.0, 1.0), a: 1.0 }
|
||||
}
|
||||
fn default_on(&self) -> DefaultOn {
|
||||
DefaultOn { full: false, compact: false }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
//! The display transform (F04.11): how a canvas shows a document's colours on a monitor. Pixels
|
||||
//! in the document's profile go through one cached transform to the monitor's profile; when that
|
||||
//! transform changes nothing, the canvas skips it.
|
||||
//!
|
||||
//! The monitor profile comes from the platform (craft-platform's display reading, or the ICC
|
||||
//! bytes of a `craft_platform::screen::ScreenImage`) or from the app's Color Settings; a
|
||||
//! profile that is missing, unreadable, not RGB or unusable as a destination falls back to sRGB,
|
||||
//! and [`MonitorStatus`] says why.
|
||||
|
||||
use std::collections::HashMap;
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use craft_cms::transform::{TransformOptions, cached};
|
||||
use craft_cms::{Builtin, CmsError, ColorSpace, Profile, Transform};
|
||||
|
||||
/// Rendering intent and black point compensation of every display transform: relative
|
||||
/// colorimetric with BPC, as Photoshop's default monitor conversion and PhotoCraft's.
|
||||
pub const DISPLAY_INTENT: craft_cms::Intent = craft_cms::Intent::RelativeColorimetric;
|
||||
|
||||
/// A display, as the platform numbers it; `None` is "the main window's display".
|
||||
pub type DisplayId = Option<u32>;
|
||||
|
||||
/// Bytes per conversion chunk of [`DisplayTransform::apply_rgba8`] (a whole number of pixels).
|
||||
const CHUNK_BYTES: usize = 4 * 65536;
|
||||
|
||||
/// Most cached transforms before the cache is cleared.
|
||||
const MAX_TRANSFORMS: usize = 32;
|
||||
|
||||
fn hash_of(v: impl std::hash::Hash) -> u64 {
|
||||
use std::hash::Hasher;
|
||||
let mut h = std::collections::hash_map::DefaultHasher::new();
|
||||
v.hash(&mut h);
|
||||
h.finish()
|
||||
}
|
||||
|
||||
/// The [`DisplayTransform::key`] of a source and monitor pair. Whether the transform is the
|
||||
/// identity follows from the pair, so it is not part of the key.
|
||||
fn signature(source: &Profile, monitor: &Profile) -> u64 {
|
||||
hash_of((source.content_hash(), monitor.content_hash()))
|
||||
}
|
||||
|
||||
/// Does `t` map every lattice point (the neutral axis only for a grey source) to itself within
|
||||
/// half an 8-bit step?
|
||||
fn is_identity(t: &Transform, neutral_only: bool) -> bool {
|
||||
const N: usize = 9;
|
||||
let s = (N - 1) as f32;
|
||||
let mut out = [0.0f32; 16];
|
||||
let mut check = |v: [f32; 3]| match t.eval(&v, &mut out) {
|
||||
Ok(()) => (0..3).all(|i| (out[i] - v[i]).abs() <= 0.5 / 255.0),
|
||||
Err(_) => false,
|
||||
};
|
||||
if neutral_only {
|
||||
return (0..=32).all(|i| check([i as f32 / 32.0; 3]));
|
||||
}
|
||||
(0..N).all(|b| (0..N).all(|g| (0..N).all(|r| check([r as f32 / s, g as f32 / s, b as f32 / s]))))
|
||||
}
|
||||
|
||||
/// `profile` as a monitor profile: it must be RGB and usable as the destination of a transform
|
||||
/// from sRGB, otherwise the canvas would silently stay unmanaged.
|
||||
fn usable_monitor(profile: Profile) -> Result<Arc<Profile>, MonitorProblem> {
|
||||
if profile.color_space != ColorSpace::Rgb {
|
||||
return Err(MonitorProblem::NotRgb { description: profile.description, space: profile.color_space });
|
||||
}
|
||||
let opts = TransformOptions { intent: DISPLAY_INTENT, bpc: true, ..TransformOptions::default() };
|
||||
cached(Builtin::Srgb.profile(), &profile, opts)
|
||||
.map_err(|e| MonitorProblem::CannotLink { description: profile.description.clone(), reason: e.to_string() })?;
|
||||
Ok(Arc::new(profile))
|
||||
}
|
||||
|
||||
fn srgb_entry(status: MonitorStatus) -> MonitorEntry {
|
||||
MonitorEntry { profile: Arc::new(Builtin::Srgb.profile().clone()), status }
|
||||
}
|
||||
|
||||
/// How one document profile shows on one monitor.
|
||||
#[derive(Debug)]
|
||||
pub struct DisplayTransform {
|
||||
/// The profile of the values the canvas texture holds (the document's composite profile).
|
||||
pub source: Arc<Profile>,
|
||||
/// The monitor profile.
|
||||
pub monitor: Arc<Profile>,
|
||||
/// Texture values to monitor values; `None` when that is the identity within half an 8-bit
|
||||
/// step on every lattice point (the neutral axis only for a grey source).
|
||||
pub transform: Option<Arc<Transform>>,
|
||||
/// Changes whenever any of the above changes, for the canvas's LUT and texture caches.
|
||||
pub key: u64,
|
||||
}
|
||||
|
||||
impl DisplayTransform {
|
||||
/// The transform from `source` to `monitor` ([`DISPLAY_INTENT`], BPC), built through
|
||||
/// `craft_cms::cached`; `transform` is `None` when it is the identity.
|
||||
// pc: crates/engine/src/display_color.rs:413 `canvas_display_for` (the build part) and :151
|
||||
// `is_identity` (9³ lattice, half an 8-bit step; the 33 grey steps for a grey source).
|
||||
pub fn new(source: Arc<Profile>, monitor: Arc<Profile>) -> Result<DisplayTransform, CmsError> {
|
||||
let key = signature(&source, &monitor);
|
||||
let transform = if source.content_hash() == monitor.content_hash() {
|
||||
None
|
||||
} else {
|
||||
let opts = TransformOptions { intent: DISPLAY_INTENT, bpc: true, ..TransformOptions::default() };
|
||||
let t = cached(&source, &monitor, opts)?;
|
||||
(!is_identity(&t, source.color_space == ColorSpace::Gray)).then_some(t)
|
||||
};
|
||||
Ok(DisplayTransform { source, monitor, transform, key })
|
||||
}
|
||||
|
||||
/// Values go to the screen unchanged.
|
||||
pub fn is_identity(&self) -> bool {
|
||||
self.transform.is_none()
|
||||
}
|
||||
|
||||
/// `rgb` (0–1 each, in the source profile) as the monitor shows it.
|
||||
// pc: crates/engine/src/display_color.rs:38 `CanvasDisplay` (callers use `transform.eval`).
|
||||
pub fn apply(&self, rgb: [f32; 3]) -> [f32; 3] {
|
||||
let Some(t) = &self.transform else { return rgb };
|
||||
let mut out = [0.0f32; 16];
|
||||
match t.eval(&rgb, &mut out) {
|
||||
Ok(()) => [out[0], out[1], out[2]],
|
||||
Err(_) => rgb,
|
||||
}
|
||||
}
|
||||
|
||||
/// RGBA8 pixels converted in place (alpha untouched); nothing happens for the identity.
|
||||
// new: the canvas's CPU path and the screen picker's loupe convert whole rows.
|
||||
pub fn apply_rgba8(&self, pixels: &mut [u8]) {
|
||||
let Some(t) = &self.transform else { return };
|
||||
// `convert_u8` reads and writes separate buffers: convert from a copy, a chunk at a time.
|
||||
let mut src = Vec::with_capacity(CHUNK_BYTES.min(pixels.len()));
|
||||
for chunk in pixels.chunks_mut(CHUNK_BYTES).map(|c| {
|
||||
let n = c.len() / 4 * 4;
|
||||
&mut c[..n]
|
||||
}) {
|
||||
src.clear();
|
||||
src.extend_from_slice(chunk);
|
||||
if t.convert_u8(&src, 4, chunk, 4, true).is_err() {
|
||||
chunk.copy_from_slice(&src);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Why the monitor profile is what it is.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum MonitorStatus {
|
||||
/// The display's own profile, as the platform reported it.
|
||||
Detected,
|
||||
/// The profile the app chose (Color Settings › Monitor Profile).
|
||||
Chosen,
|
||||
/// sRGB: the platform reports no profile for the display.
|
||||
NoProfile,
|
||||
/// sRGB: the profile could not be used, with the reason.
|
||||
Unusable(MonitorProblem),
|
||||
}
|
||||
|
||||
/// Why a monitor profile cannot be used. The UI words it (`MonitorProblem::label`, with the
|
||||
/// `ui` feature).
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum MonitorProblem {
|
||||
/// The profile describes another colour space than RGB.
|
||||
NotRgb {
|
||||
/// The profile's description text, for display.
|
||||
description: String,
|
||||
/// The colour space the profile declares.
|
||||
space: ColorSpace,
|
||||
},
|
||||
/// The profile cannot link to sRGB as a destination; `reason` is the colour engine's text.
|
||||
CannotLink {
|
||||
/// The profile's description text, for display.
|
||||
description: String,
|
||||
/// The colour engine's error text.
|
||||
reason: String,
|
||||
},
|
||||
/// The profile bytes do not parse; `reason` is the parser's text.
|
||||
Unreadable {
|
||||
/// The parser's error text.
|
||||
reason: String,
|
||||
},
|
||||
}
|
||||
|
||||
/// One monitor's profile and how it was resolved.
|
||||
#[derive(Clone, Debug)]
|
||||
struct MonitorEntry {
|
||||
profile: Arc<Profile>,
|
||||
status: MonitorStatus,
|
||||
}
|
||||
|
||||
/// The app's display caches: the monitor profile per display, and the [`DisplayTransform`] per
|
||||
/// document profile and display. Shared by every window; `Sync`.
|
||||
#[derive(Default)]
|
||||
pub struct DisplayCaches {
|
||||
monitors: Mutex<HashMap<DisplayId, MonitorEntry>>,
|
||||
chosen: Mutex<Option<MonitorEntry>>,
|
||||
transforms: Mutex<HashMap<(u64, DisplayId), Arc<DisplayTransform>>>,
|
||||
}
|
||||
|
||||
fn lock<T>(m: &Mutex<T>) -> std::sync::MutexGuard<'_, T> {
|
||||
m.lock().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
const _: () = {
|
||||
const fn shared<T: Send + Sync>() {}
|
||||
shared::<DisplayCaches>();
|
||||
};
|
||||
|
||||
impl DisplayCaches {
|
||||
/// Empty caches: no monitor profile and no transform yet.
|
||||
pub fn new() -> DisplayCaches {
|
||||
DisplayCaches::default()
|
||||
}
|
||||
|
||||
/// Records the platform's reading of `display`'s profile (`icc` bytes, `None` when it has
|
||||
/// none). A reading that fails to parse keeps the previous good one. Drops the cached
|
||||
/// transforms of that display.
|
||||
// pc: crates/engine/src/display_color.rs:301 (`set_displays`: a failed re-read keeps the
|
||||
// displays read before) and the monitor cache at :268.
|
||||
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) => {
|
||||
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() })));
|
||||
lock(&self.transforms).clear();
|
||||
}
|
||||
return;
|
||||
}
|
||||
},
|
||||
};
|
||||
lock(&self.monitors).insert(display, entry);
|
||||
// The main window's display also stands in for unknown displays.
|
||||
lock(&self.transforms).clear();
|
||||
}
|
||||
|
||||
/// The app's choice of monitor profile (Color Settings), or `None` to use each display's own.
|
||||
/// Drops every cached transform.
|
||||
// pc: crates/engine/src/display_color.rs:338 `resolved_monitor` (the `auto` / chosen branch).
|
||||
pub fn choose_monitor(&self, profile: Option<Arc<Profile>>) {
|
||||
let entry = profile.map(|p| match usable_monitor((*p).clone()) {
|
||||
Ok(profile) => MonitorEntry { profile, status: MonitorStatus::Chosen },
|
||||
Err(reason) => srgb_entry(MonitorStatus::Unusable(reason)),
|
||||
});
|
||||
*lock(&self.chosen) = entry;
|
||||
lock(&self.transforms).clear();
|
||||
}
|
||||
|
||||
/// The monitor profile for `display`: the chosen one, else the display's own, else the
|
||||
/// primary display's when `display` is unknown, else sRGB.
|
||||
// pc: crates/engine/src/display_color.rs:284 `monitor_for`, :338 `resolved_monitor`.
|
||||
pub fn monitor_for(&self, display: DisplayId) -> Arc<Profile> {
|
||||
self.resolve(display).profile
|
||||
}
|
||||
|
||||
/// What [`monitor_for`](Self::monitor_for) resolved to, and why.
|
||||
// pc: crates/engine/src/display_color.rs:294 `monitor_status_for`.
|
||||
pub fn monitor_status(&self, display: DisplayId) -> MonitorStatus {
|
||||
self.resolve(display).status
|
||||
}
|
||||
|
||||
fn resolve(&self, display: DisplayId) -> MonitorEntry {
|
||||
if let Some(e) = lock(&self.chosen).clone() {
|
||||
return e;
|
||||
}
|
||||
let monitors = lock(&self.monitors);
|
||||
monitors.get(&display).or_else(|| monitors.get(&None)).cloned().unwrap_or_else(|| srgb_entry(MonitorStatus::NoProfile))
|
||||
}
|
||||
|
||||
/// How a canvas in `source`'s profile shows on `display`, cached per source content and
|
||||
/// display.
|
||||
// pc: crates/engine/src/display_color.rs:413 `canvas_display_for`.
|
||||
pub fn canvas_display_for(&self, source: &Arc<Profile>, display: DisplayId) -> Result<Arc<DisplayTransform>, CmsError> {
|
||||
let monitor = self.monitor_for(display);
|
||||
let cache_key = (source.content_hash(), display);
|
||||
if let Some(d) = lock(&self.transforms).get(&cache_key)
|
||||
&& d.monitor.content_hash() == monitor.content_hash()
|
||||
{
|
||||
return Ok(d.clone());
|
||||
}
|
||||
let d = Arc::new(DisplayTransform::new(source.clone(), monitor)?);
|
||||
let mut cache = lock(&self.transforms);
|
||||
if cache.len() >= MAX_TRANSFORMS {
|
||||
cache.clear();
|
||||
}
|
||||
cache.insert(cache_key, d.clone());
|
||||
Ok(d)
|
||||
}
|
||||
|
||||
/// Changes whenever the transform of `source` on `display` changes (source, monitor, chosen
|
||||
/// profile): what a canvas compares to know its texture or LUT is stale.
|
||||
// pc: crates/engine/src/display_color.rs:453 `display_signature_for` (without Proof Colors,
|
||||
// Gamut Warning and the 32-bit preview: those are the app's and go into its own key).
|
||||
pub fn display_signature(&self, source: &Profile, display: DisplayId) -> u64 {
|
||||
signature(source, &self.monitor_for(display))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use craft_ui::testing::trial;
|
||||
|
||||
fn p3() -> Arc<Profile> {
|
||||
Arc::new(Builtin::DisplayP3.profile().clone())
|
||||
}
|
||||
|
||||
fn srgb() -> Arc<Profile> {
|
||||
Arc::new(Builtin::Srgb.profile().clone())
|
||||
}
|
||||
|
||||
/// Choosing another monitor profile changes the signature and drops the cached transform.
|
||||
#[trial]
|
||||
fn choosing_a_monitor_profile_changes_the_signature() {
|
||||
let caches = DisplayCaches::new();
|
||||
let source = srgb();
|
||||
let before = caches.display_signature(&source, None);
|
||||
let first = caches.canvas_display_for(&source, None).unwrap();
|
||||
assert!(Arc::ptr_eq(&first, &caches.canvas_display_for(&source, None).unwrap()));
|
||||
|
||||
caches.choose_monitor(Some(p3()));
|
||||
assert_eq!(caches.monitor_status(None), MonitorStatus::Chosen);
|
||||
assert_ne!(caches.display_signature(&source, None), before);
|
||||
let second = caches.canvas_display_for(&source, None).unwrap();
|
||||
assert!(!Arc::ptr_eq(&first, &second));
|
||||
assert_eq!(second.key, caches.display_signature(&source, None));
|
||||
|
||||
caches.choose_monitor(None);
|
||||
assert_eq!(caches.display_signature(&source, None), before);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
//! [`GrayModel`]: the grey level of a colour.
|
||||
|
||||
use craft_theme::{Channel, ColorModel, DefaultOn, MAX_CHANNELS, ModelValues, Srgba};
|
||||
|
||||
/// Grayscale, as Photoshop's Color panel Grayscale Slider: one channel, K, the black ink in
|
||||
/// percent (0 white, 100 black). A colour reads as the luma of its encoded sRGB values (Rec. 601
|
||||
/// weights); K converts back to the equal grey. Offered in no picker unless the host asks.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct GrayModel;
|
||||
|
||||
const GRAY_CHANNELS: [Channel; 1] =
|
||||
[Channel { name: "Gray", qualified: "Grayscale gray", label: "K", min: 0.0, max: 100.0, unit: "%", decimals: 0, step: 1.0, track_stops: 2 }];
|
||||
|
||||
impl ColorModel for GrayModel {
|
||||
fn id(&self) -> &'static str {
|
||||
"gray"
|
||||
}
|
||||
fn name(&self) -> &'static str {
|
||||
"Grayscale"
|
||||
}
|
||||
fn channels(&self) -> &[Channel] {
|
||||
&GRAY_CHANNELS
|
||||
}
|
||||
fn from_srgb(&self, color: Srgba) -> ModelValues {
|
||||
let luma = 0.299 * color.r + 0.587 * color.g + 0.114 * color.b;
|
||||
ModelValues::new(self.id(), &[(1.0 - luma) * 100.0])
|
||||
}
|
||||
fn to_srgb(&self, values: &[f32; MAX_CHANNELS]) -> Srgba {
|
||||
let level = 1.0 - values[0] / 100.0;
|
||||
Srgba::rgb(level, level, level)
|
||||
}
|
||||
fn default_on(&self) -> DefaultOn {
|
||||
DefaultOn { full: false, compact: false }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,385 @@
|
||||
//! Colour harmonies (F04.16): groups of colours built from a base colour by turning its hue and
|
||||
//! scaling its saturation and brightness, the variation grid round each, and five-colour themes.
|
||||
//! VectorCraft's Color Guide and Color Themes math, on encoded sRGB through HSB.
|
||||
//!
|
||||
//! ```no_run
|
||||
//! use craft_color::harmony::{Guide, GuideOptions, Harmony};
|
||||
//! use craft_theme::Srgba;
|
||||
//! let base = Srgba::rgb(0.24, 0.39, 0.87);
|
||||
//! let triad = Harmony::Triad.apply(base); // base first, then two partners
|
||||
//! let guide = Guide::new(base, Harmony::Triad, &GuideOptions::default());
|
||||
//! ```
|
||||
|
||||
use craft_theme::{Hsb, Srgba};
|
||||
|
||||
/// A harmony rule: a group of colours built from a base colour, base first. VectorCraft's 21
|
||||
/// rules, in its menu order ([`Harmony::ALL`]).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Harmony {
|
||||
#[default]
|
||||
#[allow(missing_docs)]
|
||||
Complementary,
|
||||
#[allow(missing_docs)]
|
||||
Complementary2,
|
||||
#[allow(missing_docs)]
|
||||
SplitComplementary,
|
||||
#[allow(missing_docs)]
|
||||
LeftComplement,
|
||||
#[allow(missing_docs)]
|
||||
RightComplement,
|
||||
#[allow(missing_docs)]
|
||||
Analogous,
|
||||
#[allow(missing_docs)]
|
||||
Analogous2,
|
||||
#[allow(missing_docs)]
|
||||
Monochromatic,
|
||||
#[allow(missing_docs)]
|
||||
Shades,
|
||||
#[allow(missing_docs)]
|
||||
Triad,
|
||||
#[allow(missing_docs)]
|
||||
Triad2,
|
||||
#[allow(missing_docs)]
|
||||
Triad3,
|
||||
#[allow(missing_docs)]
|
||||
Tetrad,
|
||||
#[allow(missing_docs)]
|
||||
Tetrad2,
|
||||
#[allow(missing_docs)]
|
||||
Tetrad3,
|
||||
#[allow(missing_docs)]
|
||||
Compound,
|
||||
#[allow(missing_docs)]
|
||||
Compound2,
|
||||
#[allow(missing_docs)]
|
||||
HighContrast,
|
||||
#[allow(missing_docs)]
|
||||
HighContrast2,
|
||||
#[allow(missing_docs)]
|
||||
HighContrast3,
|
||||
#[allow(missing_docs)]
|
||||
Pentagram,
|
||||
}
|
||||
|
||||
/// One colour of a rule: the base turned by `turn` degrees of hue, its saturation scaled by `sat`
|
||||
/// and its brightness scaled or flipped to the contrasting one.
|
||||
#[derive(Clone, Copy)]
|
||||
struct Tone {
|
||||
turn: f32,
|
||||
sat: f32,
|
||||
bright: Bright,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
enum Bright {
|
||||
Times(f32),
|
||||
/// Dark for a light base, light for a dark one ([`contrast`]).
|
||||
Contrast,
|
||||
}
|
||||
|
||||
const fn sv(turn: f32, sat: f32, bright: f32) -> Tone {
|
||||
Tone { turn, sat, bright: Bright::Times(bright) }
|
||||
}
|
||||
/// The base's hue turned by `turn`.
|
||||
const fn t(turn: f32) -> Tone {
|
||||
sv(turn, 1.0, 1.0)
|
||||
}
|
||||
/// A softer (half as saturated) partner.
|
||||
const fn soft(turn: f32) -> Tone {
|
||||
sv(turn, 0.5, 1.0)
|
||||
}
|
||||
/// A deeper (darker) partner.
|
||||
const fn deep(turn: f32) -> Tone {
|
||||
sv(turn, 1.0, 0.6)
|
||||
}
|
||||
/// A partner of contrasting brightness.
|
||||
const fn hc(turn: f32) -> Tone {
|
||||
Tone { turn, sat: 1.0, bright: Bright::Contrast }
|
||||
}
|
||||
|
||||
/// The brightness that contrasts with `v`.
|
||||
fn contrast(v: f32) -> f32 {
|
||||
if v >= 0.5 { v * 0.3 } else { 0.7 + 0.3 * v }
|
||||
}
|
||||
|
||||
fn lab(c: Srgba) -> [f64; 3] {
|
||||
let l = c.to_lab();
|
||||
[l.l, l.a, l.b].map(f64::from)
|
||||
}
|
||||
|
||||
fn hsb(h: f32, s: f32, b: f32) -> Srgba {
|
||||
Srgba::from_hsb(Hsb { h, s, b })
|
||||
}
|
||||
|
||||
impl Harmony {
|
||||
/// Every rule, in the menu's order.
|
||||
pub const ALL: [Harmony; 21] = [
|
||||
Harmony::Complementary,
|
||||
Harmony::Complementary2,
|
||||
Harmony::SplitComplementary,
|
||||
Harmony::LeftComplement,
|
||||
Harmony::RightComplement,
|
||||
Harmony::Analogous,
|
||||
Harmony::Analogous2,
|
||||
Harmony::Monochromatic,
|
||||
Harmony::Shades,
|
||||
Harmony::Triad,
|
||||
Harmony::Triad2,
|
||||
Harmony::Triad3,
|
||||
Harmony::Tetrad,
|
||||
Harmony::Tetrad2,
|
||||
Harmony::Tetrad3,
|
||||
Harmony::Compound,
|
||||
Harmony::Compound2,
|
||||
Harmony::HighContrast,
|
||||
Harmony::HighContrast2,
|
||||
Harmony::HighContrast3,
|
||||
Harmony::Pentagram,
|
||||
];
|
||||
|
||||
/// The rule's id, camelCase as its serialised name ("splitComplementary", "highContrast2"): the
|
||||
/// key of its name among the UI's words (`harmony.rule.<id>`).
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
Harmony::Complementary => "complementary",
|
||||
Harmony::Complementary2 => "complementary2",
|
||||
Harmony::SplitComplementary => "splitComplementary",
|
||||
Harmony::LeftComplement => "leftComplement",
|
||||
Harmony::RightComplement => "rightComplement",
|
||||
Harmony::Analogous => "analogous",
|
||||
Harmony::Analogous2 => "analogous2",
|
||||
Harmony::Monochromatic => "monochromatic",
|
||||
Harmony::Shades => "shades",
|
||||
Harmony::Triad => "triad",
|
||||
Harmony::Triad2 => "triad2",
|
||||
Harmony::Triad3 => "triad3",
|
||||
Harmony::Tetrad => "tetrad",
|
||||
Harmony::Tetrad2 => "tetrad2",
|
||||
Harmony::Tetrad3 => "tetrad3",
|
||||
Harmony::Compound => "compound",
|
||||
Harmony::Compound2 => "compound2",
|
||||
Harmony::HighContrast => "highContrast",
|
||||
Harmony::HighContrast2 => "highContrast2",
|
||||
Harmony::HighContrast3 => "highContrast3",
|
||||
Harmony::Pentagram => "pentagram",
|
||||
}
|
||||
}
|
||||
|
||||
/// The rule's colours, the base first. Each partner is the base with its hue turned, its
|
||||
/// saturation scaled and its brightness scaled or flipped to the contrasting one (dark for a
|
||||
/// light base, light for a dark one). Alpha is the base's.
|
||||
// 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 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)
|
||||
}))
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn tones(self) -> &'static [Tone] {
|
||||
match self {
|
||||
Harmony::Complementary => const { &[t(0.0), t(180.0)] },
|
||||
Harmony::Complementary2 => const { &[t(0.0), soft(0.0), t(180.0), soft(180.0)] },
|
||||
Harmony::SplitComplementary => const { &[t(0.0), t(150.0), t(210.0)] },
|
||||
Harmony::LeftComplement => const { &[t(0.0), t(-30.0), t(150.0)] },
|
||||
Harmony::RightComplement => const { &[t(0.0), t(30.0), t(210.0)] },
|
||||
Harmony::Analogous => const { &[t(0.0), t(30.0), t(-30.0)] },
|
||||
Harmony::Analogous2 => const { &[t(0.0), t(30.0), t(60.0), t(-30.0), t(-60.0)] },
|
||||
Harmony::Monochromatic => const { &[t(0.0), sv(0.0, 0.5, 1.0), sv(0.0, 1.0, 0.6), sv(0.0, 0.25, 1.0), sv(0.0, 1.0, 0.35)] },
|
||||
Harmony::Shades => const { &[t(0.0), sv(0.0, 1.0, 0.8), sv(0.0, 1.0, 0.6), sv(0.0, 1.0, 0.4), sv(0.0, 1.0, 0.2)] },
|
||||
Harmony::Triad => const { &[t(0.0), t(120.0), t(240.0)] },
|
||||
Harmony::Triad2 => const { &[t(0.0), t(120.0), soft(120.0), t(240.0), soft(240.0)] },
|
||||
Harmony::Triad3 => const { &[t(0.0), t(120.0), deep(120.0), t(240.0), deep(240.0)] },
|
||||
Harmony::Tetrad => const { &[t(0.0), t(60.0), t(180.0), t(240.0)] },
|
||||
Harmony::Tetrad2 => const { &[t(0.0), t(90.0), t(180.0), t(270.0)] },
|
||||
Harmony::Tetrad3 => const { &[t(0.0), t(30.0), t(180.0), t(210.0)] },
|
||||
Harmony::Compound => const { &[t(0.0), t(40.0), t(160.0), t(200.0)] },
|
||||
Harmony::Compound2 => const { &[t(0.0), t(-40.0), t(160.0), t(200.0)] },
|
||||
Harmony::HighContrast => const { &[t(0.0), hc(180.0)] },
|
||||
Harmony::HighContrast2 => const { &[t(0.0), hc(0.0), t(180.0), hc(180.0)] },
|
||||
Harmony::HighContrast3 => const { &[t(0.0), hc(120.0), hc(240.0)] },
|
||||
Harmony::Pentagram => const { &[t(0.0), t(72.0), t(144.0), t(216.0), t(288.0)] },
|
||||
}
|
||||
}
|
||||
|
||||
/// A [`THEME_SIZE`]-colour theme from `base`: the rule's colours, each followed by lighter or
|
||||
/// darker variations that fill the remaining places (the rule's first colours get them
|
||||
/// first), base first.
|
||||
// inv-vectorcraft: crates/color/src/harmony.rs:194 `theme`.
|
||||
pub fn theme(self, base: Srgba) -> Vec<Srgba> {
|
||||
let colors = self.apply(base);
|
||||
let n = colors.len();
|
||||
let mut rows: Vec<Vec<Srgba>> = colors.iter().map(|c| vec![*c]).collect();
|
||||
let options = GuideOptions::default();
|
||||
for k in 0..THEME_SIZE.saturating_sub(n) {
|
||||
let (i, pass) = (k % n, k / n);
|
||||
// Alternate lighter and darker along the rule and from one pass to the next.
|
||||
let step = if (i + pass) % 2 == 0 { 3 } else { -3 };
|
||||
rows[i].push(variation(colors[i], &options, step));
|
||||
}
|
||||
rows.into_iter().flatten().take(THEME_SIZE).collect()
|
||||
}
|
||||
}
|
||||
|
||||
/// The number of colours in a colour theme.
|
||||
pub const THEME_SIZE: usize = 5;
|
||||
|
||||
/// Moves colour `i` of a harmony on the hue and saturation wheel to `hsb` (hue in degrees,
|
||||
/// saturation and brightness 0–1). With `linked` the other colours keep their relation to it:
|
||||
/// they turn by the same hue, scale their saturation alike and shift their brightness by as
|
||||
/// much. An index past the end changes nothing.
|
||||
// inv-vectorcraft: crates/color/src/harmony.rs:216 `move_on_wheel`.
|
||||
pub fn move_on_wheel(colors: &mut [Srgba], i: usize, target: [f32; 3], linked: bool) {
|
||||
let Some(&old) = colors.get(i) else { return };
|
||||
let Hsb { h: h0, s: s0, b: v0 } = old.to_hsb();
|
||||
let (dh, ratio, dv) = (target[0] - h0, if s0 > 0.01 { target[1] / s0 } else { 1.0 }, target[2] - v0);
|
||||
for (j, c) in colors.iter_mut().enumerate() {
|
||||
let new = if j == i {
|
||||
target
|
||||
} else if linked {
|
||||
let Hsb { h, s, b } = c.to_hsb();
|
||||
[h + dh, (s * ratio).clamp(0.0, 1.0), (b + dv).clamp(0.0, 1.0)]
|
||||
} else {
|
||||
continue;
|
||||
};
|
||||
*c = hsb(new[0], new[1], new[2]).with_alpha(c.a);
|
||||
}
|
||||
}
|
||||
|
||||
/// What the variation grid varies.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Variation {
|
||||
/// Towards black (left) and white (right): Show Tints/Shades.
|
||||
#[default]
|
||||
TintsShades,
|
||||
/// Towards cool and warm: Show Warm/Cool.
|
||||
WarmCool,
|
||||
/// Towards grey and full saturation: Show Vivid/Muted.
|
||||
VividMuted,
|
||||
}
|
||||
|
||||
impl Variation {
|
||||
/// The three variations in menu order.
|
||||
pub const ALL: [Variation; 3] = [Variation::TintsShades, Variation::WarmCool, Variation::VividMuted];
|
||||
|
||||
/// The grid's ends, English (words keys): ("Shades", "Tints"), ("Cool", "Warm"),
|
||||
/// ("Muted", "Vivid").
|
||||
pub fn sides(self) -> (&'static str, &'static str) {
|
||||
match self {
|
||||
Variation::TintsShades => ("Shades", "Tints"),
|
||||
Variation::WarmCool => ("Cool", "Warm"),
|
||||
Variation::VividMuted => ("Muted", "Vivid"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The variation grid's options: what it varies, steps on each side and how far they reach.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct GuideOptions {
|
||||
/// Which axis the grid varies along.
|
||||
pub variation: Variation,
|
||||
/// Variations on each side of a harmony colour, 1 to [`GuideOptions::MAX_STEPS`].
|
||||
pub steps: u32,
|
||||
/// How far the outermost variations go, 0–100 (Less … More): 10 % to 90 % of the way.
|
||||
pub amount: f32,
|
||||
}
|
||||
|
||||
impl Default for GuideOptions {
|
||||
fn default() -> Self {
|
||||
GuideOptions { variation: Variation::TintsShades, steps: 4, amount: 50.0 }
|
||||
}
|
||||
}
|
||||
|
||||
impl GuideOptions {
|
||||
/// Largest accepted value of `steps`.
|
||||
pub const MAX_STEPS: u32 = 20;
|
||||
|
||||
/// The options with `steps` and `amount` in their ranges.
|
||||
pub fn clamped(self) -> GuideOptions {
|
||||
GuideOptions { steps: self.steps.clamp(1, Self::MAX_STEPS), amount: self.amount.clamp(0.0, 100.0), ..self }
|
||||
}
|
||||
}
|
||||
|
||||
/// The variation of `color` at `step` (−steps to +steps; negative towards shades, cool or muted,
|
||||
/// positive towards tints, warm or vivid; 0 is `color`).
|
||||
// inv-vectorcraft: crates/color/src/harmony.rs:299 `variation`, :292 `reach`.
|
||||
pub fn variation(color: Srgba, options: &GuideOptions, step: i32) -> Srgba {
|
||||
if step == 0 {
|
||||
return color;
|
||||
}
|
||||
let reach = 0.1 + 0.8 * options.amount.clamp(0.0, 100.0) / 100.0;
|
||||
let f = (step.unsigned_abs() as f32 / options.steps.max(1) as f32).min(1.0) * reach;
|
||||
let lerp = |to: Srgba, t: f32| Srgba::rgb(color.r + (to.r - color.r) * t, color.g + (to.g - color.g) * t, color.b + (to.b - color.b) * t);
|
||||
let v = match options.variation {
|
||||
Variation::TintsShades => lerp(if step < 0 { Srgba::BLACK } else { Srgba::WHITE }, f),
|
||||
Variation::WarmCool => lerp(if step < 0 { Srgba::rgb(0.2, 0.45, 1.0) } else { Srgba::rgb(1.0, 0.55, 0.1) }, f * 0.6),
|
||||
Variation::VividMuted => {
|
||||
let Hsb { h, s, b } = color.to_hsb();
|
||||
let s2 = if step < 0 { s * (1.0 - f) } else { s + (1.0 - s) * f };
|
||||
hsb(h, s2.clamp(0.0, 1.0), b)
|
||||
}
|
||||
};
|
||||
v.with_alpha(color.a)
|
||||
}
|
||||
|
||||
/// The Color Guide for a base colour: the harmony colours and, per colour, its row of variations
|
||||
/// from −steps to +steps, the colour itself in the centre column.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct Guide {
|
||||
/// The harmony colours, base first.
|
||||
pub colors: Vec<Srgba>,
|
||||
/// One row per harmony colour, each with `2 * steps + 1` variations from shades to tints.
|
||||
pub grid: Vec<Vec<Srgba>>,
|
||||
}
|
||||
|
||||
impl Guide {
|
||||
// inv-vectorcraft: crates/color/src/harmony.rs:328 `Guide::new`.
|
||||
/// Builds the guide for `base` under `rule`; `options` is clamped first.
|
||||
pub fn new(base: Srgba, rule: Harmony, options: &GuideOptions) -> Guide {
|
||||
let options = options.clamped();
|
||||
let n = options.steps as i32;
|
||||
let colors = rule.apply(base);
|
||||
let grid = colors.iter().map(|c| (-n..=n).map(|step| variation(*c, &options, step)).collect()).collect();
|
||||
Guide { colors, grid }
|
||||
}
|
||||
|
||||
/// The index of the centre column (the harmony colours) in each row.
|
||||
pub fn centre(&self) -> usize {
|
||||
self.grid.first().map_or(0, |row| row.len() / 2)
|
||||
}
|
||||
|
||||
/// The guide with every colour moved to the nearest of `palette` (Limit to Library; ΔE2000
|
||||
/// in Lab), the centre column too. An empty palette changes nothing.
|
||||
// inv-vectorcraft: crates/color/src/harmony.rs:342 `limited`.
|
||||
pub fn limited(mut self, palette: &[Srgba]) -> Guide {
|
||||
if palette.is_empty() {
|
||||
return self;
|
||||
}
|
||||
let labs: Vec<[f64; 3]> = palette.iter().map(|c| lab(*c)).collect();
|
||||
let nearest = |c: Srgba| {
|
||||
let l = lab(c);
|
||||
let best =
|
||||
(0..palette.len()).min_by(|&a, &b| craft_cms::math::delta_e2000(labs[a], l).total_cmp(&craft_cms::math::delta_e2000(labs[b], l)));
|
||||
best.map_or(c, |i| palette[i])
|
||||
};
|
||||
let centre = self.centre();
|
||||
for (row, c) in self.grid.iter_mut().zip(&mut self.colors) {
|
||||
for v in row.iter_mut() {
|
||||
*v = nearest(*v);
|
||||
}
|
||||
// The centre column is the harmony colour itself.
|
||||
*c = row[centre];
|
||||
}
|
||||
self
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
//! Colour for Craft apps: the colour picker, wells, swatch tables, ramps and the hex field.
|
||||
//!
|
||||
//! The widgets are behind the `ui` feature; the colour model and conversions are in `craft-theme`.
|
||||
//! Without `ui`, the crate has the helpers that need no egui: [`AreaMode`], [`GrayModel`],
|
||||
//! [`CmykModel`], web-safe colours ([`web_safe`], [`not_web_safe`]), swatch files ([`palette`]), the display transform ([`display`]) and colour
|
||||
//! harmonies ([`harmony`]).
|
||||
//! [`AreaMode`] (and `ui::RampKind`) serialize as their [`key`](AreaMode::key); the swatch and harmony settings types serialize too.
|
||||
|
||||
mod cmyk;
|
||||
pub mod display;
|
||||
mod gray;
|
||||
pub mod harmony;
|
||||
mod mode;
|
||||
pub mod palette;
|
||||
#[cfg(feature = "ui")]
|
||||
pub mod ui;
|
||||
mod web;
|
||||
|
||||
pub use cmyk::CmykModel;
|
||||
pub use gray::GrayModel;
|
||||
pub use mode::AreaMode;
|
||||
pub use web::{not_web_safe, web_safe};
|
||||
|
||||
#[cfg(all(test, feature = "screen-testing"))]
|
||||
extern crate self as craft_color;
|
||||
#[cfg(all(test, feature = "screen-testing"))]
|
||||
#[path = "../tests/it/main.rs"]
|
||||
mod integration;
|
||||
|
||||
#[cfg(test)]
|
||||
fn main() {
|
||||
craft_ui::testing::run(module_path!(), env!("CARGO_PKG_NAME"), &craft_ui::testing::registered_in(env!("CARGO_PKG_NAME")));
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
//! [`AreaMode`]: what a colour area and its strip show.
|
||||
|
||||
#[cfg(feature = "ui")]
|
||||
use craft_theme::ModelValues;
|
||||
use craft_theme::{ColorModel, HsbModel, LabModel, OklchModel, RgbModel};
|
||||
|
||||
/// What the area and the strip show: the strip's component and the area's two, across (growing to
|
||||
/// the right) and down (growing upwards). The nine modes of PhotoCraft's Color Picker, with
|
||||
/// Photoshop's axes, and three for OKLCH laid out as the HSB ones.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
pub enum AreaMode {
|
||||
/// Hue in the strip; saturation across, brightness down (HSB).
|
||||
#[default]
|
||||
#[serde(rename = "h")]
|
||||
Hue,
|
||||
/// Saturation in the strip; hue across, brightness down (HSB).
|
||||
#[serde(rename = "s")]
|
||||
Saturation,
|
||||
/// Brightness in the strip; hue across, saturation down (HSB).
|
||||
#[serde(rename = "v")]
|
||||
Brightness,
|
||||
/// Red in the strip; blue across, green down (RGB).
|
||||
#[serde(rename = "r")]
|
||||
Red,
|
||||
/// Green in the strip; blue across, red down (RGB).
|
||||
#[serde(rename = "g")]
|
||||
Green,
|
||||
/// Blue in the strip; red across, green down (RGB).
|
||||
#[serde(rename = "b")]
|
||||
Blue,
|
||||
/// Lab lightness in the strip; a across, b down.
|
||||
#[serde(rename = "lab_l")]
|
||||
LabL,
|
||||
/// Lab a in the strip; b across, lightness down.
|
||||
#[serde(rename = "lab_a")]
|
||||
LabA,
|
||||
/// Lab b in the strip; a across, lightness down.
|
||||
#[serde(rename = "lab_b")]
|
||||
LabB,
|
||||
/// OKLCH lightness in the strip; hue across, chroma down.
|
||||
#[serde(rename = "oklch_l")]
|
||||
OklchL,
|
||||
/// OKLCH chroma in the strip; hue across, lightness down.
|
||||
#[serde(rename = "oklch_c")]
|
||||
OklchC,
|
||||
/// OKLCH hue in the strip; chroma across, lightness down.
|
||||
#[serde(rename = "oklch_h")]
|
||||
OklchH,
|
||||
}
|
||||
|
||||
impl AreaMode {
|
||||
/// PhotoCraft's nine modes, in its radio order: H, S, B, R, G, B, L, a, b.
|
||||
pub const PHOTOSHOP: [AreaMode; 9] = [
|
||||
AreaMode::Hue,
|
||||
AreaMode::Saturation,
|
||||
AreaMode::Brightness,
|
||||
AreaMode::Red,
|
||||
AreaMode::Green,
|
||||
AreaMode::Blue,
|
||||
AreaMode::LabL,
|
||||
AreaMode::LabA,
|
||||
AreaMode::LabB,
|
||||
];
|
||||
|
||||
/// The OKLCH modes: L, C, H.
|
||||
pub const OKLCH: [AreaMode; 3] = [AreaMode::OklchL, AreaMode::OklchC, AreaMode::OklchH];
|
||||
|
||||
/// Every mode: PhotoCraft's nine, then OKLCH's three.
|
||||
pub const ALL: [AreaMode; 12] = [
|
||||
AreaMode::Hue,
|
||||
AreaMode::Saturation,
|
||||
AreaMode::Brightness,
|
||||
AreaMode::Red,
|
||||
AreaMode::Green,
|
||||
AreaMode::Blue,
|
||||
AreaMode::LabL,
|
||||
AreaMode::LabA,
|
||||
AreaMode::LabB,
|
||||
AreaMode::OklchL,
|
||||
AreaMode::OklchC,
|
||||
AreaMode::OklchH,
|
||||
];
|
||||
|
||||
/// The mode's key, as PhotoCraft stores it: `"h"`, `"s"`, `"v"` (brightness), `"r"`, `"g"`,
|
||||
/// `"b"`, `"lab_l"`, `"lab_a"`, `"lab_b"`, and `"oklch_l"`, `"oklch_c"`, `"oklch_h"`.
|
||||
pub fn key(self) -> &'static str {
|
||||
match self {
|
||||
AreaMode::Hue => "h",
|
||||
AreaMode::Saturation => "s",
|
||||
AreaMode::Brightness => "v",
|
||||
AreaMode::Red => "r",
|
||||
AreaMode::Green => "g",
|
||||
AreaMode::Blue => "b",
|
||||
AreaMode::LabL => "lab_l",
|
||||
AreaMode::LabA => "lab_a",
|
||||
AreaMode::LabB => "lab_b",
|
||||
AreaMode::OklchL => "oklch_l",
|
||||
AreaMode::OklchC => "oklch_c",
|
||||
AreaMode::OklchH => "oklch_h",
|
||||
}
|
||||
}
|
||||
|
||||
/// The mode with `key` ([`key`](AreaMode::key)); `None` for any other text.
|
||||
pub fn from_key(key: &str) -> Option<AreaMode> {
|
||||
AreaMode::ALL.into_iter().find(|mode| mode.key() == key)
|
||||
}
|
||||
|
||||
/// The area's accessible name, English, its two components across and down: the key a host
|
||||
/// translates ("Saturation and brightness").
|
||||
pub fn name(self) -> &'static str {
|
||||
match self {
|
||||
AreaMode::Hue => "Saturation and brightness",
|
||||
AreaMode::Saturation => "Hue and brightness",
|
||||
AreaMode::Brightness => "Hue and saturation",
|
||||
AreaMode::Red => "Blue and green",
|
||||
AreaMode::Green => "Blue and red",
|
||||
AreaMode::Blue => "Red and green",
|
||||
AreaMode::LabL => "Green-red and blue-yellow",
|
||||
AreaMode::LabA => "Blue-yellow and lightness",
|
||||
AreaMode::LabB => "Green-red and lightness",
|
||||
AreaMode::OklchL => "Hue and chroma",
|
||||
AreaMode::OklchC => "Hue and lightness",
|
||||
AreaMode::OklchH => "Chroma and lightness",
|
||||
}
|
||||
}
|
||||
|
||||
/// The model whose values the area and strip edit.
|
||||
pub fn model(self) -> &'static dyn ColorModel {
|
||||
match self {
|
||||
AreaMode::Hue | AreaMode::Saturation | AreaMode::Brightness => &HsbModel,
|
||||
AreaMode::Red | AreaMode::Green | AreaMode::Blue => &RgbModel,
|
||||
AreaMode::LabL | AreaMode::LabA | AreaMode::LabB => &LabModel,
|
||||
AreaMode::OklchL | AreaMode::OklchC | AreaMode::OklchH => &OklchModel,
|
||||
}
|
||||
}
|
||||
|
||||
/// The strip's channel, an index into the model's channels.
|
||||
pub fn strip(self) -> usize {
|
||||
match self {
|
||||
AreaMode::Hue | AreaMode::Red | AreaMode::LabL | AreaMode::OklchL => 0,
|
||||
AreaMode::Saturation | AreaMode::Green | AreaMode::LabA | AreaMode::OklchC => 1,
|
||||
AreaMode::Brightness | AreaMode::Blue | AreaMode::LabB | AreaMode::OklchH => 2,
|
||||
}
|
||||
}
|
||||
|
||||
/// The area's channels, across and down.
|
||||
pub fn area(self) -> [usize; 2] {
|
||||
match self {
|
||||
AreaMode::Hue => [1, 2],
|
||||
AreaMode::Saturation => [0, 2],
|
||||
AreaMode::Brightness => [0, 1],
|
||||
AreaMode::Red => [2, 1],
|
||||
AreaMode::Green => [2, 0],
|
||||
AreaMode::Blue => [0, 1],
|
||||
AreaMode::LabL => [1, 2],
|
||||
AreaMode::LabA => [2, 0],
|
||||
AreaMode::LabB => [1, 0],
|
||||
AreaMode::OklchL => [2, 1],
|
||||
AreaMode::OklchC => [2, 0],
|
||||
AreaMode::OklchH => [1, 0],
|
||||
}
|
||||
}
|
||||
|
||||
/// The values the strip's colours are drawn with: the colour's own, except that the HSB hue
|
||||
/// strip shows pure hues (full saturation and brightness), as Photoshop's.
|
||||
#[cfg(feature = "ui")]
|
||||
pub(crate) fn strip_base(self, values: &ModelValues) -> ModelValues {
|
||||
let mut base = *values;
|
||||
if self == AreaMode::Hue {
|
||||
base.values[1] = 100.0;
|
||||
base.values[2] = 100.0;
|
||||
}
|
||||
base
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,492 @@
|
||||
//! Swatch files (F04.14): Photoshop's `.aco` swatches and `.act` colour tables, swatch exchange
|
||||
//! `.ase` files, GIMP `.gpl` palettes and CSS custom properties, read into [`SwatchGroup`]s of
|
||||
//! [`SwatchEntry`]s and written back.
|
||||
//!
|
||||
//! Each colour stays in its own model ([`SwatchColor`]): a CMYK swatch keeps its inks and a Lab
|
||||
//! swatch its values through a read and a write. What a format cannot hold is reported, not
|
||||
//! dropped silently ([`SwatchReport`]).
|
||||
//!
|
||||
//! ```no_run
|
||||
//! use craft_color::palette::{SwatchFormat, read_swatches, write_swatches};
|
||||
//! # let bytes: Vec<u8> = Vec::new();
|
||||
//! let (groups, report) = read_swatches(&bytes, "Brand.ase")?;
|
||||
//! let (aco, report) = write_swatches(&groups, SwatchFormat::Aco)?;
|
||||
//! # Ok::<(), craft_color::palette::SwatchError>(())
|
||||
//! ```
|
||||
|
||||
use craft_cms::convert::CmykConverter;
|
||||
use craft_theme::{Hsb, Lab, Srgba};
|
||||
|
||||
/// A swatch file format.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum SwatchFormat {
|
||||
/// Photoshop swatches (`.aco`, binary, versions 1 and 2): RGB, HSB, CMYK, Lab and grey
|
||||
/// colours with names, no groups. Colour-book colours are kept as they are.
|
||||
Aco,
|
||||
/// Photoshop colour table (`.act`, 768 bytes of RGB plus an optional count and transparent
|
||||
/// index): 8-bit RGB, no names. Recognised by its file name only: the bytes have no
|
||||
/// signature.
|
||||
Act,
|
||||
/// Adobe swatch exchange (`.ase`, binary): RGB, CMYK, Lab and grey colours, global, spot or
|
||||
/// process, in groups.
|
||||
Ase,
|
||||
/// GIMP palette (`.gpl`, text): 8-bit RGB with names; groups as `# Group:` comment headers
|
||||
/// (VectorCraft's convention).
|
||||
Gpl,
|
||||
/// CSS custom properties on `:root` (`--brand-blue: #3e63dd;`), one comment per group.
|
||||
/// Written only.
|
||||
Css,
|
||||
}
|
||||
|
||||
impl SwatchFormat {
|
||||
/// Every format, in the Export menu's order.
|
||||
pub const ALL: [SwatchFormat; 5] = [SwatchFormat::Aco, SwatchFormat::Act, SwatchFormat::Ase, SwatchFormat::Gpl, SwatchFormat::Css];
|
||||
|
||||
/// The file extension, without the dot.
|
||||
pub fn extension(self) -> &'static str {
|
||||
match self {
|
||||
SwatchFormat::Aco => "aco",
|
||||
SwatchFormat::Act => "act",
|
||||
SwatchFormat::Ase => "ase",
|
||||
SwatchFormat::Gpl => "gpl",
|
||||
SwatchFormat::Css => "css",
|
||||
}
|
||||
}
|
||||
|
||||
/// The format a file name's extension names (case-insensitive), if any.
|
||||
// pc: crates/engine/src/cmd/swatch_cmds.rs:377 `Format::parse`, :394 `ext_format`.
|
||||
pub fn from_name(file_name: &str) -> Option<SwatchFormat> {
|
||||
let extension = std::path::Path::new(file_name).extension()?.to_str()?.to_ascii_lowercase();
|
||||
SwatchFormat::ALL.into_iter().find(|f| f.extension() == extension)
|
||||
}
|
||||
|
||||
/// Whether [`read_swatches`] reads the format (every one but CSS).
|
||||
pub fn can_read(self) -> bool {
|
||||
self != SwatchFormat::Css
|
||||
}
|
||||
|
||||
/// The format of `bytes`: the `ASEF` signature, `GIMP Palette` on the first line, an `.aco`
|
||||
/// version header that parses; `.act` only by `file_name` (768 or 772 bytes).
|
||||
// inv-vectorcraft: crates/color/src/palette_io.rs:346 `sniff`, :365 `sniff_bytes`; pc:
|
||||
// crates/engine/src/cmd/swatch_cmds.rs:394 `ext_format` for the name fallback.
|
||||
pub fn sniff(bytes: &[u8], file_name: &str) -> Option<SwatchFormat> {
|
||||
let by_name = SwatchFormat::from_name(file_name);
|
||||
let act_length = bytes.len() == ACT_PALETTE_LEN || bytes.len() == ACT_PALETTE_LEN + ACT_TRAILER_LEN;
|
||||
if act_length && by_name == Some(SwatchFormat::Act) {
|
||||
return Some(SwatchFormat::Act);
|
||||
}
|
||||
if bytes.starts_with(ASE_SIGNATURE) {
|
||||
return Some(SwatchFormat::Ase);
|
||||
}
|
||||
if is_gpl(bytes) {
|
||||
return Some(SwatchFormat::Gpl);
|
||||
}
|
||||
// An `.act` whose first colour is `0, 1, x` starts like an `.aco`: at `.act` lengths the
|
||||
// header counts only when its sections fill the file exactly.
|
||||
if matches!(bytes.get(..2), Some([0, 1] | [0, 2]))
|
||||
&& let Ok((_, len)) = parse_aco(bytes)
|
||||
&& (!act_length || len == bytes.len())
|
||||
{
|
||||
return Some(SwatchFormat::Aco);
|
||||
}
|
||||
by_name
|
||||
}
|
||||
}
|
||||
|
||||
/// A swatch colour in its own model.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(tag = "model", content = "values", rename_all = "camelCase")]
|
||||
pub enum SwatchColor {
|
||||
/// Encoded RGB, 0–1 each, in the RGB working space.
|
||||
Rgb([f32; 3]),
|
||||
/// Hue 0–360°, saturation and brightness 0–1 (a view of an RGB colour).
|
||||
Hsb([f32; 3]),
|
||||
/// Cyan, magenta, yellow and black ink, 0–1 each, in the CMYK working space.
|
||||
Cmyk([f32; 4]),
|
||||
/// L* 0–100, a*, b* (D50).
|
||||
Lab([f32; 3]),
|
||||
/// Black ink 0–1 (0 white), as Photoshop's K.
|
||||
Gray(f32),
|
||||
/// A colour space this crate does not model (colour-book colours in an `.aco` file), kept
|
||||
/// as stored so it survives a round trip. Shows as black.
|
||||
Book {
|
||||
/// The colour-book space id stored in the file.
|
||||
space: u16,
|
||||
/// The four stored channel values, untouched.
|
||||
values: [u16; 4],
|
||||
},
|
||||
}
|
||||
|
||||
impl SwatchColor {
|
||||
/// The colour as encoded sRGB for drawing: CMYK through `cmyk` (the document's converter),
|
||||
/// Lab through D50, HSB and grey directly; a [`Book`](SwatchColor::Book) colour is black.
|
||||
// pc: crates/ui-egui/src/panels/swatches_ui.rs:40 (`conv.rgb(&s.color)` per swatch).
|
||||
pub fn to_srgb(&self, cmyk: &CmykConverter) -> Srgba {
|
||||
match *self {
|
||||
SwatchColor::Rgb(v) => Srgba::from_rgb_array(v.map(unit)),
|
||||
SwatchColor::Hsb(v) => Srgba::from_rgb_array(hsb_to_rgb(v)),
|
||||
SwatchColor::Cmyk(v) => Srgba::from_rgb_array(cmyk.to_srgb(v.map(unit)).map(unit)),
|
||||
SwatchColor::Lab([l, a, b]) => {
|
||||
let (l, a, b) = (finite(l), finite(a), finite(b));
|
||||
// ICC v4 Lab encoding (the Lab D50 profile's device values).
|
||||
let encoded = [unit(l / 100.0), unit((a + 128.0) / 255.0), unit((b + 128.0) / 255.0)];
|
||||
match profile_to_srgb(&working_transforms().lab, &encoded) {
|
||||
Some(rgb) => Srgba::from_rgb_array(rgb),
|
||||
None => Srgba::from_lab(Lab { l, a, b }),
|
||||
}
|
||||
}
|
||||
SwatchColor::Gray(k) => {
|
||||
let level = 1.0 - unit(k);
|
||||
Srgba::from_rgb_array(profile_to_srgb(&working_transforms().gray, &[level]).unwrap_or([level; 3]))
|
||||
}
|
||||
SwatchColor::Book { .. } => Srgba::rgb(0.0, 0.0, 0.0),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// How an `.ase` file marks a colour.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum SwatchKind {
|
||||
#[default]
|
||||
#[allow(missing_docs)]
|
||||
Process,
|
||||
#[allow(missing_docs)]
|
||||
Global,
|
||||
#[allow(missing_docs)]
|
||||
Spot,
|
||||
}
|
||||
|
||||
/// One named swatch.
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct SwatchEntry {
|
||||
/// The swatch's label.
|
||||
pub name: String,
|
||||
/// The swatch's colour.
|
||||
pub color: SwatchColor,
|
||||
#[serde(default)]
|
||||
/// How the file marks the colour; `Process` unless the file says otherwise.
|
||||
pub kind: SwatchKind,
|
||||
}
|
||||
|
||||
impl SwatchEntry {
|
||||
/// A process swatch.
|
||||
pub fn new(name: impl Into<String>, color: SwatchColor) -> SwatchEntry {
|
||||
SwatchEntry { name: name.into(), color, kind: SwatchKind::Process }
|
||||
}
|
||||
}
|
||||
|
||||
/// A named group of swatches, as the Swatches panel shows them. A file without groups reads as
|
||||
/// one group named after the file.
|
||||
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
pub struct SwatchGroup {
|
||||
/// The group's label.
|
||||
pub name: String,
|
||||
/// The group's swatches in display order.
|
||||
pub entries: Vec<SwatchEntry>,
|
||||
}
|
||||
|
||||
/// What a read or a write could not keep. Each item is a sentence the app can show; the
|
||||
/// variants let it word them itself.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct SwatchReport {
|
||||
/// What was dropped or changed, in the order it was found.
|
||||
pub notes: Vec<SwatchNote>,
|
||||
}
|
||||
|
||||
/// One thing a read or a write could not keep.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum SwatchNote {
|
||||
/// Colour-book colours (`.aco` colours in a space this crate does not model) read as black,
|
||||
/// or left out of a format that cannot hold them, with their count.
|
||||
BookColors(usize),
|
||||
/// `.ase` colours in a colour model this crate does not read were skipped, with their count.
|
||||
Skipped(usize),
|
||||
/// The format has no groups: the swatches were written as one list.
|
||||
GroupsFlattened,
|
||||
/// The format has only 8-bit RGB: CMYK, Lab and grey colours were converted, with their count.
|
||||
ConvertedToRgb(usize),
|
||||
/// The format has no spot or global colours: they were written as process colours, with their
|
||||
/// count.
|
||||
KindsDropped(usize),
|
||||
/// `.act` holds at most 256 colours: the rest were left out, with their count.
|
||||
Truncated(usize),
|
||||
/// Names were cut to what the format holds (`.ase`: 1024 UTF-16 units).
|
||||
NamesCut(usize),
|
||||
}
|
||||
|
||||
/// Why a swatch file could not be read or written.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum SwatchError {
|
||||
/// Neither the content nor the name says what the file is.
|
||||
UnknownFormat,
|
||||
/// The format is write-only (CSS).
|
||||
CannotRead(SwatchFormat),
|
||||
/// The file is cut short or malformed, with the parser's message.
|
||||
Malformed(SwatchFormat, String),
|
||||
/// Nothing to write (no swatches in any group).
|
||||
Empty,
|
||||
}
|
||||
|
||||
impl std::fmt::Display for SwatchError {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
SwatchError::UnknownFormat => f.write_str("not a swatch file"),
|
||||
SwatchError::CannotRead(format) => write!(f, ".{} files can be written, not read", format.extension()),
|
||||
SwatchError::Malformed(format, message) => write!(f, "not a readable .{} file: {message}", format.extension()),
|
||||
SwatchError::Empty => f.write_str("there are no swatches to write"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for SwatchError {}
|
||||
|
||||
/// Reads a swatch file: the format from the content ([`SwatchFormat::sniff`]), `.act` from
|
||||
/// `file_name`. Ungrouped colours go into a group named after the file (its stem); a swatch
|
||||
/// without a name is "Swatch N". Names are cut to one line.
|
||||
// pc: crates/engine/src/cmd/swatch_cmds.rs:491 `read_file` (`.aco`, `.act`, `.ase` with
|
||||
// :406 `from_aco`, :435 `from_ase`), crates/psd/src/aco.rs:150 `parse`, crates/psd/src/ase.rs:180
|
||||
// `parse`, crates/psd/src/act.rs:46 `parse`; inv-vectorcraft: crates/color/src/palette_io.rs:376
|
||||
// `read_gpl`. The binary parsers move here (craft-color has no psd crate).
|
||||
pub fn read_swatches(bytes: &[u8], file_name: &str) -> Result<(Vec<SwatchGroup>, SwatchReport), SwatchError> {
|
||||
let format = SwatchFormat::sniff(bytes, file_name).ok_or(SwatchError::UnknownFormat)?;
|
||||
let stem = stem_of(file_name);
|
||||
let mut report = SwatchReport::default();
|
||||
let mut groups: Vec<SwatchGroup> = Vec::new();
|
||||
match format {
|
||||
SwatchFormat::Css => return Err(SwatchError::CannotRead(format)),
|
||||
SwatchFormat::Aco => {
|
||||
let (swatches, _) = parse_aco(bytes).map_err(|e| malformed(format, e))?;
|
||||
let books = swatches.iter().filter(|(_, c)| matches!(c, AcoColor::Other { .. })).count();
|
||||
push_note(&mut report, books, SwatchNote::BookColors);
|
||||
let entries =
|
||||
swatches.into_iter().enumerate().map(|(i, (name, color))| SwatchEntry::new(entry_name(i, &name), from_aco(color))).collect();
|
||||
groups.push(SwatchGroup { name: stem, entries });
|
||||
}
|
||||
SwatchFormat::Act => {
|
||||
let used = act_used(bytes).map_err(|e| malformed(format, e))?;
|
||||
let entries = used
|
||||
.iter()
|
||||
.enumerate()
|
||||
.map(|(i, c)| SwatchEntry::new(format!("Swatch {}", i + 1), SwatchColor::Rgb(c.map(|v| f32::from(v) / 255.0))))
|
||||
.collect();
|
||||
groups.push(SwatchGroup { name: stem, entries });
|
||||
}
|
||||
SwatchFormat::Ase => {
|
||||
let items = parse_ase(bytes).map_err(|e| malformed(format, e))?;
|
||||
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 });
|
||||
skipped += usize::from(entry.is_none());
|
||||
entry
|
||||
};
|
||||
let mut loose = Vec::new();
|
||||
for item in &items {
|
||||
match item {
|
||||
AseItem::Swatch(s) => loose.extend(convert(s)),
|
||||
AseItem::Group(name, swatches) => {
|
||||
let entries = swatches.iter().filter_map(&mut convert).collect();
|
||||
let name = clip_name(name);
|
||||
groups.push(SwatchGroup { name: if name.is_empty() { stem.clone() } else { name }, entries });
|
||||
}
|
||||
}
|
||||
}
|
||||
if !loose.is_empty() || groups.is_empty() {
|
||||
groups.insert(0, SwatchGroup { name: stem, entries: loose });
|
||||
}
|
||||
push_note(&mut report, skipped, SwatchNote::Skipped);
|
||||
}
|
||||
SwatchFormat::Gpl => groups = read_gpl(bytes, file_name),
|
||||
}
|
||||
if count_swatches(&groups) == 0 {
|
||||
return Err(malformed(format, "the file holds no swatches"));
|
||||
}
|
||||
Ok((groups, report))
|
||||
}
|
||||
|
||||
/// Writes `groups` as `format`, with what the format could not hold.
|
||||
// pc: crates/engine/src/cmd/swatch_cmds.rs:566 `write_file` (`.aco` with :418 `to_aco`, `.ase`
|
||||
// with :447 `to_ase`, `.act`), crates/psd/src/aco.rs:201 `write` (version 1 then 2),
|
||||
// crates/psd/src/act.rs:63 `write`; inv-vectorcraft: crates/color/src/palette_io.rs:128
|
||||
// `write_gpl`, :182 `write_css` with :148 `css_property`.
|
||||
pub fn write_swatches(groups: &[SwatchGroup], format: SwatchFormat) -> Result<(Vec<u8>, SwatchReport), SwatchError> {
|
||||
if count_swatches(groups) == 0 {
|
||||
return Err(SwatchError::Empty);
|
||||
}
|
||||
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 flattened = groups.len() > 1;
|
||||
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();
|
||||
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))
|
||||
}
|
||||
SwatchFormat::Act => {
|
||||
let (colors, books, converted) = rgb_colors(groups);
|
||||
let mut triplets: Vec<[u8; 3]> = colors.iter().flatten().map(|(_, c, _)| *c).collect();
|
||||
if triplets.is_empty() {
|
||||
return Err(SwatchError::Empty);
|
||||
}
|
||||
let left_out = triplets.len().saturating_sub(ACT_COLORS);
|
||||
triplets.truncate(ACT_COLORS);
|
||||
if flattened {
|
||||
report.notes.push(SwatchNote::GroupsFlattened);
|
||||
}
|
||||
push_note(&mut report, books, SwatchNote::BookColors);
|
||||
push_note(&mut report, converted, SwatchNote::ConvertedToRgb);
|
||||
push_note(&mut report, kinds, SwatchNote::KindsDropped);
|
||||
push_note(&mut report, left_out, SwatchNote::Truncated);
|
||||
let mut out: Vec<u8> = triplets.iter().flatten().copied().collect();
|
||||
out.resize(ACT_PALETTE_LEN, 0);
|
||||
out.extend((triplets.len() as u16).to_be_bytes());
|
||||
out.extend(0xFFFFu16.to_be_bytes());
|
||||
Ok((out, report))
|
||||
}
|
||||
SwatchFormat::Ase => {
|
||||
if count_swatches(groups) > ASE_MAX_SWATCHES || groups.len() > ASE_MAX_GROUPS {
|
||||
return Err(malformed(format, "too many swatches or groups for an .ase file"));
|
||||
}
|
||||
let mut body = Vec::new();
|
||||
let (mut blocks, mut books) = (0u32, 0usize);
|
||||
for g in groups {
|
||||
let mut name = Vec::new();
|
||||
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) {
|
||||
Some(color) => {
|
||||
put_ase_color(&mut body, &e.name, &color, e.kind);
|
||||
blocks += 1;
|
||||
}
|
||||
None => books += 1,
|
||||
}
|
||||
}
|
||||
put_ase_block(&mut body, ASE_GROUP_END, &[]);
|
||||
}
|
||||
push_note(&mut report, books, SwatchNote::BookColors);
|
||||
push_note(&mut report, names_cut(groups, true), SwatchNote::NamesCut);
|
||||
let mut out = Vec::with_capacity(12 + body.len());
|
||||
out.extend(ASE_SIGNATURE);
|
||||
out.extend(1u16.to_be_bytes());
|
||||
out.extend(0u16.to_be_bytes());
|
||||
out.extend(blocks.to_be_bytes());
|
||||
out.extend(body);
|
||||
Ok((out, report))
|
||||
}
|
||||
SwatchFormat::Gpl | SwatchFormat::Css => {
|
||||
let (colors, books, converted) = rgb_colors(groups);
|
||||
push_note(&mut report, books, SwatchNote::BookColors);
|
||||
push_note(&mut report, converted, SwatchNote::ConvertedToRgb);
|
||||
let text = if format == SwatchFormat::Gpl {
|
||||
push_note(&mut report, kinds, SwatchNote::KindsDropped);
|
||||
let plain: Vec<Vec<(String, [u8; 3])>> = colors.iter().map(|l| l.iter().map(|(n, c, _)| (n.clone(), *c)).collect()).collect();
|
||||
write_gpl(groups, &plain)
|
||||
} else {
|
||||
write_css(groups, &colors)
|
||||
};
|
||||
Ok((text.into_bytes(), report))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// PhotoCraft's default swatches (46 RGB colours in five groups: Grays, the exact RGB primaries
|
||||
/// and secondaries, Pastel, Pure and Dark hues), what Reset Swatches restores.
|
||||
// pc: crates/engine/src/presets/swatches.rs:294 `builtin`.
|
||||
pub fn default_swatches() -> Vec<SwatchGroup> {
|
||||
let rgb = |name: &str, c: [u8; 3]| SwatchEntry::new(name, SwatchColor::Rgb(c.map(|v| f32::from(v) / 255.0)));
|
||||
let grays = [
|
||||
("Black", 0),
|
||||
("90% Gray", 26),
|
||||
("80% Gray", 51),
|
||||
("70% Gray", 77),
|
||||
("60% Gray", 102),
|
||||
("50% Gray", 128),
|
||||
("40% Gray", 153),
|
||||
("30% Gray", 179),
|
||||
("20% Gray", 204),
|
||||
("White", 255),
|
||||
];
|
||||
let hues = ["Red", "Orange", "Yellow", "Yellow Green", "Green", "Cyan Green", "Cyan", "Blue", "Violet", "Magenta"];
|
||||
let pastel: [[u8; 3]; 10] = [
|
||||
[236, 128, 128],
|
||||
[244, 176, 132],
|
||||
[250, 224, 128],
|
||||
[214, 240, 128],
|
||||
[150, 232, 150],
|
||||
[128, 232, 200],
|
||||
[128, 220, 240],
|
||||
[128, 176, 244],
|
||||
[168, 144, 244],
|
||||
[232, 144, 232],
|
||||
];
|
||||
let pure: [[u8; 3]; 10] = [
|
||||
[230, 40, 40],
|
||||
[245, 120, 30],
|
||||
[250, 210, 30],
|
||||
[160, 220, 40],
|
||||
[40, 200, 80],
|
||||
[30, 200, 170],
|
||||
[30, 170, 230],
|
||||
[40, 100, 230],
|
||||
[120, 70, 220],
|
||||
[210, 50, 180],
|
||||
];
|
||||
let dark: [[u8; 3]; 10] = [
|
||||
[120, 20, 20],
|
||||
[130, 60, 10],
|
||||
[130, 110, 10],
|
||||
[80, 120, 20],
|
||||
[20, 100, 40],
|
||||
[10, 100, 90],
|
||||
[10, 80, 120],
|
||||
[20, 50, 120],
|
||||
[60, 30, 110],
|
||||
[110, 20, 90],
|
||||
];
|
||||
let row = |prefix: &str, colors: [[u8; 3]; 10]| -> Vec<SwatchEntry> {
|
||||
hues.iter().zip(colors).map(|(hue, c)| rgb(&if prefix.is_empty() { (*hue).to_string() } else { format!("{prefix} {hue}") }, c)).collect()
|
||||
};
|
||||
// Photoshop's order: red, yellow, green, cyan, blue, magenta.
|
||||
let exact: [(&str, [u8; 3]); 6] = [
|
||||
("RGB Red", [255, 0, 0]),
|
||||
("RGB Yellow", [255, 255, 0]),
|
||||
("RGB Green", [0, 255, 0]),
|
||||
("RGB Cyan", [0, 255, 255]),
|
||||
("RGB Blue", [0, 0, 255]),
|
||||
("RGB Magenta", [255, 0, 255]),
|
||||
];
|
||||
let group = |name: &str, entries: Vec<SwatchEntry>| SwatchGroup { name: name.into(), entries };
|
||||
vec![
|
||||
group("Grays", grays.iter().map(|(n, v)| rgb(n, [*v; 3])).collect()),
|
||||
group("RGB", exact.iter().map(|(n, c)| rgb(n, *c)).collect()),
|
||||
group("Pastel", row("Pastel", pastel)),
|
||||
group("Pure", row("", pure)),
|
||||
group("Dark", row("Dark", dark)),
|
||||
]
|
||||
}
|
||||
|
||||
mod aco;
|
||||
mod ase;
|
||||
mod reader;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
mod text;
|
||||
|
||||
use aco::*;
|
||||
use ase::*;
|
||||
use reader::*;
|
||||
use text::*;
|
||||
@@ -0,0 +1,167 @@
|
||||
//! Photoshop `.aco` swatches and `.act` colour tables.
|
||||
|
||||
use super::reader::*;
|
||||
use super::*;
|
||||
|
||||
// ---------------------------------------------------------------- .aco
|
||||
|
||||
/// A colour record as stored, at 16 bits (CMYK as ink amounts).
|
||||
#[derive(Clone, Copy)]
|
||||
pub(super) enum AcoColor {
|
||||
Rgb([u16; 3]),
|
||||
Hsb([u16; 3]),
|
||||
Cmyk([u16; 4]),
|
||||
Lab { l: u16, a: i16, b: i16 },
|
||||
Gray(u16),
|
||||
Other { space: u16, values: [u16; 4] },
|
||||
}
|
||||
|
||||
const ACO_RGB: u16 = 0;
|
||||
const ACO_HSB: u16 = 1;
|
||||
const ACO_CMYK: u16 = 2;
|
||||
const ACO_LAB: u16 = 7;
|
||||
const ACO_GRAY: u16 = 8;
|
||||
|
||||
impl AcoColor {
|
||||
fn from_record(space: u16, v: [u16; 4]) -> AcoColor {
|
||||
match space {
|
||||
ACO_RGB => AcoColor::Rgb([v[0], v[1], v[2]]),
|
||||
ACO_HSB => AcoColor::Hsb([v[0], v[1], v[2]]),
|
||||
ACO_CMYK => AcoColor::Cmyk(v.map(|x| u16::MAX - x)),
|
||||
ACO_LAB => AcoColor::Lab { l: v[0], a: v[1] as i16, b: v[2] as i16 },
|
||||
ACO_GRAY => AcoColor::Gray(v[0]),
|
||||
_ => AcoColor::Other { space, values: v },
|
||||
}
|
||||
}
|
||||
|
||||
fn to_record(self) -> (u16, [u16; 4]) {
|
||||
match self {
|
||||
AcoColor::Rgb([r, g, b]) => (ACO_RGB, [r, g, b, 0]),
|
||||
AcoColor::Hsb([h, s, b]) => (ACO_HSB, [h, s, b, 0]),
|
||||
AcoColor::Cmyk(c) => (ACO_CMYK, c.map(|x| u16::MAX - x)),
|
||||
AcoColor::Lab { l, a, b } => (ACO_LAB, [l, a as u16, b as u16, 0]),
|
||||
AcoColor::Gray(g) => (ACO_GRAY, [g, 0, 0, 0]),
|
||||
AcoColor::Other { space, values } => (space, values),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn q16(v: f32) -> u16 {
|
||||
(unit(v) * 65535.0).round() as u16
|
||||
}
|
||||
|
||||
pub(super) fn from_aco(c: AcoColor) -> SwatchColor {
|
||||
let f = |v: u16| f32::from(v) / 65535.0;
|
||||
match c {
|
||||
AcoColor::Rgb(v) => SwatchColor::Rgb(v.map(f)),
|
||||
AcoColor::Hsb([h, sa, b]) => SwatchColor::Hsb([f(h) * 360.0, f(sa), f(b)]),
|
||||
AcoColor::Cmyk(v) => SwatchColor::Cmyk(v.map(f)),
|
||||
AcoColor::Lab { l, a, b } => SwatchColor::Lab([f32::from(l.min(10000)) / 100.0, f32::from(a) / 100.0, f32::from(b) / 100.0]),
|
||||
AcoColor::Gray(g) => SwatchColor::Gray(1.0 - f32::from(g.min(10000)) / 10000.0),
|
||||
AcoColor::Other { space, values } => SwatchColor::Book { space, values },
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn to_aco(c: &SwatchColor) -> AcoColor {
|
||||
match *c {
|
||||
SwatchColor::Rgb(v) => AcoColor::Rgb(v.map(q16)),
|
||||
SwatchColor::Hsb([h, sa, b]) => {
|
||||
let h = finite(h).rem_euclid(360.0);
|
||||
AcoColor::Hsb([((h / 360.0) * 65535.0).round().min(65535.0) as u16, q16(sa), q16(b)])
|
||||
}
|
||||
SwatchColor::Cmyk(v) => AcoColor::Cmyk(v.map(q16)),
|
||||
SwatchColor::Lab([l, a, b]) => {
|
||||
let ab = |v: f32| (finite(v) * 100.0).round().clamp(-12800.0, 12700.0) as i16;
|
||||
AcoColor::Lab { l: (finite(l) * 100.0).round().clamp(0.0, 10000.0) as u16, a: ab(a), b: ab(b) }
|
||||
}
|
||||
SwatchColor::Gray(k) => AcoColor::Gray(((1.0 - unit(k)) * 10000.0).round() as u16),
|
||||
SwatchColor::Book { space, values } => AcoColor::Other { space, values },
|
||||
}
|
||||
}
|
||||
|
||||
fn aco_record(r: &mut Reader<'_>) -> Result<AcoColor, String> {
|
||||
let space = r.u16()?;
|
||||
let v = [r.u16()?, r.u16()?, r.u16()?, r.u16()?];
|
||||
Ok(AcoColor::from_record(space, v))
|
||||
}
|
||||
|
||||
fn aco_section(r: &mut Reader<'_>, named: bool) -> Result<Vec<(String, AcoColor)>, String> {
|
||||
let count = usize::from(r.u16()?);
|
||||
r.check_count(count as u64, if named { 14 } else { 10 })?;
|
||||
let mut out = Vec::with_capacity(count);
|
||||
for _ in 0..count {
|
||||
let color = aco_record(r)?;
|
||||
let name = if named {
|
||||
let n = r.u32()?;
|
||||
r.units(usize::try_from(n).map_err(|_| "a name is too long".to_string())?)?
|
||||
} else {
|
||||
String::new()
|
||||
};
|
||||
out.push((name, color));
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// The swatches of an `.aco` file (version 2 names when the file has them) and how many bytes its
|
||||
/// sections span.
|
||||
pub(super) fn parse_aco(data: &[u8]) -> Result<(Vec<(String, AcoColor)>, usize), String> {
|
||||
let mut r = Reader::new(data);
|
||||
match r.u16()? {
|
||||
1 => {
|
||||
let v1 = aco_section(&mut r, false)?;
|
||||
// Files from Photoshop 6 on follow with a version 2 section; other trailing bytes are
|
||||
// padding.
|
||||
if r.remaining() >= 4 && data[r.pos..].get(..2) == Some(&[0, 2]) {
|
||||
r.u16()?;
|
||||
let v2 = aco_section(&mut r, true)?;
|
||||
return Ok((v2, r.pos));
|
||||
}
|
||||
Ok((v1, r.pos))
|
||||
}
|
||||
2 => {
|
||||
let v2 = aco_section(&mut r, true)?;
|
||||
Ok((v2, r.pos))
|
||||
}
|
||||
v => Err(format!("unsupported version {v}")),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn write_aco(entries: &[(String, AcoColor)]) -> Vec<u8> {
|
||||
let count = entries.len() as u16;
|
||||
let mut out = Vec::with_capacity(8 + entries.len() * 40);
|
||||
for version in [1u16, 2] {
|
||||
out.extend(version.to_be_bytes());
|
||||
out.extend(count.to_be_bytes());
|
||||
for (name, color) in entries {
|
||||
let (space, v) = color.to_record();
|
||||
out.extend(space.to_be_bytes());
|
||||
for x in v {
|
||||
out.extend(x.to_be_bytes());
|
||||
}
|
||||
if version == 2 {
|
||||
let units = utf16_units(name, MAX_NAME_UNITS);
|
||||
// The length counts the terminating null.
|
||||
out.extend((units.len() as u32 + 1).to_be_bytes());
|
||||
for u in units {
|
||||
out.extend(u.to_be_bytes());
|
||||
}
|
||||
out.extend(0u16.to_be_bytes());
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- .act
|
||||
|
||||
pub(super) fn act_used(data: &[u8]) -> Result<Vec<[u8; 3]>, String> {
|
||||
if data.len() != ACT_PALETTE_LEN && data.len() != ACT_PALETTE_LEN + ACT_TRAILER_LEN {
|
||||
return Err("an .act file is 768 bytes, or 772 with the count trailer".into());
|
||||
}
|
||||
let mut colors: Vec<[u8; 3]> = data[..ACT_PALETTE_LEN].as_chunks::<3>().0.to_vec();
|
||||
if data.len() > ACT_PALETTE_LEN {
|
||||
let count = usize::from(u16::from_be_bytes([data[ACT_PALETTE_LEN], data[ACT_PALETTE_LEN + 1]]));
|
||||
colors.truncate(count.min(ACT_COLORS));
|
||||
}
|
||||
Ok(colors)
|
||||
}
|
||||
@@ -0,0 +1,197 @@
|
||||
//! Adobe swatch exchange (`.ase`) files.
|
||||
|
||||
use super::reader::*;
|
||||
use super::*;
|
||||
|
||||
// ---------------------------------------------------------------- .ase
|
||||
|
||||
pub(super) fn from_ase(c: &AseColor) -> Option<SwatchColor> {
|
||||
Some(match *c {
|
||||
AseColor::Rgb(v) => SwatchColor::Rgb(v),
|
||||
AseColor::Cmyk(v) => SwatchColor::Cmyk(v),
|
||||
// L is stored as a fraction (L*/100); a few writers store L* itself, which can only be told
|
||||
// apart above 1.
|
||||
AseColor::Lab([l, a, b]) => SwatchColor::Lab([if l > 1.0 { l } else { l * 100.0 }, a, b]),
|
||||
AseColor::Gray(g) => SwatchColor::Gray(1.0 - g),
|
||||
AseColor::Other => return None,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn to_ase(c: &SwatchColor) -> Option<AseColor> {
|
||||
Some(match *c {
|
||||
SwatchColor::Rgb(v) => AseColor::Rgb(v),
|
||||
SwatchColor::Hsb(v) => AseColor::Rgb(hsb_to_rgb(v)),
|
||||
SwatchColor::Cmyk(v) => AseColor::Cmyk(v),
|
||||
SwatchColor::Lab([l, a, b]) => AseColor::Lab([l / 100.0, a, b]),
|
||||
SwatchColor::Gray(k) => AseColor::Gray(1.0 - k),
|
||||
SwatchColor::Book { .. } => return None,
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn hsb_to_rgb([h, s, b]: [f32; 3]) -> [f32; 3] {
|
||||
Srgba::from_hsb(Hsb { h: finite(h), s: unit(s), b: unit(b) }).to_rgb_array().map(unit)
|
||||
}
|
||||
|
||||
pub(super) enum AseColor {
|
||||
Rgb([f32; 3]),
|
||||
Cmyk([f32; 4]),
|
||||
Lab([f32; 3]),
|
||||
Gray(f32),
|
||||
/// A colour model this crate does not read.
|
||||
Other,
|
||||
}
|
||||
|
||||
pub(super) struct AseSwatch {
|
||||
pub(super) name: String,
|
||||
pub(super) color: AseColor,
|
||||
pub(super) kind: SwatchKind,
|
||||
}
|
||||
|
||||
pub(super) enum AseItem {
|
||||
Swatch(AseSwatch),
|
||||
Group(String, Vec<AseSwatch>),
|
||||
}
|
||||
|
||||
fn ase_name(r: &mut Reader<'_>) -> Result<String, String> {
|
||||
if r.remaining() == 0 {
|
||||
return Ok(String::new());
|
||||
}
|
||||
let n = usize::from(r.u16()?);
|
||||
r.units(n)
|
||||
}
|
||||
|
||||
fn ase_color(body: &mut Reader<'_>) -> Result<AseSwatch, String> {
|
||||
let name = ase_name(body)?;
|
||||
let model: [u8; 4] = body.array()?;
|
||||
let color = match &model {
|
||||
b"RGB " => AseColor::Rgb([body.f32()?, body.f32()?, body.f32()?]),
|
||||
b"CMYK" => AseColor::Cmyk([body.f32()?, body.f32()?, body.f32()?, body.f32()?]),
|
||||
b"LAB " => AseColor::Lab([body.f32()?, body.f32()?, body.f32()?]),
|
||||
b"Gray" => AseColor::Gray(body.f32()?),
|
||||
_ => {
|
||||
// Everything but the trailing colour type belongs to the unknown model.
|
||||
let n = body.remaining().saturating_sub(2);
|
||||
body.bytes(n)?;
|
||||
AseColor::Other
|
||||
}
|
||||
};
|
||||
// Some writers omit the colour type; it defaults to process.
|
||||
let kind = if body.remaining() >= 2 {
|
||||
match body.u16()? {
|
||||
0 => SwatchKind::Global,
|
||||
1 => SwatchKind::Spot,
|
||||
_ => SwatchKind::Process,
|
||||
}
|
||||
} else {
|
||||
SwatchKind::Process
|
||||
};
|
||||
Ok(AseSwatch { name, color, kind })
|
||||
}
|
||||
|
||||
pub(super) fn parse_ase(data: &[u8]) -> Result<Vec<AseItem>, String> {
|
||||
let mut r = Reader::new(data);
|
||||
let sig: [u8; 4] = r.array()?;
|
||||
if &sig != ASE_SIGNATURE {
|
||||
return Err("the ASEF signature is missing".into());
|
||||
}
|
||||
let major = r.u16()?;
|
||||
let _minor = r.u16()?;
|
||||
if major != 1 {
|
||||
return Err(format!("unsupported version {major}"));
|
||||
}
|
||||
let count = u64::from(r.u32()?);
|
||||
// Every block has at least a type and a length.
|
||||
r.check_count(count, 6)?;
|
||||
let mut items = Vec::new();
|
||||
let mut open: Option<(String, Vec<AseSwatch>)> = None;
|
||||
let (mut total, mut groups) = (0usize, 0usize);
|
||||
for _ in 0..count {
|
||||
let kind = r.u16()?;
|
||||
let len = usize::try_from(r.u32()?).map_err(|_| "a block is too long".to_string())?;
|
||||
let mut body = Reader::new(r.bytes(len)?);
|
||||
match kind {
|
||||
ASE_GROUP_START => {
|
||||
groups += 1;
|
||||
if groups > ASE_MAX_GROUPS {
|
||||
return Err("too many groups".into());
|
||||
}
|
||||
if let Some((name, swatches)) = open.take() {
|
||||
items.push(AseItem::Group(name, swatches));
|
||||
}
|
||||
open = Some((ase_name(&mut body)?, Vec::new()));
|
||||
}
|
||||
ASE_GROUP_END => {
|
||||
if let Some((name, swatches)) = open.take() {
|
||||
items.push(AseItem::Group(name, swatches));
|
||||
}
|
||||
}
|
||||
ASE_COLOR => {
|
||||
total += 1;
|
||||
if total > ASE_MAX_SWATCHES {
|
||||
return Err("too many swatches".into());
|
||||
}
|
||||
let s = ase_color(&mut body)?;
|
||||
match open.as_mut() {
|
||||
Some((_, v)) => v.push(s),
|
||||
None => items.push(AseItem::Swatch(s)),
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if let Some((name, swatches)) = open.take() {
|
||||
items.push(AseItem::Group(name, swatches));
|
||||
}
|
||||
Ok(items)
|
||||
}
|
||||
|
||||
pub(super) fn put_ase_name(out: &mut Vec<u8>, name: &str) {
|
||||
let units = utf16_units(name, MAX_NAME_UNITS);
|
||||
out.extend((units.len() as u16 + 1).to_be_bytes());
|
||||
for u in units {
|
||||
out.extend(u.to_be_bytes());
|
||||
}
|
||||
out.extend(0u16.to_be_bytes());
|
||||
}
|
||||
|
||||
pub(super) fn put_ase_block(out: &mut Vec<u8>, kind: u16, body: &[u8]) {
|
||||
out.extend(kind.to_be_bytes());
|
||||
out.extend((body.len() as u32).to_be_bytes());
|
||||
out.extend(body);
|
||||
}
|
||||
|
||||
pub(super) fn put_ase_color(out: &mut Vec<u8>, name: &str, color: &AseColor, kind: SwatchKind) {
|
||||
let mut b = Vec::with_capacity(64);
|
||||
put_ase_name(&mut b, name);
|
||||
let floats = |b: &mut Vec<u8>, v: &[f32]| {
|
||||
for x in v {
|
||||
b.extend(x.to_bits().to_be_bytes());
|
||||
}
|
||||
};
|
||||
match color {
|
||||
AseColor::Rgb(c) => {
|
||||
b.extend(b"RGB ");
|
||||
floats(&mut b, c);
|
||||
}
|
||||
AseColor::Cmyk(c) => {
|
||||
b.extend(b"CMYK");
|
||||
floats(&mut b, c);
|
||||
}
|
||||
AseColor::Lab(c) => {
|
||||
b.extend(b"LAB ");
|
||||
floats(&mut b, c);
|
||||
}
|
||||
AseColor::Gray(g) => {
|
||||
b.extend(b"Gray");
|
||||
floats(&mut b, &[*g]);
|
||||
}
|
||||
AseColor::Other => {}
|
||||
}
|
||||
let code: u16 = match kind {
|
||||
SwatchKind::Global => 0,
|
||||
SwatchKind::Spot => 1,
|
||||
SwatchKind::Process => 2,
|
||||
};
|
||||
b.extend(code.to_be_bytes());
|
||||
put_ase_block(out, ASE_COLOR, &b);
|
||||
}
|
||||
@@ -0,0 +1,189 @@
|
||||
//! Byte reader, name and count helpers and limits shared by the swatch codecs.
|
||||
|
||||
use super::*;
|
||||
|
||||
// ---------------------------------------------------------------- file helpers
|
||||
|
||||
/// Longest name in a binary swatch file, in UTF-16 code units.
|
||||
pub(super) const MAX_NAME_UNITS: usize = 1024;
|
||||
/// Longest swatch or group name kept from a file, in characters.
|
||||
const MAX_NAME_CHARS: usize = 255;
|
||||
pub(super) const GPL_HEADER: &str = "GIMP Palette";
|
||||
pub(super) const GPL_GROUP: &str = "# Group:";
|
||||
pub(super) const ASE_SIGNATURE: &[u8; 4] = b"ASEF";
|
||||
pub(super) const ASE_GROUP_START: u16 = 0xC001;
|
||||
pub(super) const ASE_GROUP_END: u16 = 0xC002;
|
||||
pub(super) const ASE_COLOR: u16 = 0x0001;
|
||||
pub(super) const ASE_MAX_SWATCHES: usize = 100_000;
|
||||
pub(super) const ASE_MAX_GROUPS: usize = 10_000;
|
||||
pub(super) const ACO_MAX_SWATCHES: usize = u16::MAX as usize;
|
||||
pub(super) const ACT_COLORS: usize = 256;
|
||||
pub(super) const ACT_PALETTE_LEN: usize = ACT_COLORS * 3;
|
||||
pub(super) const ACT_TRAILER_LEN: usize = 4;
|
||||
|
||||
/// Transforms from the Lab D50 and sGray profiles to sRGB (relative colorimetric, black point
|
||||
/// compensation); `None` when one does not link.
|
||||
pub(super) struct WorkingTransforms {
|
||||
pub(super) lab: Option<std::sync::Arc<craft_cms::Transform>>,
|
||||
pub(super) gray: Option<std::sync::Arc<craft_cms::Transform>>,
|
||||
}
|
||||
|
||||
pub(super) fn working_transforms() -> &'static WorkingTransforms {
|
||||
static TRANSFORMS: std::sync::OnceLock<WorkingTransforms> = std::sync::OnceLock::new();
|
||||
TRANSFORMS.get_or_init(|| {
|
||||
let opts = craft_cms::TransformOptions { intent: craft_cms::Intent::RelativeColorimetric, bpc: true, ..Default::default() };
|
||||
let srgb = craft_cms::Builtin::Srgb.profile();
|
||||
let link = |source: &craft_cms::Profile| craft_cms::cached(source, srgb, opts).ok();
|
||||
WorkingTransforms { lab: link(craft_cms::Builtin::LabD50.profile()), gray: link(craft_cms::Builtin::SGray.profile()) }
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn profile_to_srgb(transform: &Option<std::sync::Arc<craft_cms::Transform>>, input: &[f32]) -> Option<[f32; 3]> {
|
||||
let mut out = [0.0f32; 3];
|
||||
transform.as_ref()?.eval(input, &mut out).ok()?;
|
||||
Some(out.map(unit))
|
||||
}
|
||||
|
||||
pub(super) fn malformed(format: SwatchFormat, message: impl Into<String>) -> SwatchError {
|
||||
SwatchError::Malformed(format, message.into())
|
||||
}
|
||||
|
||||
pub(super) fn unit(v: f32) -> f32 {
|
||||
if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }
|
||||
}
|
||||
|
||||
pub(super) fn finite(v: f32) -> f32 {
|
||||
if v.is_finite() { v } else { 0.0 }
|
||||
}
|
||||
|
||||
/// One line of text, cut to the length a name may have.
|
||||
pub(super) fn clip_name(name: &str) -> String {
|
||||
let line = name.split(['\n', '\r', '\t']).collect::<Vec<_>>().join(" ");
|
||||
line.trim().chars().take(MAX_NAME_CHARS).collect()
|
||||
}
|
||||
|
||||
pub(super) fn entry_name(index: usize, name: &str) -> String {
|
||||
let name = clip_name(name);
|
||||
if name.is_empty() { format!("Swatch {}", index + 1) } else { name }
|
||||
}
|
||||
|
||||
/// The group name for ungrouped colours: the file's stem.
|
||||
pub(super) fn stem_of(file_name: &str) -> String {
|
||||
let stem = std::path::Path::new(file_name).file_stem().and_then(|s| s.to_str()).unwrap_or("");
|
||||
let stem = clip_name(stem);
|
||||
if stem.is_empty() { "Imported Swatches".into() } else { stem }
|
||||
}
|
||||
|
||||
pub(super) fn count_swatches(groups: &[SwatchGroup]) -> usize {
|
||||
groups.iter().map(|g| g.entries.len()).sum()
|
||||
}
|
||||
|
||||
/// Whole UTF-16 scalar values of `name` that fit in `max` units.
|
||||
pub(super) fn utf16_units(name: &str, max: usize) -> Vec<u16> {
|
||||
let mut units = Vec::new();
|
||||
for c in name.chars() {
|
||||
if units.len() + c.len_utf16() > max {
|
||||
break;
|
||||
}
|
||||
let mut buf = [0u16; 2];
|
||||
units.extend_from_slice(c.encode_utf16(&mut buf));
|
||||
}
|
||||
units
|
||||
}
|
||||
|
||||
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();
|
||||
swatches + if include_groups { groups.iter().filter(|g| cut(&g.name)).count() } else { 0 }
|
||||
}
|
||||
|
||||
/// A bounds-checked big-endian cursor.
|
||||
pub(super) struct Reader<'a> {
|
||||
data: &'a [u8],
|
||||
pub(super) pos: usize,
|
||||
}
|
||||
|
||||
impl<'a> Reader<'a> {
|
||||
pub(super) fn new(data: &'a [u8]) -> Self {
|
||||
Reader { data, pos: 0 }
|
||||
}
|
||||
pub(super) fn remaining(&self) -> usize {
|
||||
self.data.len() - self.pos
|
||||
}
|
||||
pub(super) fn bytes(&mut self, n: usize) -> Result<&'a [u8], String> {
|
||||
if n > self.remaining() {
|
||||
return Err(format!("the file is cut short at byte {}", self.pos));
|
||||
}
|
||||
let out = &self.data[self.pos..self.pos + n];
|
||||
self.pos += n;
|
||||
Ok(out)
|
||||
}
|
||||
pub(super) fn array<const N: usize>(&mut self) -> Result<[u8; N], String> {
|
||||
let mut out = [0u8; N];
|
||||
out.copy_from_slice(self.bytes(N)?);
|
||||
Ok(out)
|
||||
}
|
||||
pub(super) fn u16(&mut self) -> Result<u16, String> {
|
||||
Ok(u16::from_be_bytes(self.array()?))
|
||||
}
|
||||
pub(super) fn u32(&mut self) -> Result<u32, String> {
|
||||
Ok(u32::from_be_bytes(self.array()?))
|
||||
}
|
||||
pub(super) fn f32(&mut self) -> Result<f32, String> {
|
||||
Ok(finite(f32::from_bits(self.u32()?)))
|
||||
}
|
||||
/// Fails when `count` items of at least `min_size` bytes cannot fit in what is left.
|
||||
pub(super) fn check_count(&self, count: u64, min_size: u64) -> Result<(), String> {
|
||||
if count.saturating_mul(min_size) > self.remaining() as u64 { Err(format!("the file is cut short at byte {}", self.pos)) } else { Ok(()) }
|
||||
}
|
||||
/// A name of `n` UTF-16 units that include the trailing null; units past the limit are dropped.
|
||||
pub(super) fn units(&mut self, n: usize) -> Result<String, String> {
|
||||
self.check_count(n as u64, 2)?;
|
||||
let mut units = Vec::with_capacity(n.min(MAX_NAME_UNITS));
|
||||
for _ in 0..n {
|
||||
let u = self.u16()?;
|
||||
if units.len() < MAX_NAME_UNITS {
|
||||
units.push(u);
|
||||
}
|
||||
}
|
||||
while units.last() == Some(&0) {
|
||||
units.pop();
|
||||
}
|
||||
Ok(String::from_utf16_lossy(&units))
|
||||
}
|
||||
}
|
||||
|
||||
/// Name, 8-bit colour and whether it is a spot colour.
|
||||
pub(super) type RgbSwatch = (String, [u8; 3], bool);
|
||||
|
||||
/// The colours of a format that holds only 8-bit RGB: other models converted, colour-book colours
|
||||
/// left out. Returns the colours per group with the `BookColors` and `ConvertedToRgb` counts.
|
||||
pub(super) fn rgb_colors(groups: &[SwatchGroup]) -> (Vec<Vec<RgbSwatch>>, usize, usize) {
|
||||
let (mut books, mut converted) = (0, 0);
|
||||
let out = groups
|
||||
.iter()
|
||||
.map(|g| {
|
||||
g.entries
|
||||
.iter()
|
||||
.filter_map(|e| {
|
||||
match e.color {
|
||||
SwatchColor::Book { .. } => {
|
||||
books += 1;
|
||||
return None;
|
||||
}
|
||||
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))
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.collect();
|
||||
(out, books, converted)
|
||||
}
|
||||
|
||||
pub(super) fn push_note(report: &mut SwatchReport, count: usize, note: impl FnOnce(usize) -> SwatchNote) {
|
||||
if count > 0 {
|
||||
report.notes.push(note(count));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
//! Tests for the swatch file codecs.
|
||||
|
||||
use super::*;
|
||||
use craft_ui::testing::trial;
|
||||
|
||||
fn values(c: &SwatchColor) -> Vec<f32> {
|
||||
match *c {
|
||||
SwatchColor::Rgb(v) | SwatchColor::Hsb(v) | SwatchColor::Lab(v) => v.to_vec(),
|
||||
SwatchColor::Cmyk(v) => v.to_vec(),
|
||||
SwatchColor::Gray(k) => vec![k],
|
||||
SwatchColor::Book { .. } => Vec::new(),
|
||||
}
|
||||
}
|
||||
|
||||
fn assert_same(a: &SwatchColor, b: &SwatchColor) {
|
||||
assert_eq!(std::mem::discriminant(a), std::mem::discriminant(b), "{a:?} vs {b:?}");
|
||||
if let (SwatchColor::Book { .. }, SwatchColor::Book { .. }) = (a, b) {
|
||||
assert_eq!(a, b);
|
||||
}
|
||||
for (x, y) in values(a).into_iter().zip(values(b)) {
|
||||
assert!((x - y).abs() < 1e-3, "{a:?} vs {b:?}");
|
||||
}
|
||||
}
|
||||
|
||||
fn group(name: &str, entries: Vec<SwatchEntry>) -> SwatchGroup {
|
||||
SwatchGroup { name: name.into(), entries }
|
||||
}
|
||||
|
||||
/// An `.aco` file with RGB, CMYK and Lab swatches round-trips with each colour in its model.
|
||||
#[trial]
|
||||
fn aco_round_trips_colours_in_their_own_model() {
|
||||
let colors = [
|
||||
("Red", SwatchColor::Rgb([1.0, 0.0, 0.25])),
|
||||
("Hue", SwatchColor::Hsb([120.0, 0.5, 0.75])),
|
||||
("Cyan ink", SwatchColor::Cmyk([1.0, 0.0, 0.25, 0.1])),
|
||||
("Lab", SwatchColor::Lab([53.0, -80.0, 67.5])),
|
||||
("Gray", SwatchColor::Gray(0.4)),
|
||||
("Book 日本", SwatchColor::Book { space: 3, values: [1, 2, 3, 4] }),
|
||||
];
|
||||
let entries = colors.iter().map(|(n, c)| SwatchEntry::new(*n, *c)).collect();
|
||||
let (bytes, report) = write_swatches(&[group("All", entries)], SwatchFormat::Aco).unwrap();
|
||||
assert!(report.notes.is_empty(), "{report:?}");
|
||||
let (groups, report) = read_swatches(&bytes, "Brand.aco").unwrap();
|
||||
assert_eq!(report.notes, [SwatchNote::BookColors(1)]);
|
||||
assert_eq!(groups.len(), 1);
|
||||
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);
|
||||
}
|
||||
// A version 1 section comes first, then version 2 with the names.
|
||||
assert_eq!(&bytes[..4], &[0, 1, 0, 6]);
|
||||
assert!(bytes.windows(4).any(|w| w == [0, 2, 0, 6]));
|
||||
}
|
||||
|
||||
/// `.ase` keeps groups and spot colours; `.aco` flattens them and says so.
|
||||
#[trial]
|
||||
fn ase_keeps_groups_and_aco_reports_flattening() {
|
||||
let mut spot = SwatchEntry::new("Spot Orange", SwatchColor::Cmyk([0.0, 0.5, 1.0, 0.0]));
|
||||
spot.kind = SwatchKind::Spot;
|
||||
let groups = vec![
|
||||
group("Brand", vec![SwatchEntry::new("Blue", SwatchColor::Rgb([0.0, 0.0, 1.0])), spot]),
|
||||
group("Greys", vec![SwatchEntry::new("Mid", SwatchColor::Gray(0.5))]),
|
||||
];
|
||||
let (ase, report) = write_swatches(&groups, SwatchFormat::Ase).unwrap();
|
||||
assert!(report.notes.is_empty());
|
||||
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));
|
||||
|
||||
// A colour in a model this crate does not read is skipped and counted.
|
||||
let mut unknown = Vec::new();
|
||||
put_ase_name(&mut unknown, "Odd");
|
||||
unknown.extend(b"XYZ ");
|
||||
unknown.extend([0u8; 12]);
|
||||
unknown.extend(2u16.to_be_bytes());
|
||||
let mut file = ase.clone();
|
||||
put_ase_block(&mut file, ASE_COLOR, &unknown);
|
||||
file[8..12].copy_from_slice(&(u32::from_be_bytes(ase[8..12].try_into().unwrap()) + 1).to_be_bytes());
|
||||
let (skipped, report) = read_swatches(&file, "x.ase").unwrap();
|
||||
assert_eq!(report.notes, [SwatchNote::Skipped(1)]);
|
||||
assert_eq!(count_swatches(&skipped), 3);
|
||||
|
||||
let (aco, report) = write_swatches(&groups, SwatchFormat::Aco).unwrap();
|
||||
assert_eq!(report.notes, [SwatchNote::GroupsFlattened, SwatchNote::KindsDropped(1)]);
|
||||
let (flat, _) = read_swatches(&aco, "x.aco").unwrap();
|
||||
assert_eq!(flat.len(), 1);
|
||||
assert_eq!(flat[0].entries.len(), 3);
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
//! GIMP `.gpl` palettes and CSS custom properties.
|
||||
|
||||
use super::reader::*;
|
||||
use super::*;
|
||||
|
||||
// ---------------------------------------------------------------- .gpl and .css
|
||||
|
||||
fn one_line(s: &str) -> String {
|
||||
s.split(['\n', '\r', '\t']).collect::<Vec<_>>().join(" ").trim().to_string()
|
||||
}
|
||||
|
||||
pub(super) fn rgb8(c: [f32; 3]) -> [u8; 3] {
|
||||
c.map(|v| (unit(v) * 255.0).round() as u8)
|
||||
}
|
||||
|
||||
pub(super) fn read_gpl(bytes: &[u8], file_name: &str) -> Vec<SwatchGroup> {
|
||||
let text = String::from_utf8_lossy(bytes);
|
||||
let text = text.trim_start_matches('\u{feff}');
|
||||
let mut groups: Vec<SwatchGroup> = Vec::new();
|
||||
let mut seen = 0usize;
|
||||
let mut grouped = false;
|
||||
for line in text.lines().skip(1) {
|
||||
let line = line.trim();
|
||||
if let Some(g) = line.strip_prefix(GPL_GROUP) {
|
||||
let name = clip_name(g);
|
||||
groups.push(SwatchGroup { name: if name.is_empty() { "Color Group".into() } else { name }, entries: Vec::new() });
|
||||
grouped = true;
|
||||
continue;
|
||||
}
|
||||
let words: Vec<&str> = line.split_whitespace().collect();
|
||||
let rgb: Vec<u8> = words.iter().take(3).map_while(|v| v.parse().ok()).collect();
|
||||
let [r, g, b] = rgb[..] else { continue };
|
||||
let entry = SwatchEntry::new(entry_name(seen, &words[3..].join(" ")), SwatchColor::Rgb([r, g, b].map(|v| f32::from(v) / 255.0)));
|
||||
seen += 1;
|
||||
if !grouped && groups.is_empty() {
|
||||
groups.push(SwatchGroup { name: stem_of(file_name), entries: Vec::new() });
|
||||
}
|
||||
if let Some(group) = groups.last_mut() {
|
||||
group.entries.push(entry);
|
||||
}
|
||||
}
|
||||
groups
|
||||
}
|
||||
|
||||
pub(super) fn write_gpl(groups: &[SwatchGroup], colors: &[Vec<(String, [u8; 3])>]) -> String {
|
||||
let title = groups.first().map_or_else(String::new, |g| one_line(&g.name));
|
||||
let mut out = format!("{GPL_HEADER}\nName: {title}\nColumns: 0\n#\n");
|
||||
for (group, list) in groups.iter().zip(colors) {
|
||||
out.push_str(&format!("{GPL_GROUP} {}\n", one_line(&group.name)));
|
||||
for (name, [r, g, b]) in list {
|
||||
out.push_str(&format!("{r:3} {g:3} {b:3}\t{}\n", one_line(name)));
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `name` as a CSS custom property (`--` and an escaped identifier): lower case, spaces as
|
||||
/// hyphens, other characters an identifier can't hold escaped with a backslash.
|
||||
pub(super) fn css_property(name: &str) -> String {
|
||||
let mut out = String::from("--");
|
||||
for word in name.split_whitespace() {
|
||||
if out.len() > 2 {
|
||||
out.push('-');
|
||||
}
|
||||
for ch in word.chars().flat_map(char::to_lowercase) {
|
||||
if ch.is_ascii_alphanumeric() || ch == '-' || ch == '_' || !ch.is_ascii() {
|
||||
out.push(ch);
|
||||
} else if ch.is_ascii_graphic() {
|
||||
out.push('\\');
|
||||
out.push(ch);
|
||||
} else {
|
||||
out.push_str(&format!("\\{:x} ", ch as u32));
|
||||
}
|
||||
}
|
||||
}
|
||||
if out.len() == 2 {
|
||||
out.push_str("swatch");
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// A comment's text: `*/` can't end it early.
|
||||
fn css_comment(s: &str) -> String {
|
||||
one_line(s).replace("*/", "* /")
|
||||
}
|
||||
|
||||
pub(super) fn write_css(groups: &[SwatchGroup], colors: &[Vec<RgbSwatch>]) -> String {
|
||||
let mut out = String::from(":root {\n");
|
||||
let mut taken: std::collections::HashSet<String> = std::collections::HashSet::new();
|
||||
// The next number to try for each base, so repeated names don't search the ones used before.
|
||||
let mut next: std::collections::HashMap<String, usize> = std::collections::HashMap::new();
|
||||
for (group, list) in groups.iter().zip(colors) {
|
||||
out.push_str(&format!(" /* {} */\n", css_comment(&group.name)));
|
||||
for (name, [r, g, b], spot) in list {
|
||||
// Names differing only in case or punctuation map to one property: number the others.
|
||||
let base = css_property(name);
|
||||
let property = if taken.insert(base.clone()) {
|
||||
base
|
||||
} else {
|
||||
let n = next.entry(base.clone()).or_insert(1);
|
||||
loop {
|
||||
*n += 1;
|
||||
let candidate = format!("{base}-{n}");
|
||||
if taken.insert(candidate.clone()) {
|
||||
break candidate;
|
||||
}
|
||||
}
|
||||
};
|
||||
let note = if *spot { " /* spot */" } else { "" };
|
||||
out.push_str(&format!(" {property}: #{r:02x}{g:02x}{b:02x};{note}\n"));
|
||||
}
|
||||
}
|
||||
out.push_str("}\n");
|
||||
out
|
||||
}
|
||||
|
||||
/// Whether the head of `bytes` reads as a GIMP palette.
|
||||
pub(super) fn is_gpl(bytes: &[u8]) -> bool {
|
||||
let head = String::from_utf8_lossy(bytes.get(..1024).unwrap_or(bytes));
|
||||
head.trim_start_matches('\u{feff}').trim_start().starts_with(GPL_HEADER)
|
||||
}
|
||||
@@ -0,0 +1,208 @@
|
||||
//! [`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 crate::AreaMode;
|
||||
use craft_behavior::{Metrics, Mixed, Proposal, Sense};
|
||||
use craft_theme::ModelValues;
|
||||
use craft_ui::contract::{
|
||||
Access, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, MeasureCx, PaintUi, Props as _, Role, WordSetCx as _,
|
||||
};
|
||||
use craft_ui::primitives::ContentPainterCx;
|
||||
use craft_ui::runtime::env::Label;
|
||||
use craft_ui::style::{ComponentStyle, StyleCx};
|
||||
use craft_ui::value_drag::PointPicker;
|
||||
use egui::{Mesh, Rect, Vec2, pos2};
|
||||
|
||||
#[cfg(feature = "screen-testing")]
|
||||
mod stories;
|
||||
|
||||
/// Vertices along each side of the area's colour mesh (PhotoCraft's 32).
|
||||
const MESH: usize = 32;
|
||||
|
||||
/// 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 2D field of a colour picker: two components of the colour across and down, the others fixed, as an
|
||||
/// [`AreaMode`] lays them out (PhotoCraft's Color Picker field). It shows a `PointPicker` over the mode's two
|
||||
/// channels, with the colours of the field as the picker's backdrop, so pointer, keys, wheel and AccessKit are the
|
||||
/// picker's: a press jumps the point there, a drag follows the pointer (also outside the area, where the value stays
|
||||
/// at the edge), the arrow keys step the across and down components (Up raises the down one, Shift steps ten) and a
|
||||
/// step is the channel's (1 degree, 1 percent, 1 of 255, 0.001 of chroma).
|
||||
///
|
||||
/// The host gives the colour as the mode's model values and gets them back with only the area's two components
|
||||
/// changed, so a host that keeps the values it was sent keeps the hue of a grey and the hue and saturation of black.
|
||||
/// The area keeps its axes right to left: across still grows to the right. Its value text names both components
|
||||
/// ("Saturation 40 %, Brightness 70 %", from [`names`](ColorArea::names)).
|
||||
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
|
||||
pub struct ColorArea<'a> {
|
||||
#[common]
|
||||
common: Common,
|
||||
mode: AreaMode,
|
||||
values: Bind<'a, ModelValues>,
|
||||
/// Puts the colour the area reports on this many levels (at least two) per red, green and blue channel, whatever
|
||||
/// the mode: a web-safe field has 6. The pointer takes the nearest such colour and a key steps one level of the
|
||||
/// channel's range. The field shows flat cells of the snapped colours.
|
||||
#[prop]
|
||||
quantize: Option<usize>,
|
||||
/// The names of the across and down components in the value text; the model's channel names without them.
|
||||
#[prop]
|
||||
names: Option<[Label; 2]>,
|
||||
}
|
||||
|
||||
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 }.label(label).ltr_axis()
|
||||
}
|
||||
|
||||
/// The across and down channels of the mode's model.
|
||||
fn channels(&self) -> [usize; 2] {
|
||||
self.mode.area()
|
||||
}
|
||||
|
||||
fn levels(&self) -> Option<usize> {
|
||||
self.quantize.map(|levels| levels.max(2))
|
||||
}
|
||||
|
||||
/// The picker over `shown`, whose backdrop paints the field of `base`.
|
||||
fn picker<'c>(&self, shown: Option<&ModelValues>, field: bool) -> PointPicker<'c> {
|
||||
let model = self.mode.model();
|
||||
let [across, down] = self.channels();
|
||||
let base = shown.copied().unwrap_or_else(|| ModelValues::new(model.id(), &[]));
|
||||
let point = match shown {
|
||||
Some(values) => Mixed::each([values.values[across], values.values[down]].map(f64::from)),
|
||||
None => [Mixed::Mixed; 2],
|
||||
};
|
||||
let (x, y) = (channel_range(model, across), channel_range(model, down));
|
||||
let y = *y.end()..=*y.start();
|
||||
let steps = [across, down].map(|channel| match self.levels() {
|
||||
Some(levels) => {
|
||||
let range = channel_range(model, channel);
|
||||
(range.end() - range.start()) / (levels - 1) as f64
|
||||
}
|
||||
None => channel_step(model, channel),
|
||||
});
|
||||
let (mode, levels) = (self.mode, self.levels());
|
||||
let picker = PointPicker::new(Bind::given(point), x, y).steps(steps);
|
||||
if field { picker.backdrop(move |painter: &ContentPainterCx, plot: Rect| paint_field(painter, plot, mode, &base, levels)) } else { picker }
|
||||
}
|
||||
}
|
||||
|
||||
impl Component for ColorArea<'_> {
|
||||
const SINGLE_VALUE: bool = true;
|
||||
const ROLE: Role = Role::GROUP;
|
||||
const PARTS: bool = false;
|
||||
const STOPS: bool = false;
|
||||
const OVERLAYS: bool = false;
|
||||
type Style = ColorAreaStyle;
|
||||
type Output = EditResponse<ModelValues>;
|
||||
|
||||
fn style(_: &StyleCx<'_>, _: ColorAreaStyleKey) -> ColorAreaStyle {
|
||||
ColorAreaStyle { metrics: Metrics::new() }
|
||||
}
|
||||
|
||||
fn sense(&self) -> Sense {
|
||||
Sense::empty()
|
||||
}
|
||||
|
||||
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
let mut picker = self.picker(cx.value(), false);
|
||||
cx.child("picker", &mut picker, Proposal::Ideal)
|
||||
}
|
||||
|
||||
fn bind(&mut self) -> Option<BindMut<'_, ModelValues>> {
|
||||
Some(self.values.reborrow())
|
||||
}
|
||||
|
||||
fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) {
|
||||
let Some(values) = cx.value() else { return };
|
||||
let model = self.mode.model();
|
||||
let channels = self.channels();
|
||||
let names = match &self.names {
|
||||
Some(names) => names.clone().map(|name| cx.env.resolve(&name).as_str().to_owned()),
|
||||
None => channels.map(|channel| model.channels()[channel].name.to_owned()),
|
||||
};
|
||||
let text = |at: usize| spoken(&names[at], model, channels[at], values.values[channels[at]]);
|
||||
access.value(format!("{}, {}", text(0), text(1)));
|
||||
}
|
||||
|
||||
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
|
||||
let model = self.mode.model();
|
||||
let [across, down] = self.channels();
|
||||
let picker = self.picker(cx.value(), true).label(cx.label());
|
||||
let edit = ui.inner("picker", cx.rect, picker);
|
||||
let levels = self.levels();
|
||||
let start = ModelValues::new(model.id(), &[]);
|
||||
cx.adopt(&edit, &start, |point, mine| {
|
||||
for (channel, axis) in [(across, 0), (down, 1)] {
|
||||
if let Some(value) = point[axis].same() {
|
||||
mine.values[channel] = settled(model, channel, *value as f32);
|
||||
}
|
||||
}
|
||||
if let Some(levels) = levels {
|
||||
*mine = quantized(model, mine, levels);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> EditResponse<ModelValues> {
|
||||
cx.edit_response()
|
||||
}
|
||||
}
|
||||
|
||||
/// 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>) {
|
||||
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;
|
||||
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)
|
||||
};
|
||||
let mut mesh = Mesh::default();
|
||||
match levels {
|
||||
Some(levels) => flat_cells(&mut mesh, plot, &at, levels),
|
||||
None => smooth_mesh(&mut mesh, plot, &at),
|
||||
}
|
||||
painter.painter.add(mesh);
|
||||
}
|
||||
|
||||
/// The colours as a mesh of vertices, blending between them.
|
||||
fn smooth_mesh(mesh: &mut Mesh, plot: Rect, at: &dyn Fn(f32, f32) -> craft_theme::Srgba) {
|
||||
let last = (MESH - 1) as f32;
|
||||
for row in 0..MESH {
|
||||
for col in 0..MESH {
|
||||
let (fx, fy) = (col as f32 / last, row as f32 / last);
|
||||
mesh.colored_vertex(pos2(egui::lerp(plot.x_range(), fx), egui::lerp(plot.y_range(), fy)), at(fx, fy).into());
|
||||
}
|
||||
}
|
||||
for row in 0..MESH - 1 {
|
||||
for col in 0..MESH - 1 {
|
||||
let a = (row * MESH + col) as u32;
|
||||
let b = a + MESH as u32;
|
||||
mesh.add_triangle(a, a + 1, b + 1);
|
||||
mesh.add_triangle(a, b + 1, b);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// 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) {
|
||||
let n = QUANTIZE_CELLS;
|
||||
let (w, h) = (plot.width() / n as f32, plot.height() / n as f32);
|
||||
for row in 0..n {
|
||||
for col in 0..n {
|
||||
let (fx, fy) = ((col as f32 + 0.5) / n as f32, (row as f32 + 0.5) / n as f32);
|
||||
let min = pos2(plot.left() + col as f32 * w, plot.top() + row as f32 * h);
|
||||
mesh.add_colored_rect(Rect::from_min_size(min, Vec2::new(w, h)), snapped(at(fx, fy), levels).into());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
//! Stories of `ColorArea`: a hue-mode area and a web-safe one.
|
||||
|
||||
use super::ColorArea;
|
||||
use crate::AreaMode;
|
||||
use craft_theme::{ColorModel, HsbModel, Srgba};
|
||||
use craft_ui::contract::{Bind, Show as _, Validity};
|
||||
use craft_ui::runtime::env::Message;
|
||||
use craft_ui::testing::{Drive, Grip, StoryData, StoryOutput, story};
|
||||
use craft_ui::value_drag::PointPicker;
|
||||
use egui::Ui;
|
||||
|
||||
/// The value changes through the drag of the point picker the area shows inside itself.
|
||||
#[story(ColorArea<'static>, covers = [Default], drive = Drive::DragChild(Grip::new(PointPicker::WELL)))]
|
||||
fn color_area(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let values = data.value("values", HsbModel.from_srgb(Srgba::rgb(0.2, 0.5, 0.8)));
|
||||
ColorArea::new("Saturation and brightness", AreaMode::Hue, Bind::bound(values)).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(ColorArea<'static>, covers = [], drive = Drive::Never)]
|
||||
fn color_area_web_safe(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let values = data.value("values", HsbModel.from_srgb(Srgba::rgb(0.2, 0.6, 0.8)));
|
||||
ColorArea::new("Saturation and brightness", AreaMode::Hue, Bind::bound(values)).quantize(6).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(ColorArea<'static>, covers = [Invalid], drive = Drive::Never)]
|
||||
fn color_area_invalid(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let refuse_dim =
|
||||
|values: &craft_theme::ModelValues| if values.values[2] < 50.0 { Validity::Refuse(Message::new("Too dim")) } else { Validity::Ok };
|
||||
let values = data.value("values", HsbModel.from_srgb(Srgba::rgb(0.1, 0.2, 0.3)));
|
||||
ColorArea::new("Saturation and brightness", AreaMode::Hue, Bind::bound(values).check(refuse_dim)).show(ui).into()
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
//! The channel maths the colour area, strip, wheel and ramp share: a model channel's range and step, web-safe
|
||||
//! quantizing and the spoken form of a component.
|
||||
|
||||
use craft_theme::{ColorModel, ModelValues, Srgba};
|
||||
use std::ops::RangeInclusive;
|
||||
|
||||
/// The levels of a web colour's channels: 0x00, 0x33 ... 0xFF.
|
||||
pub(crate) const WEB_LEVELS: usize = 6;
|
||||
|
||||
/// Cells per side of a quantised field, and rows of a quantised strip: fine enough that the level edges follow the
|
||||
/// colour model, coarse enough to draw every frame.
|
||||
pub(crate) const QUANTIZE_CELLS: usize = 64;
|
||||
|
||||
/// The range of `channel` of `model`, smallest first.
|
||||
pub(crate) fn channel_range(model: &dyn ColorModel, channel: usize) -> RangeInclusive<f64> {
|
||||
let ch = model.channels()[channel];
|
||||
f64::from(ch.min)..=f64::from(ch.max)
|
||||
}
|
||||
|
||||
/// The step of one arrow press on `channel` of `model`: the channel's own (1 degree, 1 percent, 1 of 255, 0.001 of
|
||||
/// chroma).
|
||||
pub(crate) fn channel_step(model: &dyn ColorModel, channel: usize) -> f64 {
|
||||
f64::from(model.channels()[channel].step)
|
||||
}
|
||||
|
||||
/// `value` of `channel` kept in the channel's range and on its step.
|
||||
pub(crate) fn settled(model: &dyn ColorModel, channel: usize, value: f32) -> f32 {
|
||||
let (range, step) = (channel_range(model, channel), channel_step(model, channel));
|
||||
let (min, max) = (*range.start(), *range.end());
|
||||
let value = f64::from(value).clamp(min, max);
|
||||
let on_step = if step > 0.0 { min + ((value - min) / step).round() * step } else { value };
|
||||
on_step.min(max) as f32
|
||||
}
|
||||
|
||||
/// `values` with each red, green and blue channel of their colour on the nearest of `levels` evenly spaced levels (at
|
||||
/// least two) from 0 to 1, in the model's values again (a web-safe colour has 6). The other components are what the
|
||||
/// snapped colour gives.
|
||||
pub(crate) fn quantized(model: &dyn ColorModel, values: &ModelValues, levels: usize) -> ModelValues {
|
||||
model.from_srgb(snapped(model.to_srgb(&values.values), levels))
|
||||
}
|
||||
|
||||
/// `color` with each channel on the nearest of `levels` levels.
|
||||
pub(crate) fn snapped(color: Srgba, levels: usize) -> Srgba {
|
||||
let top = (levels.max(2) - 1) as f32;
|
||||
let snap = |v: f32| (v.clamp(0.0, 1.0) * top).round() / top;
|
||||
Srgba::new(snap(color.r), snap(color.g), snap(color.b), color.a)
|
||||
}
|
||||
|
||||
/// A component as a screen reader reads it: "Saturation 40 %", "Hue 120°", "Lightness 50".
|
||||
pub(crate) fn spoken(name: &str, model: &dyn ColorModel, channel: usize, value: f32) -> String {
|
||||
let ch = model.channels()[channel];
|
||||
let factor = 10f32.powi(i32::from(ch.decimals));
|
||||
// Adding zero turns a rounded -0 into 0.
|
||||
let value = (value * factor).round() / factor + 0.0;
|
||||
let number = format!("{value:.*}", usize::from(ch.decimals));
|
||||
match ch.unit {
|
||||
"" => format!("{name} {number}"),
|
||||
"°" => format!("{name} {number}°"),
|
||||
unit => format!("{name} {number} {unit}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// `value` when it is a number, else 0.
|
||||
pub(crate) fn finite(value: f32) -> f32 {
|
||||
if value.is_finite() { value } else { 0.0 }
|
||||
}
|
||||
|
||||
/// `values` with every non-finite channel set to 0, as PhotoCraft's model wrapper did: a NaN or infinity from
|
||||
/// automation or a field must not reach the colour or the remembered values.
|
||||
pub fn finite_values(mut values: ModelValues) -> ModelValues {
|
||||
for v in &mut values.values {
|
||||
*v = finite(*v);
|
||||
}
|
||||
values
|
||||
}
|
||||
|
||||
/// Whether the press that `press` reports was made with the primary button: a drag with another button is the host's.
|
||||
pub(crate) fn primary(press: &craft_behavior::PressState) -> bool {
|
||||
press.phase.start().is_some_and(|start| start.button == craft_behavior::PointerButton::Primary)
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
//! `ColorChoice`: a choice among named colours with a custom colour, as Photoshop's pasteboard colour
|
||||
//! (Preferences, Interface), the Crop shield colour and the Note colour.
|
||||
|
||||
#[cfg(feature = "screen-testing")]
|
||||
mod stories;
|
||||
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::contract::{Bind, Entry, NoValue, Outcome, Props as _, Show as _};
|
||||
use craft_ui::pickers::Select;
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
use craft_ui::runtime::requests::ColorRequest;
|
||||
use egui::{Response, Ui};
|
||||
|
||||
craft_ui::words! {
|
||||
/// The choice's own rows, English by default.
|
||||
#[non_exhaustive]
|
||||
pub struct ColorChoiceWords {
|
||||
/// The row of the custom colour last picked.
|
||||
custom: "colorChoice.custom" = "Custom";
|
||||
/// The row that opens the Color Picker.
|
||||
select_custom: "colorChoice.selectCustom" = "Select Custom Color…";
|
||||
}
|
||||
}
|
||||
|
||||
/// One named colour of a [`ColorChoice`]: its id (what the app stores), its label and the colour its swatch shows,
|
||||
/// `None` for one whose colour the theme decides (Photoshop's "Default" pasteboard).
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct NamedColor {
|
||||
/// What the app stores for this colour.
|
||||
pub id: String,
|
||||
/// The name shown.
|
||||
pub label: Label,
|
||||
/// The swatch colour, or `None` to let the theme decide.
|
||||
pub color: Option<Srgba>,
|
||||
}
|
||||
|
||||
impl NamedColor {
|
||||
/// A named colour with the given id, label and swatch colour.
|
||||
pub fn new(id: impl Into<String>, label: impl Into<Label>, color: Option<Srgba>) -> NamedColor {
|
||||
NamedColor { id: id.into(), label: label.into(), color }
|
||||
}
|
||||
}
|
||||
|
||||
/// What a [`ColorChoice`] holds: one of the named colours by id, or the custom colour.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub enum ChosenColor {
|
||||
/// The named colour with this id.
|
||||
Named(String),
|
||||
/// The custom colour set by [`ColorChoice::custom`].
|
||||
Custom,
|
||||
}
|
||||
|
||||
/// What [`ColorChoice::show`] reports.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
#[must_use = "the host applies the choice and opens the picker"]
|
||||
pub struct ColorChoiceOutput {
|
||||
/// The choice's response.
|
||||
pub response: Response,
|
||||
/// The row chosen this pass; the host stores it.
|
||||
pub chosen: Option<ChosenColor>,
|
||||
/// "Select Custom Color…" was chosen, for this pass only: the app opens its colour picker from the request (key
|
||||
/// [`ColorChoice::CUSTOM_KEY`], the custom colour) and, on OK, stores the colour and chooses
|
||||
/// [`ChosenColor::Custom`].
|
||||
pub pick_color: Option<ColorRequest>,
|
||||
}
|
||||
|
||||
impl Outcome for ColorChoiceOutput {
|
||||
type Value = NoValue;
|
||||
|
||||
fn response(&self) -> &Response {
|
||||
&self.response
|
||||
}
|
||||
}
|
||||
|
||||
/// What a row of the list stands for.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
enum Row {
|
||||
Named(String),
|
||||
Custom,
|
||||
SelectCustom,
|
||||
}
|
||||
|
||||
/// A `Select` of named colours, each row with a swatch before its label, then "Custom" (the custom colour, shown once
|
||||
/// there is one), a separator and "Select Custom Color…". The closed control shows the chosen row's swatch and label.
|
||||
/// Keys and AccessKit are the `Select`'s; the swatch is decoration (the label names the row).
|
||||
#[derive(craft_ui::contract::Pattern)]
|
||||
pub struct ColorChoice<'a> {
|
||||
label: Label,
|
||||
value: &'a ChosenColor,
|
||||
named: Vec<NamedColor>,
|
||||
custom: Option<Srgba>,
|
||||
enabled: bool,
|
||||
}
|
||||
|
||||
impl<'a> ColorChoice<'a> {
|
||||
/// The key of the [`ColorRequest`] that "Select Custom Color…" reports.
|
||||
pub const CUSTOM_KEY: &'static str = "colorChoice.custom";
|
||||
|
||||
/// A choice showing `value`, named `label`.
|
||||
pub fn new(label: impl Into<Label>, value: &'a ChosenColor) -> ColorChoice<'a> {
|
||||
ColorChoice { label: label.into(), value, named: Vec::new(), custom: None, enabled: true }
|
||||
}
|
||||
|
||||
/// The named colours, in order.
|
||||
#[must_use]
|
||||
pub fn named(mut self, named: impl IntoIterator<Item = NamedColor>) -> Self {
|
||||
self.named = named.into_iter().collect();
|
||||
self
|
||||
}
|
||||
|
||||
/// The custom colour; without it the "Custom" row is not shown.
|
||||
#[must_use]
|
||||
pub fn custom(mut self, color: Option<Srgba>) -> Self {
|
||||
self.custom = color;
|
||||
self
|
||||
}
|
||||
|
||||
/// Turns input on or off; on by default.
|
||||
#[must_use]
|
||||
pub fn enabled(mut self, enabled: bool) -> Self {
|
||||
self.enabled = enabled;
|
||||
self
|
||||
}
|
||||
|
||||
/// Shows the choice.
|
||||
pub fn show(self, ui: &mut Ui) -> ColorChoiceOutput {
|
||||
let words = Env::of(ui).words::<ColorChoiceWords>();
|
||||
let row = match self.value {
|
||||
ChosenColor::Named(id) => Row::Named(id.clone()),
|
||||
ChosenColor::Custom => Row::Custom,
|
||||
};
|
||||
// The picker opens on the custom colour, else on the colour of the chosen row.
|
||||
let chosen_color = match self.value {
|
||||
ChosenColor::Named(id) => self.named.iter().find(|named| named.id == *id).and_then(|named| named.color),
|
||||
ChosenColor::Custom => None,
|
||||
};
|
||||
let start = self.custom.or(chosen_color).unwrap_or(Srgba::rgb(0.0, 0.0, 0.0));
|
||||
let swatch = |entry: Entry<Row>, color: Option<Srgba>| match color {
|
||||
Some(color) => entry.swatch(color),
|
||||
None => entry,
|
||||
};
|
||||
let mut entries: Vec<Entry<Row>> =
|
||||
self.named.iter().map(|named| swatch(Entry::new(Row::Named(named.id.clone()), named.label.clone()), named.color)).collect();
|
||||
if self.custom.is_some() {
|
||||
entries.push(swatch(Entry::new(Row::Custom, words.custom.as_str().to_owned()), self.custom));
|
||||
}
|
||||
entries.push(Entry::separator());
|
||||
entries.push(Entry::new(Row::SelectCustom, words.select_custom.as_str().to_owned()));
|
||||
let shown = Select::new(self.label.clone(), Bind::given(row), &entries).enabled(self.enabled).show(ui);
|
||||
let picked = shown.value().cloned();
|
||||
let mut pick_color = None;
|
||||
let chosen = match picked {
|
||||
Some(Row::Named(id)) => Some(ChosenColor::Named(id)),
|
||||
Some(Row::Custom) => Some(ChosenColor::Custom),
|
||||
Some(Row::SelectCustom) => {
|
||||
let title = words.select_custom.as_str().trim_end_matches('…').to_owned();
|
||||
pick_color = Some(ColorRequest::new(Self::CUSTOM_KEY, start).title(title));
|
||||
None
|
||||
}
|
||||
None => None,
|
||||
};
|
||||
ColorChoiceOutput { response: shown.response, chosen, pick_color }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
//! Stories of `ColorChoice`: named colours with the custom row.
|
||||
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use egui::Ui;
|
||||
|
||||
use super::{ChosenColor, ColorChoice, NamedColor};
|
||||
|
||||
#[story(ColorChoice<'static>, covers = [Default], drive = Drive::Never)]
|
||||
fn color_choice(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let chosen = data.value("chosen", ChosenColor::Named("black".into())).clone();
|
||||
let named = [
|
||||
NamedColor::new("default", "Default", None),
|
||||
NamedColor::new("black", "Black", Some(Srgba::rgb(0.0, 0.0, 0.0))),
|
||||
NamedColor::new("gray", "Medium Gray", Some(Srgba::rgb(0.5, 0.5, 0.5))),
|
||||
];
|
||||
let out = ColorChoice::new("Pasteboard color", &chosen).named(named).custom(Some(Srgba::rgb(0.8, 0.3, 0.1))).show(ui);
|
||||
if let Some(next) = out.chosen.clone() {
|
||||
*data.value("chosen", ChosenColor::Named("black".into())) = next;
|
||||
}
|
||||
out.into()
|
||||
}
|
||||
@@ -0,0 +1,439 @@
|
||||
//! [`ColorDisc`]: a hue and saturation disc with one draggable marker per colour of a set, as VectorCraft's harmony
|
||||
//! wheel.
|
||||
|
||||
use super::channels::{finite, primary};
|
||||
use super::wheel::{hue_at, hue_direction, vertex};
|
||||
use craft_behavior::{AccessAction, CancelReason, HitShape, Metrics, NavMove, PartKey, PressPhase, Sense};
|
||||
use craft_theme::{ColorModel, Flags, HsbModel, ModelValues, Resolve as _, Srgba, State, StateMix, Stateful};
|
||||
use craft_ui::contract::{
|
||||
Access, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Focus as _, Input, Name, Numeric, Outcome, PaintUi, PartsCx, Pointer as _,
|
||||
Props as _, Remember as _, Role, WordSetCx as _,
|
||||
};
|
||||
use craft_ui::primitives::{PaintShape, StrokeWidth};
|
||||
use craft_ui::runtime::env::Label;
|
||||
use craft_ui::runtime::focus::{ActivateKeys, FocusShape, KeepKeys, KeyUse};
|
||||
use craft_ui::style::{ComponentStyle, DataColor, FocusLook, StyleColor, StyleCx};
|
||||
use egui::{Color32, Mesh, Pos2, Response, Vec2};
|
||||
|
||||
#[cfg(feature = "screen-testing")]
|
||||
mod stories;
|
||||
|
||||
/// The disc: a press on it grabs the nearest marker within reach.
|
||||
const DISC: PartKey = PartKey::new("disc");
|
||||
/// A marker: `MARKER.at(i)`; the selected one is the disc's Tab stop.
|
||||
const MARKER: PartKey = PartKey::new("marker");
|
||||
|
||||
/// Share of `overlay.handle_fill` the marker spokes draw at, so the disc shows through.
|
||||
const SPOKE_SHARE: f32 = 0.63;
|
||||
/// Segments round the disc and rings out from its centre (VectorCraft's 72 and 8).
|
||||
const SEGMENTS: u32 = 72;
|
||||
const RINGS: u32 = 8;
|
||||
/// The least brightness the disc draws, as a proportion.
|
||||
const DISC_FLOOR: f32 = 0.15;
|
||||
/// The distance below which the pointer has no hue, in points.
|
||||
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;
|
||||
|
||||
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} %";
|
||||
}
|
||||
}
|
||||
|
||||
/// A marker's place on the disc: what a drag or a key changes.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct DiscMove {
|
||||
/// Index of the marker, in the order of the colours the disc was given.
|
||||
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,
|
||||
}
|
||||
|
||||
impl DiscMove {
|
||||
/// Marker `marker` at `hue` degrees and `saturation`.
|
||||
pub const fn new(marker: usize, hue: f32, saturation: f32) -> Self {
|
||||
DiscMove { marker, hue, saturation }
|
||||
}
|
||||
}
|
||||
|
||||
/// The style of a colour disc.
|
||||
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
|
||||
#[non_exhaustive]
|
||||
pub struct ColorDiscStyle {
|
||||
#[style(metrics)]
|
||||
metrics: Metrics,
|
||||
#[style(focus)]
|
||||
focus: FocusLook,
|
||||
/// The distance from the area's edge to the disc.
|
||||
inset: f32,
|
||||
/// A marker's radius; the selected marker's is larger.
|
||||
marker: Stateful<f32>,
|
||||
/// A press within this of a marker grabs it.
|
||||
grab: f32,
|
||||
/// The disc's edge.
|
||||
edge: StyleColor,
|
||||
/// The line from the centre to a marker.
|
||||
spoke: StyleColor,
|
||||
/// A marker's inner ring and the halo round it.
|
||||
ring: StyleColor,
|
||||
halo: StyleColor,
|
||||
}
|
||||
|
||||
/// What [`ColorDisc`] returns.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
pub struct ColorDiscOutput {
|
||||
/// This pass's edit, carrying the moved marker.
|
||||
pub edit: EditResponse<DiscMove>,
|
||||
/// The marker a press grabbed: the host selects it.
|
||||
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>,
|
||||
}
|
||||
|
||||
impl Outcome for ColorDiscOutput {
|
||||
type Value = DiscMove;
|
||||
|
||||
fn response(&self) -> &Response {
|
||||
&self.edit.response
|
||||
}
|
||||
|
||||
#[cfg(feature = "screen-testing")]
|
||||
fn story_facts(&self) -> craft_ui::testing::StoryOutput {
|
||||
self.edit.story_facts()
|
||||
}
|
||||
}
|
||||
|
||||
/// The marker a press grabbed, and the colour that marker had the pass before.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct Grab {
|
||||
marker: Option<usize>,
|
||||
last: Option<Srgba>,
|
||||
}
|
||||
|
||||
/// Hue and saturation disc with a marker per colour; the host owns the colours and the rule that moves them
|
||||
/// together.
|
||||
///
|
||||
/// - Pointer (primary button): a press grabs the nearest marker within `size.hit.target`
|
||||
/// ([`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.
|
||||
/// - Keys: one Tab stop, the selected marker (the first without a selection). Left and Right change the hue by 1
|
||||
/// degree, Up and Down the saturation by 1 percent; Shift steps ten; each key is a `Set`. During a drag keys change
|
||||
/// nothing. Esc during a drag cancels it.
|
||||
/// - AccessKit: a `Group` named `label` holding a `Slider` per marker (the hue, 0 to 360, step 1, increment, decrement
|
||||
/// and set value), named by [`names`](ColorDisc::names) or "Color N", with the value text "Hue 120 degrees,
|
||||
/// saturation 80 %".
|
||||
/// - Right to left nothing mirrors: red stays at 3 o'clock.
|
||||
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
|
||||
#[component(content_painter)]
|
||||
pub struct ColorDisc<'a> {
|
||||
#[common]
|
||||
common: Common,
|
||||
markers: &'a [Srgba],
|
||||
drag: Bind<'a, DiscMove>,
|
||||
/// The marker drawn larger and reached by Tab; 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 markers' accessible names, in order; a marker without one is "Color N".
|
||||
#[prop(into)]
|
||||
names: Vec<Label>,
|
||||
pressed: Option<usize>,
|
||||
grabbed: Option<usize>,
|
||||
}
|
||||
|
||||
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()
|
||||
}
|
||||
|
||||
/// The disc's centre and radius in the area `rect`, `inset` inside its shorter side.
|
||||
pub fn geometry(rect: egui::Rect, inset: f32) -> (Pos2, f32) {
|
||||
(rect.center(), (rect.width().min(rect.height()) / 2.0 - inset).max(1.0))
|
||||
}
|
||||
|
||||
/// Where a marker of hue `hue` degrees and saturation `saturation` (0 to 1) lies.
|
||||
pub fn marker_pos(center: Pos2, radius: f32, hue: f32, saturation: f32) -> Pos2 {
|
||||
center + hue_direction(hue) * (radius * saturation.clamp(0.0, 1.0))
|
||||
}
|
||||
|
||||
/// The marker with the Tab stop: the selected one, else the first.
|
||||
fn stop(&self) -> usize {
|
||||
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.
|
||||
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]]
|
||||
}
|
||||
|
||||
/// Marker `index` where the host has it.
|
||||
fn resting(&self, index: usize) -> DiscMove {
|
||||
let [hue, saturation, _] = self.hsb(index);
|
||||
DiscMove::new(index, hue, saturation)
|
||||
}
|
||||
}
|
||||
|
||||
impl Component for ColorDisc<'_> {
|
||||
const KEYS: KeyUse = KeyUse::of(Input::Pointer).with_keep(KeepKeys::BlockArrows).with_activate(ActivateKeys::Neither);
|
||||
const SINGLE_VALUE: bool = true;
|
||||
const ROLE: Role = Role::GROUP;
|
||||
const OVERLAYS: bool = false;
|
||||
type Style = ColorDiscStyle;
|
||||
type Output = ColorDiscOutput;
|
||||
|
||||
fn style(cx: &StyleCx<'_>, _: ColorDiscStyleKey) -> ColorDiscStyle {
|
||||
let tokens = cx.tokens;
|
||||
let colors = &tokens.color;
|
||||
ColorDiscStyle {
|
||||
metrics: Metrics::new().min_size(Vec2::new(tokens.size.plot.width, tokens.size.plot.height)),
|
||||
focus: cx.focus_look(),
|
||||
inset: tokens.space.pad.regular,
|
||||
marker: Stateful::new(tokens.size.handle.sm).when(Flags::SELECTED, tokens.size.handle.md),
|
||||
grab: tokens.size.hit.target,
|
||||
edge: cx.color(colors.line.control_edge),
|
||||
spoke: cx.color(colors.overlay.handle_fill.faded(SPOKE_SHARE)),
|
||||
ring: cx.color(colors.overlay.handle_fill),
|
||||
halo: cx.color(colors.overlay.halo),
|
||||
}
|
||||
}
|
||||
|
||||
fn sense(&self) -> Sense {
|
||||
Sense::empty()
|
||||
}
|
||||
|
||||
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)
|
||||
.pointer_only("the arrow keys move the marker");
|
||||
let stop = self.stop();
|
||||
for index in 0..self.markers.len() {
|
||||
let at = match cx.value().filter(|moved| moved.marker == index) {
|
||||
Some(moved) => *moved,
|
||||
None => self.resting(index),
|
||||
};
|
||||
let radius_of = marker_radius(cx.style, self.chosen == Some(index));
|
||||
let part = cx.part(MARKER.at(index as u64), HitShape::circle(Self::marker_pos(center, radius, at.hue, at.saturation), radius_of));
|
||||
// A marker takes no press of its own (the disc grabs the nearest) and only the selected one is a Tab stop.
|
||||
if index == stop {
|
||||
part.focusable().focus_shape(FocusShape::Circle);
|
||||
} else {
|
||||
part.keyboard_via(MARKER);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn bind(&mut self) -> Option<BindMut<'_, DiscMove>> {
|
||||
Some(self.drag.reborrow())
|
||||
}
|
||||
|
||||
fn update(&mut self, cx: &mut Cx<'_, Self>) {
|
||||
let (center, radius) = Self::geometry(cx.rect, cx.style.inset);
|
||||
let grab_reach = cx.style.grab;
|
||||
let press = cx.part(DISC).press;
|
||||
let stop = self.stop();
|
||||
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))
|
||||
});
|
||||
cx.memory::<Grab>().marker = near.map(|(index, _)| index);
|
||||
self.pressed = near.map(|(index, _)| index);
|
||||
if near.is_some() && !self.markers.is_empty() {
|
||||
cx.focus_part(MARKER.at(stop 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.
|
||||
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]) {
|
||||
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
|
||||
};
|
||||
if primary(&press)
|
||||
&& let Some(marker) = grabbed
|
||||
{
|
||||
match press.phase {
|
||||
PressPhase::DragStart { pos, .. } => {
|
||||
cx.begin();
|
||||
cx.propose(value_at(&*cx, marker, pos));
|
||||
}
|
||||
PressPhase::Drag { pos, .. } if cx.gesture().is_some() => cx.propose(value_at(&*cx, marker, pos)),
|
||||
PressPhase::Release { pos, click, .. } => {
|
||||
if cx.gesture().is_some() {
|
||||
cx.propose(value_at(&*cx, marker, pos));
|
||||
cx.commit();
|
||||
} else if click {
|
||||
cx.set(value_at(&*cx, marker, pos));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if matches!(press.phase, PressPhase::Release { .. } | PressPhase::Cancel { .. }) {
|
||||
*cx.memory::<Grab>() = Grab::default();
|
||||
}
|
||||
let mut now = self.resting(stop);
|
||||
let on_stop = cx.active_part() == Some(MARKER.at(stop as u64));
|
||||
while let Some((mv, mods)) = cx.intents().take_move() {
|
||||
if running || !on_stop || self.markers.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let by = if mods.extend { FAR } else { KEY_STEP };
|
||||
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,
|
||||
_ => continue,
|
||||
}
|
||||
now.hue = now.hue.round().rem_euclid(360.0);
|
||||
now.saturation = (now.saturation * 100.0).round().clamp(0.0, 100.0) / 100.0;
|
||||
cx.set(now);
|
||||
}
|
||||
for index in 0..self.markers.len() {
|
||||
if let Some(value) = cx.intents().take_set_value_at(MARKER.at(index as u64)).filter(|value| value.is_finite() && !running) {
|
||||
let mut moved = cx.value().filter(|moved| moved.marker == index).copied().unwrap_or_else(|| self.resting(index));
|
||||
moved.hue = value.round().rem_euclid(360.0) as f32;
|
||||
cx.set(moved);
|
||||
}
|
||||
}
|
||||
while let Some(request) = cx.intents().take_access() {
|
||||
let Some(index) = (0..self.markers.len()).find(|index| request.target == Some(MARKER.at(*index as u64))) else { continue };
|
||||
let step = match request.action {
|
||||
AccessAction::Increment => KEY_STEP,
|
||||
AccessAction::Decrement => -KEY_STEP,
|
||||
_ => continue,
|
||||
};
|
||||
if !running {
|
||||
let mut moved = cx.value().filter(|moved| moved.marker == index).copied().unwrap_or_else(|| self.resting(index));
|
||||
moved.hue = (moved.hue + step).round().rem_euclid(360.0);
|
||||
cx.set(moved);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) {
|
||||
let words = cx.words::<ColorDiscWords>();
|
||||
for index in 0..self.markers.len() {
|
||||
let live = cx.value().filter(|moved| moved.marker == index).copied().unwrap_or_else(|| self.resting(index));
|
||||
let name = match self.names.get(index) {
|
||||
Some(name) => cx.env.resolve(name).as_str().to_owned(),
|
||||
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 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())]);
|
||||
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 painter = ui.content_painter(cx);
|
||||
painter.painter.add(disc_mesh(center, radius, brightness));
|
||||
let draw = ui.draw();
|
||||
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)
|
||||
})
|
||||
.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);
|
||||
for index in order {
|
||||
let r = marker_radius(cx.style, Some(index) == selected);
|
||||
let circle = PaintShape::Circle(places[index], r);
|
||||
draw.data_fill(&circle, DataColor::new(Color32::from(self.markers[index])));
|
||||
draw.stroke(&circle, StrokeWidth::Thick, cx.style.halo);
|
||||
draw.stroke(&circle, StrokeWidth::Medium, cx.style.ring);
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> ColorDiscOutput {
|
||||
let (pressed, grabbed) = (self.pressed, self.grabbed);
|
||||
ColorDiscOutput { edit: cx.edit_response(), pressed, grabbed }
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 {
|
||||
let mut mesh = Mesh::default();
|
||||
let b = brightness * 100.0;
|
||||
mesh.colored_vertex(center, vertex(0.0, 0.0, b));
|
||||
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));
|
||||
}
|
||||
}
|
||||
let at = |ring: u32, k: u32| if ring == 0 { 0 } else { 1 + (ring - 1) * SEGMENTS + k % SEGMENTS };
|
||||
for ring in 0..RINGS {
|
||||
for k in 0..SEGMENTS {
|
||||
if ring == 0 {
|
||||
mesh.add_triangle(0, at(1, k), at(1, k + 1));
|
||||
} else {
|
||||
mesh.add_triangle(at(ring, k), at(ring + 1, k), at(ring + 1, k + 1));
|
||||
mesh.add_triangle(at(ring, k), at(ring + 1, k + 1), at(ring, k + 1));
|
||||
}
|
||||
}
|
||||
}
|
||||
mesh
|
||||
}
|
||||
|
||||
/// The radius of a marker, larger while it is the selected one.
|
||||
fn marker_radius(style: &ColorDiscStyle, selected: bool) -> f32 {
|
||||
let flags = if selected { Flags::SELECTED } else { Flags::empty() };
|
||||
style.marker.resolve(State::Rest, flags, StateMix::default())
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
//! Stories of `ColorDisc`: three markers with one selected.
|
||||
|
||||
use super::{ColorDisc, DiscMove, MARKER};
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::contract::{Bind, Show as _, Validity};
|
||||
use craft_ui::runtime::env::Message;
|
||||
use craft_ui::testing::{Drive, Grip, StoryData, StoryOutput, story};
|
||||
use egui::Ui;
|
||||
|
||||
const MARKERS: [Srgba; 3] = [Srgba::rgb(0.9, 0.2, 0.2), Srgba::rgb(0.2, 0.7, 0.4), Srgba::rgb(0.3, 0.4, 0.9)];
|
||||
|
||||
#[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 = data.value("move", DiscMove::new(0, 0.0, 0.7));
|
||||
ColorDisc::new("Harmony", &MARKERS, Bind::bound(moved)).chosen(1).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 moved = Bind::bound(data.value("pale", DiscMove::new(1, 0.0, 0.2))).check(refuse_pale);
|
||||
ColorDisc::new("Harmony", &MARKERS, moved).chosen(1).show(ui).into()
|
||||
}
|
||||
@@ -0,0 +1,201 @@
|
||||
//! Dialog droppers (F04.02): a dialog's pipette that samples the canvas. The dialog's `DropperButton` asks the host to
|
||||
//! arm its canvas ([`EyedropperRequest`]); the host runs a [`DropperTool`] on the canvas, which samples under the
|
||||
//! dialog's modal layer (the dialog registers the canvas with the sampler) and answers the request with the sample.
|
||||
//!
|
||||
//! ```ignore
|
||||
//! // In a Levels dialog: the black-point dropper.
|
||||
//! let button = DropperButton::new("Sample in image to set black point", Bind::bound(&mut armed)).kind(DropperKind::Black).show(ui);
|
||||
//! if let Some(request) = button.request {
|
||||
//! host.arm(request);
|
||||
//! }
|
||||
//! // In the app's canvas pass, while a dropper is armed:
|
||||
//! let mut tool = DropperTool::new(|doc| composite_color(doc));
|
||||
//! tool_host.run(ui, &canvas, &mut tool);
|
||||
//! if let Some(color) = tool.take() {
|
||||
//! requests.answer_eyedropper(key, color);
|
||||
//! }
|
||||
//! ```
|
||||
|
||||
use craft_behavior::kurbo::Point;
|
||||
use craft_behavior::{CancelReason, Cursor, IconId, PaintedCursor};
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::buttons::ToggleButton;
|
||||
use craft_ui::canvas::{CanvasTool, ToolAction, ToolContext, ToolKey, ToolPath, ToolPointer};
|
||||
use craft_ui::contract::{Bind, EditResponse, Outcome, Pattern, Props as _, Show as _};
|
||||
use craft_ui::primitives::Draw;
|
||||
use craft_ui::runtime::env::Label;
|
||||
use craft_ui::runtime::requests::EyedropperRequest;
|
||||
use egui::{Pos2, Response, Ui, Vec2};
|
||||
|
||||
#[cfg(feature = "screen-testing")]
|
||||
mod stories;
|
||||
|
||||
/// The pipette icon's tip, in the icon's own 24-unit box.
|
||||
const HOTSPOT: [f32; 2] = [2.0, 22.0];
|
||||
|
||||
/// What a dropper samples into: the colour itself, or one of a levels dialog's three points.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
#[non_exhaustive]
|
||||
pub enum DropperKind {
|
||||
/// The sampled colour is the colour.
|
||||
#[default]
|
||||
Sample,
|
||||
/// The black point.
|
||||
Black,
|
||||
/// The gray point.
|
||||
Gray,
|
||||
/// The white point.
|
||||
White,
|
||||
}
|
||||
|
||||
impl DropperKind {
|
||||
/// The key a dropper of this kind files its request under, so one dialog can hold several droppers.
|
||||
fn key(self) -> &'static str {
|
||||
match self {
|
||||
DropperKind::Sample => "dropper",
|
||||
DropperKind::Black => "dropper.black",
|
||||
DropperKind::Gray => "dropper.gray",
|
||||
DropperKind::White => "dropper.white",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The pipette button of a dialog: a pressed toggle while its dropper is armed.
|
||||
///
|
||||
/// The button reports the toggle as an [`EyedropperRequest`] the dialog files with its `HostRequests`; the host owns
|
||||
/// the armed state and the sampling.
|
||||
#[must_use = "show the button with `show`"]
|
||||
#[derive(Pattern)]
|
||||
pub struct DropperButton<'a> {
|
||||
label: Label,
|
||||
armed: Bind<'a, bool>,
|
||||
kind: DropperKind,
|
||||
key: Option<String>,
|
||||
}
|
||||
|
||||
/// What [`DropperButton::show`] reports.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
#[must_use = "the dialog files the request"]
|
||||
pub struct DropperButtonOutput {
|
||||
/// The toggle's edit: the new armed state when the user flipped it.
|
||||
pub edit: EditResponse<bool>,
|
||||
/// The request to arm the host's canvas, in the pass the user armed the dropper.
|
||||
pub request: Option<EyedropperRequest>,
|
||||
}
|
||||
|
||||
impl Outcome for DropperButtonOutput {
|
||||
type Value = bool;
|
||||
|
||||
fn response(&self) -> &Response {
|
||||
&self.edit.response
|
||||
}
|
||||
|
||||
#[cfg(feature = "screen-testing")]
|
||||
fn story_facts(&self) -> craft_ui::testing::StoryOutput {
|
||||
self.edit.story_facts()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> DropperButton<'a> {
|
||||
/// A pipette button named `label` ("Sample in image to set black point"), pressed while `armed`.
|
||||
pub fn new(label: impl Into<Label>, armed: Bind<'a, bool>) -> Self {
|
||||
DropperButton { label: label.into(), armed, kind: DropperKind::Sample, key: None }
|
||||
}
|
||||
|
||||
/// What the dropper samples into; the kind is the request's key unless [`key`](Self::key) says otherwise.
|
||||
pub fn kind(mut self, kind: DropperKind) -> Self {
|
||||
self.kind = kind;
|
||||
self
|
||||
}
|
||||
|
||||
/// The key of the request the button files.
|
||||
pub fn key(mut self, key: impl Into<String>) -> Self {
|
||||
self.key = Some(key.into());
|
||||
self
|
||||
}
|
||||
|
||||
/// Shows the button.
|
||||
pub fn show(self, ui: &mut Ui) -> DropperButtonOutput {
|
||||
let DropperButton { label, armed, kind, key } = self;
|
||||
let edit = ToggleButton::new(label, armed).icon(IconId::new("eyedropper")).icon_only().id_salt(kind.key()).show(ui);
|
||||
let request = edit.value().copied().filter(|on| *on).map(|_| EyedropperRequest::new(key.unwrap_or_else(|| kind.key().to_owned())));
|
||||
DropperButtonOutput { edit, request }
|
||||
}
|
||||
}
|
||||
|
||||
/// The canvas tool of an armed dropper: a press, drag and release sample through the app's closure (Photoshop updates
|
||||
/// the dialog while the button is held), and Escape on the canvas cancels. The host disarms on
|
||||
/// [`cancelled`](DropperTool::cancelled).
|
||||
pub struct DropperTool<'a> {
|
||||
sample: Box<dyn FnMut([f64; 2]) -> Option<Srgba> + 'a>,
|
||||
sampled: Option<Srgba>,
|
||||
cancelled: bool,
|
||||
}
|
||||
|
||||
impl<'a> DropperTool<'a> {
|
||||
/// A dropper sampling the document point it gets through `sample` (`None` outside the document).
|
||||
pub fn new(sample: impl FnMut([f64; 2]) -> Option<Srgba> + 'a) -> Self {
|
||||
DropperTool { sample: Box::new(sample), sampled: None, cancelled: false }
|
||||
}
|
||||
|
||||
/// The newest sample, once.
|
||||
pub fn take(&mut self) -> Option<Srgba> {
|
||||
self.sampled.take()
|
||||
}
|
||||
|
||||
/// Whether the user cancelled the dropper (Escape on the canvas) since the last call.
|
||||
pub fn cancelled(&mut self) -> bool {
|
||||
std::mem::take(&mut self.cancelled)
|
||||
}
|
||||
|
||||
fn sample_at(&mut self, at: Pos2, cx: &ToolContext<'_>) {
|
||||
let Some(space) = cx.space() else { return };
|
||||
let Point { x, y } = space.view.to_doc(at);
|
||||
if let Some(color) = (self.sample)([x, y]) {
|
||||
self.sampled = Some(color);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl CanvasTool for DropperTool<'_> {
|
||||
fn press(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) -> ToolAction {
|
||||
self.sample_at(pointer.pos, cx);
|
||||
ToolAction::Claimed
|
||||
}
|
||||
|
||||
fn drag(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) {
|
||||
self.sample_at(pointer.pos, cx);
|
||||
}
|
||||
|
||||
fn release(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) {
|
||||
self.sample_at(pointer.pos, cx);
|
||||
}
|
||||
|
||||
fn cancel(&mut self, _: CancelReason, _: &mut ToolContext<'_>) {
|
||||
self.cancelled = true;
|
||||
}
|
||||
|
||||
fn key(&mut self, key: &ToolKey, _: &mut ToolContext<'_>) -> bool {
|
||||
if matches!(key, ToolKey::Cancel) {
|
||||
self.cancelled = true;
|
||||
return true;
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn paint(&self, _: &Draw<'_>, _: &ToolContext<'_>) {}
|
||||
|
||||
/// The pipette with its tip on the sampled pixel (the icon's lower left, in its 24-unit box).
|
||||
fn cursor(&self, _: &ToolContext<'_>) -> Cursor {
|
||||
PaintedCursor::tool(IconId::new("eyedropper"), Vec2::from(HOTSPOT), None).into()
|
||||
}
|
||||
|
||||
fn autoscrolls(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn command_form(&self) -> ToolPath {
|
||||
ToolPath::Command("the Color Picker command")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
//! Stories of `DropperButton`.
|
||||
|
||||
use super::{DropperButton, DropperKind};
|
||||
use craft_ui::contract::Bind;
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use egui::Ui;
|
||||
|
||||
fn button(ui: &mut Ui, data: &mut StoryData, kind: DropperKind, armed: bool) -> StoryOutput {
|
||||
let armed = data.value("armed", armed);
|
||||
StoryOutput::from(DropperButton::new("Sample in image", Bind::bound(armed)).kind(kind).show(ui))
|
||||
}
|
||||
|
||||
#[story(DropperButton<'static>, covers = [], drive = Drive::Never)]
|
||||
fn sample(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
button(ui, data, DropperKind::Sample, false)
|
||||
}
|
||||
|
||||
#[story(DropperButton<'static>, covers = [], drive = Drive::Never)]
|
||||
fn black_point(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
button(ui, data, DropperKind::Black, false)
|
||||
}
|
||||
|
||||
#[story(DropperButton<'static>, covers = [], drive = Drive::Never)]
|
||||
fn gray_point(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
button(ui, data, DropperKind::Gray, false)
|
||||
}
|
||||
|
||||
#[story(DropperButton<'static>, covers = [], drive = Drive::Never)]
|
||||
fn white_point_armed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
button(ui, data, DropperKind::White, true)
|
||||
}
|
||||
@@ -0,0 +1,373 @@
|
||||
//! The Eyedropper tool (F04.01): `SampleSize`, `SampleSource` and `EyedropperOptions` as data, `EyedropperBar` for the
|
||||
//! options bar and `EyedropperTool` for the canvas.
|
||||
//!
|
||||
//! ```ignore
|
||||
//! Bar::new("Eyedropper options", BarKind::Options).show(ui, |ui, _| {
|
||||
//! EyedropperBar::new(&mut options).show(ui);
|
||||
//! });
|
||||
//! let mut tool = EyedropperTool::new(options, |doc, size, source| composite_color(doc, size, source)).foreground(foreground);
|
||||
//! tool_host.run(ui, &canvas, &mut tool);
|
||||
//! if let Some(pick) = tool.take() {
|
||||
//! *(if pick.background { &mut background } else { &mut foreground }) = pick.color;
|
||||
//! }
|
||||
//! ```
|
||||
|
||||
use std::f32::consts::{PI, TAU};
|
||||
|
||||
use craft_behavior::kurbo::Point;
|
||||
use craft_behavior::{CancelReason, Cursor, EditEvents, IconId, PaintedCursor};
|
||||
use craft_host::target::Os;
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::canvas::{CanvasTool, ToolAction, ToolContext, ToolPath, ToolPointer};
|
||||
use craft_ui::choice::Checkbox;
|
||||
use craft_ui::contract::{Bind, EditResponse, Entry, Outcome, Pattern, Props as _, Show as _, ShowContainer as _};
|
||||
use craft_ui::display::Text;
|
||||
use craft_ui::form::Field;
|
||||
use craft_ui::pickers::Select;
|
||||
use craft_ui::primitives::{Draw, PaintShape, StrokeWidth};
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
use craft_ui::style::DataColor;
|
||||
use egui::{Color32, Pos2, Response, Ui, Vec2, vec2};
|
||||
|
||||
#[cfg(feature = "screen-testing")]
|
||||
mod stories;
|
||||
|
||||
craft_ui::words! {
|
||||
/// The Eyedropper options bar's words, English by default.
|
||||
#[non_exhaustive]
|
||||
pub struct EyedropperWords {
|
||||
sample_size: "eyedropper.sampleSize" = "Sample Size:";
|
||||
size: "eyedropper.size" = "Size";
|
||||
point_sample: "eyedropper.pointSample" = "Point Sample";
|
||||
/// `{n}` is the side of the averaged square in pixels.
|
||||
average: template "eyedropper.average" = "{n} by {n} Average";
|
||||
sample: "eyedropper.sample" = "Sample:";
|
||||
source: "eyedropper.source" = "Source";
|
||||
current_layer: "eyedropper.currentLayer" = "Current Layer";
|
||||
current_and_below: "eyedropper.currentAndBelow" = "Current & Below";
|
||||
all_layers: "eyedropper.allLayers" = "All Layers";
|
||||
all_layers_no_adjustments: "eyedropper.allLayersNoAdjustments" = "All Layers No Adjustments";
|
||||
current_and_below_no_adjustments: "eyedropper.currentAndBelowNoAdjustments" = "Current & Below No Adjustments";
|
||||
show_ring: "eyedropper.showRing" = "Show Sampling Ring";
|
||||
/// `{key}` is the modifier that picks the background colour.
|
||||
hint: template "eyedropper.hint" = "Click to sample the foreground color · {key}-click for background";
|
||||
}
|
||||
}
|
||||
|
||||
/// How many pixels around the pointer the eyedropper averages: Photoshop's Sample Size list.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub enum SampleSize {
|
||||
/// The pixel under the pointer.
|
||||
#[default]
|
||||
Point,
|
||||
/// 3 by 3 pixels.
|
||||
Avg3,
|
||||
/// 5 by 5 pixels.
|
||||
Avg5,
|
||||
/// 11 by 11 pixels.
|
||||
Avg11,
|
||||
/// 31 by 31 pixels.
|
||||
Avg31,
|
||||
/// 51 by 51 pixels.
|
||||
Avg51,
|
||||
/// 101 by 101 pixels.
|
||||
Avg101,
|
||||
}
|
||||
|
||||
impl SampleSize {
|
||||
/// Every size in menu order.
|
||||
pub const ALL: [SampleSize; 7] =
|
||||
[SampleSize::Point, SampleSize::Avg3, SampleSize::Avg5, SampleSize::Avg11, SampleSize::Avg31, SampleSize::Avg51, SampleSize::Avg101];
|
||||
|
||||
/// The side of the sampled square in pixels.
|
||||
pub fn pixels(self) -> u32 {
|
||||
match self {
|
||||
SampleSize::Point => 1,
|
||||
SampleSize::Avg3 => 3,
|
||||
SampleSize::Avg5 => 5,
|
||||
SampleSize::Avg11 => 11,
|
||||
SampleSize::Avg31 => 31,
|
||||
SampleSize::Avg51 => 51,
|
||||
SampleSize::Avg101 => 101,
|
||||
}
|
||||
}
|
||||
|
||||
/// The menu text: "Point Sample" or "11 by 11 Average".
|
||||
pub fn label(self, words: &EyedropperWords) -> Label {
|
||||
match self {
|
||||
SampleSize::Point => words.point_sample.clone(),
|
||||
average => Label::from(words.average.fill(&[("n", &average.pixels().to_string())])),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Which layers the eyedropper reads: Photoshop's Sample list.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub enum SampleSource {
|
||||
/// The current layer.
|
||||
Current,
|
||||
/// The current layer and the ones below.
|
||||
CurrentAndBelow,
|
||||
/// Every layer.
|
||||
#[default]
|
||||
All,
|
||||
/// Every layer but adjustments.
|
||||
AllNoAdjustments,
|
||||
/// The current layer and the ones below, but no adjustments.
|
||||
CurrentAndBelowNoAdjustments,
|
||||
}
|
||||
|
||||
impl SampleSource {
|
||||
/// Every source in menu order.
|
||||
pub const ALL: [SampleSource; 5] = [
|
||||
SampleSource::Current,
|
||||
SampleSource::CurrentAndBelow,
|
||||
SampleSource::All,
|
||||
SampleSource::AllNoAdjustments,
|
||||
SampleSource::CurrentAndBelowNoAdjustments,
|
||||
];
|
||||
|
||||
/// The stable id of the source, for settings and scripts.
|
||||
pub fn id(self) -> &'static str {
|
||||
match self {
|
||||
SampleSource::Current => "current",
|
||||
SampleSource::CurrentAndBelow => "currentAndBelow",
|
||||
SampleSource::All => "all",
|
||||
SampleSource::AllNoAdjustments => "allNoAdjustments",
|
||||
SampleSource::CurrentAndBelowNoAdjustments => "currentAndBelowNoAdjustments",
|
||||
}
|
||||
}
|
||||
|
||||
/// The menu text.
|
||||
pub fn label(self, words: &EyedropperWords) -> Label {
|
||||
match self {
|
||||
SampleSource::Current => &words.current_layer,
|
||||
SampleSource::CurrentAndBelow => &words.current_and_below,
|
||||
SampleSource::All => &words.all_layers,
|
||||
SampleSource::AllNoAdjustments => &words.all_layers_no_adjustments,
|
||||
SampleSource::CurrentAndBelowNoAdjustments => &words.current_and_below_no_adjustments,
|
||||
}
|
||||
.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// The Eyedropper's options bar values.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub struct EyedropperOptions {
|
||||
/// How many pixels are averaged.
|
||||
pub size: SampleSize,
|
||||
/// Which layers are read.
|
||||
pub source: SampleSource,
|
||||
/// Whether the sampling ring shows while the button is down.
|
||||
pub show_ring: bool,
|
||||
}
|
||||
|
||||
impl Default for EyedropperOptions {
|
||||
/// Point Sample, All Layers, ring on.
|
||||
fn default() -> Self {
|
||||
EyedropperOptions { size: SampleSize::Point, source: SampleSource::All, show_ring: true }
|
||||
}
|
||||
}
|
||||
|
||||
/// The Eyedropper's members of an options bar: Sample Size and Sample as selects, Show Sampling Ring as a check box,
|
||||
/// and the hint. Show it inside the options `Bar`; the members write into `options`.
|
||||
#[must_use = "show the bar with `show`"]
|
||||
#[derive(Pattern)]
|
||||
pub struct EyedropperBar<'a> {
|
||||
options: &'a mut EyedropperOptions,
|
||||
}
|
||||
|
||||
/// What [`EyedropperBar::show`] reports: the edit of each member.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
pub struct EyedropperBarOutput {
|
||||
/// Sample Size.
|
||||
pub size: EditResponse<SampleSize>,
|
||||
/// Sample.
|
||||
pub source: EditResponse<SampleSource>,
|
||||
/// Show Sampling Ring.
|
||||
pub ring: EditResponse<bool>,
|
||||
}
|
||||
|
||||
impl Outcome for EyedropperBarOutput {
|
||||
type Value = EyedropperOptions;
|
||||
|
||||
fn response(&self) -> &Response {
|
||||
&self.size.response
|
||||
}
|
||||
|
||||
#[cfg(feature = "screen-testing")]
|
||||
fn story_facts(&self) -> craft_ui::testing::StoryOutput {
|
||||
self.size.story_facts()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> EyedropperBar<'a> {
|
||||
/// The members over `options`.
|
||||
pub fn new(options: &'a mut EyedropperOptions) -> Self {
|
||||
EyedropperBar { options }
|
||||
}
|
||||
|
||||
/// Shows the members.
|
||||
pub fn show(self, ui: &mut Ui) -> EyedropperBarOutput {
|
||||
let EyedropperBar { options } = self;
|
||||
let env = Env::of(ui);
|
||||
let words = env.words::<EyedropperWords>();
|
||||
let sizes: Vec<Entry<SampleSize>> = SampleSize::ALL.iter().map(|size| Entry::new(*size, size.label(&words))).collect();
|
||||
let sources: Vec<Entry<SampleSource>> = SampleSource::ALL.iter().map(|source| Entry::new(*source, source.label(&words))).collect();
|
||||
let size =
|
||||
Field::new(words.sample_size.clone()).show(ui, |ui, _| Select::new(words.size.clone(), Bind::bound(&mut options.size), &sizes).show(ui));
|
||||
let source =
|
||||
Field::new(words.sample.clone()).show(ui, |ui, _| Select::new(words.source.clone(), Bind::bound(&mut options.source), &sources).show(ui));
|
||||
let ring = Checkbox::new(Bind::bound(&mut options.show_ring)).label(words.show_ring.clone()).show(ui);
|
||||
let key = if env.view().shell().os == Os::Mac { "Option" } else { "Alt" };
|
||||
Text::new(Label::from(words.hint.fill(&[("key", key)]))).show(ui);
|
||||
// A parent's sizing pass places a field without running its body: that run reports no edit.
|
||||
let (size_response, source_response) = (size.response().clone(), source.response().clone());
|
||||
EyedropperBarOutput {
|
||||
size: size.inner.unwrap_or_else(|| EditResponse::lifted(size_response, EditEvents::new(), None)),
|
||||
source: source.inner.unwrap_or_else(|| EditResponse::lifted(source_response, EditEvents::new(), None)),
|
||||
ring,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The picked colour, and whether it is for the background.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct EyedropperPick {
|
||||
/// The sampled colour.
|
||||
pub color: Srgba,
|
||||
/// Alt was held: the colour is for the background.
|
||||
pub background: bool,
|
||||
}
|
||||
|
||||
/// The pipette icon's tip, in the icon's own 24-unit box.
|
||||
const HOTSPOT: [f32; 2] = [2.0, 22.0];
|
||||
/// The ring's outer radius in points.
|
||||
const RING_OUTER_RADIUS: f32 = 105.0;
|
||||
/// The width of each of the ring's two colour bands in points.
|
||||
const RING_BAND: f32 = 17.0;
|
||||
/// How many segments approximate a ring.
|
||||
const RING_SEGMENTS: usize = 48;
|
||||
|
||||
/// The Eyedropper tool: a press samples the foreground (Alt: the background) and a drag resamples. The sampling ring
|
||||
/// (the new colour over the current one) paints while the button is held.
|
||||
pub struct EyedropperTool<'a> {
|
||||
options: EyedropperOptions,
|
||||
sample: Box<dyn FnMut([f64; 2], SampleSize, SampleSource) -> Option<Srgba> + 'a>,
|
||||
held: Option<(Pos2, Srgba)>,
|
||||
picked: Option<EyedropperPick>,
|
||||
foreground: Srgba,
|
||||
}
|
||||
|
||||
impl<'a> EyedropperTool<'a> {
|
||||
/// A tool sampling through `sample` with the document point, the sample size and the source (`None` outside the
|
||||
/// document).
|
||||
pub fn new(options: EyedropperOptions, sample: impl FnMut([f64; 2], SampleSize, SampleSource) -> Option<Srgba> + 'a) -> Self {
|
||||
EyedropperTool { options, sample: Box::new(sample), held: None, picked: None, foreground: Srgba::rgb(0.0, 0.0, 0.0) }
|
||||
}
|
||||
|
||||
/// The current foreground colour: the lower half of the sampling ring.
|
||||
#[must_use]
|
||||
pub fn foreground(mut self, color: Srgba) -> Self {
|
||||
self.foreground = color;
|
||||
self
|
||||
}
|
||||
|
||||
/// The newest pick, once.
|
||||
pub fn take(&mut self) -> Option<EyedropperPick> {
|
||||
self.picked.take()
|
||||
}
|
||||
|
||||
fn sample_at(&mut self, pointer: &ToolPointer, cx: &ToolContext<'_>) {
|
||||
let Some(space) = cx.space() else { return };
|
||||
let Point { x, y } = space.view.to_doc(pointer.pos);
|
||||
match (self.sample)([x, y], self.options.size, self.options.source) {
|
||||
Some(color) => {
|
||||
self.held = Some((pointer.pos, color));
|
||||
self.picked = Some(EyedropperPick { color, background: pointer.mods.alt });
|
||||
}
|
||||
None => self.held = None,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The points of the arc of `radius` from angle `from` to `to` around `center`.
|
||||
fn arc(center: Pos2, radius: f32, from: f32, to: f32) -> Vec<Pos2> {
|
||||
(0..=RING_SEGMENTS)
|
||||
.map(|i| {
|
||||
let angle = from + (to - from) * i as f32 / RING_SEGMENTS as f32;
|
||||
center + vec2(angle.cos(), angle.sin()) * radius
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A band of `color` between the radii `inner` and `outer` over the angles `from` to `to`, as convex quads.
|
||||
fn band(draw: &Draw<'_>, center: Pos2, (inner, outer): (f32, f32), (from, to): (f32, f32), color: Srgba) {
|
||||
let (near, far) = (arc(center, inner, from, to), arc(center, outer, from, to));
|
||||
for at in 0..RING_SEGMENTS {
|
||||
let quad = vec![near[at], far[at], far[at + 1], near[at + 1]];
|
||||
draw.data_fill(&PaintShape::Polygon(quad), DataColor::new(Color32::from(color)));
|
||||
}
|
||||
}
|
||||
|
||||
impl CanvasTool for EyedropperTool<'_> {
|
||||
fn press(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) -> ToolAction {
|
||||
self.picked = None;
|
||||
self.sample_at(pointer, cx);
|
||||
cx.request_repaint();
|
||||
ToolAction::Claimed
|
||||
}
|
||||
|
||||
fn drag(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) {
|
||||
self.sample_at(pointer, cx);
|
||||
cx.request_repaint();
|
||||
}
|
||||
|
||||
fn release(&mut self, _: &ToolPointer, _: &mut ToolContext<'_>) {
|
||||
self.held = None;
|
||||
}
|
||||
|
||||
fn cancel(&mut self, _: CancelReason, _: &mut ToolContext<'_>) {
|
||||
self.held = None;
|
||||
self.picked = None;
|
||||
}
|
||||
|
||||
fn paint(&self, draw: &Draw<'_>, cx: &ToolContext<'_>) {
|
||||
let (true, Some((center, new)), Some(style)) = (self.options.show_ring, self.held, cx.style()) else { return };
|
||||
let tokens = style.tokens;
|
||||
let inner = RING_OUTER_RADIUS - 2.0 * RING_BAND;
|
||||
band(draw, center, (inner, inner + RING_BAND), (PI, TAU), new);
|
||||
band(draw, center, (inner, inner + RING_BAND), (0.0, PI), self.foreground);
|
||||
let grey = style.color(tokens.color.overlay.grid);
|
||||
let ring = |radius: f32| {
|
||||
let mut points = arc(center, radius, 0.0, TAU);
|
||||
points.truncate(RING_SEGMENTS);
|
||||
points.push(points[0]);
|
||||
PaintShape::Path(points)
|
||||
};
|
||||
draw.stroke(&ring(inner + RING_BAND * 1.5), StrokeWidth::Thick, grey);
|
||||
draw.stroke(&ring(RING_OUTER_RADIUS), StrokeWidth::Hairline, style.color(tokens.color.overlay.halo));
|
||||
draw.stroke(&ring(inner), StrokeWidth::Hairline, style.color(tokens.color.overlay.halo));
|
||||
}
|
||||
|
||||
/// The pipette with its tip on the sampled pixel (the icon's lower left, in its 24-unit box).
|
||||
fn cursor(&self, _: &ToolContext<'_>) -> Cursor {
|
||||
PaintedCursor::tool(IconId::new("eyedropper"), Vec2::from(HOTSPOT), None).into()
|
||||
}
|
||||
|
||||
fn autoscrolls(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn command_form(&self) -> ToolPath {
|
||||
ToolPath::Command("the Color Picker command")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
//! Stories of `EyedropperBar`.
|
||||
|
||||
use super::{EyedropperBar, EyedropperOptions};
|
||||
use craft_ui::bars::{Bar, BarKind};
|
||||
use craft_ui::contract::ShowContainer as _;
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use egui::Ui;
|
||||
|
||||
#[story(EyedropperBar<'static>, covers = [], drive = Drive::Never)]
|
||||
fn eyedropper_bar(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let options = data.value("options", EyedropperOptions::default());
|
||||
let shown = Bar::new("Eyedropper options", BarKind::Options).show(ui, |ui, _| EyedropperBar::new(&mut *options).show(ui));
|
||||
match shown.inner {
|
||||
Some(output) => StoryOutput::from(output),
|
||||
None => StoryOutput::from(shown.output),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,447 @@
|
||||
//! Harmony controls: `HarmonyWheel`, the colours of a harmony as markers on a hue and saturation wheel, and
|
||||
//! `HarmonyPanel`, Color Guide (rule, harmony strip, variation grid). The maths is [`crate::harmony`].
|
||||
|
||||
use craft_behavior::{EditEvent, Selection};
|
||||
use craft_theme::{Hsb, Srgba};
|
||||
use craft_ui::contract::{Bind, CommandSet, Entry, Held, NoValue, Outcome, Pattern, Props as _, Remember as _, Show as _, ShowContainer as _};
|
||||
use craft_ui::display::Text;
|
||||
use craft_ui::layout::RowAlign;
|
||||
use craft_ui::layout_components::{Row, Stack};
|
||||
use craft_ui::menu::PanelRow;
|
||||
use craft_ui::pickers::Select;
|
||||
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 super::picker::{ChannelRow, ChannelRule};
|
||||
use super::{ColorDisc, SwatchTable, SwatchTableOutput};
|
||||
use crate::harmony::{Guide, GuideOptions, Harmony, Variation};
|
||||
|
||||
#[cfg(feature = "screen-testing")]
|
||||
mod stories;
|
||||
|
||||
craft_ui::words! {
|
||||
/// The words of the harmony controls and of the Color Guide panel menu.
|
||||
#[non_exhaustive]
|
||||
pub struct HarmonyWords {
|
||||
rule: "harmony.rule" = "Rule";
|
||||
brightness: "harmony.brightness" = "Brightness";
|
||||
set_base: "harmony.setBase" = "Set base color to the current color";
|
||||
harmony: "harmony.harmony" = "Harmony colors";
|
||||
variations: "harmony.variations" = "Variations";
|
||||
shades: "harmony.shades" = "Shades";
|
||||
tints: "harmony.tints" = "Tints";
|
||||
cool: "harmony.cool" = "Cool";
|
||||
warm: "harmony.warm" = "Warm";
|
||||
muted: "harmony.muted" = "Muted";
|
||||
vivid: "harmony.vivid" = "Vivid";
|
||||
complementary: "harmony.ruleComplementary" = "Complementary";
|
||||
complementary2: "harmony.ruleComplementary2" = "Complementary 2";
|
||||
split_complementary: "harmony.ruleSplitComplementary" = "Split Complementary";
|
||||
left_complement: "harmony.ruleLeftComplement" = "Left Complement";
|
||||
right_complement: "harmony.ruleRightComplement" = "Right Complement";
|
||||
analogous: "harmony.ruleAnalogous" = "Analogous";
|
||||
analogous2: "harmony.ruleAnalogous2" = "Analogous 2";
|
||||
monochromatic: "harmony.ruleMonochromatic" = "Monochromatic";
|
||||
shades_rule: "harmony.ruleShades" = "Shades";
|
||||
triad: "harmony.ruleTriad" = "Triad";
|
||||
triad2: "harmony.ruleTriad2" = "Triad 2";
|
||||
triad3: "harmony.ruleTriad3" = "Triad 3";
|
||||
tetrad: "harmony.ruleTetrad" = "Tetrad";
|
||||
tetrad2: "harmony.ruleTetrad2" = "Tetrad 2";
|
||||
tetrad3: "harmony.ruleTetrad3" = "Tetrad 3";
|
||||
compound: "harmony.ruleCompound" = "Compound";
|
||||
compound2: "harmony.ruleCompound2" = "Compound 2";
|
||||
high_contrast: "harmony.ruleHighContrast" = "High Contrast";
|
||||
high_contrast2: "harmony.ruleHighContrast2" = "High Contrast 2";
|
||||
high_contrast3: "harmony.ruleHighContrast3" = "High Contrast 3";
|
||||
pentagram: "harmony.rulePentagram" = "Pentagram";
|
||||
}
|
||||
}
|
||||
|
||||
impl HarmonyWords {
|
||||
/// The name of `rule`.
|
||||
pub fn rule_name(&self, rule: Harmony) -> &Label {
|
||||
match rule {
|
||||
Harmony::Complementary => &self.complementary,
|
||||
Harmony::Complementary2 => &self.complementary2,
|
||||
Harmony::SplitComplementary => &self.split_complementary,
|
||||
Harmony::LeftComplement => &self.left_complement,
|
||||
Harmony::RightComplement => &self.right_complement,
|
||||
Harmony::Analogous => &self.analogous,
|
||||
Harmony::Analogous2 => &self.analogous2,
|
||||
Harmony::Monochromatic => &self.monochromatic,
|
||||
Harmony::Shades => &self.shades_rule,
|
||||
Harmony::Triad => &self.triad,
|
||||
Harmony::Triad2 => &self.triad2,
|
||||
Harmony::Triad3 => &self.triad3,
|
||||
Harmony::Tetrad => &self.tetrad,
|
||||
Harmony::Tetrad2 => &self.tetrad2,
|
||||
Harmony::Tetrad3 => &self.tetrad3,
|
||||
Harmony::Compound => &self.compound,
|
||||
Harmony::Compound2 => &self.compound2,
|
||||
Harmony::HighContrast => &self.high_contrast,
|
||||
Harmony::HighContrast2 => &self.high_contrast2,
|
||||
Harmony::HighContrast3 => &self.high_contrast3,
|
||||
Harmony::Pentagram => &self.pentagram,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a [`HarmonyWheel`] reports.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
#[must_use = "the host applies the edits"]
|
||||
pub struct HarmonyWheelOutput {
|
||||
/// The wheel's response.
|
||||
pub response: Response,
|
||||
/// The colour whose marker was pressed; it becomes the selected one.
|
||||
pub pressed: Option<usize>,
|
||||
/// 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),
|
||||
/// linked while a rule is chosen. A pass reports the marker's edit and the slider's, in that order, when both
|
||||
/// happened. An edit with no value (a cancel) is for the selected colour.
|
||||
pub edits: Vec<(usize, EditEvent<[Option<f32>; 3]>)>,
|
||||
}
|
||||
|
||||
impl Outcome for HarmonyWheelOutput {
|
||||
type Value = NoValue;
|
||||
|
||||
fn response(&self) -> &Response {
|
||||
&self.response
|
||||
}
|
||||
}
|
||||
|
||||
/// A hue and saturation wheel at the selected colour's brightness (hue around, saturation outwards), a marker per
|
||||
/// colour joined to the centre by a line (the selected one larger), and a Brightness slider for the selected colour
|
||||
/// under it.
|
||||
///
|
||||
/// - Press a marker to select it; drag it to move that colour. The keys are the disc's.
|
||||
/// - AccessKit: a group named by the label; each marker named by its hex.
|
||||
#[must_use = "show the wheel with `show`"]
|
||||
#[derive(Pattern)]
|
||||
pub struct HarmonyWheel<'a> {
|
||||
label: Label,
|
||||
colors: &'a [Srgba],
|
||||
selected: Option<usize>,
|
||||
}
|
||||
|
||||
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 }
|
||||
}
|
||||
|
||||
/// Marks the colour at this index as selected; none by default.
|
||||
pub fn selected_marker(mut self, selected: Option<usize>) -> Self {
|
||||
self.selected = selected;
|
||||
self
|
||||
}
|
||||
|
||||
/// Shows the wheel and the Brightness row.
|
||||
pub fn show(self, ui: &mut Ui) -> HarmonyWheelOutput {
|
||||
let HarmonyWheel { label, colors, selected } = self;
|
||||
let words = Env::of(ui).words::<HarmonyWords>();
|
||||
let selected = 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);
|
||||
let names: Vec<Label> = colors.iter().map(|c| Label::from(c.to_hex())).collect();
|
||||
let mut pressed = 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(selected) = selected {
|
||||
disc = disc.chosen(selected);
|
||||
}
|
||||
let disc = disc.brightness(brightness).names(names.clone()).show(ui);
|
||||
pressed = disc.pressed;
|
||||
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])));
|
||||
}
|
||||
}
|
||||
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 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);
|
||||
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)])));
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
HarmonyWheelOutput { response: shown.output, pressed, edits }
|
||||
}
|
||||
}
|
||||
|
||||
/// The Color Guide panel's settings, kept across runs.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub struct HarmonyPanelState {
|
||||
/// The chosen harmony rule.
|
||||
pub rule: Harmony,
|
||||
/// The variation grid's options.
|
||||
pub options: GuideOptions,
|
||||
}
|
||||
|
||||
/// A Color Guide panel menu entry the app carries out.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub enum HarmonyMenuAction {
|
||||
/// Save Colors as Swatches: the selected cells' colours, in grid order.
|
||||
SaveAsSwatches(Vec<Srgba>),
|
||||
/// Color Guide Options…: the app opens its options dialog (steps 1 to 20 and the Less to More amount of
|
||||
/// [`GuideOptions`]).
|
||||
Options,
|
||||
}
|
||||
|
||||
/// 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>,
|
||||
}
|
||||
|
||||
impl HarmonyPicked {
|
||||
/// The chosen colours, in grid order.
|
||||
pub fn colors(&self) -> &[Srgba] {
|
||||
&self.colors
|
||||
}
|
||||
}
|
||||
|
||||
/// What a [`HarmonyPanel`] reports.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
#[must_use = "the host applies the chosen colour"]
|
||||
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>,
|
||||
/// The base swatch was clicked: the app sets the base to its current colour.
|
||||
pub set_base: bool,
|
||||
}
|
||||
|
||||
impl Outcome for HarmonyPanelOutput {
|
||||
type Value = NoValue;
|
||||
|
||||
fn response(&self) -> &Response {
|
||||
&self.response
|
||||
}
|
||||
}
|
||||
|
||||
/// What the guide is made from.
|
||||
#[derive(Clone, PartialEq)]
|
||||
struct GuideKey {
|
||||
base: Srgba,
|
||||
rule: Harmony,
|
||||
options: GuideOptions,
|
||||
limit: Option<Vec<Srgba>>,
|
||||
}
|
||||
|
||||
impl GuideKey {
|
||||
fn stamp(&self) -> u64 {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
format!("{:?}", (self.base, self.rule, self.options, &self.limit)).hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
}
|
||||
|
||||
/// The guide kept until what it is made from changes: snapping every cell to a library is slow to redo each pass.
|
||||
#[derive(Clone, Default)]
|
||||
struct GuideCache(Option<(GuideKey, Guide)>);
|
||||
|
||||
impl GuideCache {
|
||||
fn of(&mut self, key: &GuideKey) -> Guide {
|
||||
if let Some((kept, guide)) = &self.0
|
||||
&& kept == key
|
||||
{
|
||||
return guide.clone();
|
||||
}
|
||||
let guide = Guide::new(key.base, key.rule, &key.options);
|
||||
let guide = match &key.limit {
|
||||
Some(palette) => guide.limited(palette),
|
||||
None => guide,
|
||||
};
|
||||
self.0 = Some((key.clone(), guide.clone()));
|
||||
guide
|
||||
}
|
||||
}
|
||||
|
||||
/// 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 grid's end labels. A click on any cell chooses its colour; Shift or Cmd selects
|
||||
/// several for Save Colors as Swatches.
|
||||
#[must_use = "show the panel with `show`"]
|
||||
#[derive(Pattern)]
|
||||
pub struct HarmonyPanel<'a> {
|
||||
state: Bind<'a, HarmonyPanelState>,
|
||||
picked: Bind<'a, HarmonyPicked>,
|
||||
base: Srgba,
|
||||
limit: Option<&'a [Srgba]>,
|
||||
}
|
||||
|
||||
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 }
|
||||
}
|
||||
|
||||
/// Limit to Library: every colour snaps to the nearest of `palette`.
|
||||
pub fn limit(mut self, palette: &'a [Srgba]) -> Self {
|
||||
self.limit = Some(palette);
|
||||
self
|
||||
}
|
||||
|
||||
/// Shows the panel.
|
||||
pub fn show(self, ui: &mut Ui) -> HarmonyPanelOutput {
|
||||
let HarmonyPanel { state, picked, base, limit } = self;
|
||||
let words = Env::of(ui).words::<HarmonyWords>();
|
||||
let mut held_state = Held::new(state);
|
||||
let mut held_picked = Held::new(picked);
|
||||
let (mut chosen, mut set_base) = (None, false);
|
||||
let mut shown = Stack::new().show(ui, |ui, cx| {
|
||||
let before = held_state.read(cx)?;
|
||||
let before_picked = held_picked.read(cx).unwrap_or_default();
|
||||
let key = GuideKey { base, rule: before.rule, options: before.options, limit: limit.map(<[Srgba]>::to_vec) };
|
||||
let stamp = key.stamp();
|
||||
let guide = cx.memory::<GuideCache>().of(&key);
|
||||
let mut now = before;
|
||||
|
||||
let rules: Vec<Entry<Harmony>> = Harmony::ALL.iter().map(|rule| Entry::new(*rule, words.rule_name(*rule).clone())).collect();
|
||||
Row::new().show(ui, |ui, _| {
|
||||
set_base |= craft_ui::choice::Swatch::new(words.set_base.clone(), base).tooltip(words.set_base.clone()).show(ui).clicked;
|
||||
if let Some(rule) = Select::new(words.rule.clone(), Bind::given(before.rule), &rules).show(ui).value().copied() {
|
||||
now.rule = rule;
|
||||
}
|
||||
});
|
||||
|
||||
let strip: Vec<(Label, Srgba)> = guide.colors.iter().map(|c| (Label::from(c.to_hex()), *c)).collect();
|
||||
let mut strip_selection = Selection::default();
|
||||
let out =
|
||||
SwatchTable::new(words.harmony.clone(), &strip).per_row(strip.len().max(1)).selection(Bind::bound(&mut strip_selection)).show_all(ui);
|
||||
if let Some(i) = out.selected {
|
||||
chosen = strip.get(i).map(|(_, c)| *c);
|
||||
}
|
||||
|
||||
let columns = guide.grid.first().map_or(1, Vec::len);
|
||||
let flat: Vec<(Label, Srgba)> = guide.grid.iter().flatten().map(|c| (Label::from(c.to_hex()), *c)).collect();
|
||||
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).multiple(true).per_row(columns).selection(Bind::bound(&mut selection)).show_all(ui);
|
||||
if let Some(i) = selected
|
||||
&& cells.len() == 1
|
||||
{
|
||||
chosen = flat.get(i).map(|(_, c)| *c);
|
||||
}
|
||||
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 (left, right) = match before.options.variation {
|
||||
Variation::TintsShades => (&words.shades, &words.tints),
|
||||
Variation::WarmCool => (&words.cool, &words.warm),
|
||||
Variation::VividMuted => (&words.muted, &words.vivid),
|
||||
};
|
||||
Row::new().align(RowAlign::SpaceBetween).show(ui, |ui, _| {
|
||||
Text::new(left.clone()).show(ui);
|
||||
Text::new(right.clone()).show(ui);
|
||||
});
|
||||
|
||||
Some((before, now, before_picked, after_picked))
|
||||
});
|
||||
// Once per pass, after the real run: the edited rule and the picked cells are stored.
|
||||
shown.settle(|cx, edited| {
|
||||
let Some((before, now, before_picked, after_picked)) = edited.take() else { return };
|
||||
if after_picked != before_picked {
|
||||
held_picked.write(cx, &before_picked, after_picked, words.variations.as_str());
|
||||
}
|
||||
if now != before {
|
||||
held_state.write(cx, &before, now, words.rule.as_str());
|
||||
}
|
||||
});
|
||||
HarmonyPanelOutput { response: shown.output, chosen, set_base }
|
||||
}
|
||||
}
|
||||
|
||||
/// The Color Guide panel menu's commands.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, CommandSet)]
|
||||
#[command(prefix = "colorGuide")]
|
||||
#[non_exhaustive]
|
||||
pub enum HarmonyCommand {
|
||||
/// Show the variation grid from shades to tints.
|
||||
#[command(label = "Show Tints/Shades", kind = "radio", group = "colorGuide.variation")]
|
||||
TintsShades,
|
||||
/// Show the variation grid from cool to warm.
|
||||
#[command(label = "Show Warm/Cool", kind = "radio", group = "colorGuide.variation")]
|
||||
WarmCool,
|
||||
/// Show the variation grid from muted to vivid.
|
||||
#[command(label = "Show Vivid/Muted", kind = "radio", group = "colorGuide.variation")]
|
||||
VividMuted,
|
||||
/// Save the chosen cells' colours as swatches.
|
||||
#[command(label = "Save Colors as Swatches")]
|
||||
SaveAsSwatches,
|
||||
/// Open the Color Guide options.
|
||||
#[command(label = "Color Guide Options…")]
|
||||
Options,
|
||||
}
|
||||
|
||||
/// The Color Guide panel menu: the rows for the dock's panel menu, the states the host publishes, and the carrying out
|
||||
/// of a fired command.
|
||||
pub struct HarmonyMenu;
|
||||
|
||||
impl HarmonyMenu {
|
||||
/// The rows: Show Tints/Shades, Show Warm/Cool, Show Vivid/Muted, a separator, Save Colors as Swatches and Color
|
||||
/// Guide Options….
|
||||
pub fn rows() -> Vec<PanelRow> {
|
||||
let row = |command: HarmonyCommand| PanelRow::Command(CommandRef::from(command));
|
||||
vec![
|
||||
row(HarmonyCommand::TintsShades),
|
||||
row(HarmonyCommand::WarmCool),
|
||||
row(HarmonyCommand::VividMuted),
|
||||
PanelRow::Separator,
|
||||
row(HarmonyCommand::SaveAsSwatches),
|
||||
row(HarmonyCommand::Options),
|
||||
]
|
||||
}
|
||||
|
||||
/// The state of each command: the current variation checked; Save Colors as Swatches enabled while cells are
|
||||
/// chosen.
|
||||
pub fn states(state: &HarmonyPanelState, picked: &HarmonyPicked) -> Vec<(HarmonyCommand, CommandState)> {
|
||||
let variation = |command, mine| (command, CommandState::new().checked(state.options.variation == mine));
|
||||
vec![
|
||||
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::Options, CommandState::new()),
|
||||
]
|
||||
}
|
||||
|
||||
/// Carries out `command`: a variation is set in `state`; the others come back for the app.
|
||||
pub fn run_command(state: &mut HarmonyPanelState, picked: &HarmonyPicked, command: HarmonyCommand) -> Option<HarmonyMenuAction> {
|
||||
match command {
|
||||
HarmonyCommand::TintsShades => state.options.variation = Variation::TintsShades,
|
||||
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()));
|
||||
}
|
||||
HarmonyCommand::Options => return Some(HarmonyMenuAction::Options),
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
//! Stories of `HarmonyWheel` and `HarmonyPanel`.
|
||||
|
||||
use super::{HarmonyPanel, HarmonyPanelState, HarmonyPicked, HarmonyWheel};
|
||||
use crate::harmony::Harmony;
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::contract::{Bind, ShowContainer as _};
|
||||
use craft_ui::layout_components::Stack;
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use egui::Ui;
|
||||
|
||||
const BASE: Srgba = Srgba::rgb(0.86, 0.24, 0.16);
|
||||
|
||||
#[story(HarmonyPanel<'static>, covers = [], drive = Drive::Never)]
|
||||
fn harmony_panel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let (state, picked) = data.value("guide", (triad(), HarmonyPicked::default()));
|
||||
let colors = state.rule.apply(BASE);
|
||||
// The wheel above the panel shows the panel's rule on the base colour, as a Color Guide works with the wheel.
|
||||
Stack::new()
|
||||
.show(ui, |ui, _| {
|
||||
let _ = HarmonyWheel::new("Harmony", &colors).selected_marker(Some(0)).show(ui);
|
||||
StoryOutput::from(HarmonyPanel::new(Bind::bound(&mut *state), Bind::bound(&mut *picked), BASE).show(ui))
|
||||
})
|
||||
.inner
|
||||
.unwrap_or_default()
|
||||
}
|
||||
|
||||
/// The panel set to a triad.
|
||||
fn triad() -> HarmonyPanelState {
|
||||
HarmonyPanelState { rule: Harmony::Triad, ..HarmonyPanelState::default() }
|
||||
}
|
||||
|
||||
#[story(HarmonyWheel<'static>, covers = [], drive = Drive::Never)]
|
||||
fn harmony_wheel(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
let colors = Harmony::Triad.apply(BASE);
|
||||
HarmonyWheel::new("Harmony", &colors).selected_marker(Some(1)).show(ui).into()
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
//! `PairCodec` and `HexPairField`: a byte as two hex digits, the field of a Web Color slider.
|
||||
//!
|
||||
//! The colour's own hex field is `craft_ui::text::HexField`.
|
||||
|
||||
use craft_behavior::{Caret, Codec, NotAValue};
|
||||
use craft_ui::contract::Bind;
|
||||
use craft_ui::runtime::env::Label;
|
||||
use craft_ui::text::TextField;
|
||||
use std::borrow::Cow;
|
||||
|
||||
/// The widest text a byte takes, for the field's ideal width.
|
||||
const WIDEST: &str = "FF";
|
||||
|
||||
/// A byte as two hex digits, uppercase as Photoshop's Web Color Sliders show it. Typed text is exactly two hex
|
||||
/// digits; anything else is not a value.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub struct PairCodec;
|
||||
|
||||
impl Codec for PairCodec {
|
||||
type Value = u8;
|
||||
|
||||
fn format(&self, value: &u8) -> String {
|
||||
format!("{value:02X}")
|
||||
}
|
||||
|
||||
fn parse(&self, text: &str, _start: &u8) -> Result<u8, NotAValue> {
|
||||
// Two hex digits only: `from_str_radix` would also take a sign.
|
||||
let text = text.trim();
|
||||
match u8::from_str_radix(text, 16) {
|
||||
Ok(value) if text.len() == 2 && text.bytes().all(|byte| byte.is_ascii_hexdigit()) => Ok(value),
|
||||
_ => Err(NotAValue),
|
||||
}
|
||||
}
|
||||
|
||||
fn applies_as_typed(&self, _text: &str) -> bool {
|
||||
true
|
||||
}
|
||||
|
||||
fn filter(&self, c: char) -> bool {
|
||||
c.is_ascii_hexdigit()
|
||||
}
|
||||
|
||||
fn caret_on_focus(&self, _text: &str) -> Caret {
|
||||
Caret::All
|
||||
}
|
||||
|
||||
fn sample(&self, _current: &u8) -> Cow<'_, str> {
|
||||
Cow::Borrowed(WIDEST)
|
||||
}
|
||||
}
|
||||
|
||||
/// A text field over a byte's two hex digits.
|
||||
pub type HexPairField<'a> = TextField<'a, PairCodec>;
|
||||
|
||||
/// The constructor of [`HexPairField`].
|
||||
pub trait HexPair<'a> {
|
||||
/// A pair field named `label` that shows and edits `value`.
|
||||
fn hex_pair(label: impl Into<Label>, value: Bind<'a, u8>) -> Self;
|
||||
}
|
||||
|
||||
impl<'a> HexPair<'a> for TextField<'a, PairCodec> {
|
||||
fn hex_pair(label: impl Into<Label>, value: Bind<'a, u8>) -> Self {
|
||||
TextField::with_codec(label, value, PairCodec)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,398 @@
|
||||
//! [`LutPicker`] (F04.04): the 3D LUT choice of a Color Lookup adjustment, as PhotoCraft's: Load
|
||||
//! 3D LUT…, None, the built-in looks ([`craft_cms::lutfile::BUILTIN`]), the files of the app's
|
||||
//! LUT folder, and the loaded LUT. Load 3D LUT… picks the file through the host's
|
||||
//! [`Files`](craft_host::Files) and reads and parses it as a [`Jobs`](craft_host::Jobs) job.
|
||||
|
||||
use std::path::{Path, PathBuf};
|
||||
use std::sync::{Arc, OnceLock};
|
||||
use std::time::Instant;
|
||||
|
||||
use craft_behavior::{EditEvent, EditEvents, Metrics, Mixed, Proposal, Sense};
|
||||
use craft_cms::lutfile::{LutError, LutFile};
|
||||
use craft_host::{PickId, PickRequest, Picked};
|
||||
use craft_ui::contract::{
|
||||
Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Entry, Job, MeasureCx, Outcome, PaintUi, Pending, Remember as _, Role,
|
||||
WordSetCx as _,
|
||||
};
|
||||
use craft_ui::pickers::Select;
|
||||
use craft_ui::runtime::env::Label;
|
||||
use craft_ui::style::{ComponentStyle, StyleCx};
|
||||
use egui::{Response, Vec2};
|
||||
|
||||
#[cfg(feature = "screen-testing")]
|
||||
mod stories;
|
||||
|
||||
craft_ui::words! {
|
||||
/// The LUT picker's rows, English by default, and the built-in looks' names in
|
||||
/// [`BUILTIN`](craft_cms::lutfile::BUILTIN)'s order.
|
||||
#[non_exhaustive]
|
||||
pub struct LutWords {
|
||||
label: "lut.label" = "3D LUT File";
|
||||
load: "lut.load" = "Load 3D LUT…";
|
||||
none: "lut.none" = "None";
|
||||
/// The loaded LUT's row; `{name}` its title, `{size}` its grid size ("Film (33³)").
|
||||
custom: template "lut.custom" = "{name} ({size}³)";
|
||||
warm: "lut.builtinWarm" = "Warm Filter";
|
||||
cool: "lut.builtinCool" = "Cool Filter";
|
||||
teal_orange: "lut.builtinTealOrange" = "Teal & Orange";
|
||||
bleach_bypass: "lut.builtinBleachBypass" = "Bleach Bypass";
|
||||
faded_film: "lut.builtinFadedFilm" = "Faded Film";
|
||||
day_for_night: "lut.builtinDayForNight" = "Day for Night";
|
||||
mono_contrast: "lut.builtinMonoContrast" = "Mono High Contrast";
|
||||
cross_process: "lut.builtinCrossProcess" = "Cross Process";
|
||||
}
|
||||
}
|
||||
|
||||
/// The chosen LUT.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum LutChoice {
|
||||
/// No LUT.
|
||||
None,
|
||||
/// A built-in look by id ([`craft_cms::lutfile::builtin`]).
|
||||
Builtin(&'static str),
|
||||
/// A file of the LUT folder; the app reads and embeds it.
|
||||
Folder(PathBuf),
|
||||
/// The LUT the layer holds, loaded before: its title and grid size.
|
||||
#[non_exhaustive]
|
||||
Loaded {
|
||||
/// The LUT's title.
|
||||
name: String,
|
||||
/// The grid size: points per side.
|
||||
size: usize,
|
||||
},
|
||||
}
|
||||
|
||||
impl LutChoice {
|
||||
/// The LUT the layer holds, called `name`, with `size` points per side.
|
||||
pub fn loaded(name: impl Into<String>, size: usize) -> Self {
|
||||
LutChoice::Loaded { name: name.into(), size }
|
||||
}
|
||||
}
|
||||
|
||||
type FolderFiles = Vec<(String, PathBuf)>;
|
||||
|
||||
/// What [`LutPicker`] returns.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
#[must_use = "the host applies the choice"]
|
||||
pub struct LutPickerOutput {
|
||||
/// A row was chosen. A step of the wheel or the arrow keys over the closed field reports only None and the
|
||||
/// built-ins; a folder file's LUT is read only on the committed pick.
|
||||
pub edit: EditResponse<LutChoice>,
|
||||
/// The LUT file Load 3D LUT… picked, once it is read and parsed, or why it could not be: the
|
||||
/// app embeds the LUT and sets the choice to [`LutChoice::Loaded`]. The choice itself does not
|
||||
/// change until the app does. A cancelled picker reports nothing.
|
||||
pub loaded: Option<Result<LutFile, LutError>>,
|
||||
}
|
||||
|
||||
impl Outcome for LutPickerOutput {
|
||||
type Value = LutChoice;
|
||||
|
||||
fn response(&self) -> &Response {
|
||||
&self.edit.response
|
||||
}
|
||||
|
||||
#[cfg(feature = "screen-testing")]
|
||||
fn story_facts(&self) -> craft_ui::testing::StoryOutput {
|
||||
self.edit.story_facts()
|
||||
}
|
||||
}
|
||||
|
||||
/// The style of the picker: no look of its own, the select is a child.
|
||||
#[derive(Clone, Debug, Default, PartialEq, ComponentStyle)]
|
||||
#[non_exhaustive]
|
||||
pub struct LutPickerStyle {
|
||||
#[style(metrics)]
|
||||
metrics: Metrics,
|
||||
}
|
||||
|
||||
/// A row of the select: Load 3D LUT… or a choice.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
enum Row {
|
||||
Load,
|
||||
Choice(LutChoice),
|
||||
}
|
||||
|
||||
/// How often the LUT folder is scanned again, in seconds.
|
||||
const RESCAN: u64 = 2;
|
||||
|
||||
/// The purpose of the LUT file picker: its folder is remembered under it.
|
||||
const PICK_PURPOSE: &str = "lut";
|
||||
|
||||
/// Where Load 3D LUT… is: the picker open, or the chosen file being read.
|
||||
#[derive(Clone, Default)]
|
||||
enum Load {
|
||||
#[default]
|
||||
Idle,
|
||||
Picking(PickId),
|
||||
Reading(PickId, Source),
|
||||
}
|
||||
|
||||
/// What the chosen file is read from.
|
||||
#[derive(Clone)]
|
||||
enum Source {
|
||||
Path(PathBuf),
|
||||
Contents(String, Arc<Vec<u8>>),
|
||||
}
|
||||
|
||||
/// The scan and the load kept between passes.
|
||||
#[derive(Clone, Default)]
|
||||
struct LutState {
|
||||
folder: Option<PathBuf>,
|
||||
files: Arc<FolderFiles>,
|
||||
load: Load,
|
||||
}
|
||||
|
||||
/// A parsed file as a job result.
|
||||
#[derive(Clone)]
|
||||
struct Parsed(Arc<Result<LutFile, LutError>>);
|
||||
|
||||
impl Default for Parsed {
|
||||
fn default() -> Self {
|
||||
Parsed(Arc::new(Err(LutError(String::new()))))
|
||||
}
|
||||
}
|
||||
|
||||
/// The seconds since the first scan of the process, for the rescan interval.
|
||||
fn seconds() -> u64 {
|
||||
static START: OnceLock<Instant> = OnceLock::new();
|
||||
START.get_or_init(Instant::now).elapsed().as_secs()
|
||||
}
|
||||
|
||||
/// A select of LUTs.
|
||||
///
|
||||
/// - Rows: Load 3D LUT…, None, the eight built-in looks, the LUT folder's files by name (in the language's
|
||||
/// order), and the loaded LUT ("name (33³)") when the layer holds one.
|
||||
/// - Load 3D LUT… asks the host's file service for a `.cube`, `.3dl` or `.look` file (purpose
|
||||
/// `"lut"`) and answers in [`LutPickerOutput::loaded`] on the pass the file is parsed. Without
|
||||
/// a host it does nothing.
|
||||
/// - The folder is scanned as a host job at most every 2 seconds (a network share can be
|
||||
/// slow); until a scan ends the list shows the last one. Another folder drops the old list at
|
||||
/// once. Web has no folder.
|
||||
/// - The wheel and the arrow keys over the closed field step through None and the built-ins
|
||||
/// only (a folder file would be read from disk at each step).
|
||||
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
|
||||
#[component]
|
||||
pub struct LutPicker<'a> {
|
||||
#[common]
|
||||
common: Common,
|
||||
value: Bind<'a, LutChoice>,
|
||||
/// The app's LUT folder (Preferences › File Handling › LUT Folder).
|
||||
#[prop(into)]
|
||||
folder: Option<PathBuf>,
|
||||
loaded: Option<Result<LutFile, LutError>>,
|
||||
load_asked: bool,
|
||||
}
|
||||
|
||||
impl<'a> LutPicker<'a> {
|
||||
/// A picker over `value`.
|
||||
pub fn new(value: Bind<'a, LutChoice>) -> Self {
|
||||
LutPicker { common: Common::new(), value, folder: None, loaded: None, load_asked: false }
|
||||
}
|
||||
|
||||
fn entries(words: &LutWords, current: Option<&LutChoice>, files: &FolderFiles) -> Vec<Entry<Row>> {
|
||||
let mut entries = vec![Entry::new(Row::Load, words.load.clone()), Entry::new(Row::Choice(LutChoice::None), words.none.clone())];
|
||||
for (id, _) in craft_cms::lutfile::BUILTIN {
|
||||
entries.push(Entry::new(Row::Choice(LutChoice::Builtin(id)), builtin_name(words, id)));
|
||||
}
|
||||
let mut listed = false;
|
||||
for (name, path) in files {
|
||||
listed |= matches!(current, Some(LutChoice::Folder(held)) if held == path);
|
||||
entries.push(Entry::new(Row::Choice(LutChoice::Folder(path.clone())), Label::from(name.clone())));
|
||||
}
|
||||
// The file in use while a scan has not found it yet (or the folder changed under it).
|
||||
if let Some(LutChoice::Folder(path)) = current
|
||||
&& !listed
|
||||
{
|
||||
let name = path.file_name().map_or_else(|| path.display().to_string(), |n| n.to_string_lossy().into_owned());
|
||||
entries.push(Entry::new(Row::Choice(LutChoice::Folder(path.clone())), Label::from(name)));
|
||||
}
|
||||
if let Some(LutChoice::Loaded { name, size }) = current {
|
||||
let text = words.custom.fill(&[("name", name), ("size", &size.to_string())]);
|
||||
entries.push(Entry::new(Row::Choice(current.cloned().unwrap_or(LutChoice::None)), Label::from(text)));
|
||||
}
|
||||
entries
|
||||
}
|
||||
|
||||
fn select<'e>(words: &LutWords, shown: Mixed<Row>, entries: &'e [Entry<Row>]) -> Select<'e, Row> {
|
||||
Select::new(words.label.clone(), Bind::given(shown), entries)
|
||||
}
|
||||
}
|
||||
|
||||
impl Component for LutPicker<'_> {
|
||||
const SINGLE_VALUE: bool = true;
|
||||
const ROLE: Role = Role::GROUP;
|
||||
const PARTS: bool = false;
|
||||
const STOPS: bool = false;
|
||||
type Style = LutPickerStyle;
|
||||
type Output = LutPickerOutput;
|
||||
|
||||
fn style(_: &StyleCx<'_>, _: LutPickerStyleKey) -> LutPickerStyle {
|
||||
LutPickerStyle::default()
|
||||
}
|
||||
|
||||
fn sense(&self) -> Sense {
|
||||
Sense::empty()
|
||||
}
|
||||
|
||||
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
let words = cx.words::<LutWords>();
|
||||
let entries = Self::entries(&words, cx.value(), &Vec::new());
|
||||
let mut select = Self::select(&words, Mixed::Mixed, &entries);
|
||||
cx.child("select", &mut select, Proposal::Ideal)
|
||||
}
|
||||
|
||||
fn bind(&mut self) -> Option<BindMut<'_, LutChoice>> {
|
||||
Some(self.value.reborrow())
|
||||
}
|
||||
|
||||
/// Moves the scan and Load 3D LUT… along: a finished scan replaces the list, a new scan starts at most every
|
||||
/// [`RESCAN`] seconds, the picker's answer starts the read and a finished read is reported.
|
||||
fn update(&mut self, cx: &mut Cx<'_, Self>) {
|
||||
let host = cx.env.host().cloned();
|
||||
let mut state = cx.memory::<LutState>().clone();
|
||||
if state.folder != self.folder {
|
||||
state = LutState { folder: self.folder.clone(), load: state.load, ..LutState::default() };
|
||||
}
|
||||
if let Some(folder) = self.folder.clone() {
|
||||
let key = ("lut-scan", folder.clone(), seconds() / RESCAN);
|
||||
let started = folder.clone();
|
||||
if let Pending::Ready(found) = cx.pending(key, move || Job::new(move |_, _| Ok::<_, ()>(Arc::new(list_folder(&started))))) {
|
||||
let mut files = (**found).clone();
|
||||
cx.env.collator().sort_by_key(&mut files, |(name, _)| name.as_str());
|
||||
state.files = Arc::new(files);
|
||||
}
|
||||
}
|
||||
if let Some(host) = host {
|
||||
match state.load.clone() {
|
||||
Load::Idle => {}
|
||||
Load::Picking(id) => {
|
||||
if let Some(picked) = host.files().take_answer(id) {
|
||||
state.load = match picked {
|
||||
Picked::Paths(paths) => paths.into_iter().next().map_or(Load::Idle, |path| Load::Reading(id, Source::Path(path))),
|
||||
Picked::Contents(contents) => contents
|
||||
.into_iter()
|
||||
.next()
|
||||
.map_or(Load::Idle, |(name, bytes)| Load::Reading(id, Source::Contents(name, Arc::new(bytes)))),
|
||||
_ => Load::Idle,
|
||||
};
|
||||
}
|
||||
}
|
||||
Load::Reading(id, source) => {
|
||||
let reader = Arc::clone(&host);
|
||||
let done = match cx.pending(("lut-load", id.0), move || {
|
||||
Job::new(move |_, _| {
|
||||
let parsed = match source {
|
||||
Source::Path(path) => reader
|
||||
.files()
|
||||
.read(&path)
|
||||
.map_err(|e| LutError(e.to_string()))
|
||||
.and_then(|bytes| craft_cms::lutfile::parse(&file_name(&path), &bytes)),
|
||||
Source::Contents(name, bytes) => craft_cms::lutfile::parse(&name, &bytes),
|
||||
};
|
||||
Ok::<_, ()>(Parsed(Arc::new(parsed)))
|
||||
})
|
||||
}) {
|
||||
Pending::Ready(parsed) => Some((*parsed.0).clone()),
|
||||
Pending::Failed(()) | Pending::Lost => Some(Err(LutError(String::new()))),
|
||||
_ => None,
|
||||
};
|
||||
if let Some(result) = done {
|
||||
state.load = Load::Idle;
|
||||
self.loaded = Some(result);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
*cx.memory::<LutState>() = state;
|
||||
}
|
||||
|
||||
/// The select, with the rows of the last scan. A pick of a row is the component's edit; a pick of Load 3D LUT…
|
||||
/// keeps the value and asks for the file.
|
||||
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
|
||||
let words = cx.words::<LutWords>();
|
||||
let state = cx.recall::<LutState>();
|
||||
let entries = Self::entries(&words, cx.value(), &state.files);
|
||||
let shown = cx.value().map_or(Mixed::Mixed, |value| Mixed::Same(Row::Choice(value.clone())));
|
||||
let out = ui.child("select", cx.rect, Self::select(&words, shown, &entries));
|
||||
let mut adopted = EditEvents::new();
|
||||
for event in &out.events {
|
||||
match event.value() {
|
||||
Some(Row::Load) => self.load_asked |= matches!(event, EditEvent::Commit { .. }),
|
||||
Some(Row::Choice(choice)) => {
|
||||
let step = matches!(event, EditEvent::Set { .. });
|
||||
if !step || matches!(choice, LutChoice::None | LutChoice::Builtin(_)) {
|
||||
adopted.push(event.clone());
|
||||
}
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
let adopted = EditResponse::lifted(out.response().clone(), adopted, None);
|
||||
cx.adopt(&adopted, &LutChoice::None, |value, mine| {
|
||||
if let Row::Choice(choice) = value {
|
||||
mine.clone_from(choice);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn finish(self, mut cx: Cx<'_, Self>) -> LutPickerOutput {
|
||||
if self.load_asked
|
||||
&& let Some(host) = cx.env.host().cloned()
|
||||
{
|
||||
if let Load::Picking(old) = cx.memory::<LutState>().load {
|
||||
host.files().forget(old);
|
||||
}
|
||||
let title = cx.words::<LutWords>().load.as_str().trim_end_matches('…').to_owned();
|
||||
let request = PickRequest::open(PICK_PURPOSE).title(title).filter("3D LUT", &["cube", "3dl", "look"]);
|
||||
cx.memory::<LutState>().load = Load::Picking(host.files().pick(request));
|
||||
}
|
||||
LutPickerOutput { edit: cx.edit_response(), loaded: self.loaded }
|
||||
}
|
||||
}
|
||||
|
||||
fn builtin_name(words: &LutWords, id: &str) -> Label {
|
||||
match id {
|
||||
"warm" => words.warm.clone(),
|
||||
"cool" => words.cool.clone(),
|
||||
"tealOrange" => words.teal_orange.clone(),
|
||||
"bleachBypass" => words.bleach_bypass.clone(),
|
||||
"fadedFilm" => words.faded_film.clone(),
|
||||
"dayForNight" => words.day_for_night.clone(),
|
||||
"monoContrast" => words.mono_contrast.clone(),
|
||||
"crossProcess" => words.cross_process.clone(),
|
||||
other => Label::from(other.to_owned()),
|
||||
}
|
||||
}
|
||||
|
||||
fn file_name(path: &Path) -> String {
|
||||
path.file_name().map_or_else(String::new, |n| n.to_string_lossy().into_owned())
|
||||
}
|
||||
/// Most files [`list_folder`] lists.
|
||||
const MAX_FILES: usize = 500;
|
||||
/// Largest file [`list_folder`] lists: a 129³ `.cube` is about 60 MB.
|
||||
const MAX_BYTES: u64 = 64 << 20;
|
||||
|
||||
/// The `.cube`, `.3dl` and `.look` files directly in `dir` as (file name, path), sorted by name
|
||||
/// without regard to case. An unreadable folder lists nothing; hidden files, subfolders and files
|
||||
/// too large to be a LUT are skipped, and a symlink to a LUT file is listed.
|
||||
fn list_folder(dir: &Path) -> FolderFiles {
|
||||
let Ok(entries) = std::fs::read_dir(dir) else { return Vec::new() };
|
||||
let mut out: FolderFiles = entries
|
||||
.flatten()
|
||||
.filter_map(|entry| {
|
||||
let name = entry.file_name().into_string().ok()?;
|
||||
let extension = name.rsplit_once('.')?.1.to_ascii_lowercase();
|
||||
if name.starts_with('.') || !matches!(extension.as_str(), "cube" | "3dl" | "look") {
|
||||
return None;
|
||||
}
|
||||
let path = entry.path();
|
||||
let meta = std::fs::metadata(&path).ok()?;
|
||||
(meta.is_file() && meta.len() <= MAX_BYTES).then_some((name, path))
|
||||
})
|
||||
.collect();
|
||||
out.sort_by_key(|(name, _)| name.to_lowercase());
|
||||
out.truncate(MAX_FILES);
|
||||
out
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
//! Stories of the LUT picker.
|
||||
|
||||
use super::{LutChoice, LutPicker};
|
||||
use craft_ui::contract::{Bind, Props as _, Role, Show as _, Validity};
|
||||
use craft_ui::runtime::env::Message;
|
||||
use craft_ui::testing::{Drive, Fixture, StoryData, StoryOutput, story};
|
||||
use egui::{Key, Modifiers, Ui};
|
||||
|
||||
/// Opens the select and takes the row after the first with the keys.
|
||||
fn pick_second(fixture: &mut Fixture) {
|
||||
if let Some(field) = fixture.by_role(Role::COMBO_BOX).first().copied() {
|
||||
fixture.click(&field);
|
||||
}
|
||||
fixture.key(Key::ArrowDown, Modifiers::NONE);
|
||||
fixture.key(Key::ArrowDown, Modifiers::NONE);
|
||||
fixture.key(Key::Enter, Modifiers::NONE);
|
||||
fixture.idle(2);
|
||||
}
|
||||
|
||||
#[story(LutPicker<'static>, covers = [Default], drive = Drive::Custom(pick_second))]
|
||||
fn lut_picker(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
LutPicker::new(Bind::bound(data.value("lut", LutChoice::Builtin("warm")))).label("3D LUT File").show(ui).into()
|
||||
}
|
||||
|
||||
#[story(LutPicker<'static>, covers = [], drive = Drive::Never)]
|
||||
fn lut_picker_loaded(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
LutPicker::new(Bind::bound(data.value("lut", LutChoice::loaded("Film", 33)))).label("3D LUT File").show(ui).into()
|
||||
}
|
||||
|
||||
#[story(LutPicker<'static>, covers = [Invalid], drive = Drive::Never)]
|
||||
fn lut_picker_invalid(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let refuse_builtin = |choice: &LutChoice| match choice {
|
||||
LutChoice::Builtin(_) => Validity::Refuse(Message::new("Load a file")),
|
||||
_ => Validity::Ok,
|
||||
};
|
||||
LutPicker::new(Bind::bound(data.value("lut", LutChoice::Builtin("warm"))).check(refuse_builtin)).label("3D LUT File").show(ui).into()
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
//! The colour widgets.
|
||||
//!
|
||||
//! - Fields and strips of a colour model: [`ColorArea`], [`ColorStrip`], [`ColorRamp`], [`ColorDisc`], [`ColorWheel`].
|
||||
//! - The picker: [`ColorPicker`], its popover and dialog, the hex and readout fields, the choice list and the droppers.
|
||||
//! - Wells and paints: [`SwatchPair`], [`PaintChip`], [`PaintList`], [`SwatchPalette`], [`SwatchTable`].
|
||||
//! - Panels: [`ColorPanel`], [`HarmonyPanel`], [`SwatchesPanel`].
|
||||
//! - Sampling: the eyedropper, colour samplers and the screen picker.
|
||||
//! - Imaging prompts: [`LutPicker`] and [`ProfileMismatchDialog`].
|
||||
//!
|
||||
//! Colour edits are values of a colour model ([`ModelValues`](craft_theme::ModelValues)) or of [`PickedColor`], and
|
||||
//! report through the edit lifecycle of the contract.
|
||||
|
||||
mod area;
|
||||
mod channels;
|
||||
mod choice;
|
||||
mod disc;
|
||||
mod droppers;
|
||||
mod eyedropper;
|
||||
mod harmony;
|
||||
mod hex;
|
||||
mod lut_picker;
|
||||
mod paint_chip;
|
||||
mod pair;
|
||||
mod palette;
|
||||
mod panel;
|
||||
mod picker;
|
||||
mod picker_dialog;
|
||||
mod popover;
|
||||
mod profile_prompts;
|
||||
mod ramp;
|
||||
mod readout;
|
||||
mod samplers;
|
||||
mod screen_picker;
|
||||
mod strip;
|
||||
mod swatches;
|
||||
/// The stories and trials this crate registers for the integration binary.
|
||||
#[cfg(feature = "screen-testing")]
|
||||
pub mod testing;
|
||||
mod wheel;
|
||||
|
||||
pub use crate::AreaMode;
|
||||
pub use area::{ColorArea, ColorAreaStyle};
|
||||
pub use channels::finite_values;
|
||||
pub use choice::{ChosenColor, ColorChoice, ColorChoiceOutput, ColorChoiceWords, NamedColor};
|
||||
pub use disc::{ColorDisc, ColorDiscOutput, ColorDiscStyle, ColorDiscWords, DiscMove};
|
||||
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,
|
||||
};
|
||||
pub use hex::{HexPair, HexPairField, PairCodec};
|
||||
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,
|
||||
};
|
||||
pub use pair::{PairWell, SwatchPair, SwatchPairOutput, Well};
|
||||
pub use palette::{SwatchCell, SwatchCellStyle, SwatchPalette, SwatchPaletteOutput, SwatchRows, SwatchTable, SwatchTableOutput, SwatchTableStyle};
|
||||
pub use panel::{
|
||||
ColorPanel, ColorPanelCommand, ColorPanelMenu, ColorPanelMode, ColorPanelOutput, ColorPanelRamp, ColorPanelState, ColorPanelWords, PanelTarget,
|
||||
};
|
||||
pub use picker::{
|
||||
ColorConstraint, ColorPicker, ColorPickerLayout, ColorPickerOutput, ColorPickerWords, ColorWarning, ColorWarningChip, ColorWarningChipOutput,
|
||||
PickedColor, ScreenPickGesture,
|
||||
};
|
||||
pub use picker_dialog::{ColorPickerDialog, ColorPickerDialogWords, ColorPickerMemory, ColorPickerResult};
|
||||
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 readout::{ChannelEdit, ColorReadout, ColorReadoutOutput, ColorReadoutWords, ReadoutChannel};
|
||||
pub use samplers::{
|
||||
ColorSamplerCommand, ColorSamplerMarks, ColorSamplerTool, ColorSamplers, MAX_SAMPLERS, SamplerCache, SamplerError, SamplerOptions,
|
||||
SamplerOptionsOutput, SamplerReadout, SamplerReadouts, SamplerWords,
|
||||
};
|
||||
pub use screen_picker::{CaptureResult, CaptureSource, LOUPE_PIXELS, LOUPE_ZOOM, ScreenColorPicker, ScreenPick, ScreenPickerWords, StillCapture};
|
||||
pub use strip::{ColorStrip, ColorStripStyle};
|
||||
pub use swatches::{
|
||||
MAX_GROUPS, MAX_SWATCHES, SwatchAt, SwatchKey, SwatchLibrary, SwatchesCommand, SwatchesFileOutput, SwatchesMenu, SwatchesMenuOutput,
|
||||
SwatchesPanel, SwatchesPanelOutput, SwatchesState, SwatchesWords,
|
||||
};
|
||||
pub use wheel::{
|
||||
ColorWheel, ColorWheelStyle, ColorWheelWords, WheelGeometry, WheelPart, hue_at, hue_direction, triangle_corners, triangle_point, triangle_sv,
|
||||
};
|
||||
@@ -0,0 +1,560 @@
|
||||
//! [`PaintChip`] (F04.06): a shape's fill or stroke paint as a chip that opens a popover with No
|
||||
//! Color, Solid and Gradient, as PhotoCraft's shape options bar and Properties panel; and
|
||||
//! [`PaintList`], named paints in rows with their chips.
|
||||
//!
|
||||
//! The gradient editor is craft-draw's, and craft-draw depends on craft-color, so the chip takes
|
||||
//! the editor's body from the host ([`PaintChip::gradient_editor`]); so do the Pattern and Picture
|
||||
//! tabs ([`PaintChip::pattern_editor`], [`PaintChip::picture_editor`]: craft-draw's
|
||||
//! `PatternFillEditor` and `PictureFillEditor`).
|
||||
|
||||
use craft_behavior::Mixed;
|
||||
use craft_behavior::{Axis, EditEvent, EditEvents, Metrics, PartKey};
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::choice::{ChoiceWords, Segmented, Swatch};
|
||||
use craft_ui::contract::{
|
||||
Access, Activation, Bind, Common, Component, Cx, Edit as _, EditResponse, Entry, Outcome, Overlay, OverlayUi, Overlays as _, PaintUi, PartsCx,
|
||||
Pointer as _, PopupKind, Props as _, Remember as _, Role, Show as _, WordSetCx as _,
|
||||
};
|
||||
use craft_ui::primitives::textures::CachedTexture;
|
||||
use craft_ui::primitives::{ContentPainterCx, PaintShape, StrokeWidth};
|
||||
use craft_ui::runtime::env::Label;
|
||||
use craft_ui::style::{ComponentStyle, DataColor, FocusLook, StyleColor, StyleCx};
|
||||
use egui::{Color32, Pos2, Rect, Response, Ui, pos2, vec2};
|
||||
|
||||
use super::popover::compact_picker;
|
||||
use super::{PickedColor, ScreenPickGesture};
|
||||
|
||||
mod paint_list;
|
||||
#[cfg(feature = "screen-testing")]
|
||||
mod stories;
|
||||
|
||||
pub use paint_list::{PaintLink, PaintLinkKind, PaintList, PaintListEvent, PaintListOptions, PaintListOutput, PaintRow};
|
||||
|
||||
/// The chip is this many control heights wide.
|
||||
const CHIP_WIDTH_IN_HEIGHTS: f32 = 1.5;
|
||||
/// 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");
|
||||
|
||||
craft_ui::words! {
|
||||
/// The words of [`PaintChip`] and [`PaintList`], English by default.
|
||||
#[non_exhaustive]
|
||||
pub struct PaintWords {
|
||||
no_color: "paint.noColor" = "No Color";
|
||||
solid: "paint.solid" = "Solid";
|
||||
gradient: "paint.gradient" = "Gradient";
|
||||
pattern: "paint.pattern" = "Pattern";
|
||||
picture: "paint.picture" = "Picture";
|
||||
/// The chip's value for a screen reader: `{name}` the pattern's name.
|
||||
pattern_named: template "paint.patternNamed" = "Pattern: {name}";
|
||||
/// The chip's value for a screen reader: `{name}` the picture's name.
|
||||
picture_named: template "paint.pictureNamed" = "Picture: {name}";
|
||||
/// A row's chip: opens the picker.
|
||||
edit: "paintList.edit" = "Edit color";
|
||||
hex: "paintList.hex" = "Color";
|
||||
invalid: "paintList.invalid" = "Invalid color";
|
||||
opacity: "paintList.opacity" = "Opacity";
|
||||
detach_style: "paintList.detachStyle" = "Detach style";
|
||||
detach_variable: "paintList.detachVariable" = "Detach variable";
|
||||
styles: "paintList.styles" = "Color styles";
|
||||
/// A row's button: `{name}` the paint it selects the layers of.
|
||||
select_users: template "paintList.selectUsers" = "Select layers with {name}";
|
||||
add: "paintList.add" = "Add";
|
||||
/// A row's button: `{name}` the paint it removes.
|
||||
remove: template "paintList.remove" = "Remove {name}";
|
||||
}
|
||||
}
|
||||
|
||||
/// A gradient as the chip draws it: stops at 0–1 along a start-to-end ramp. The gradient itself
|
||||
/// (angle, style, midpoints) is the host's; it gives this preview with the paint.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct GradientPreview {
|
||||
/// Stops as (position 0–1, colour), ascending by position.
|
||||
pub stops: Vec<(f32, Srgba)>,
|
||||
}
|
||||
|
||||
impl GradientPreview {
|
||||
/// A preview through `stops`.
|
||||
pub fn new(stops: Vec<(f32, Srgba)>) -> Self {
|
||||
GradientPreview { stops }
|
||||
}
|
||||
}
|
||||
|
||||
/// A pattern or picture as the chip draws it: the host's texture of the image (a pattern's tile,
|
||||
/// tiled across the chip at 1:1; a picture, stretched to it) and its name for a screen reader. The
|
||||
/// pattern or picture itself is the host's.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct ImagePreview {
|
||||
/// "Bubbles", "photo.png".
|
||||
pub name: String,
|
||||
/// The image's texture, `None` while the host has none (the chip shows the field fill).
|
||||
pub texture: Option<CachedTexture>,
|
||||
}
|
||||
|
||||
impl ImagePreview {
|
||||
/// A preview of `name` drawn from `texture`.
|
||||
pub fn new(name: impl Into<String>, texture: Option<CachedTexture>) -> Self {
|
||||
ImagePreview { name: name.into(), texture }
|
||||
}
|
||||
}
|
||||
|
||||
/// A paint: none, a solid colour, a gradient, a pattern or a picture. More kinds may come: a
|
||||
/// `match` on it outside craft-color needs a `_` arm.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub enum Paint {
|
||||
/// No paint.
|
||||
None,
|
||||
/// A flat colour.
|
||||
Solid(Srgba),
|
||||
/// A gradient, as the chip previews it.
|
||||
Gradient(GradientPreview),
|
||||
/// A pattern fill (Photoshop's shape Pattern tab, PowerPoint's Pattern fill).
|
||||
Pattern(ImagePreview),
|
||||
/// A picture fill (PowerPoint's Picture or texture fill).
|
||||
Picture(ImagePreview),
|
||||
}
|
||||
|
||||
/// The kinds of paint, as the chip's tabs and an app's fill-type switch name them.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
#[non_exhaustive]
|
||||
pub enum FillKind {
|
||||
#[allow(missing_docs)]
|
||||
None,
|
||||
#[allow(missing_docs)]
|
||||
Solid,
|
||||
#[allow(missing_docs)]
|
||||
Gradient,
|
||||
#[allow(missing_docs)]
|
||||
Pattern,
|
||||
#[allow(missing_docs)]
|
||||
Picture,
|
||||
}
|
||||
|
||||
impl FillKind {
|
||||
/// The kind of `paint`.
|
||||
pub fn of(paint: &Paint) -> FillKind {
|
||||
match paint {
|
||||
Paint::None => FillKind::None,
|
||||
Paint::Solid(_) => FillKind::Solid,
|
||||
Paint::Gradient(_) => FillKind::Gradient,
|
||||
Paint::Pattern(_) => FillKind::Pattern,
|
||||
Paint::Picture(_) => FillKind::Picture,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type PaintEditorFn<'a, T> = Box<dyn FnMut(&mut Ui) -> Option<T> + 'a>;
|
||||
|
||||
/// The host's editor body for one fill kind, drawn in the popover: it edits the host's fill and returns the new
|
||||
/// preview when it changed.
|
||||
pub struct PaintEditor<'a, T>(PaintEditorFn<'a, T>);
|
||||
|
||||
impl<'a, T, F: FnMut(&mut Ui) -> Option<T> + 'a> From<F> for PaintEditor<'a, T> {
|
||||
fn from(editor: F) -> Self {
|
||||
PaintEditor(Box::new(editor))
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> PaintEditor<'_, T> {
|
||||
fn show(&mut self, ui: &mut Ui) -> Option<T> {
|
||||
(self.0)(ui)
|
||||
}
|
||||
}
|
||||
|
||||
/// The style of a paint chip.
|
||||
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
|
||||
#[non_exhaustive]
|
||||
pub struct PaintChipStyle {
|
||||
#[style(metrics)]
|
||||
metrics: Metrics,
|
||||
#[style(focus)]
|
||||
focus: FocusLook,
|
||||
/// The chip's height.
|
||||
height: f32,
|
||||
/// The chip's corners.
|
||||
radius: egui::CornerRadius,
|
||||
/// The ring on the chip's outline.
|
||||
edge: StyleColor,
|
||||
/// The fill of an empty chip: the field's.
|
||||
none_fill: StyleColor,
|
||||
/// The No Color diagonal.
|
||||
none_mark: StyleColor,
|
||||
}
|
||||
|
||||
/// The last solid colour the chip held: a switch back to Solid starts from it.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct LastSolid(Option<Srgba>);
|
||||
|
||||
/// What the popover's body reported this pass.
|
||||
#[derive(Default)]
|
||||
struct Shown {
|
||||
kind: Option<FillKind>,
|
||||
edit: EditEvents<PickedColor>,
|
||||
screen_pick: Option<ScreenPickGesture>,
|
||||
gradient: Option<GradientPreview>,
|
||||
pattern: Option<ImagePreview>,
|
||||
picture: Option<ImagePreview>,
|
||||
}
|
||||
|
||||
/// What a paint chip reports.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
pub struct PaintChipOutput {
|
||||
/// The edit of the paint: a switch of kind is one `Set`, the picker's gestures report as the picker does.
|
||||
pub edit: EditResponse<Paint>,
|
||||
/// The screen eyedropper's press: the host runs the screen pick and answers through [`PaintChip::sampled`].
|
||||
pub screen_pick: Option<ScreenPickGesture>,
|
||||
}
|
||||
|
||||
impl Outcome for PaintChipOutput {
|
||||
type Value = Paint;
|
||||
|
||||
fn response(&self) -> &Response {
|
||||
&self.edit.response
|
||||
}
|
||||
|
||||
#[cfg(feature = "screen-testing")]
|
||||
fn story_facts(&self) -> craft_ui::testing::StoryOutput {
|
||||
self.edit.story_facts()
|
||||
}
|
||||
}
|
||||
|
||||
/// A paint chip, a control high and 1.5 times as wide.
|
||||
///
|
||||
/// - 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
|
||||
/// from bottom start to top end; a pattern tiles its texture at 1:1; a picture is stretched.
|
||||
/// - Click, Enter or Space opens a popover under the chip: a segmented No Color / Solid / Gradient / Pattern /
|
||||
/// Picture switch (No Color only with [`none_allowed`](Self::none_allowed); Gradient, Pattern and Picture only
|
||||
/// when the host gave their editor), then the Compact [`ColorPicker`] (Solid, with the screen eyedropper) or the
|
||||
/// host's editor. Switching to Solid starts from the last solid colour (or the fallback), to Gradient, Pattern
|
||||
/// or Picture from the host's default.
|
||||
/// - Edits: a switch is a `Set`; picker gestures report as the picker does. A screen sample keeps alpha.
|
||||
/// - AccessKit: a colour well named by the label, its value the hex or "No Color", "Gradient", the pattern's or
|
||||
/// picture's name.
|
||||
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
|
||||
#[component(overlay, content_painter)]
|
||||
pub struct PaintChip<'a> {
|
||||
#[common]
|
||||
common: Common,
|
||||
paint: Bind<'a, Paint>,
|
||||
fallback: Srgba,
|
||||
/// No Color is offered (a stroke can be none, a text colour cannot).
|
||||
#[prop(flag)]
|
||||
none_allowed: bool,
|
||||
gradient: Option<(GradientPreview, PaintEditor<'a, GradientPreview>)>,
|
||||
pattern: Option<(ImagePreview, PaintEditor<'a, ImagePreview>)>,
|
||||
picture: Option<(ImagePreview, PaintEditor<'a, ImagePreview>)>,
|
||||
/// The host's answer to the screen eyedropper: a `Set` of the sampled colour that keeps the alpha.
|
||||
#[prop]
|
||||
sampled: Option<Srgba>,
|
||||
screen_pick: Option<ScreenPickGesture>,
|
||||
}
|
||||
|
||||
impl<'a> PaintChip<'a> {
|
||||
/// A chip for `paint` named `label`; `fallback` is the solid colour a switch to Solid starts from when the
|
||||
/// paint has none.
|
||||
pub fn new(label: impl Into<Label>, paint: Bind<'a, Paint>, fallback: Srgba) -> Self {
|
||||
PaintChip {
|
||||
common: Common::new(),
|
||||
paint,
|
||||
fallback,
|
||||
none_allowed: false,
|
||||
gradient: None,
|
||||
pattern: None,
|
||||
picture: None,
|
||||
sampled: None,
|
||||
screen_pick: None,
|
||||
}
|
||||
.label(label)
|
||||
}
|
||||
|
||||
/// The Gradient tab: `default_gradient` is what a switch to Gradient sets, `editor` draws the host's editor.
|
||||
/// Without it there is no Gradient tab.
|
||||
#[must_use]
|
||||
pub fn gradient_editor(mut self, default_gradient: GradientPreview, editor: impl Into<PaintEditor<'a, GradientPreview>>) -> Self {
|
||||
self.gradient = Some((default_gradient, editor.into()));
|
||||
self
|
||||
}
|
||||
|
||||
/// The Pattern tab: `default_pattern` is what a switch to Pattern sets, `editor` draws the host's editor.
|
||||
/// Without it there is no Pattern tab.
|
||||
#[must_use]
|
||||
pub fn pattern_editor(mut self, default_pattern: ImagePreview, editor: impl Into<PaintEditor<'a, ImagePreview>>) -> Self {
|
||||
self.pattern = Some((default_pattern, editor.into()));
|
||||
self
|
||||
}
|
||||
|
||||
/// The Picture tab: `default_picture` is what a switch to Picture sets, `editor` draws the host's editor.
|
||||
/// Without it there is no Picture tab.
|
||||
#[must_use]
|
||||
pub fn picture_editor(mut self, default_picture: ImagePreview, editor: impl Into<PaintEditor<'a, ImagePreview>>) -> Self {
|
||||
self.picture = Some((default_picture, editor.into()));
|
||||
self
|
||||
}
|
||||
|
||||
/// The tabs the popover shows, in order: No Color (when allowed), Solid, then Gradient, Pattern and Picture
|
||||
/// when the host gave their editors.
|
||||
pub fn kinds(&self) -> Vec<FillKind> {
|
||||
let offered = [
|
||||
(FillKind::None, self.none_allowed),
|
||||
(FillKind::Solid, true),
|
||||
(FillKind::Gradient, self.gradient.is_some()),
|
||||
(FillKind::Pattern, self.pattern.is_some()),
|
||||
(FillKind::Picture, self.picture.is_some()),
|
||||
];
|
||||
offered.into_iter().filter_map(|(kind, on)| on.then_some(kind)).collect()
|
||||
}
|
||||
|
||||
/// The gradient a switch to Gradient sets, when the host gave an editor.
|
||||
pub fn default_gradient(&self) -> Option<&GradientPreview> {
|
||||
self.gradient.as_ref().map(|(default, _)| default)
|
||||
}
|
||||
|
||||
/// The paint a switch to `kind` sets.
|
||||
fn switched(&self, kind: FillKind, solid: Srgba) -> Paint {
|
||||
match kind {
|
||||
FillKind::None => Paint::None,
|
||||
FillKind::Solid => Paint::Solid(solid),
|
||||
FillKind::Gradient => Paint::Gradient(self.gradient.as_ref().map(|(default, _)| default.clone()).unwrap_or_default()),
|
||||
FillKind::Pattern => Paint::Pattern(self.pattern.as_ref().map(|(default, _)| default.clone()).unwrap_or_default()),
|
||||
FillKind::Picture => Paint::Picture(self.picture.as_ref().map(|(default, _)| default.clone()).unwrap_or_default()),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn kind_label(words: &PaintWords, kind: FillKind) -> Label {
|
||||
match kind {
|
||||
FillKind::None => words.no_color.clone(),
|
||||
FillKind::Solid => words.solid.clone(),
|
||||
FillKind::Gradient => words.gradient.clone(),
|
||||
FillKind::Pattern => words.pattern.clone(),
|
||||
FillKind::Picture => words.picture.clone(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The chip's value for a screen reader: the hex, "No Color", "Gradient", "Pattern: Bubbles" or "Picture:
|
||||
/// photo.png"; the kind alone for an image without a name.
|
||||
fn value_text(words: &PaintWords, paint: &Paint) -> String {
|
||||
let (named, kind, preview) = match paint {
|
||||
Paint::None => return words.no_color.as_str().to_owned(),
|
||||
Paint::Solid(color) => return color.to_hex(),
|
||||
Paint::Gradient(_) => return words.gradient.as_str().to_owned(),
|
||||
Paint::Pattern(preview) => (&words.pattern_named, &words.pattern, preview),
|
||||
Paint::Picture(preview) => (&words.picture_named, &words.picture, preview),
|
||||
};
|
||||
if preview.name.is_empty() { kind.as_str().to_owned() } else { named.fill(&[("name", preview.name.as_str())]) }
|
||||
}
|
||||
|
||||
impl Component for PaintChip<'_> {
|
||||
const ROLE: Role = Role::COLOR_WELL;
|
||||
type Style = PaintChipStyle;
|
||||
type Output = PaintChipOutput;
|
||||
|
||||
fn style(cx: &StyleCx<'_>, _: PaintChipStyleKey) -> PaintChipStyle {
|
||||
let colors = &cx.tokens.color;
|
||||
let metrics = craft_ui::choice::SwatchMetrics::of(cx);
|
||||
PaintChipStyle {
|
||||
metrics: Metrics::new(),
|
||||
focus: cx.focus_look(),
|
||||
height: metrics.side,
|
||||
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),
|
||||
}
|
||||
}
|
||||
|
||||
fn sense(&self) -> craft_behavior::Sense {
|
||||
craft_behavior::Sense::CLICK | craft_behavior::Sense::FOCUS
|
||||
}
|
||||
|
||||
fn measure(&mut self, cx: &craft_ui::contract::MeasureCx<'_, Self>) -> egui::Vec2 {
|
||||
vec2(cx.style.height * CHIP_WIDTH_IN_HEIGHTS, cx.style.height)
|
||||
}
|
||||
|
||||
fn parts(&mut self, rect: egui::Rect, cx: &mut PartsCx<'_, Self>) {
|
||||
let _ = cx.part(WELL, rect);
|
||||
}
|
||||
|
||||
fn bind(&mut self) -> Option<craft_ui::contract::BindMut<'_, Paint>> {
|
||||
Some(self.paint.reborrow())
|
||||
}
|
||||
|
||||
/// A click, Enter or Space toggles the popover; the last solid colour is kept for a switch back to Solid.
|
||||
fn update(&mut self, cx: &mut Cx<'_, Self>) {
|
||||
if let Some(Paint::Solid(color)) = cx.value() {
|
||||
let color = *color;
|
||||
cx.memory::<LastSolid>().0 = Some(color);
|
||||
}
|
||||
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 open {
|
||||
popup.close(cx);
|
||||
} else {
|
||||
popup.open(cx);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn overlay(&mut self, ui: &mut OverlayUi<'_>, cx: &mut Cx<'_, Self>) {
|
||||
let popup = cx.popup("picker");
|
||||
let words = cx.words::<PaintWords>();
|
||||
let name = cx.label();
|
||||
let paint = cx.value().cloned().unwrap_or(Paint::None);
|
||||
let solid = cx.memory::<LastSolid>().0.unwrap_or(self.fallback);
|
||||
let current = FillKind::of(&paint);
|
||||
let sampled = self.sampled;
|
||||
let entries: Vec<Entry<FillKind>> = self.kinds().into_iter().map(|kind| Entry::new(kind, kind_label(&words, kind))).collect();
|
||||
let (gradient, pattern, picture) = (&mut self.gradient, &mut self.pattern, &mut self.picture);
|
||||
let shown = ui.show(popup, Overlay::popover(), |ui, _| {
|
||||
let mut shown = Shown::default();
|
||||
let mut kind = current;
|
||||
Segmented::new(name.clone(), Bind::bound(&mut kind), &entries).show(ui);
|
||||
shown.kind = (kind != current).then_some(kind);
|
||||
match &paint {
|
||||
Paint::None => {}
|
||||
Paint::Solid(color) => {
|
||||
let picked = compact_picker(name.clone(), Bind::given(PickedColor::rgb(*color)), sampled).alpha(true).eyedropper(true).show(ui);
|
||||
shown.edit = picked.events;
|
||||
shown.screen_pick = picked.screen_pick;
|
||||
}
|
||||
Paint::Gradient(_) => shown.gradient = gradient.as_mut().and_then(|(_, editor)| editor.show(ui)),
|
||||
Paint::Pattern(_) => shown.pattern = pattern.as_mut().and_then(|(_, editor)| editor.show(ui)),
|
||||
Paint::Picture(_) => shown.picture = picture.as_mut().and_then(|(_, editor)| editor.show(ui)),
|
||||
}
|
||||
shown
|
||||
});
|
||||
let Some(shown) = shown else { return };
|
||||
self.screen_pick = shown.screen_pick;
|
||||
if let Some(kind) = shown.kind {
|
||||
let next = self.switched(kind, solid);
|
||||
cx.set(next);
|
||||
} else {
|
||||
for event in &shown.edit {
|
||||
forward(cx, event);
|
||||
}
|
||||
}
|
||||
if let Some(preview) = shown.gradient {
|
||||
cx.set(Paint::Gradient(preview));
|
||||
}
|
||||
if let Some(preview) = shown.pattern {
|
||||
cx.set(Paint::Pattern(preview));
|
||||
}
|
||||
if let Some(preview) = shown.picture {
|
||||
cx.set(Paint::Picture(preview));
|
||||
}
|
||||
}
|
||||
|
||||
fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) {
|
||||
let words = cx.words::<PaintWords>();
|
||||
match cx.value() {
|
||||
Some(paint) => access.value(value_text(&words, paint)),
|
||||
None => access.value(cx.words::<ChoiceWords>().swatch_mixed.as_str()),
|
||||
};
|
||||
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 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 => {
|
||||
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 !preview.stops.is_empty() {
|
||||
painter.ramp(well, &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);
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> PaintChipOutput {
|
||||
PaintChipOutput { edit: cx.edit_response(), screen_pick: self.screen_pick }
|
||||
}
|
||||
}
|
||||
|
||||
/// Reports one of the picker's `event`s as an edit of the chip's paint.
|
||||
fn forward(cx: &mut Cx<'_, PaintChip<'_>>, event: &EditEvent<PickedColor>) {
|
||||
let value = event.value().map(|picked| Paint::Solid(picked.color));
|
||||
match (event, value) {
|
||||
(EditEvent::Set { .. }, Some(value)) => cx.set(value),
|
||||
(EditEvent::Begin { .. }, value) => {
|
||||
cx.begin();
|
||||
if let Some(value) = value {
|
||||
cx.propose(value);
|
||||
}
|
||||
}
|
||||
(EditEvent::Update { .. }, Some(value)) => cx.propose(value),
|
||||
(EditEvent::Commit { .. }, Some(value)) => {
|
||||
cx.propose(value);
|
||||
cx.commit();
|
||||
}
|
||||
(EditEvent::Cancel { reason, .. }, _) => cx.cancel(*reason),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The gradient's stops for the ramp painter, held flat before the first and after the last, mirrored for right to
|
||||
/// left.
|
||||
pub(super) fn ramp_stops(preview: &GradientPreview, rtl: bool) -> Vec<(f32, DataColor)> {
|
||||
let mut stops: Vec<(f32, Color32)> = preview.stops.iter().map(|(at, color)| (at.clamp(0.0, 1.0), Color32::from(*color))).collect();
|
||||
stops.sort_by(|a, b| a.0.total_cmp(&b.0));
|
||||
if rtl {
|
||||
stops = stops.into_iter().rev().map(|(at, color)| (1.0 - at, color)).collect();
|
||||
}
|
||||
stops.into_iter().map(|(at, color)| (at, DataColor::new(color))).collect()
|
||||
}
|
||||
|
||||
/// Paints a pattern tiled across `well` at the tile's pixel size, or a picture stretched to it.
|
||||
pub(super) fn paint_image(painter: &ContentPainterCx<'_>, well: Rect, texture: CachedTexture, tiled: bool) {
|
||||
let whole = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 1.0));
|
||||
let tile = texture.size_vec2() / painter.painter.pixels_per_point();
|
||||
let tiled = tiled && tile.x > 0.0 && tile.y > 0.0 && tile.x.is_finite() && tile.y.is_finite();
|
||||
let (cols, rows) = if tiled { ((well.width() / tile.x).ceil(), (well.height() / tile.y).ceil()) } else { (1.0, 1.0) };
|
||||
if !tiled || cols * rows > MAX_TILES {
|
||||
painter.picture(texture.id, well, whole, 0.0);
|
||||
return;
|
||||
}
|
||||
for row in 0..rows as usize {
|
||||
for col in 0..cols as usize {
|
||||
let cell = Rect::from_min_size(well.min + vec2(col as f32 * tile.x, row as f32 * tile.y), tile).intersect(well);
|
||||
let uv_max: Pos2 = pos2(cell.width() / tile.x, cell.height() / tile.y);
|
||||
painter.picture(texture.id, cell, Rect::from_min_max(pos2(0.0, 0.0), uv_max), 0.0);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,380 @@
|
||||
//! `PaintList`: named paints in rows, with their events and thumbnails.
|
||||
|
||||
use craft_behavior::{Axis, EditEvent, IconId, Selection};
|
||||
use craft_behavior::{DisplayOrder, ItemSource, Mixed, SelectionChange};
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::buttons::Button;
|
||||
use craft_ui::contract::ShowContainer as _;
|
||||
use craft_ui::contract::{Bind, Outcome, Show as _, ShowCollection as _};
|
||||
use craft_ui::contract::{CollectionEvent, NoValue, Rename};
|
||||
use craft_ui::layout_components::Stack;
|
||||
use craft_ui::list::{List, ListRow, RowEvent, ThumbAspect, ThumbSize, TrailingFace, TrailingPart};
|
||||
use craft_ui::primitives::{ContentPainterCx, IconSpec, PaintShape};
|
||||
use craft_ui::runtime::env::Label;
|
||||
use egui::{Color32, Rect, Response, Ui};
|
||||
|
||||
use super::{Paint, PaintWords, paint_image, ramp_stops};
|
||||
|
||||
/// How a paint is bound (FigCraft's colour style or variable).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
#[non_exhaustive]
|
||||
pub enum PaintLinkKind {
|
||||
/// A colour style.
|
||||
Style,
|
||||
/// A variable.
|
||||
Variable,
|
||||
}
|
||||
|
||||
/// A row's binding: the style's or variable's name, shown after the paint's name, with a Detach button when
|
||||
/// [`PaintListOptions::bind`] is on.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
#[non_exhaustive]
|
||||
pub struct PaintLink {
|
||||
/// The style's or variable's name.
|
||||
pub name: String,
|
||||
/// Whether it is a style or a variable.
|
||||
pub kind: PaintLinkKind,
|
||||
}
|
||||
|
||||
impl PaintLink {
|
||||
/// A binding to the style or variable `name`.
|
||||
pub fn new(name: impl Into<String>, kind: PaintLinkKind) -> Self {
|
||||
PaintLink { name: name.into(), kind }
|
||||
}
|
||||
}
|
||||
|
||||
/// What a row shows beyond the chip and the name, by index in the list's paints.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct PaintRow {
|
||||
/// The style or variable the paint is bound to.
|
||||
pub link: Option<PaintLink>,
|
||||
}
|
||||
|
||||
impl PaintRow {
|
||||
/// A row bound to `link`.
|
||||
pub fn linked(link: PaintLink) -> Self {
|
||||
PaintRow { link: Some(link) }
|
||||
}
|
||||
}
|
||||
|
||||
/// The row actions a [`PaintList`] offers; all off by default (the list is then PhotoCraft's).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
#[non_exhaustive]
|
||||
pub struct PaintListOptions {
|
||||
/// A click on a row's chip opens the colour picker on it.
|
||||
pub edit: bool,
|
||||
/// A hex field per row.
|
||||
pub hex: bool,
|
||||
/// An opacity field per row (percent).
|
||||
pub opacity: bool,
|
||||
/// Bind and Detach buttons (styles and variables).
|
||||
pub bind: bool,
|
||||
/// "Select layers with this color".
|
||||
pub select_users: bool,
|
||||
/// An Add button under the rows.
|
||||
pub add: bool,
|
||||
/// A Remove button per row.
|
||||
pub remove: bool,
|
||||
}
|
||||
|
||||
impl PaintListOptions {
|
||||
/// FigCraft's Selection colors: edit, hex, opacity, bind and select users.
|
||||
pub const SELECTION_COLORS: PaintListOptions =
|
||||
PaintListOptions { edit: true, hex: true, opacity: true, bind: true, select_users: true, add: false, remove: false };
|
||||
|
||||
/// Turns the `edit` action on or off.
|
||||
#[must_use]
|
||||
pub const fn edit(mut self, on: bool) -> Self {
|
||||
self.edit = on;
|
||||
self
|
||||
}
|
||||
|
||||
/// Turns the `hex` action on or off.
|
||||
#[must_use]
|
||||
pub const fn hex(mut self, on: bool) -> Self {
|
||||
self.hex = on;
|
||||
self
|
||||
}
|
||||
|
||||
/// Turns the `opacity` action on or off.
|
||||
#[must_use]
|
||||
pub const fn opacity(mut self, on: bool) -> Self {
|
||||
self.opacity = on;
|
||||
self
|
||||
}
|
||||
|
||||
/// Turns the `bind` action on or off.
|
||||
#[must_use]
|
||||
pub const fn bind(mut self, on: bool) -> Self {
|
||||
self.bind = on;
|
||||
self
|
||||
}
|
||||
|
||||
/// Turns the `select_users` action on or off.
|
||||
#[must_use]
|
||||
pub const fn select_users(mut self, on: bool) -> Self {
|
||||
self.select_users = on;
|
||||
self
|
||||
}
|
||||
|
||||
/// Turns the `add` action on or off.
|
||||
#[must_use]
|
||||
pub const fn add(mut self, on: bool) -> Self {
|
||||
self.add = on;
|
||||
self
|
||||
}
|
||||
|
||||
/// Turns the `remove` action on or off.
|
||||
#[must_use]
|
||||
pub const fn remove(mut self, on: bool) -> Self {
|
||||
self.remove = on;
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether any row action is on.
|
||||
pub fn any(&self) -> bool {
|
||||
self.edit || self.hex || self.opacity || self.bind || self.select_users || self.add || self.remove
|
||||
}
|
||||
}
|
||||
|
||||
/// A row action of [`PaintList`], by row index.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub enum PaintListEvent {
|
||||
/// The chip's picker edited the paint (as [`PaintChip`] reports).
|
||||
#[non_exhaustive]
|
||||
Edit {
|
||||
/// The row's index.
|
||||
row: usize,
|
||||
/// The edit of the row's paint.
|
||||
event: EditEvent<Paint>,
|
||||
},
|
||||
/// A hex typed and committed.
|
||||
#[non_exhaustive]
|
||||
Hex {
|
||||
/// The row's index.
|
||||
row: usize,
|
||||
/// The committed colour.
|
||||
color: Srgba,
|
||||
},
|
||||
/// The opacity field: `Set` when typed, a gesture when scrubbed; 0–1.
|
||||
#[non_exhaustive]
|
||||
Opacity {
|
||||
/// The row's index.
|
||||
row: usize,
|
||||
/// The edit of the opacity.
|
||||
event: EditEvent<f32>,
|
||||
},
|
||||
/// Bind the paint of the row at this index to a style or variable: the app opens its picker.
|
||||
Bind(usize),
|
||||
/// Detach the style or variable of the row at this index.
|
||||
Detach(usize),
|
||||
/// Select the layers that use the paint of the row at this index.
|
||||
SelectUsers(usize),
|
||||
/// Add a paint under the rows.
|
||||
Add,
|
||||
/// Remove the paint of the row at this index.
|
||||
Remove(usize),
|
||||
/// Renamed in place.
|
||||
#[non_exhaustive]
|
||||
Rename {
|
||||
/// The row's index.
|
||||
row: usize,
|
||||
/// The new name.
|
||||
name: String,
|
||||
},
|
||||
}
|
||||
|
||||
/// What a paint list reports.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
pub struct PaintListOutput {
|
||||
/// The list's response.
|
||||
pub response: Response,
|
||||
/// The row a click or key selected in this pass.
|
||||
pub selected: Option<usize>,
|
||||
/// The row actions of this pass, in order; a rename is here too.
|
||||
pub events: Vec<PaintListEvent>,
|
||||
}
|
||||
|
||||
impl Outcome for PaintListOutput {
|
||||
type Value = NoValue;
|
||||
|
||||
fn response(&self) -> &Response {
|
||||
&self.response
|
||||
}
|
||||
}
|
||||
|
||||
/// The paints as a list source, keyed by position.
|
||||
struct Paints<'a>(&'a [(String, Paint)]);
|
||||
|
||||
impl DisplayOrder<usize> for Paints<'_> {
|
||||
fn len(&self) -> usize {
|
||||
self.0.len()
|
||||
}
|
||||
|
||||
fn key(&self, at: usize) -> usize {
|
||||
at
|
||||
}
|
||||
|
||||
fn index_of(&self, key: &usize) -> Option<usize> {
|
||||
(*key < self.0.len()).then_some(*key)
|
||||
}
|
||||
|
||||
fn text(&self, at: usize) -> Option<std::borrow::Cow<'_, str>> {
|
||||
self.0.get(at).map(|(name, _)| std::borrow::Cow::Borrowed(name.as_str()))
|
||||
}
|
||||
}
|
||||
|
||||
impl ItemSource<usize> for Paints<'_> {}
|
||||
|
||||
const REMOVE: TrailingPart = TrailingPart::new(0);
|
||||
const SELECT_USERS: TrailingPart = TrailingPart::new(1);
|
||||
const BIND: TrailingPart = TrailingPart::new(2);
|
||||
|
||||
/// The chip's width to height in a row.
|
||||
const ROW_CHIP: (u16, u16) = (3, 2);
|
||||
|
||||
/// Named paints in rows: the chip, then the name; a click on a row selects it, a double-click or F2 renames it in
|
||||
/// place. The Paints list of a document (PhotoCraft's shape paints; FigCraft's and VectorCraft's document colours).
|
||||
///
|
||||
/// With [`options`](Self::options) a row also offers the binding's name with Bind and Detach ([`rows`](Self::rows)),
|
||||
/// "Select layers with this color" and Remove after the name, and Add under the rows. Each reports a
|
||||
/// [`PaintListEvent`]. The per-row chip edit, hex field and opacity field wait for a row slot that holds field
|
||||
/// controls.
|
||||
#[derive(craft_ui::contract::Pattern, craft_ui::contract::Props)]
|
||||
pub struct PaintList<'a> {
|
||||
label: Label,
|
||||
paints: &'a [(String, Paint)],
|
||||
selected: Bind<'a, Option<usize>>,
|
||||
/// The row actions offered; none by default.
|
||||
#[prop]
|
||||
options: PaintListOptions,
|
||||
/// Each paint's row data (its binding), by index; rows past the end have none.
|
||||
#[prop]
|
||||
rows: &'a [PaintRow],
|
||||
/// The solid colour a row's switch to Solid starts from when the row was never solid.
|
||||
#[prop]
|
||||
fallback: Option<Srgba>,
|
||||
}
|
||||
|
||||
impl<'a> PaintList<'a> {
|
||||
/// Black: a switch to Solid in a list with no solid paint and no [`fallback`](Self::fallback).
|
||||
pub const DEFAULT_SOLID: Srgba = Srgba::rgb(0.0, 0.0, 0.0);
|
||||
|
||||
/// A list of `paints` (name and paint per row) named `label`; `selected` is the selected row.
|
||||
pub fn new(label: impl Into<Label>, paints: &'a [(String, Paint)], selected: Bind<'a, Option<usize>>) -> Self {
|
||||
PaintList { label: label.into(), paints, selected, options: PaintListOptions::default(), rows: &[], fallback: None }
|
||||
}
|
||||
|
||||
/// Draws the rows and returns the selection, any rename and the row actions of this pass.
|
||||
pub fn show(self, ui: &mut Ui) -> PaintListOutput {
|
||||
let words = craft_ui::runtime::env::Env::of(ui).words::<PaintWords>();
|
||||
let mut selected_bind = self.selected;
|
||||
let (paints, rows, options, label) = (self.paints, self.rows, self.options, self.label.clone());
|
||||
let mut output = None;
|
||||
let mut add = false;
|
||||
let shown = Stack::new().show(ui, |ui, cx| {
|
||||
let held = match selected_bind.reborrow().read(cx) {
|
||||
Some(Mixed::Same(Some(row))) if row < paints.len() => Selection::single(row),
|
||||
_ => Selection::default(),
|
||||
};
|
||||
let list = List::<usize>::new(label.clone()).selection(Bind::given(held)).can_rename(|_| true);
|
||||
output = Some(list.show_items(ui, &Paints(paints), &mut |row, _| {
|
||||
let (name, paint) = &paints[*row];
|
||||
let mut item =
|
||||
ListRow::new(name.clone()).thumb_aspect(ThumbSize::Small, ThumbAspect::new(ROW_CHIP.0, ROW_CHIP.1), move |painter, rect| {
|
||||
paint_thumb(painter, rect, paint);
|
||||
});
|
||||
if let Some(link) = rows.get(*row).and_then(|data| data.link.as_ref()) {
|
||||
item = item.trailing(link.name.clone());
|
||||
}
|
||||
if options.bind {
|
||||
let (name, icon) = match rows.get(*row).and_then(|data| data.link.as_ref()) {
|
||||
Some(PaintLink { kind: PaintLinkKind::Style, .. }) => (words.detach_style.clone(), "unlink"),
|
||||
Some(PaintLink { kind: PaintLinkKind::Variable, .. }) => (words.detach_variable.clone(), "unlink"),
|
||||
None => (words.styles.clone(), "palette"),
|
||||
};
|
||||
item = item.trailing_part(BIND, TrailingFace::Icon(IconSpec::svg(IconId::new(icon))), name);
|
||||
}
|
||||
if options.select_users {
|
||||
item = item.trailing_part(
|
||||
SELECT_USERS,
|
||||
TrailingFace::Icon(IconSpec::svg(IconId::new("layers"))),
|
||||
Label::from(words.select_users.fill(&[("name", name.as_str())])),
|
||||
);
|
||||
}
|
||||
if options.remove {
|
||||
item = item.trailing_part(
|
||||
REMOVE,
|
||||
TrailingFace::Icon(IconSpec::svg(IconId::new("minus"))),
|
||||
Label::from(words.remove.fill(&[("name", name.as_str())])),
|
||||
);
|
||||
}
|
||||
item
|
||||
}));
|
||||
if options.add {
|
||||
add = craft_ui::contract::clicked(&Button::new(words.add.clone()).icon(IconId::new("plus")).show(ui));
|
||||
}
|
||||
});
|
||||
// A parent's measuring run reuses what it measured and does not run the body.
|
||||
let Some(list) = output else { return PaintListOutput { response: shown.output, selected: None, events: Vec::new() } };
|
||||
let mut selected = None;
|
||||
let mut events = Vec::new();
|
||||
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::Rename(event) if matches!(event, EditEvent::Commit { .. }) => {
|
||||
if let Some(Rename { key, name, .. }) = event.value() {
|
||||
events.push(PaintListEvent::Rename { row: *key, name: name.clone() });
|
||||
}
|
||||
}
|
||||
CollectionEvent::Item(row, RowEvent::Trailing { part, .. }) => {
|
||||
let linked = self.rows.get(row).is_some_and(|data| data.link.is_some());
|
||||
events.push(match part {
|
||||
REMOVE => PaintListEvent::Remove(row),
|
||||
SELECT_USERS => PaintListEvent::SelectUsers(row),
|
||||
_ if linked => PaintListEvent::Detach(row),
|
||||
_ => PaintListEvent::Bind(row),
|
||||
});
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if add {
|
||||
events.push(PaintListEvent::Add);
|
||||
}
|
||||
PaintListOutput { response: list.response, selected, events }
|
||||
}
|
||||
}
|
||||
|
||||
/// Draws `paint` into a row's thumbnail: a solid paint over the checkerboard where it has alpha, a gradient ramp,
|
||||
/// the well for No Color with a diagonal, a pattern tiled or a picture stretched.
|
||||
fn paint_thumb(painter: &ContentPainterCx<'_>, rect: Rect, paint: &Paint) {
|
||||
match paint {
|
||||
Paint::Solid(color) => {
|
||||
if color.a < 1.0 {
|
||||
painter.checker(rect);
|
||||
}
|
||||
painter.painter.rect_filled(rect, 0.0, Color32::from(*color));
|
||||
}
|
||||
Paint::None => {
|
||||
let inner = painter.plot_frame(rect);
|
||||
painter.outline(&PaintShape::Path(vec![inner.left_bottom(), inner.right_top()]));
|
||||
}
|
||||
Paint::Gradient(preview) => {
|
||||
painter.checker(rect);
|
||||
if !preview.stops.is_empty() {
|
||||
painter.ramp(rect, &ramp_stops(preview, false), Axis::X);
|
||||
}
|
||||
}
|
||||
Paint::Pattern(image) | Paint::Picture(image) => {
|
||||
painter.checker(rect);
|
||||
if let Some(texture) = image.texture {
|
||||
paint_image(painter, rect, texture, matches!(paint, Paint::Pattern(_)));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,100 @@
|
||||
//! Stories of the paint chip and the paint list.
|
||||
|
||||
use super::{GradientPreview, ImagePreview, Paint, PaintChip, PaintLink, PaintLinkKind, PaintList, PaintListOptions, PaintRow};
|
||||
use craft_behavior::Mixed;
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::contract::Role;
|
||||
use craft_ui::contract::{Bind, Show as _, Validity};
|
||||
use craft_ui::runtime::env::Message;
|
||||
use craft_ui::testing::{Drive, Fixture, StoryData, StoryOutput, story};
|
||||
use egui::Ui;
|
||||
|
||||
/// Opens the popover with a click.
|
||||
fn open_popover(fixture: &mut Fixture) {
|
||||
let chip = fixture.by_role(Role::COLOR_WELL);
|
||||
if let Some(chip) = chip.first() {
|
||||
fixture.click(chip);
|
||||
}
|
||||
fixture.idle(4);
|
||||
}
|
||||
|
||||
/// Opens the popover and takes the last fill kind it offers.
|
||||
fn take_last_kind(fixture: &mut Fixture) {
|
||||
open_popover(fixture);
|
||||
if let Some(kind) = fixture.by_role(Role::RADIO_BUTTON).last().copied() {
|
||||
fixture.click(&kind);
|
||||
}
|
||||
fixture.idle(2);
|
||||
}
|
||||
|
||||
const BLUE: Srgba = Srgba::rgb(0.2, 0.4, 0.8);
|
||||
|
||||
fn chip(ui: &mut Ui, data: &mut StoryData, paint: Paint) -> StoryOutput {
|
||||
let stops = vec![(0.0, BLUE), (1.0, Srgba::rgb(1.0, 1.0, 1.0))];
|
||||
let held = data.value("paint", paint);
|
||||
PaintChip::new("Fill", Bind::bound(held), BLUE).none_allowed().gradient_editor(GradientPreview::new(stops), |_: &mut Ui| None).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(PaintChip<'static>, covers = [Default], drive = Drive::Custom(take_last_kind))]
|
||||
fn paint_chip(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
chip(ui, data, Paint::Solid(Srgba { r: 0.9, g: 0.2, b: 0.2, a: 0.6 }))
|
||||
}
|
||||
|
||||
#[story(PaintChip<'static>, covers = [Mixed], drive = Drive::Never)]
|
||||
fn paint_chip_mixed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let held = data.value("mixed", Mixed::<Paint>::Mixed);
|
||||
PaintChip::new("Fill", Bind::bound_mixed(held), BLUE).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(PaintChip<'static>, covers = [Open], drive = Drive::Custom(open_popover))]
|
||||
fn paint_chip_open(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
chip(ui, data, Paint::Solid(BLUE))
|
||||
}
|
||||
|
||||
#[story(PaintChip<'static>, covers = [], drive = Drive::Never)]
|
||||
fn paint_chip_no_color(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
chip(ui, data, Paint::None)
|
||||
}
|
||||
|
||||
#[story(PaintChip<'static>, covers = [], drive = Drive::Never)]
|
||||
fn paint_chip_gradient(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
chip(ui, data, Paint::Gradient(GradientPreview::new(vec![(0.0, BLUE), (0.5, Srgba::rgb(0.9, 0.8, 0.1)), (1.0, Srgba::rgb(0.9, 0.2, 0.2))])))
|
||||
}
|
||||
|
||||
#[story(PaintChip<'static>, covers = [], drive = Drive::Never)]
|
||||
fn paint_chip_pattern(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
chip(ui, data, Paint::Pattern(ImagePreview::new("Bubbles", None)))
|
||||
}
|
||||
|
||||
fn paints() -> Vec<(String, Paint)> {
|
||||
vec![
|
||||
("Brand blue".to_owned(), Paint::Solid(BLUE)),
|
||||
("Sky".to_owned(), Paint::Solid(Srgba { r: 0.5, g: 0.7, b: 1.0, a: 0.5 })),
|
||||
("Sunset".to_owned(), Paint::Gradient(GradientPreview::new(vec![(0.0, Srgba::rgb(0.9, 0.5, 0.1)), (1.0, Srgba::rgb(0.6, 0.1, 0.4))]))),
|
||||
("Nothing".to_owned(), Paint::None),
|
||||
]
|
||||
}
|
||||
|
||||
#[story(PaintList<'static>, covers = [Default], drive = Drive::Never)]
|
||||
fn paint_list(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let paints = paints();
|
||||
PaintList::new("Paints", &paints, Bind::bound(data.value("selected", None::<usize>))).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(PaintList<'static>, covers = [], drive = Drive::Never)]
|
||||
fn paint_list_selection_colors(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let paints = paints();
|
||||
let rows = [PaintRow::linked(PaintLink::new("Primary / Blue", PaintLinkKind::Style))];
|
||||
PaintList::new("Selection colors", &paints, Bind::bound(data.value("selected", Some(0usize))))
|
||||
.options(PaintListOptions { select_users: true, bind: true, remove: true, add: true, ..PaintListOptions::SELECTION_COLORS })
|
||||
.rows(&rows)
|
||||
.show(ui)
|
||||
.into()
|
||||
}
|
||||
|
||||
#[story(PaintChip<'static>, covers = [Invalid], drive = Drive::Never)]
|
||||
fn paint_chip_invalid(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let refuse_none = |paint: &Paint| if matches!(paint, Paint::None) { Validity::Refuse(Message::new("A fill is required")) } else { Validity::Ok };
|
||||
let held = Bind::bound(data.value("paint", Paint::None)).check(refuse_none);
|
||||
PaintChip::new("Fill", held, BLUE).none_allowed().show(ui).into()
|
||||
}
|
||||
@@ -0,0 +1,470 @@
|
||||
//! [`SwatchPair`]: two overlapping colour wells, foreground over background or fill over stroke.
|
||||
|
||||
use craft_behavior::{EditEvents, Flow, HitLevel, HitPriority, IconId, Metrics, Mixed, NavShape, PartKey, PressPhase, Roving, Sense};
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::buttons::IconButton;
|
||||
use craft_ui::choice::{ChoiceWords, Swatch, SwatchMetrics};
|
||||
use craft_ui::contract::{
|
||||
Access, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Focus as _, MeasureCx, Outcome, Overlay, OverlayUi, Overlays as _,
|
||||
PaintUi, PartsCx, Pointer as _, Props as _, Remember as _, Role, WordSetCx as _,
|
||||
};
|
||||
use craft_ui::primitives::{PaintShape, StrokeWidth};
|
||||
use craft_ui::runtime::commands::FireSource;
|
||||
use craft_ui::runtime::env::Label;
|
||||
use craft_ui::style::{ComponentStyle, DataColor, Flags, FocusLook, StyleColor, StyleCx};
|
||||
use egui::{Color32, Rect, Response, Vec2, pos2, vec2};
|
||||
|
||||
use super::popover::compact_picker;
|
||||
use super::{ColorPicker, PickedColor, ScreenPickGesture};
|
||||
|
||||
#[cfg(feature = "screen-testing")]
|
||||
mod stories;
|
||||
|
||||
/// One of the wells, `WELL.at(0)` the primary and `WELL.at(1)` the secondary.
|
||||
const WELL: PartKey = PartKey::new("well");
|
||||
/// The Default Colours button.
|
||||
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.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
#[non_exhaustive]
|
||||
pub enum Well {
|
||||
#[default]
|
||||
/// The primary well: at the start, top.
|
||||
Primary,
|
||||
/// The secondary well: offset towards the end and down.
|
||||
Secondary,
|
||||
}
|
||||
|
||||
impl Well {
|
||||
/// The other well.
|
||||
pub fn other(self) -> Well {
|
||||
match self {
|
||||
Well::Primary => Well::Secondary,
|
||||
Well::Secondary => Well::Primary,
|
||||
}
|
||||
}
|
||||
|
||||
fn index(self) -> u64 {
|
||||
match self {
|
||||
Well::Primary => 0,
|
||||
Well::Secondary => 1,
|
||||
}
|
||||
}
|
||||
|
||||
fn of(index: u64) -> Well {
|
||||
if index == 0 { Well::Primary } else { Well::Secondary }
|
||||
}
|
||||
}
|
||||
|
||||
/// What a [`SwatchPair`] shows for one well.
|
||||
#[derive(Clone, Debug)]
|
||||
#[non_exhaustive]
|
||||
pub struct PairWell {
|
||||
label: Label,
|
||||
color: Mixed<Srgba>,
|
||||
ring: bool,
|
||||
}
|
||||
|
||||
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 }
|
||||
}
|
||||
|
||||
/// Draws the well as a ring (a stroke, as DesignCraft's stroke well) instead of a filled square. The middle shows
|
||||
/// what is behind it.
|
||||
#[must_use]
|
||||
pub fn ring(mut self, ring: bool) -> Self {
|
||||
self.ring = ring;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// The style of a swatch pair.
|
||||
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
|
||||
#[non_exhaustive]
|
||||
pub struct SwatchPairStyle {
|
||||
#[style(metrics)]
|
||||
metrics: Metrics,
|
||||
#[style(focus)]
|
||||
focus: FocusLook,
|
||||
/// The side of a well: `size.icon.lg`.
|
||||
well: f32,
|
||||
/// The offset of the secondary well from the primary one on both axes: `size.icon.sm`.
|
||||
step: f32,
|
||||
/// The gap in the panel's colour round the front well: `space.gap.tight`.
|
||||
gap: f32,
|
||||
/// The height of the button row.
|
||||
buttons: f32,
|
||||
/// The colour the pair sits on, for the gap.
|
||||
ground: StyleColor,
|
||||
/// The edge of a ring well.
|
||||
edge: StyleColor,
|
||||
}
|
||||
|
||||
/// A closure that sets up the picker of the popup.
|
||||
pub struct PickerSetup<'a>(Box<dyn Fn(ColorPicker<'a>) -> ColorPicker<'a> + 'a>);
|
||||
|
||||
impl<'a> PickerSetup<'a> {
|
||||
/// A setup that runs `setup` on the popup's picker.
|
||||
pub fn new(setup: impl Fn(ColorPicker<'a>) -> ColorPicker<'a> + 'a) -> Self {
|
||||
PickerSetup(Box::new(setup))
|
||||
}
|
||||
}
|
||||
|
||||
/// The well whose popup is open.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct Opened(Option<u64>);
|
||||
|
||||
/// What a swatch pair reports.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
pub struct SwatchPairOutput {
|
||||
/// The pair's response.
|
||||
pub response: Response,
|
||||
/// The active well after this pass: the host's, or the one the user chose.
|
||||
pub active: Well,
|
||||
/// The user made another well active in this pass.
|
||||
pub activated: bool,
|
||||
/// The well clicked in this pass, by the pointer or by Enter or Space on the focused well (with the popup on,
|
||||
/// Enter opens the popup instead). Reported whether or not the click made the well active.
|
||||
pub clicked: Option<Well>,
|
||||
/// The well double-clicked in this pass.
|
||||
pub double_clicked: Option<Well>,
|
||||
/// The edits of the picker in the popup, in order; empty while no popup is open.
|
||||
pub events: EditEvents<PickedColor>,
|
||||
/// The well `events` belong to: the one whose popup is open.
|
||||
pub well: Well,
|
||||
/// The swap button was pressed.
|
||||
pub swap: bool,
|
||||
/// The default button was pressed.
|
||||
pub defaults: bool,
|
||||
/// The picker's screen eyedropper press: the host answers through [`SwatchPair::sampled`].
|
||||
pub screen_pick: Option<ScreenPickGesture>,
|
||||
/// The well whose popup is open after this pass.
|
||||
pub open: Option<Well>,
|
||||
/// The edit of the active well: another well made active is one `Set`.
|
||||
pub choice: EditResponse<Well>,
|
||||
}
|
||||
|
||||
impl Outcome for SwatchPairOutput {
|
||||
type Value = Well;
|
||||
|
||||
fn response(&self) -> &Response {
|
||||
&self.response
|
||||
}
|
||||
|
||||
#[cfg(feature = "screen-testing")]
|
||||
fn story_facts(&self) -> craft_ui::testing::StoryOutput {
|
||||
self.choice.story_facts()
|
||||
}
|
||||
}
|
||||
|
||||
/// Two overlapping colour wells, the active one in front, as PhotoCraft's foreground and background chips and
|
||||
/// DesignCraft's fill and stroke proxy.
|
||||
///
|
||||
/// - The host holds the active well and the colours. A click on a well, or an arrow key while one has the focus,
|
||||
/// makes it active and returns it as [`SwatchPairOutput::active`]; it is drawn in front with a gap in the colour the
|
||||
/// pair sits on round it. The wells keep their places.
|
||||
/// - A double-click, or Enter on the focused well, opens a popup with the Compact picker, which edits that well's
|
||||
/// colour (`edit`, `well`, `open`); a click outside closes it.
|
||||
/// - Host-picker mode, as PhotoCraft's tool rail: [`popover(false)`](SwatchPair::popover) turns the popup off, so a
|
||||
/// click, or Enter or Space on the focused well, reports `clicked` and a double-click `double_clicked` for the host
|
||||
/// to open its own picker. `click_activates(false)` keeps the host's active well in front whatever is clicked; the
|
||||
/// arrow keys then move the focus between the wells without changing it.
|
||||
/// - The optional buttons ([`swap_button`](SwatchPair::swap_button), [`default_button`](SwatchPair::default_button))
|
||||
/// are icons in a row over the wells, the default one at the start and the swap one at the end, as Photoshop's.
|
||||
/// - 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> {
|
||||
#[common]
|
||||
common: Common,
|
||||
wells: [PairWell; 2],
|
||||
active: Bind<'a, Well>,
|
||||
/// The Swap Colours button's name; without it there is no button.
|
||||
#[prop(into)]
|
||||
swap_button: Option<Label>,
|
||||
/// The Default Colours button's name; without it there is no button.
|
||||
#[prop(into)]
|
||||
default_button: Option<Label>,
|
||||
/// Whether a double-click or Enter opens the popup; off, the pair is in host-picker mode.
|
||||
#[prop]
|
||||
popover: bool,
|
||||
/// Whether a click or an arrow makes a well active.
|
||||
#[prop]
|
||||
click_activates: bool,
|
||||
/// The host's answer to the picker's screen eyedropper.
|
||||
#[prop]
|
||||
sampled: Option<Srgba>,
|
||||
/// Sets up the popup's picker.
|
||||
#[prop(func = "Fn(ColorPicker<'a>) -> ColorPicker<'a>")]
|
||||
picker: Option<PickerSetup<'a>>,
|
||||
clicked: Option<Well>,
|
||||
double_clicked: Option<Well>,
|
||||
activated: bool,
|
||||
swap: bool,
|
||||
defaults: bool,
|
||||
edit: EditEvents<PickedColor>,
|
||||
edited: Option<Well>,
|
||||
screen_pick: Option<ScreenPickGesture>,
|
||||
}
|
||||
|
||||
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 {
|
||||
common: Common::new(),
|
||||
wells,
|
||||
active,
|
||||
swap_button: None,
|
||||
default_button: None,
|
||||
popover: true,
|
||||
click_activates: true,
|
||||
sampled: None,
|
||||
picker: None,
|
||||
clicked: None,
|
||||
double_clicked: None,
|
||||
activated: false,
|
||||
swap: false,
|
||||
defaults: false,
|
||||
edit: EditEvents::new(),
|
||||
edited: None,
|
||||
screen_pick: None,
|
||||
}
|
||||
.label(label)
|
||||
}
|
||||
|
||||
fn has_buttons(&self) -> bool {
|
||||
self.swap_button.is_some() || self.default_button.is_some()
|
||||
}
|
||||
|
||||
/// The buttons' rects in logical coordinates from the pair's start edge: default colours at the start, swap at the
|
||||
/// end.
|
||||
fn button_rects(style: &SwatchPairStyle) -> [Rect; 2] {
|
||||
let side = Vec2::splat(style.buttons);
|
||||
[Rect::from_min_size(pos2(0.0, 0.0), side), Rect::from_min_size(pos2(style.well + style.step - style.buttons, 0.0), side)]
|
||||
}
|
||||
|
||||
/// The wells' rects in logical coordinates from the pair's start edge, primary first.
|
||||
fn well_rects(&self, style: &SwatchPairStyle, size: Vec2) -> [Rect; 2] {
|
||||
let top = if self.has_buttons() { style.buttons + style.metrics.gap } else { 0.0 };
|
||||
let square = Vec2::splat(style.well);
|
||||
let primary = Rect::from_min_size(pos2(0.0, top), square);
|
||||
let secondary = Rect::from_min_size(pos2(size.x.min(style.well + style.step) - style.well, top + style.step), square);
|
||||
[primary, secondary]
|
||||
}
|
||||
}
|
||||
|
||||
impl Component for SwatchPair<'_> {
|
||||
const ROLE: Role = Role::GROUP;
|
||||
|
||||
type Style = SwatchPairStyle;
|
||||
type Output = SwatchPairOutput;
|
||||
|
||||
fn style(cx: &StyleCx<'_>, _: SwatchPairStyleKey) -> SwatchPairStyle {
|
||||
let colors = &cx.tokens.color;
|
||||
SwatchPairStyle {
|
||||
metrics: Metrics::new().gap(cx.control().gap),
|
||||
focus: cx.focus_look(),
|
||||
well: cx.tokens.size.icon.lg,
|
||||
step: cx.tokens.size.icon.sm,
|
||||
gap: cx.tokens.space.gap.tight,
|
||||
buttons: SwatchMetrics::of(cx).side,
|
||||
ground: cx.color(colors.surface.panel),
|
||||
edge: cx.color(colors.line.control_edge),
|
||||
}
|
||||
}
|
||||
|
||||
fn sense(&self) -> Sense {
|
||||
Sense::empty()
|
||||
}
|
||||
|
||||
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
let style = cx.style;
|
||||
let wells = Vec2::splat(style.well + style.step);
|
||||
if self.has_buttons() { vec2(wells.x, wells.y + style.buttons + style.metrics.gap) } else { wells }
|
||||
}
|
||||
|
||||
fn bind(&mut self) -> Option<BindMut<'_, Well>> {
|
||||
Some(self.active.reborrow())
|
||||
}
|
||||
|
||||
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 active = cx.value().copied().unwrap_or_default();
|
||||
for (i, logical) in rects.into_iter().enumerate() {
|
||||
let front = Well::of(i as u64) == active;
|
||||
let at = flow.to_physical(logical.translate(rect.min.to_vec2()));
|
||||
let mut flags = Flags::empty();
|
||||
flags.set(Flags::MIXED, self.wells[i].color.same().is_none());
|
||||
flags.set(Flags::CHECKED, front);
|
||||
let part = cx
|
||||
.part(WELL.at(i as u64), at)
|
||||
.sense(Sense::CLICK | Sense::FOCUS)
|
||||
.priority(HitPriority::new(HitLevel::Body, u8::from(front)))
|
||||
.flags(flags)
|
||||
.focusable();
|
||||
if self.popover {
|
||||
part.pointer_only("Enter opens the picker");
|
||||
}
|
||||
}
|
||||
let buttons = Self::button_rects(cx.style);
|
||||
for (key, button, shown) in [(DEFAULT, buttons[0], self.default_button.is_some()), (SWAP, buttons[1], self.swap_button.is_some())] {
|
||||
if shown {
|
||||
let at = flow.to_physical(button.translate(rect.min.to_vec2()));
|
||||
cx.part(key, at).sense(Sense::CLICK).pointer_only("The host's Default Colours and Swap Colours commands");
|
||||
}
|
||||
}
|
||||
cx.roving(Roving::new(NavShape::Flat));
|
||||
}
|
||||
|
||||
fn update(&mut self, cx: &mut Cx<'_, Self>) {
|
||||
// Asking registers the popup for this pass, which the overlay hook needs even while it stays closed.
|
||||
let _ = cx.popup("picker").is_open(cx);
|
||||
let active = cx.value().copied().unwrap_or_default();
|
||||
for i in 0..2u64 {
|
||||
let well = Well::of(i);
|
||||
let press = cx.part(WELL.at(i)).press;
|
||||
if let PressPhase::Release { start, click: true, .. } = press.phase {
|
||||
self.clicked = Some(well);
|
||||
if start.clicks >= 2 {
|
||||
self.double_clicked = Some(well);
|
||||
}
|
||||
if self.click_activates && well != active {
|
||||
cx.set(well);
|
||||
self.activated = true;
|
||||
}
|
||||
if self.popover && start.clicks >= 2 {
|
||||
cx.memory::<Opened>().0 = Some(i);
|
||||
let popup = cx.popup("picker");
|
||||
popup.open(cx);
|
||||
}
|
||||
}
|
||||
if cx.part_activated(WELL.at(i)) == Some(FireSource::Key) {
|
||||
if self.popover {
|
||||
cx.memory::<Opened>().0 = Some(i);
|
||||
let popup = cx.popup("picker");
|
||||
popup.open(cx);
|
||||
} else {
|
||||
self.clicked = Some(well);
|
||||
}
|
||||
}
|
||||
}
|
||||
self.defaults |= cx.part_activated(DEFAULT).is_some();
|
||||
self.swap |= cx.part_activated(SWAP).is_some();
|
||||
if self.click_activates
|
||||
&& cx.is_focused()
|
||||
&& let Some(part) = cx.active_part()
|
||||
&& part.key == WELL
|
||||
&& let Some(well) = part.index.map(Well::of)
|
||||
&& well != active
|
||||
{
|
||||
cx.set(well);
|
||||
self.activated = true;
|
||||
}
|
||||
}
|
||||
|
||||
fn overlay(&mut self, ui: &mut OverlayUi<'_>, cx: &mut Cx<'_, Self>) {
|
||||
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 setup = self.picker.as_ref();
|
||||
let sampled = self.sampled;
|
||||
let shown = ui.show(popup, Overlay::popover(), |ui, _| {
|
||||
let mut picker = compact_picker(name.clone(), Bind::given(PickedColor::rgb(color)), sampled).alpha(true).eyedropper(true);
|
||||
if let Some(setup) = setup {
|
||||
picker = (setup.0)(picker);
|
||||
}
|
||||
picker.show(ui)
|
||||
});
|
||||
if let Some(picked) = shown {
|
||||
self.edit = picked.events;
|
||||
self.edited = Some(opened);
|
||||
self.screen_pick = picked.screen_pick;
|
||||
}
|
||||
}
|
||||
|
||||
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(),
|
||||
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.
|
||||
access.node(WELL.at(i as u64), Role::RADIO_BUTTON).value(value);
|
||||
}
|
||||
}
|
||||
|
||||
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 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 of the ground colour round it.
|
||||
for well in [active.other(), active] {
|
||||
let at = place(rects[well.index() as usize]);
|
||||
let shown = &self.wells[well.index() as usize];
|
||||
if well == active {
|
||||
ui.draw().fill(&PaintShape::Rect(at.expand(style.gap), egui::CornerRadius::ZERO), style.ground);
|
||||
}
|
||||
match shown.color.same() {
|
||||
Some(color) if shown.ring => paint_ring(ui, at, *color, style),
|
||||
_ => ui.face(WELL.at(well.index()), Swatch::new(shown.label.clone(), shown.color).selected(well == active)),
|
||||
}
|
||||
}
|
||||
if let Some(name) = self.default_button.clone() {
|
||||
ui.face(DEFAULT, IconButton::new(IconId::new("default_colors")).label(name));
|
||||
}
|
||||
if let Some(name) = self.swap_button.clone() {
|
||||
ui.face(SWAP, IconButton::new(IconId::new("swap_colors")).label(name));
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> SwatchPairOutput {
|
||||
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 {
|
||||
response,
|
||||
active,
|
||||
activated: self.activated,
|
||||
clicked: self.clicked,
|
||||
double_clicked: self.double_clicked,
|
||||
events: self.edit,
|
||||
well: self.edited.unwrap_or_default(),
|
||||
swap: self.swap,
|
||||
defaults: self.defaults,
|
||||
screen_pick: self.screen_pick,
|
||||
open,
|
||||
choice: cx.edit_response(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A ring well: a band of the colour round the edge, the middle open to what is behind.
|
||||
fn paint_ring(ui: &mut PaintUi<'_>, at: Rect, color: Srgba, style: &SwatchPairStyle) {
|
||||
let band = at.width() * RING_SHARE;
|
||||
let fill = DataColor::new(Color32::from(color));
|
||||
let draw = ui.draw();
|
||||
let bands = [
|
||||
Rect::from_min_max(at.min, pos2(at.max.x, at.min.y + band)),
|
||||
Rect::from_min_max(pos2(at.min.x, at.max.y - band), at.max),
|
||||
Rect::from_min_max(pos2(at.min.x, at.min.y + band), pos2(at.min.x + band, at.max.y - band)),
|
||||
Rect::from_min_max(pos2(at.max.x - band, at.min.y + band), pos2(at.max.x, at.max.y - band)),
|
||||
];
|
||||
for part in bands {
|
||||
draw.data_fill(&PaintShape::Rect(part, egui::CornerRadius::ZERO), fill);
|
||||
}
|
||||
draw.stroke(&PaintShape::Rect(at, egui::CornerRadius::ZERO), StrokeWidth::Thin, style.edge);
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
//! Stories of the swatch pair.
|
||||
|
||||
use super::{PairWell, SwatchPair, Well};
|
||||
use craft_behavior::Mixed;
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::contract::{Bind, Show as _, Validity};
|
||||
use craft_ui::runtime::env::Message;
|
||||
use craft_ui::testing::{Drive, Fixture, StoryData, StoryOutput, story};
|
||||
use egui::{Key, Modifiers, Ui};
|
||||
|
||||
/// Tab arrives at the active well; the arrow moves to the other well and makes it active.
|
||||
fn next_well(fixture: &mut Fixture) {
|
||||
fixture.key(Key::Tab, Modifiers::NONE);
|
||||
fixture.key(Key::ArrowRight, Modifiers::NONE);
|
||||
fixture.idle(2);
|
||||
}
|
||||
|
||||
fn wells(ring: bool) -> [PairWell; 2] {
|
||||
[
|
||||
PairWell::new("Foreground colour", Srgba::rgb(0.1, 0.3, 0.8)),
|
||||
PairWell::new("Background colour", Srgba { r: 1.0, g: 1.0, b: 1.0, a: 0.7 }).ring(ring),
|
||||
]
|
||||
}
|
||||
|
||||
#[story(SwatchPair<'static>, covers = [Default], drive = Drive::Custom(next_well))]
|
||||
fn swatch_pair(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
SwatchPair::new("Colours", wells(false), Bind::bound(data.value("active", Well::Primary)))
|
||||
.swap_button("Swap colours")
|
||||
.default_button("Default colours")
|
||||
.show(ui)
|
||||
.into()
|
||||
}
|
||||
|
||||
#[story(SwatchPair<'static>, covers = [], drive = Drive::Never)]
|
||||
fn swatch_pair_ring(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
SwatchPair::new("Fill and stroke", wells(true), Bind::bound(data.value("active", Well::Secondary))).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(SwatchPair<'static>, covers = [], drive = Drive::Never)]
|
||||
fn swatch_pair_host_picker(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
SwatchPair::new("Colours", wells(false), Bind::bound(data.value("active", Well::Primary))).popover(false).click_activates(false).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(SwatchPair<'static>, 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, Bind::bound(data.value("active", Well::Primary))).show(ui).into()
|
||||
}
|
||||
|
||||
/// Opens the picker of the focused well with Enter.
|
||||
fn open_picker(fixture: &mut Fixture) {
|
||||
fixture.key(Key::Tab, Modifiers::NONE);
|
||||
fixture.key(Key::Enter, Modifiers::NONE);
|
||||
fixture.idle(4);
|
||||
}
|
||||
|
||||
#[story(SwatchPair<'static>, covers = [Open], drive = Drive::Custom(open_picker))]
|
||||
fn swatch_pair_open(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
SwatchPair::new("Colours", wells(false), Bind::bound(data.value("active", Well::Primary))).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(SwatchPair<'static>, 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), Bind::bound(data.value("active", Well::Secondary)).check(refuse_secondary)).show(ui).into()
|
||||
}
|
||||
@@ -0,0 +1,331 @@
|
||||
//! `SwatchPalette`: a wrapping grid of colour cells that chooses one colour. `SwatchTable`: a table of touching cells
|
||||
//! selected by index, for a colour table whose entries may repeat a colour.
|
||||
|
||||
use craft_behavior::{DisplayOrder, EditEvent, ItemSource, Metrics, Mixed, PartKey, Selection, Sense, TileLayout};
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::choice::{Swatch, SwatchMetrics};
|
||||
use craft_ui::contract::{
|
||||
Access, ActivateOn, Bind, BindMut, Collection, CollectionEvent, CollectionProps, Common, Component, ContainerProps, Cx, Held, MeasureCx, NoValue,
|
||||
Outcome, PaintUi, PartsCx, Pattern, Props, Role, SelectMode, ShowCollection as _, ShowContainer as _, Sizing, Styled as _,
|
||||
};
|
||||
use craft_ui::layout_components::Stack;
|
||||
use craft_ui::runtime::env::Label;
|
||||
use craft_ui::style::{ComponentStyle, Flags, FocusLook, StyleCx};
|
||||
use egui::{Rect, Response, Ui, Vec2};
|
||||
use std::sync::Arc;
|
||||
|
||||
#[cfg(feature = "screen-testing")]
|
||||
mod stories;
|
||||
|
||||
/// The part of a cell that shows the colour.
|
||||
const WELL: PartKey = PartKey::new("well");
|
||||
|
||||
/// What a [`SwatchPalette`] reports.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
#[must_use = "the host reads the pick"]
|
||||
pub struct SwatchPaletteOutput {
|
||||
/// The palette's response.
|
||||
pub response: Response,
|
||||
/// The pick of this pass as one `Set` of the swatch's colour; `None` when nothing was picked. The palette has
|
||||
/// already written it to its binding.
|
||||
pub edit: Option<EditEvent<Srgba>>,
|
||||
}
|
||||
|
||||
impl Outcome for SwatchPaletteOutput {
|
||||
type Value = NoValue;
|
||||
|
||||
fn response(&self) -> &Response {
|
||||
&self.response
|
||||
}
|
||||
}
|
||||
|
||||
/// A wrapping grid of colour cells from the host's list of named colours that chooses one colour.
|
||||
///
|
||||
/// - The swatch equal to the colour (compared in 8 bits, the first when several are) is selected; the name is its
|
||||
/// tooltip.
|
||||
/// - A click, Space or Enter on a swatch, or a screen reader's click, sets its colour as one `Set`.
|
||||
/// - The palette is one Tab stop: Tab enters on the selected swatch (the first when none is) and the next Tab leaves.
|
||||
/// Arrows move the focus through the cells as the rows lie, Up and Down to the cell above or below; they choose
|
||||
/// nothing.
|
||||
/// - AccessKit: a list box named by the label; each cell a list box option named by its name, with the hex colour as
|
||||
/// its value.
|
||||
#[must_use = "show the palette with `show`"]
|
||||
#[derive(Pattern)]
|
||||
pub struct SwatchPalette<'a> {
|
||||
label: Label,
|
||||
color: Bind<'a, Srgba>,
|
||||
swatches: &'a [(Label, Srgba)],
|
||||
}
|
||||
|
||||
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, swatches }
|
||||
}
|
||||
|
||||
/// Shows the palette.
|
||||
pub fn show(self, ui: &mut Ui) -> SwatchPaletteOutput {
|
||||
let SwatchPalette { label, color, swatches } = self;
|
||||
let mut held = Held::new(color);
|
||||
let name = label.clone();
|
||||
let mut shown = Stack::new().show(ui, |ui, cx| {
|
||||
let before = held.read(cx)?;
|
||||
let selected = swatches.iter().position(|(_, c)| c.to_rgba() == before.to_rgba());
|
||||
let mut current = selected.map_or_else(Selection::default, Selection::single);
|
||||
let table = SwatchTable::new(label.clone(), swatches).tips(true).selection(Bind::bound(&mut current)).show_all(ui);
|
||||
let picked = table.selected.or(table.open)?;
|
||||
let after = swatches.get(picked)?.1;
|
||||
if after.to_rgba() == before.to_rgba() {
|
||||
return None;
|
||||
}
|
||||
Some((before, after))
|
||||
});
|
||||
// Once per pass, after the real run: the picked colour is stored and reported.
|
||||
let edit = shown
|
||||
.settle(|cx, picked| {
|
||||
let (before, after) = picked.take()?;
|
||||
held.write(cx, &before, after, name.as_str());
|
||||
Some(EditEvent::set(Mixed::Same(before), after, Arc::from(name.as_str()), None))
|
||||
})
|
||||
.flatten();
|
||||
SwatchPaletteOutput { response: shown.output, edit }
|
||||
}
|
||||
}
|
||||
|
||||
/// The entries of a colour table as an item source: keyed by index, named for type-ahead.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub struct SwatchRows<'a>(&'a [(Label, Srgba)]);
|
||||
|
||||
impl<'a> SwatchRows<'a> {
|
||||
/// The entries of `swatches`.
|
||||
pub const fn new(swatches: &'a [(Label, Srgba)]) -> Self {
|
||||
SwatchRows(swatches)
|
||||
}
|
||||
}
|
||||
|
||||
impl DisplayOrder<usize> for SwatchRows<'_> {
|
||||
fn len(&self) -> usize {
|
||||
self.0.len()
|
||||
}
|
||||
|
||||
fn key(&self, at: usize) -> usize {
|
||||
at
|
||||
}
|
||||
|
||||
fn index_of(&self, key: &usize) -> Option<usize> {
|
||||
(*key < self.0.len()).then_some(*key)
|
||||
}
|
||||
|
||||
fn text(&self, at: usize) -> Option<std::borrow::Cow<'_, str>> {
|
||||
self.0.get(at).map(|(name, _)| std::borrow::Cow::Borrowed(name.as_str()))
|
||||
}
|
||||
}
|
||||
|
||||
impl ItemSource<usize> for SwatchRows<'_> {}
|
||||
|
||||
/// The style of a table cell: the swatch's own look is painted as the cell's face.
|
||||
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
|
||||
#[non_exhaustive]
|
||||
pub struct SwatchCellStyle {
|
||||
#[style(metrics)]
|
||||
metrics: Metrics,
|
||||
#[style(focus)]
|
||||
focus: FocusLook,
|
||||
/// The side of the cell.
|
||||
side: f32,
|
||||
}
|
||||
|
||||
/// One cell of a [`SwatchTable`]: a touching, square swatch named by its entry and valued by its hex colour.
|
||||
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
|
||||
pub struct SwatchCell {
|
||||
#[common]
|
||||
common: Common,
|
||||
color: Srgba,
|
||||
}
|
||||
|
||||
impl SwatchCell {
|
||||
/// A cell of `color` named `name`.
|
||||
pub fn new(name: impl Into<Label>, color: Srgba) -> Self {
|
||||
SwatchCell { common: Common::new(), color }.label(name)
|
||||
}
|
||||
}
|
||||
|
||||
impl Component for SwatchCell {
|
||||
const ROLE: Role = Role::LIST_BOX_OPTION;
|
||||
const OVERLAYS: bool = false;
|
||||
type Style = SwatchCellStyle;
|
||||
type Output = Response;
|
||||
|
||||
fn style(cx: &StyleCx<'_>, _: SwatchCellStyleKey) -> SwatchCellStyle {
|
||||
let side = SwatchMetrics::of(cx).cell;
|
||||
SwatchCellStyle { metrics: Metrics::new(), focus: cx.focus_look(), side }
|
||||
}
|
||||
|
||||
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
Vec2::splat(cx.style.side)
|
||||
}
|
||||
|
||||
fn sense(&self) -> Sense {
|
||||
Sense::CLICK | Sense::FOCUS
|
||||
}
|
||||
|
||||
fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) {
|
||||
let _ = cx.part(WELL, rect);
|
||||
}
|
||||
|
||||
fn access(&self, access: &mut Access, _: &Cx<'_, Self>) {
|
||||
access.value(self.color.to_hex());
|
||||
access.color(self.color);
|
||||
}
|
||||
|
||||
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
|
||||
let selected = cx.resolved.selected == Some(true) || cx.state().flags.contains(Flags::SELECTED);
|
||||
ui.face(WELL, Swatch::new(cx.resolved.label.to_owned(), self.color).cell().selected(selected));
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> Response {
|
||||
cx.response.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// What a [`SwatchTable`] reports.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
#[must_use = "the host applies the selection and the open request"]
|
||||
pub struct SwatchTableOutput {
|
||||
/// The cells.
|
||||
pub response: Response,
|
||||
/// The entry a click, Space or a screen reader's click selected this pass: the lead of the selection it made.
|
||||
pub selected: Option<usize>,
|
||||
/// The selected entries after the pass, in selection order.
|
||||
pub chosen: Vec<usize>,
|
||||
/// The entry a double click or Enter asked to edit this pass.
|
||||
pub open: Option<usize>,
|
||||
}
|
||||
|
||||
impl Outcome for SwatchTableOutput {
|
||||
type Value = NoValue;
|
||||
|
||||
fn response(&self) -> &Response {
|
||||
&self.response
|
||||
}
|
||||
}
|
||||
|
||||
/// A table of touching colour cells, one per entry, wrapping to the width or to a fixed count per row. Entries are
|
||||
/// told apart by index, so duplicates select one cell.
|
||||
///
|
||||
/// - A click or Space selects the cell; a double click or Enter reports `open` and the Enter is the table's, so a
|
||||
/// dialog around it does not also answer OK.
|
||||
/// - The table is one Tab stop; the arrows move through the cells as a grid.
|
||||
/// - AccessKit: a list box named by the label; each cell a list box option named by its entry, with the hex colour as
|
||||
/// its value.
|
||||
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
|
||||
#[component(collection)]
|
||||
pub struct SwatchTable<'a> {
|
||||
#[common]
|
||||
common: Common,
|
||||
#[container]
|
||||
props: ContainerProps,
|
||||
#[collection]
|
||||
items: CollectionProps,
|
||||
swatches: &'a [(Label, Srgba)],
|
||||
/// The selection the caller owns.
|
||||
#[prop]
|
||||
selection: Option<Bind<'a, Selection<usize>>>,
|
||||
/// A fixed number of cells to a row instead of wrapping to the width.
|
||||
#[prop]
|
||||
per_row: Option<usize>,
|
||||
/// Whether each cell's name is its tooltip.
|
||||
#[prop]
|
||||
tips: bool,
|
||||
}
|
||||
|
||||
impl<'a> SwatchTable<'a> {
|
||||
/// A table named `label` of `swatches`, each a name and a colour.
|
||||
pub fn new(label: impl Into<Label>, swatches: &'a [(Label, Srgba)]) -> Self {
|
||||
SwatchTable {
|
||||
common: Common::new(),
|
||||
props: ContainerProps::new().sizing(Sizing::FillWidth),
|
||||
items: CollectionProps::new().select(SelectMode::Single).activate(ActivateOn::DoubleClick).arrows_select(false).natural_height(true),
|
||||
swatches,
|
||||
selection: None,
|
||||
per_row: None,
|
||||
tips: false,
|
||||
}
|
||||
.label(label)
|
||||
}
|
||||
|
||||
/// Whether Shift or Cmd adds cells to the selection.
|
||||
#[must_use]
|
||||
pub fn multiple(mut self, on: bool) -> Self {
|
||||
self.items = self.items.select(if on { SelectMode::Multi } else { SelectMode::Single });
|
||||
self
|
||||
}
|
||||
|
||||
/// Shows the table.
|
||||
pub fn show_all(self, ui: &mut Ui) -> SwatchTableOutput {
|
||||
let (swatches, tips) = (self.swatches, self.tips);
|
||||
self.show_items(ui, &SwatchRows::new(swatches), &mut |key, _| {
|
||||
let (name, color) = &swatches[*key];
|
||||
let cell = SwatchCell::new(name.clone(), *color);
|
||||
if tips { cell.tooltip(name.clone()) } else { cell }
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// The style of a table: it has no look of its own; its cells paint the swatches.
|
||||
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
|
||||
#[non_exhaustive]
|
||||
pub struct SwatchTableStyle {
|
||||
#[style(metrics)]
|
||||
metrics: Metrics,
|
||||
}
|
||||
|
||||
impl Component for SwatchTable<'_> {
|
||||
const SINGLE_VALUE: bool = true;
|
||||
const ROLE: Role = Role::LIST_BOX;
|
||||
const PARTS: bool = false;
|
||||
type Style = SwatchTableStyle;
|
||||
type Output = SwatchTableOutput;
|
||||
|
||||
fn style(_: &StyleCx<'_>, _: SwatchTableStyleKey) -> SwatchTableStyle {
|
||||
SwatchTableStyle { metrics: Metrics::new() }
|
||||
}
|
||||
|
||||
fn finish(self, mut cx: Cx<'_, Self>) -> SwatchTableOutput {
|
||||
let selection = cx.collection_selection().cloned().unwrap_or_default();
|
||||
let response = cx.collection_response();
|
||||
let open = response.events.iter().find_map(|event| match event {
|
||||
CollectionEvent::Activate(key) => Some(*key),
|
||||
_ => None,
|
||||
});
|
||||
let changed = response.events.iter().any(|event| matches!(event, CollectionEvent::Selection(_)));
|
||||
SwatchTableOutput { response: response.response, selected: selection.lead.filter(|_| changed), chosen: selection.items, open }
|
||||
}
|
||||
}
|
||||
|
||||
impl Collection for SwatchTable<'_> {
|
||||
type Key = usize;
|
||||
type ItemLayout = TileLayout;
|
||||
type Selection = Selection<usize>;
|
||||
type Item<'r> = SwatchCell;
|
||||
type ItemEvent = std::convert::Infallible;
|
||||
|
||||
fn items(&self) -> &CollectionProps {
|
||||
&self.items
|
||||
}
|
||||
|
||||
fn selection(&mut self) -> Option<BindMut<'_, Selection<usize>>> {
|
||||
self.selection.as_mut().map(Bind::reborrow)
|
||||
}
|
||||
|
||||
fn item_layout(&self, source: &dyn ItemSource<usize>, width: f32, cx: &StyleCx<'_>) -> TileLayout {
|
||||
let cell = SwatchMetrics::of(cx).cell;
|
||||
let layout = TileLayout::new(source, width, Vec2::splat(cell), 0.0);
|
||||
match self.per_row {
|
||||
Some(columns) => layout.in_columns(columns),
|
||||
None => layout,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
//! Stories of `SwatchPalette` and `SwatchTable`.
|
||||
|
||||
use super::{SwatchCell, SwatchPalette, SwatchTable};
|
||||
use craft_behavior::Selection;
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::contract::Bind;
|
||||
use craft_ui::runtime::env::Label;
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, show_as_only_item, story};
|
||||
use egui::Ui;
|
||||
|
||||
/// The twelve colours of the palette story.
|
||||
const PALETTE: [(&str, Srgba); 12] = [
|
||||
("Red", Srgba::rgb(0.90, 0.28, 0.30)),
|
||||
("Orange", Srgba::rgb(0.97, 0.42, 0.08)),
|
||||
("Amber", Srgba::rgb(0.96, 0.65, 0.14)),
|
||||
("Yellow", Srgba::rgb(0.96, 0.85, 0.04)),
|
||||
("Lime", Srgba::rgb(0.48, 0.77, 0.36)),
|
||||
("Green", Srgba::rgb(0.19, 0.64, 0.42)),
|
||||
("Teal", Srgba::rgb(0.07, 0.65, 0.58)),
|
||||
("Cyan", Srgba::rgb(0.00, 0.62, 0.88)),
|
||||
("Blue", Srgba::rgb(0.24, 0.39, 0.87)),
|
||||
("Violet", Srgba::rgb(0.56, 0.31, 0.78)),
|
||||
("Magenta", Srgba::rgb(0.84, 0.25, 0.62)),
|
||||
("Grey", Srgba::rgb(0.53, 0.55, 0.57)),
|
||||
];
|
||||
|
||||
fn named(entries: impl IntoIterator<Item = (String, Srgba)>) -> Vec<(Label, Srgba)> {
|
||||
entries.into_iter().map(|(name, color)| (Label::from(name), color)).collect()
|
||||
}
|
||||
|
||||
/// A 256-entry table whose entries repeat colours: index 3 and 7 share one.
|
||||
fn table_entries() -> Vec<(Label, Srgba)> {
|
||||
named((0..256usize).map(|i| {
|
||||
let shade = if i == 7 { 3 } else { i };
|
||||
(format!("Index {i}"), Srgba::rgb(shade as f32 / 255.0, (shade % 16) as f32 / 15.0, 0.5))
|
||||
}))
|
||||
}
|
||||
|
||||
#[story(SwatchPalette<'static>, covers = [], drive = Drive::Never)]
|
||||
fn swatch_palette(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let swatches = named(PALETTE.iter().map(|(name, color)| ((*name).to_owned(), *color)));
|
||||
SwatchPalette::new("Swatches", Bind::bound(data.value("color", PALETTE[8].1)), &swatches).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(SwatchTable<'static>, covers = [Default, Many], drive = Drive::Never)]
|
||||
fn swatch_table(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let entries = table_entries();
|
||||
SwatchTable::new("Color Table", &entries)
|
||||
.selection(Bind::bound(data.value("selected", Selection::single(5usize))))
|
||||
.per_row(16)
|
||||
.show_all(ui)
|
||||
.into()
|
||||
}
|
||||
|
||||
#[story(SwatchTable<'static>, covers = [], drive = Drive::Never)]
|
||||
fn swatch_table_multiple(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let entries = table_entries();
|
||||
let start = Selection::new(vec![2usize, 3, 18], Some(18), Some(2));
|
||||
SwatchTable::new("Color Table", &entries).multiple(true).selection(Bind::bound(data.value("selected", start))).per_row(16).show_all(ui).into()
|
||||
}
|
||||
|
||||
#[story(SwatchTable<'static>, covers = [Empty], drive = Drive::Never)]
|
||||
fn swatch_table_empty(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
SwatchTable::new("Color Table", &[]).empty("No colors").show_all(ui).into()
|
||||
}
|
||||
|
||||
#[story(SwatchTable<'static>, covers = [One], drive = Drive::Never)]
|
||||
fn swatch_table_one(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let entries = table_entries().into_iter().take(1).collect::<Vec<_>>();
|
||||
SwatchTable::new("Color Table", &entries).selection(Bind::bound(data.value("selected", Selection::single(0usize)))).show_all(ui).into()
|
||||
}
|
||||
|
||||
#[story(SwatchCell, covers = [Default], drive = Drive::Never)]
|
||||
fn swatch_cell(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
show_as_only_item(ui, SwatchCell::new("Swatch", Srgba::rgb(0.2, 0.4, 0.8))).into()
|
||||
}
|
||||
@@ -0,0 +1,777 @@
|
||||
//! `ColorPanel`: Photoshop's Color panel. The foreground and background wells, one of nine views of the edited colour
|
||||
//! (two cubes, a wheel, five slider sets), the out-of-gamut and web-colour warnings, and the colour ramp under the
|
||||
//! sliders; the panel menu chooses the view and the ramp and copies the colour.
|
||||
|
||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||
|
||||
use craft_behavior::{EditEvent, GesturePhase, IconId, Mixed};
|
||||
use craft_cms::convert::CmykConverter;
|
||||
use craft_theme::{ColorModel, HsbModel, LabModel, ModelValues, RgbModel, Srgba};
|
||||
use craft_ui::buttons::IconButton;
|
||||
use craft_ui::contract::{Bind, CommandSet, Held, NoValue, Outcome, Pattern, Props as _, Remember as _, Show as _, ShowContainer as _, clicked};
|
||||
use craft_ui::layout::RowAlign;
|
||||
use craft_ui::layout_components::{Row, Stack};
|
||||
use craft_ui::menu::{Menu, MenuItem, PanelRow};
|
||||
use craft_ui::runtime::commands::{CommandRef, CommandState};
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
use craft_ui::runtime::requests::ColorRequest;
|
||||
use egui::{Response, Ui};
|
||||
|
||||
use super::channels::finite_values;
|
||||
use super::picker::{ChannelRow, ChannelRule, channel_name};
|
||||
use super::{
|
||||
AreaMode, ColorArea, ColorPickerDialogWords, ColorRamp, ColorReadout, ColorStrip, ColorWarning, ColorWarningChip, ColorWheel, PairWell,
|
||||
PickedColor, RampKind, SwatchPair, Well,
|
||||
};
|
||||
use crate::{CmykModel, GrayModel, not_web_safe};
|
||||
|
||||
#[cfg(feature = "screen-testing")]
|
||||
mod stories;
|
||||
|
||||
craft_ui::words! {
|
||||
/// The Color panel's words.
|
||||
#[non_exhaustive]
|
||||
pub struct ColorPanelWords {
|
||||
title: "colorPanel.title" = "Color";
|
||||
hue_cube: "colorPanel.hueCube" = "Hue Cube";
|
||||
brightness_cube: "colorPanel.brightnessCube" = "Brightness Cube";
|
||||
color_wheel: "colorPanel.colorWheel" = "Color Wheel";
|
||||
grayscale_slider: "colorPanel.grayscaleSlider" = "Grayscale Slider";
|
||||
rgb_sliders: "colorPanel.rgbSliders" = "RGB Sliders";
|
||||
hsb_sliders: "colorPanel.hsbSliders" = "HSB Sliders";
|
||||
cmyk_sliders: "colorPanel.cmykSliders" = "CMYK Sliders";
|
||||
lab_sliders: "colorPanel.labSliders" = "Lab Sliders";
|
||||
web_color_sliders: "colorPanel.webColorSliders" = "Web Color Sliders";
|
||||
rgb_spectrum: "colorPanel.rgbSpectrum" = "RGB Spectrum";
|
||||
cmyk_spectrum: "colorPanel.cmykSpectrum" = "CMYK Spectrum";
|
||||
grayscale_ramp: "colorPanel.grayscaleRamp" = "Grayscale Ramp";
|
||||
current_colors: "colorPanel.currentColors" = "Current Colors";
|
||||
color_ramp: "colorPanel.colorRamp" = "Color Ramp";
|
||||
foreground: "colorPanel.foreground" = "Foreground color";
|
||||
background: "colorPanel.background" = "Background color";
|
||||
wells: "colorPanel.wells" = "Colors";
|
||||
add_to_swatches: "colorPanel.addToSwatches" = "Add to Swatches";
|
||||
create_swatch: "colorPanel.createSwatch" = "Create new swatch";
|
||||
hex_color: "colorPanel.hexColor" = "Hex color";
|
||||
}
|
||||
}
|
||||
|
||||
/// What the panel shows: Photoshop's panel menu choices, in its order. Hue Cube is the default;
|
||||
/// the theme never changes it.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub enum ColorPanelMode {
|
||||
#[default]
|
||||
#[allow(missing_docs)]
|
||||
HueCube,
|
||||
#[allow(missing_docs)]
|
||||
BrightnessCube,
|
||||
#[allow(missing_docs)]
|
||||
ColorWheel,
|
||||
#[allow(missing_docs)]
|
||||
GrayscaleSlider,
|
||||
#[allow(missing_docs)]
|
||||
RgbSliders,
|
||||
#[allow(missing_docs)]
|
||||
HsbSliders,
|
||||
#[allow(missing_docs)]
|
||||
CmykSliders,
|
||||
#[allow(missing_docs)]
|
||||
LabSliders,
|
||||
#[allow(missing_docs)]
|
||||
WebColorSliders,
|
||||
}
|
||||
|
||||
impl ColorPanelMode {
|
||||
/// Every mode, in the panel menu's order (one section, no separator).
|
||||
pub const ALL: [ColorPanelMode; 9] = [
|
||||
ColorPanelMode::HueCube,
|
||||
ColorPanelMode::BrightnessCube,
|
||||
ColorPanelMode::ColorWheel,
|
||||
ColorPanelMode::GrayscaleSlider,
|
||||
ColorPanelMode::RgbSliders,
|
||||
ColorPanelMode::HsbSliders,
|
||||
ColorPanelMode::CmykSliders,
|
||||
ColorPanelMode::LabSliders,
|
||||
ColorPanelMode::WebColorSliders,
|
||||
];
|
||||
|
||||
/// Hue Cube and Brightness Cube.
|
||||
pub fn is_cube(self) -> bool {
|
||||
matches!(self, ColorPanelMode::HueCube | ColorPanelMode::BrightnessCube)
|
||||
}
|
||||
|
||||
/// The slider modes, which show the ramp under their sliders.
|
||||
pub fn is_sliders(self) -> bool {
|
||||
!matches!(self, ColorPanelMode::HueCube | ColorPanelMode::BrightnessCube | ColorPanelMode::ColorWheel)
|
||||
}
|
||||
|
||||
/// The menu item.
|
||||
pub fn label(self, labels: &ColorPanelWords) -> Label {
|
||||
match self {
|
||||
ColorPanelMode::HueCube => &labels.hue_cube,
|
||||
ColorPanelMode::BrightnessCube => &labels.brightness_cube,
|
||||
ColorPanelMode::ColorWheel => &labels.color_wheel,
|
||||
ColorPanelMode::GrayscaleSlider => &labels.grayscale_slider,
|
||||
ColorPanelMode::RgbSliders => &labels.rgb_sliders,
|
||||
ColorPanelMode::HsbSliders => &labels.hsb_sliders,
|
||||
ColorPanelMode::CmykSliders => &labels.cmyk_sliders,
|
||||
ColorPanelMode::LabSliders => &labels.lab_sliders,
|
||||
ColorPanelMode::WebColorSliders => &labels.web_color_sliders,
|
||||
}
|
||||
.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// The ramp under the sliders. Shift-click on the ramp cycles them in this order.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub enum ColorPanelRamp {
|
||||
#[default]
|
||||
#[allow(missing_docs)]
|
||||
RgbSpectrum,
|
||||
#[allow(missing_docs)]
|
||||
CmykSpectrum,
|
||||
#[allow(missing_docs)]
|
||||
GrayscaleRamp,
|
||||
#[allow(missing_docs)]
|
||||
CurrentColors,
|
||||
}
|
||||
|
||||
impl ColorPanelRamp {
|
||||
/// All ramps, in menu order.
|
||||
pub const ALL: [ColorPanelRamp; 4] =
|
||||
[ColorPanelRamp::RgbSpectrum, ColorPanelRamp::CmykSpectrum, ColorPanelRamp::GrayscaleRamp, ColorPanelRamp::CurrentColors];
|
||||
|
||||
/// The next ramp of the Shift-click cycle (Current Colors goes back to RGB Spectrum).
|
||||
pub fn next(self) -> ColorPanelRamp {
|
||||
let i = ColorPanelRamp::ALL.iter().position(|r| *r == self).unwrap_or(0);
|
||||
ColorPanelRamp::ALL.get(i + 1).copied().unwrap_or(ColorPanelRamp::RgbSpectrum)
|
||||
}
|
||||
|
||||
/// The [`ColorRamp`](super::ColorRamp) kind that draws it: Spectrum, CmykSpectrum,
|
||||
/// Grayscale, or Between the foreground and background.
|
||||
pub fn kind(self) -> RampKind {
|
||||
match self {
|
||||
ColorPanelRamp::RgbSpectrum => RampKind::Spectrum,
|
||||
ColorPanelRamp::CmykSpectrum => RampKind::CmykSpectrum,
|
||||
ColorPanelRamp::GrayscaleRamp => RampKind::Grayscale,
|
||||
ColorPanelRamp::CurrentColors => RampKind::Between,
|
||||
}
|
||||
}
|
||||
|
||||
/// The menu item.
|
||||
pub fn label(self, labels: &ColorPanelWords) -> Label {
|
||||
match self {
|
||||
ColorPanelRamp::RgbSpectrum => &labels.rgb_spectrum,
|
||||
ColorPanelRamp::CmykSpectrum => &labels.cmyk_spectrum,
|
||||
ColorPanelRamp::GrayscaleRamp => &labels.grayscale_ramp,
|
||||
ColorPanelRamp::CurrentColors => &labels.current_colors,
|
||||
}
|
||||
.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// The Color panel's settings, kept across runs (settings section `color_panel`).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub struct ColorPanelState {
|
||||
/// The panel edits the background colour (its well was clicked), not the foreground.
|
||||
pub background: bool,
|
||||
/// The picker layout.
|
||||
pub mode: ColorPanelMode,
|
||||
/// The colour ramp under the picker.
|
||||
pub ramp: ColorPanelRamp,
|
||||
/// Make Ramp Web Safe: the ramp shows and picks web colours only.
|
||||
pub web_safe_ramp: bool,
|
||||
}
|
||||
|
||||
impl craft_host::Section for ColorPanelState {
|
||||
const KEY: &'static str = "color_panel";
|
||||
}
|
||||
|
||||
/// Which colour a [`ColorPanel`] edit is for.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum PanelTarget {
|
||||
/// The foreground colour.
|
||||
Foreground,
|
||||
/// The background colour.
|
||||
Background,
|
||||
}
|
||||
|
||||
impl PanelTarget {
|
||||
/// The key of the [`ColorRequest`] for this colour's picker.
|
||||
pub fn key(self) -> &'static str {
|
||||
match self {
|
||||
PanelTarget::Foreground => "colorPanel.foreground",
|
||||
PanelTarget::Background => "colorPanel.background",
|
||||
}
|
||||
}
|
||||
|
||||
/// The target whose [`key`](PanelTarget::key) is `key`.
|
||||
pub fn from_key(key: &str) -> Option<PanelTarget> {
|
||||
[PanelTarget::Foreground, PanelTarget::Background].into_iter().find(|t| t.key() == key)
|
||||
}
|
||||
|
||||
fn index(self) -> usize {
|
||||
match self {
|
||||
PanelTarget::Foreground => 0,
|
||||
PanelTarget::Background => 1,
|
||||
}
|
||||
}
|
||||
|
||||
fn other(self) -> PanelTarget {
|
||||
match self {
|
||||
PanelTarget::Foreground => PanelTarget::Background,
|
||||
PanelTarget::Background => PanelTarget::Foreground,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What [`ColorPanel::show`] returns.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
#[must_use = "the host applies the edit"]
|
||||
pub struct ColorPanelOutput {
|
||||
/// The panel's response.
|
||||
pub response: Response,
|
||||
/// The edits of the foreground or background colour this pass (from the view, the sliders, the ramp or a warning
|
||||
/// chip), in order, each with the colour it is for. Usually one; a field that commits as a slider begins makes
|
||||
/// two.
|
||||
pub edits: Vec<(PanelTarget, EditEvent<PickedColor>)>,
|
||||
/// A well was clicked while it was already the edited one, for this pass only: the app opens the colour picker
|
||||
/// dialog from the request (Photoshop). Its key is the well's [`PanelTarget::key`]; the colour is the well's.
|
||||
pub pick_color: Option<ColorRequest>,
|
||||
/// 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>,
|
||||
}
|
||||
|
||||
impl Outcome for ColorPanelOutput {
|
||||
type Value = NoValue;
|
||||
|
||||
fn response(&self) -> &Response {
|
||||
&self.response
|
||||
}
|
||||
}
|
||||
|
||||
/// What the panel keeps between passes: the values last edited, one list per colour, and the ramp gesture's target.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
struct Kept {
|
||||
values: [Vec<ModelValues>; 2],
|
||||
/// The values the slider tracks were drawn from when a drag began, per model and colour.
|
||||
tracks: Vec<(&'static str, usize, ModelValues)>,
|
||||
/// A channel gesture is running.
|
||||
dragging: bool,
|
||||
/// The ramp gesture in progress picks for the colour not edited.
|
||||
other: bool,
|
||||
}
|
||||
|
||||
/// The Color panel.
|
||||
///
|
||||
/// - Wells: the foreground over the background (`SwatchPair`); a click on the other well makes it the edited one
|
||||
/// ([`ColorPanelState::background`]); a click on the edited one asks for the picker. The swap and default buttons
|
||||
/// are the pair's.
|
||||
/// - Views: Hue Cube and Brightness Cube are `ColorArea` and `ColorStrip` (hue or brightness in the strip); Color
|
||||
/// Wheel is `ColorWheel`; the slider modes are the channel rows of that model (Grayscale is [`GrayModel`], CMYK is
|
||||
/// [`CmykModel`] through the converter, Web Color is RGB with sliders that snap to web colours). Slider values show
|
||||
/// rounded to whole numbers, as Photoshop's fields.
|
||||
/// - Warnings: in the slider modes, the out-of-gamut and web-colour chips beside the wells, the cubes the gamut chip
|
||||
/// only; a click takes the nearest colour.
|
||||
/// - 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.
|
||||
/// - Focus: the panel never takes the focus when shown.
|
||||
#[must_use = "show the panel with `show`"]
|
||||
#[derive(Pattern)]
|
||||
pub struct ColorPanel<'a> {
|
||||
state: Bind<'a, ColorPanelState>,
|
||||
colors: [Srgba; 2],
|
||||
cmyk: Option<&'a CmykConverter>,
|
||||
dynamic: bool,
|
||||
}
|
||||
|
||||
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 }
|
||||
}
|
||||
|
||||
/// The document's CMYK converter, for the CMYK sliders, the CMYK Spectrum ramp and the gamut warning; without it
|
||||
/// they use the built-in coated CMYK.
|
||||
pub fn cmyk(mut self, converter: &'a CmykConverter) -> Self {
|
||||
self.cmyk = Some(converter);
|
||||
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 {
|
||||
self.dynamic = on;
|
||||
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 env = Env::of(ui);
|
||||
let (words, dialog) = (env.words::<ColorPanelWords>(), env.words::<ColorPickerDialogWords>());
|
||||
let mut held = Held::new(state);
|
||||
let (mut edits, mut pick_color, mut add_to_swatches) = (Vec::new(), None, None);
|
||||
let mut shown = Stack::new().label(words.title.clone()).show(ui, |ui, cx| {
|
||||
let before = held.read(cx)?;
|
||||
let target = if before.background { PanelTarget::Background } else { PanelTarget::Foreground };
|
||||
let mut body = Body {
|
||||
target,
|
||||
colors,
|
||||
converter: cmyk.unwrap_or_else(|| CmykConverter::coated()),
|
||||
dynamic,
|
||||
words: &words,
|
||||
dialog: &dialog,
|
||||
now: before,
|
||||
kept: cx.memory::<Kept>().clone(),
|
||||
events: Vec::new(),
|
||||
pick_color: None,
|
||||
add_to_swatches: None,
|
||||
};
|
||||
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))
|
||||
});
|
||||
// Once per pass, after the real run: the edited state is stored.
|
||||
shown.settle(|cx, state| {
|
||||
if let Some((before, now)) = state.take()
|
||||
&& now != before
|
||||
{
|
||||
held.write(cx, &before, now, words.title.as_str());
|
||||
}
|
||||
});
|
||||
ColorPanelOutput { response: shown.output, edits, pick_color, add_to_swatches }
|
||||
}
|
||||
}
|
||||
|
||||
/// The commands of the Color panel menu and of the ramp's context menu.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, CommandSet)]
|
||||
#[command(prefix = "colorPanel")]
|
||||
#[non_exhaustive]
|
||||
pub enum ColorPanelCommand {
|
||||
/// Hue Cube view.
|
||||
#[command(label = "Hue Cube", kind = "radio", group = "colorPanel.mode")]
|
||||
HueCube,
|
||||
/// Brightness Cube view.
|
||||
#[command(label = "Brightness Cube", kind = "radio", group = "colorPanel.mode")]
|
||||
BrightnessCube,
|
||||
/// Color Wheel view.
|
||||
#[command(label = "Color Wheel", kind = "radio", group = "colorPanel.mode")]
|
||||
ColorWheel,
|
||||
/// Grayscale Slider view.
|
||||
#[command(label = "Grayscale Slider", kind = "radio", group = "colorPanel.mode")]
|
||||
GrayscaleSlider,
|
||||
/// RGB Sliders view.
|
||||
#[command(label = "RGB Sliders", kind = "radio", group = "colorPanel.mode")]
|
||||
RgbSliders,
|
||||
/// HSB Sliders view.
|
||||
#[command(label = "HSB Sliders", kind = "radio", group = "colorPanel.mode")]
|
||||
HsbSliders,
|
||||
/// CMYK Sliders view.
|
||||
#[command(label = "CMYK Sliders", kind = "radio", group = "colorPanel.mode")]
|
||||
CmykSliders,
|
||||
/// Lab Sliders view.
|
||||
#[command(label = "Lab Sliders", kind = "radio", group = "colorPanel.mode")]
|
||||
LabSliders,
|
||||
/// Web Color Sliders view.
|
||||
#[command(label = "Web Color Sliders", kind = "radio", group = "colorPanel.mode")]
|
||||
WebColorSliders,
|
||||
/// Copy the edited colour as `color="#rrggbb"`.
|
||||
#[command(label = "Copy Color as HTML")]
|
||||
CopyHtml,
|
||||
/// Copy the edited colour's hex code.
|
||||
#[command(label = "Copy Color's Hex Code")]
|
||||
CopyHex,
|
||||
/// The RGB Spectrum ramp.
|
||||
#[command(label = "RGB Spectrum", kind = "radio", group = "colorPanel.ramp")]
|
||||
RgbSpectrum,
|
||||
/// The CMYK Spectrum ramp.
|
||||
#[command(label = "CMYK Spectrum", kind = "radio", group = "colorPanel.ramp")]
|
||||
CmykSpectrum,
|
||||
/// The Grayscale Ramp.
|
||||
#[command(label = "Grayscale Ramp", kind = "radio", group = "colorPanel.ramp")]
|
||||
GrayscaleRamp,
|
||||
/// The Current Colors ramp.
|
||||
#[command(label = "Current Colors", kind = "radio", group = "colorPanel.ramp")]
|
||||
CurrentColors,
|
||||
/// The ramp shows and picks web colours only.
|
||||
#[command(label = "Make Ramp Web Safe", kind = "toggle")]
|
||||
WebSafeRamp,
|
||||
}
|
||||
|
||||
impl ColorPanelMode {
|
||||
/// The command that chooses this view.
|
||||
pub fn command(self) -> ColorPanelCommand {
|
||||
match self {
|
||||
ColorPanelMode::HueCube => ColorPanelCommand::HueCube,
|
||||
ColorPanelMode::BrightnessCube => ColorPanelCommand::BrightnessCube,
|
||||
ColorPanelMode::ColorWheel => ColorPanelCommand::ColorWheel,
|
||||
ColorPanelMode::GrayscaleSlider => ColorPanelCommand::GrayscaleSlider,
|
||||
ColorPanelMode::RgbSliders => ColorPanelCommand::RgbSliders,
|
||||
ColorPanelMode::HsbSliders => ColorPanelCommand::HsbSliders,
|
||||
ColorPanelMode::CmykSliders => ColorPanelCommand::CmykSliders,
|
||||
ColorPanelMode::LabSliders => ColorPanelCommand::LabSliders,
|
||||
ColorPanelMode::WebColorSliders => ColorPanelCommand::WebColorSliders,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl ColorPanelRamp {
|
||||
/// The command that chooses this ramp.
|
||||
pub fn command(self) -> ColorPanelCommand {
|
||||
match self {
|
||||
ColorPanelRamp::RgbSpectrum => ColorPanelCommand::RgbSpectrum,
|
||||
ColorPanelRamp::CmykSpectrum => ColorPanelCommand::CmykSpectrum,
|
||||
ColorPanelRamp::GrayscaleRamp => ColorPanelCommand::GrayscaleRamp,
|
||||
ColorPanelRamp::CurrentColors => ColorPanelCommand::CurrentColors,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The Color panel menu: the rows for the dock's panel menu, the states the host publishes, and the carrying out of a
|
||||
/// fired command (also the ramp's context menu's).
|
||||
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> {
|
||||
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
|
||||
}
|
||||
|
||||
/// The ramps, a separator and Make Ramp Web Safe: the last rows of the menu and the ramp's context menu.
|
||||
pub fn ramp_rows() -> Vec<PanelRow> {
|
||||
let row = |command: ColorPanelCommand| PanelRow::Command(CommandRef::from(command));
|
||||
let mut rows: Vec<PanelRow> = ColorPanelRamp::ALL.iter().map(|ramp| row(ramp.command())).collect();
|
||||
rows.extend([PanelRow::Separator, row(ColorPanelCommand::WebSafeRamp)]);
|
||||
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 mut states: Vec<(ColorPanelCommand, CommandState)> =
|
||||
ColorPanelMode::ALL.iter().map(|mode| (mode.command(), CommandState::new().checked(state.mode == *mode))).collect();
|
||||
states.extend([(ColorPanelCommand::CopyHtml, CommandState::new()), (ColorPanelCommand::CopyHex, CommandState::new())]);
|
||||
states.extend(ColorPanelRamp::ALL.iter().map(|ramp| (ramp.command(), CommandState::new().checked(state.ramp == *ramp))));
|
||||
states.push((ColorPanelCommand::WebSafeRamp, CommandState::new().checked(state.web_safe_ramp)));
|
||||
states
|
||||
}
|
||||
|
||||
/// 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> {
|
||||
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) {
|
||||
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());
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
/// What the panel draws and collects in one pass.
|
||||
struct Body<'a> {
|
||||
/// The colour the panel edits.
|
||||
target: PanelTarget,
|
||||
colors: [Srgba; 2],
|
||||
converter: &'a CmykConverter,
|
||||
dynamic: bool,
|
||||
words: &'a ColorPanelWords,
|
||||
dialog: &'a ColorPickerDialogWords,
|
||||
/// The state as this pass leaves it.
|
||||
now: ColorPanelState,
|
||||
kept: Kept,
|
||||
events: Vec<(PanelTarget, EditEvent<PickedColor>)>,
|
||||
pick_color: Option<ColorRequest>,
|
||||
add_to_swatches: Option<PanelTarget>,
|
||||
}
|
||||
|
||||
impl Body<'_> {
|
||||
fn color(&self) -> Srgba {
|
||||
self.colors[self.target.index()]
|
||||
}
|
||||
|
||||
fn push(&mut self, target: PanelTarget, event: EditEvent<PickedColor>) {
|
||||
self.events.push((target, event));
|
||||
}
|
||||
|
||||
fn show(&mut self, ui: &mut Ui) {
|
||||
let mode = self.now.mode;
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
Row::new().show(ui, |ui, _| {
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
self.wells(ui);
|
||||
// The cubes show the out-of-gamut chip only: the web-colour chip is for Web Color.
|
||||
if mode.is_sliders() || mode.is_cube() {
|
||||
self.warnings(ui, mode == ColorPanelMode::WebColorSliders);
|
||||
}
|
||||
});
|
||||
Stack::new().fill_width().show(ui, |ui, _| match mode {
|
||||
ColorPanelMode::HueCube => self.cube(ui, AreaMode::Hue),
|
||||
ColorPanelMode::BrightnessCube => self.cube(ui, AreaMode::Brightness),
|
||||
ColorPanelMode::ColorWheel => self.rows(ui, &HsbModel, false),
|
||||
ColorPanelMode::GrayscaleSlider => self.rows(ui, &GrayModel, false),
|
||||
ColorPanelMode::RgbSliders => self.rows(ui, &RgbModel, false),
|
||||
ColorPanelMode::HsbSliders => self.rows(ui, &HsbModel, 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),
|
||||
});
|
||||
});
|
||||
match mode {
|
||||
ColorPanelMode::HueCube | ColorPanelMode::BrightnessCube => self.readout(ui),
|
||||
ColorPanelMode::ColorWheel => self.wheel(ui),
|
||||
_ => self.ramp(ui),
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// The foreground over the background: a click on the other well edits it, a click on the edited one asks for the
|
||||
/// picker.
|
||||
fn wells(&mut self, ui: &mut Ui) {
|
||||
let was = if self.now.background { Well::Secondary } else { Well::Primary };
|
||||
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).show(ui);
|
||||
self.now.background = active == Well::Secondary;
|
||||
if pair.clicked.as_ref() == 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));
|
||||
}
|
||||
}
|
||||
|
||||
/// The out-of-gamut chip and, for Web Color, the web-colour chip under the wells.
|
||||
fn warnings(&mut self, ui: &mut Ui, web: bool) {
|
||||
let color = self.color();
|
||||
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 web && let Some(near) = not_web_safe(rgb) {
|
||||
warnings.push(ColorWarning::web_colors(self.dialog.not_web_color.clone(), nearest(near)));
|
||||
}
|
||||
Row::new().show(ui, |ui, _| {
|
||||
for warning in warnings.clone() {
|
||||
if ColorWarningChip::new(&warning).show(ui).clicked {
|
||||
let picked = PickedColor { color: warning.nearest().with_alpha(color.a), model: None };
|
||||
let name = self.words.title.as_str();
|
||||
self.push(self.target, EditEvent::set(Mixed::Same(PickedColor { color, model: None }), picked, name.into(), None));
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
/// The model's values for the edited colour, whole numbers as Photoshop's fields.
|
||||
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
|
||||
}
|
||||
|
||||
/// `color` in `model`. HSB takes the hue of a grey, and the hue and saturation of black, from the last HSB values
|
||||
/// (PhotoCraft's remembered hue), which no longer give the colour.
|
||||
fn read(&self, model: &dyn ColorModel, color: Srgba) -> ModelValues {
|
||||
let mut values = model.from_srgb(color);
|
||||
if model.id() == HsbModel.id()
|
||||
&& let Some(old) = self.kept.values[self.target.index()].iter().find(|v| v.model == model.id())
|
||||
{
|
||||
if values.values[2] < 1.0 {
|
||||
values.values[0] = old.values[0];
|
||||
values.values[1] = old.values[1];
|
||||
} else if values.values[1] < 1.0 {
|
||||
values.values[0] = old.values[0];
|
||||
}
|
||||
}
|
||||
values
|
||||
}
|
||||
|
||||
/// Keeps `values`, edited in `model`, and the hue and saturation of the colour they give.
|
||||
fn remember(&mut self, model: &dyn ColorModel, values: ModelValues) {
|
||||
let kept = &mut self.kept.values[self.target.index()];
|
||||
kept.retain(|v| v.model != values.model);
|
||||
kept.push(values);
|
||||
if model.id() != HsbModel.id() {
|
||||
let hsb = HsbModel.from_srgb(model.to_srgb(&values.values));
|
||||
if hsb.values[1] >= 1.0 && hsb.values[2] >= 1.0 {
|
||||
kept.retain(|v| v.model != hsb.model);
|
||||
kept.push(hsb);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// An edit of `model`'s values for the edited colour.
|
||||
fn model_event(&mut self, model: &dyn ColorModel, event: EditEvent<ModelValues>) {
|
||||
let event = event.map(finite_values);
|
||||
self.kept.dragging = matches!(event.phase(), Some(GesturePhase::Begin | GesturePhase::Update));
|
||||
if let Some(values) = event.value() {
|
||||
self.remember(model, *values);
|
||||
}
|
||||
let alpha = self.color().a;
|
||||
let event = event.map(|values| PickedColor { color: model.to_srgb(&values.values).with_alpha(alpha), model: Some(values) });
|
||||
self.push(self.target, event);
|
||||
}
|
||||
|
||||
/// An edit of channel `channel` of `current`.
|
||||
fn channel_event(&mut self, model: &dyn ColorModel, current: ModelValues, channel: usize, event: EditEvent<f64>) {
|
||||
self.model_event(
|
||||
model,
|
||||
event.map(|x| {
|
||||
let mut values = current;
|
||||
values.values[channel] = x as f32;
|
||||
values
|
||||
}),
|
||||
);
|
||||
}
|
||||
|
||||
/// The channel rows of `model`: a label that scrubs the number field at the row's end, and the slider over the
|
||||
/// channel's colours. Web Color has sliders that step by the web levels.
|
||||
fn rows(&mut self, ui: &mut Ui, model: &dyn ColorModel, web: bool) {
|
||||
let current = self.values(model);
|
||||
// Dynamic Color Sliders off: the tracks keep the colours they had when a drag began.
|
||||
let slot = (model.id(), self.target.index());
|
||||
let held = self.kept.tracks.iter().find(|(id, target, _)| (*id, *target) == slot).map(|(_, _, values)| *values);
|
||||
let basis = if self.dynamic || !self.kept.dragging { current } else { held.unwrap_or(current) };
|
||||
if !self.kept.dragging {
|
||||
self.kept.tracks.retain(|(id, target, _)| (*id, *target) != slot);
|
||||
self.kept.tracks.push((slot.0, slot.1, current));
|
||||
}
|
||||
for (i, ch) in model.channels().iter().enumerate() {
|
||||
let mut rule = ChannelRule::of(ch);
|
||||
if web {
|
||||
rule.step = WEB_STEP;
|
||||
}
|
||||
let mut track_values = basis;
|
||||
// The hue track is the whole spectrum, whatever the saturation and brightness.
|
||||
if model.id() == HsbModel.id() && i == 0 {
|
||||
track_values.values[1] = 100.0;
|
||||
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).track(track).show(ui);
|
||||
for event in row.into_iter().flat_map(|row| row.events) {
|
||||
self.channel_event(model, current, i, event);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Hue Cube or Brightness Cube: the area and the strip of `mode`.
|
||||
fn cube(&mut self, ui: &mut Ui, mode: AreaMode) {
|
||||
let model = mode.model();
|
||||
let values = self.values(model);
|
||||
let [across, down] = mode.area();
|
||||
let names = [channel_name(model, across, &[model]), channel_name(model, down, &[model])];
|
||||
let (area_name, strip_name) = (Label::from(mode.name()), channel_name(model, mode.strip(), &[model]));
|
||||
let (area, strip) = Row::new()
|
||||
.show(ui, |ui, _| {
|
||||
let area = ColorArea::new(area_name.clone(), mode, Bind::given(values)).names(names.clone()).show(ui);
|
||||
let strip = ColorStrip::new(strip_name.clone(), mode, Bind::given(values)).show(ui);
|
||||
(area, strip)
|
||||
})
|
||||
.inner
|
||||
.map_or_else(Default::default, |(area, strip)| (area.events, strip.events));
|
||||
for event in area.into_iter().chain(strip) {
|
||||
self.model_event(model, event);
|
||||
}
|
||||
}
|
||||
|
||||
/// The readout under the cubes: the hex field and the R, G and B number fields. Any of them sets the colour.
|
||||
fn readout(&mut self, ui: &mut Ui) {
|
||||
let color = self.color();
|
||||
let edit = ColorReadout::new(self.words.hex_color.clone(), Bind::given(color.to_rgba())).show(ui);
|
||||
for event in edit.events {
|
||||
self.push(self.target, event.map(|rgba| PickedColor { color: Srgba::from(rgba).with_alpha(color.a), model: None }));
|
||||
}
|
||||
}
|
||||
|
||||
/// The Color Wheel with its Add to Swatches button.
|
||||
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 {
|
||||
self.model_event(&HsbModel, event);
|
||||
}
|
||||
let add = Row::new().align(RowAlign::End).show(ui, |ui, _| {
|
||||
IconButton::new(IconId::new("plus")).label(self.words.add_to_swatches.clone()).tooltip(self.words.create_swatch.clone()).show(ui).response
|
||||
});
|
||||
if add.inner.as_ref().is_some_and(clicked) {
|
||||
self.add_to_swatches = Some(self.target);
|
||||
}
|
||||
}
|
||||
|
||||
/// 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)
|
||||
};
|
||||
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)
|
||||
.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 {
|
||||
if let Some(pick) = event.value() {
|
||||
self.kept.other = pick.other;
|
||||
}
|
||||
let target = if self.kept.other { self.target.other() } else { self.target };
|
||||
let alpha = self.colors[target.index()].a;
|
||||
self.push(target, event.map(|pick| PickedColor { color: pick.color.with_alpha(alpha), model: None }));
|
||||
}
|
||||
if ramp.cycle {
|
||||
self.now.ramp = self.now.ramp.next();
|
||||
}
|
||||
Menu::context(self.words.color_ramp.clone(), &ramp.edit.response).show(ui, |ui, _| {
|
||||
for row in ColorPanelMenu::ramp_rows() {
|
||||
if let PanelRow::Command(command) = row {
|
||||
MenuItem::command(command).show(ui);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
/// The step of a Web Color slider: the distance between two web-safe levels in 0 to 255.
|
||||
const WEB_STEP: f64 = 51.0;
|
||||
@@ -0,0 +1,30 @@
|
||||
//! Stories of `ColorPanel`.
|
||||
|
||||
use super::{ColorPanel, ColorPanelMode, ColorPanelRamp, ColorPanelState};
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::contract::Bind;
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
|
||||
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)];
|
||||
|
||||
fn panel(ui: &mut Ui, data: &mut StoryData, state: ColorPanelState) -> StoryOutput {
|
||||
ColorPanel::new(Bind::bound(data.value("state", state)), COLORS).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(ColorPanel<'static>, covers = [], drive = Drive::Never)]
|
||||
fn color_panel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
panel(ui, data, ColorPanelState::default())
|
||||
}
|
||||
|
||||
#[story(ColorPanel<'static>, covers = [], drive = Drive::Never)]
|
||||
fn color_panel_sliders(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let state = ColorPanelState { mode: ColorPanelMode::WebColorSliders, ramp: ColorPanelRamp::RgbSpectrum, ..ColorPanelState::default() };
|
||||
panel(ui, data, state)
|
||||
}
|
||||
|
||||
#[story(ColorPanel<'static>, covers = [], drive = Drive::Never)]
|
||||
fn color_panel_wheel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
panel(ui, data, ColorPanelState { mode: ColorPanelMode::ColorWheel, ..ColorPanelState::default() })
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
//! The channel row: a label that scrubs a slider whose track shows the channel's colours, and a number field after
|
||||
//! it. Shared with the panels that show channels.
|
||||
|
||||
use std::ops::RangeInclusive;
|
||||
|
||||
use craft_behavior::{Axis, Sense};
|
||||
use craft_theme::{Channel, ColorModel, Srgba};
|
||||
use craft_ui::contract::{Bind, Common, Component, Cx, EditResponse, MeasureCx, Role, Show as _};
|
||||
use craft_ui::form::SliderField;
|
||||
use craft_ui::primitives::{PaintShape, StrokeWidth};
|
||||
use craft_ui::runtime::env::{Label, UnitKind};
|
||||
use craft_ui::style::{ComponentStyle, DataColor, StyleColor, StyleCx};
|
||||
use craft_ui::value_drag::TrackFace;
|
||||
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 {
|
||||
pub range: RangeInclusive<f64>,
|
||||
pub step: f64,
|
||||
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(crate) 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 {
|
||||
None,
|
||||
Percent,
|
||||
Degrees,
|
||||
/// Any other unit text a model declares.
|
||||
Text(&'static str),
|
||||
}
|
||||
|
||||
impl ChannelUnit {
|
||||
pub(crate) fn of(unit: &'static str) -> ChannelUnit {
|
||||
match unit {
|
||||
"" => ChannelUnit::None,
|
||||
"%" => ChannelUnit::Percent,
|
||||
"°" => ChannelUnit::Degrees,
|
||||
other => ChannelUnit::Text(other),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Channel `channel` of `model`'s accessible name: the channel's name, or its qualified name ("OKLCH hue") when
|
||||
/// another of the `visible` models has a channel of that name.
|
||||
pub(crate) fn channel_name(model: &dyn ColorModel, channel: usize, visible: &[&dyn ColorModel]) -> Label {
|
||||
let ch = model.channels()[channel];
|
||||
let clash = visible.iter().any(|m| m.id() != model.id() && m.channels().iter().any(|other| other.name == ch.name));
|
||||
Label::from(if clash { ch.qualified } else { ch.name })
|
||||
}
|
||||
|
||||
/// The style of a track ramp: the line round its edge.
|
||||
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
|
||||
#[non_exhaustive]
|
||||
pub struct TrackRampStyle {
|
||||
#[style(metrics)]
|
||||
metrics: craft_behavior::Metrics,
|
||||
edge: StyleColor,
|
||||
/// The ramp's own size when nothing sets it: a value track's length and groove.
|
||||
length: f32,
|
||||
thickness: f32,
|
||||
}
|
||||
|
||||
/// The look of a slider's track that shows colours: stops spread evenly from the start to the end, over the
|
||||
/// transparency checkerboard where `checker` is set.
|
||||
#[derive(Clone, craft_ui::contract::Component)]
|
||||
#[component(content_painter)]
|
||||
pub(crate) struct TrackRamp {
|
||||
#[common]
|
||||
common: Common,
|
||||
stops: Vec<Srgba>,
|
||||
checker: bool,
|
||||
}
|
||||
|
||||
impl TrackRamp {
|
||||
pub(crate) fn new(stops: Vec<Srgba>, checker: bool) -> Self {
|
||||
TrackRamp { common: Common::new(), stops, checker }
|
||||
}
|
||||
}
|
||||
|
||||
impl Component for TrackRamp {
|
||||
const ROLE: Role = Role::IMAGE;
|
||||
const PARTS: bool = false;
|
||||
const STOPS: bool = false;
|
||||
const OVERLAYS: bool = false;
|
||||
type Style = TrackRampStyle;
|
||||
type Output = egui::Response;
|
||||
|
||||
fn style(cx: &StyleCx<'_>, _: TrackRampStyleKey) -> TrackRampStyle {
|
||||
TrackRampStyle {
|
||||
metrics: craft_behavior::Metrics::new(),
|
||||
edge: cx.color(cx.tokens.color.line.control_edge),
|
||||
length: cx.tokens.size.length.track,
|
||||
thickness: cx.tokens.size.ramp.groove,
|
||||
}
|
||||
}
|
||||
|
||||
fn sense(&self) -> Sense {
|
||||
Sense::empty()
|
||||
}
|
||||
|
||||
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
Vec2::new(cx.style.length, cx.style.thickness)
|
||||
}
|
||||
|
||||
fn paint(&mut self, ui: &mut craft_ui::contract::PaintUi<'_>, cx: &Cx<'_, Self>) {
|
||||
let rect = cx.rect;
|
||||
let painter = ui.content_painter(cx);
|
||||
if self.checker {
|
||||
painter.checker(rect);
|
||||
}
|
||||
let last = self.stops.len().saturating_sub(1).max(1) as f32;
|
||||
let stops: Vec<(f32, DataColor)> =
|
||||
self.stops.iter().enumerate().map(|(i, color)| (i as f32 / last, DataColor::new(Color32::from(*color)))).collect();
|
||||
painter.ramp(rect, &stops, Axis::X);
|
||||
ui.draw().stroke(&PaintShape::Rect(rect, CornerRadius::ZERO), StrokeWidth::Thin, cx.style.edge);
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> egui::Response {
|
||||
cx.response.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// The slider and number field of a channel, over `value`, with `track` colours on the groove.
|
||||
pub(crate) fn channel_slider<'a>(
|
||||
name: Label,
|
||||
value: Bind<'a, f64>,
|
||||
rule: &ChannelRule,
|
||||
unit: ChannelUnit,
|
||||
track: Option<(Vec<Srgba>, bool)>,
|
||||
) -> SliderField<'a> {
|
||||
let field = SliderField::new(name, value, rule.range.clone()).step(rule.step);
|
||||
let field = match unit {
|
||||
ChannelUnit::None => field,
|
||||
ChannelUnit::Percent => field.unit_kind(UnitKind::Percent),
|
||||
ChannelUnit::Degrees => field.unit_kind(UnitKind::Degrees),
|
||||
ChannelUnit::Text(text) => field.unit(Label::from(text)),
|
||||
};
|
||||
match track {
|
||||
Some((stops, checker)) => field.track_face(TrackFace::new(TrackRamp::new(stops, checker))),
|
||||
None => field,
|
||||
}
|
||||
}
|
||||
|
||||
/// One channel: the word label and number field on a line over the slider across the channel's colours.
|
||||
#[derive(craft_ui::contract::Pattern)]
|
||||
pub(crate) struct ChannelRow<'a> {
|
||||
label: Label,
|
||||
value: Bind<'a, f64>,
|
||||
rule: ChannelRule,
|
||||
track: Option<Vec<Srgba>>,
|
||||
/// Whether the track shows over the transparency checkerboard.
|
||||
checker: bool,
|
||||
unit: ChannelUnit,
|
||||
}
|
||||
|
||||
impl<'a> ChannelRow<'a> {
|
||||
pub(crate) fn new(label: impl Into<Label>, value: Bind<'a, f64>, rule: ChannelRule) -> Self {
|
||||
ChannelRow { label: label.into(), value, rule, track: None, checker: false, unit: ChannelUnit::None }
|
||||
}
|
||||
|
||||
/// The colours of the track, from the channel's start to its end.
|
||||
pub(crate) 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 {
|
||||
self.checker = on;
|
||||
self
|
||||
}
|
||||
|
||||
pub(crate) fn unit(mut self, unit: ChannelUnit) -> Self {
|
||||
self.unit = unit;
|
||||
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, mut value, rule, track, checker, unit } = self;
|
||||
Some(channel_slider(label, value.reborrowed(), &rule, unit, track.map(|stops| (stops, checker))).show(ui))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,141 @@
|
||||
//! The picker's body: the Compact layout, and the parts both layouts show (the area and strip, the hex field and the
|
||||
//! screen-pick button). The Full layout is in `full.rs`.
|
||||
|
||||
use craft_behavior::Mixed;
|
||||
use craft_theme::{ColorModel, Srgba};
|
||||
use craft_ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _};
|
||||
use craft_ui::form::FieldGroup;
|
||||
use craft_ui::layout_components::Row;
|
||||
use craft_ui::pickers::Select;
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
use craft_ui::runtime::focus::{self, FocusTarget};
|
||||
use craft_ui::text::TextField;
|
||||
use egui::Ui;
|
||||
|
||||
use super::channel::{ChannelRow, ChannelRule, ChannelUnit, channel_name};
|
||||
use super::screen_pick::ScreenPickButton;
|
||||
use super::{Collected, ColorPickerLayout, ColorPickerWords, ColorWarning, Pass};
|
||||
use crate::ui::channels::WEB_LEVELS;
|
||||
use crate::ui::{AreaMode, ColorArea, ColorStrip};
|
||||
|
||||
/// What the body shows.
|
||||
pub(super) struct Body<'a> {
|
||||
pub layout: ColorPickerLayout,
|
||||
pub models: Vec<&'a dyn ColorModel>,
|
||||
pub warnings: Vec<ColorWarning>,
|
||||
pub compare: Option<Mixed<Srgba>>,
|
||||
pub alpha: bool,
|
||||
pub dynamic_tracks: bool,
|
||||
pub eyedropper: bool,
|
||||
pub eyedropper_busy: bool,
|
||||
/// Whether the host holds Only Web Colors, so the Full layout shows its check box.
|
||||
pub has_web_check: bool,
|
||||
}
|
||||
|
||||
impl<'a> Body<'a> {
|
||||
/// Fills the container's body; what the children report is left in `got`.
|
||||
pub(super) fn run(&self, ui: &mut Ui, pass: &Pass<'a>, got: &mut Collected) {
|
||||
match self.layout {
|
||||
ColorPickerLayout::Compact => self.compact(ui, pass, got),
|
||||
ColorPickerLayout::Full => self.full(ui, pass, got),
|
||||
}
|
||||
}
|
||||
|
||||
/// The area and strip over the channel rows of one model, the model switch, the hex row and the opacity row.
|
||||
fn compact(&self, ui: &mut Ui, pass: &Pass<'a>, got: &mut Collected) {
|
||||
let words = Env::of(ui).words::<ColorPickerWords>();
|
||||
let model = self.models.iter().copied().find(|m| Some(m.id()) == pass.model);
|
||||
let visible: Vec<&dyn ColorModel> = model.into_iter().chain([pass.mode.model()]).collect();
|
||||
self.area_and_strip(ui, pass, &visible, got);
|
||||
if let Some(model) = model {
|
||||
FieldGroup::new(words.channels.as_str().to_owned()).show(ui, |ui, _| {
|
||||
let values = pass.shown.values_in(model);
|
||||
for (i, channel) in model.channels().iter().enumerate() {
|
||||
let mut row = ChannelRow::new(
|
||||
channel_name(model, i, &visible),
|
||||
Bind::given(pass.shows(f64::from(values.values[i]))),
|
||||
ChannelRule::of(channel),
|
||||
)
|
||||
.unit(ChannelUnit::of(channel.unit));
|
||||
if self.dynamic_tracks {
|
||||
row = row.track(model.track(i, &values));
|
||||
}
|
||||
if let Some(edit) = row.show(ui) {
|
||||
got.adopt(edit, pass.shown, |v, mine| *mine = mine.with_channel(model, i, *v, &pass.rules));
|
||||
}
|
||||
}
|
||||
self.alpha_row(ui, pass, &words, got);
|
||||
});
|
||||
if self.models.len() > 1 {
|
||||
let entries: Vec<Entry<&'static str>> = self.models.iter().map(|m| Entry::new(m.id(), Label::from(m.name()))).collect();
|
||||
let label = words.color_model.fill(&[("model", model.name())]);
|
||||
let out = Select::new(label, Bind::given(model.id()), &entries).show(ui);
|
||||
if let Some(picked) = out.value() {
|
||||
got.model_pick = Some(*picked);
|
||||
}
|
||||
}
|
||||
}
|
||||
Row::new().show(ui, |ui, _| {
|
||||
self.hex_field(ui, pass, &words, got);
|
||||
self.sample_button(ui, &words, got);
|
||||
});
|
||||
}
|
||||
|
||||
/// The area and the strip beside it, for the mode of the pass.
|
||||
pub(super) fn area_and_strip(&self, ui: &mut Ui, pass: &Pass<'a>, visible: &[&dyn ColorModel], got: &mut Collected) {
|
||||
let mode: AreaMode = pass.mode;
|
||||
let model = mode.model();
|
||||
let [across, down] = mode.area();
|
||||
let values = pass.shown.values_in(model);
|
||||
let levels = pass.rules.web.then_some(WEB_LEVELS);
|
||||
Row::new().show(ui, |ui, _| {
|
||||
let mut area = ColorArea::new(Label::from(mode.name()), mode, Bind::given(values))
|
||||
.names([channel_name(model, across, visible), channel_name(model, down, visible)]);
|
||||
let mut strip = ColorStrip::new(channel_name(model, mode.strip(), visible), mode, Bind::given(values));
|
||||
if let Some(levels) = levels {
|
||||
area = area.quantize(levels);
|
||||
strip = strip.quantize(levels);
|
||||
}
|
||||
let edit = area.show(ui);
|
||||
got.adopt(edit, pass.shown, |v, mine| *mine = mine.with_values(v, model, &pass.rules));
|
||||
let edit = strip.show(ui);
|
||||
got.adopt(edit, pass.shown, |v, mine| *mine = mine.with_values(v, model, &pass.rules));
|
||||
});
|
||||
}
|
||||
|
||||
/// The "Opacity" row, 0 to 100 % over the checkerboard, when the picker edits alpha.
|
||||
pub(super) fn alpha_row(&self, ui: &mut Ui, pass: &Pass<'a>, words: &ColorPickerWords, got: &mut Collected) {
|
||||
if !self.alpha {
|
||||
return;
|
||||
}
|
||||
let opaque = pass.shown.color.with_alpha(1.0);
|
||||
let row = ChannelRow::new(words.opacity.as_str().to_owned(), Bind::given(pass.shows(pass.shown.alpha_percent())), ChannelRule::ALPHA)
|
||||
.unit(ChannelUnit::Percent)
|
||||
.track(vec![opaque.with_alpha(0.0), opaque])
|
||||
.checker(true);
|
||||
if let Some(edit) = row.show(ui) {
|
||||
got.adopt(edit, pass.shown, |v, mine| *mine = mine.with_alpha(*v, &pass.rules));
|
||||
}
|
||||
}
|
||||
|
||||
/// The hex field. The Full layout's first show focuses it.
|
||||
pub(super) fn hex_field(&self, ui: &mut Ui, pass: &Pass<'a>, words: &ColorPickerWords, got: &mut Collected) {
|
||||
let edit = TextField::hex(words.hex.as_str().to_owned(), Bind::given(pass.shows(pass.shown.color.to_rgba())))
|
||||
.empty(pass.shown.color.to_rgba())
|
||||
.show(ui);
|
||||
if pass.focus_hex {
|
||||
focus::request(ui.ctx(), FocusTarget::Id(edit.response.id));
|
||||
}
|
||||
got.adopt(edit, pass.shown, |v, mine| *mine = mine.with_hex(*v, &pass.rules));
|
||||
}
|
||||
|
||||
/// The screen-pick button; its press is the output's `screen_pick`.
|
||||
pub(super) fn sample_button(&self, ui: &mut Ui, words: &ColorPickerWords, got: &mut Collected) {
|
||||
if !self.eyedropper {
|
||||
return;
|
||||
}
|
||||
let label = words.sample_screen.as_str().to_owned();
|
||||
let out = ScreenPickButton::new().label(label.clone()).tooltip(label).enabled(!self.eyedropper_busy).show(ui);
|
||||
got.screen_pick = out.gesture;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
//! The Full layout of `ColorPicker` (the Color Picker dialog), and the warnings beside its compare swatch.
|
||||
|
||||
use craft_behavior::{ColumnWidth, IconId, Metrics, Mixed, NavShape, Sense};
|
||||
use craft_theme::{ColorModel, HsbModel, OklchModel, RgbModel, Srgba};
|
||||
use craft_ui::choice::{Checkbox, Radio, RadioGroup, Swatch};
|
||||
use craft_ui::contract::{
|
||||
Bind, Common, Component, Cx, GlyphLabel, LabelKind, MeasureCx, Outcome, PaintUi, Props as _, Role, Show as _, ShowContainer as _, SideLabel,
|
||||
};
|
||||
use craft_ui::display::{Icon, Shade, Text};
|
||||
use craft_ui::form::{Field, FieldGroup};
|
||||
use craft_ui::layout_components::{Grid, Row, Stack};
|
||||
use craft_ui::primitives::IconSpec;
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
use craft_ui::style::{ComponentStyle, StyleCx, TypeRole};
|
||||
use craft_ui::text::NumberField;
|
||||
use egui::{Rect, Response, Ui, Vec2};
|
||||
|
||||
use super::channel::{ChannelRule, ChannelUnit, channel_name};
|
||||
use super::compact::Body;
|
||||
use super::{Collected, ColorPicker, ColorPickerWords, Pass};
|
||||
use crate::ui::AreaMode;
|
||||
|
||||
/// A warning the host shows beside the Full picker's compare swatch, as the out-of-gamut and web-colour warnings of
|
||||
/// Photoshop's Color Picker: an icon over a chip of the nearest colour that passes. A click on it sets that colour;
|
||||
/// AccessKit and the tooltip name it by its tip.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub struct ColorWarning {
|
||||
tip: Label,
|
||||
nearest: Srgba,
|
||||
icon: IconId,
|
||||
}
|
||||
|
||||
/// The models the picker shows and the area modes it offers.
|
||||
#[derive(Clone, Copy)]
|
||||
struct ModelChoice<'m> {
|
||||
visible: &'m [&'m dyn ColorModel],
|
||||
offered: &'m [AreaMode],
|
||||
}
|
||||
|
||||
impl ColorWarning {
|
||||
/// A warning that says `tip` ("Out of gamut for printing") and offers `nearest`.
|
||||
pub fn new(tip: impl Into<Label>, nearest: Srgba) -> Self {
|
||||
ColorWarning { tip: tip.into(), nearest, icon: IconId::new("warning") }
|
||||
}
|
||||
|
||||
/// A warning that the colour is not a web-safe colour (the cube Photoshop's Color Picker shows), offering
|
||||
/// `nearest`, the nearest web colour.
|
||||
pub fn web_colors(tip: impl Into<Label>, nearest: Srgba) -> Self {
|
||||
Self::new(tip, nearest).icon(IconId::new("web_colors"))
|
||||
}
|
||||
|
||||
/// The colour that passes, nearest the warned one: what a click on the warning sets.
|
||||
pub fn nearest(&self) -> Srgba {
|
||||
self.nearest
|
||||
}
|
||||
|
||||
/// The icon over the chip.
|
||||
#[must_use]
|
||||
pub fn icon(mut self, icon: IconId) -> Self {
|
||||
self.icon = icon;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
/// The style of a warning chip: the icon over the chip, and their sizes.
|
||||
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
|
||||
#[non_exhaustive]
|
||||
pub struct ColorWarningChipStyle {
|
||||
#[style(metrics)]
|
||||
metrics: Metrics,
|
||||
icon: f32,
|
||||
chip: f32,
|
||||
gap: f32,
|
||||
}
|
||||
|
||||
/// What a [`ColorWarningChip`] reports.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
pub struct ColorWarningChipOutput {
|
||||
/// The chip's response.
|
||||
pub response: Response,
|
||||
/// The chip was activated by click, Enter or Space: the host applies [`ColorWarning::nearest`].
|
||||
pub clicked: bool,
|
||||
}
|
||||
|
||||
impl Outcome for ColorWarningChipOutput {
|
||||
type Value = craft_ui::contract::NoValue;
|
||||
|
||||
fn response(&self) -> &Response {
|
||||
&self.response
|
||||
}
|
||||
}
|
||||
|
||||
/// A [`ColorWarning`] as the Full picker draws it, for a host that draws it beside its own swatch: the warning's icon
|
||||
/// over a swatch of the nearest passing colour. The host applies [`ColorWarning::nearest`] when it is clicked. The tip
|
||||
/// is the tooltip and the accessible name.
|
||||
#[must_use = "show the chip with `show`"]
|
||||
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
|
||||
pub struct ColorWarningChip<'a> {
|
||||
#[common]
|
||||
common: Common,
|
||||
warning: &'a ColorWarning,
|
||||
clicked: bool,
|
||||
}
|
||||
|
||||
impl<'a> ColorWarningChip<'a> {
|
||||
/// A chip for `warning`.
|
||||
pub fn new(warning: &'a ColorWarning) -> Self {
|
||||
ColorWarningChip { common: Common::new(), warning, clicked: false }.label(warning.tip.clone())
|
||||
}
|
||||
}
|
||||
|
||||
impl Component for ColorWarningChip<'_> {
|
||||
const ROLE: Role = Role::GROUP;
|
||||
const PARTS: bool = false;
|
||||
const STOPS: bool = false;
|
||||
const OVERLAYS: bool = false;
|
||||
type Style = ColorWarningChipStyle;
|
||||
type Output = ColorWarningChipOutput;
|
||||
|
||||
fn style(cx: &StyleCx<'_>, _: ColorWarningChipStyleKey) -> ColorWarningChipStyle {
|
||||
ColorWarningChipStyle { metrics: Metrics::new(), icon: cx.tokens.size.icon.md, chip: cx.control().height, gap: cx.tokens.space.gap.tight }
|
||||
}
|
||||
|
||||
fn sense(&self) -> Sense {
|
||||
Sense::empty()
|
||||
}
|
||||
|
||||
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
Vec2::new(cx.style.icon.max(cx.style.chip), cx.style.icon + cx.style.gap + cx.style.chip)
|
||||
}
|
||||
|
||||
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
|
||||
let style = cx.style;
|
||||
let icon = Rect::from_center_size(egui::pos2(cx.rect.center().x, cx.rect.top() + style.icon / 2.0), Vec2::splat(style.icon));
|
||||
let chip = Rect::from_center_size(egui::pos2(cx.rect.center().x, cx.rect.bottom() - style.chip / 2.0), Vec2::splat(style.chip));
|
||||
let _ = ui.child("icon", icon, Icon::new(IconSpec::svg(self.warning.icon.clone())));
|
||||
let swatch = Swatch::new(self.warning.tip.clone(), self.warning.nearest).tooltip(self.warning.tip.clone());
|
||||
self.clicked = ui.child("chip", chip, swatch).clicked;
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> ColorWarningChipOutput {
|
||||
ColorWarningChipOutput { response: cx.response.clone(), clicked: self.clicked }
|
||||
}
|
||||
}
|
||||
|
||||
/// Columns that take the width of their content: the Full layout's two halves, and its channel grid of one to three
|
||||
/// columns. A group of fields that fills the width would take all of a row's room otherwise.
|
||||
const HALVES: &[ColumnWidth] = &[ColumnWidth::Content, ColumnWidth::Content];
|
||||
const ONE_COLUMN: &[ColumnWidth] = &[ColumnWidth::Content];
|
||||
const THREE_COLUMNS: &[ColumnWidth] = &[ColumnWidth::Content, ColumnWidth::Content, ColumnWidth::Content];
|
||||
|
||||
/// A grid column of the Full layout: HSB and RGB, then Lab and the host's models, then OKLCH.
|
||||
fn column_of(model: &dyn ColorModel) -> usize {
|
||||
match model.id() {
|
||||
id if id == HsbModel.id() || id == RgbModel.id() => 0,
|
||||
id if id == OklchModel.id() => 2,
|
||||
_ => 1,
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> Body<'a> {
|
||||
/// The Color Picker dialog: the area and strip over the check box, the opacity row and the screen-pick button;
|
||||
/// beside them the compare swatch and the warnings over the channel grid, where radios choose what the area shows.
|
||||
pub(super) fn full(&self, ui: &mut Ui, pass: &Pass<'a>, got: &mut Collected) {
|
||||
let words = Env::of(ui).words::<ColorPickerWords>();
|
||||
let visible: Vec<&dyn ColorModel> = self.models.iter().copied().chain([pass.mode.model()]).collect();
|
||||
Grid::new(HALVES).show(ui, |ui, _| {
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
self.area_and_strip(ui, pass, &visible, got);
|
||||
if self.has_web_check {
|
||||
let check = Checkbox::new(Bind::given(pass.web)).label(words.only_web_colors.as_str().to_owned()).show(ui);
|
||||
if let Some(on) = check.value() {
|
||||
got.web_pick = Some(*on);
|
||||
}
|
||||
}
|
||||
self.alpha_row(ui, pass, &words, got);
|
||||
self.sample_button(ui, &words, got);
|
||||
});
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
if self.compare.is_some() || !self.warnings.is_empty() {
|
||||
Row::new().show(ui, |ui, _| {
|
||||
if let Some(current) = self.compare {
|
||||
self.compare_swatch(ui, pass, current, &words, got);
|
||||
}
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
for warning in &self.warnings {
|
||||
if ColorWarningChip::new(warning).show(ui).clicked {
|
||||
got.clicks.push(warning.nearest);
|
||||
}
|
||||
}
|
||||
});
|
||||
});
|
||||
}
|
||||
self.grid(ui, pass, &visible, &words, got);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
/// The compare swatch: the colour being edited over the current one, with their captions; a click on the current
|
||||
/// half sets it.
|
||||
fn compare_swatch(&self, ui: &mut Ui, pass: &Pass<'a>, current: Mixed<Srgba>, words: &ColorPickerWords, got: &mut Collected) {
|
||||
let caption = |text: &str| Text::new(text.to_owned()).role(TypeRole::Caption).shade(Shade::Muted);
|
||||
Stack::new().show(ui, |ui, _| {
|
||||
caption(words.new_caption.as_str()).show(ui);
|
||||
Swatch::new(words.new_color.as_str().to_owned(), pass.shows(pass.shown.color)).fill().show(ui);
|
||||
let restore = words.restore.as_str().to_owned();
|
||||
if Swatch::new(restore.clone(), current).tooltip(restore).fill().show(ui).clicked
|
||||
&& let Mixed::Same(current) = current
|
||||
{
|
||||
got.clicks.push(current);
|
||||
}
|
||||
caption(words.current_caption.as_str()).show(ui);
|
||||
});
|
||||
}
|
||||
|
||||
/// The channel grid: one column of fields per group of models, each column sharing its label column, with the
|
||||
/// radios of "Field shows" in front of the channels that choose an area mode, and the hex field under the first.
|
||||
fn grid(&self, ui: &mut Ui, pass: &Pass<'a>, visible: &[&dyn ColorModel], words: &ColorPickerWords, got: &mut Collected) {
|
||||
let offered = ColorPicker::offered(&self.models);
|
||||
let group = RadioGroup::new(words.field_shows.as_str().to_owned(), Bind::given(pass.mode)).nav(NavShape::Spatial);
|
||||
let picked = group
|
||||
.show(ui, |ui, _| {
|
||||
let columns: Vec<Vec<&'a dyn ColorModel>> = (0..3)
|
||||
.map(|column| self.models.iter().copied().filter(|m| column_of(*m) == column).collect::<Vec<_>>())
|
||||
.enumerate()
|
||||
.filter(|(column, models)| *column == 0 || !models.is_empty())
|
||||
.map(|(_, models)| models)
|
||||
.collect();
|
||||
let widths = match columns.len() {
|
||||
1 => ONE_COLUMN,
|
||||
2 => &THREE_COLUMNS[..2],
|
||||
_ => THREE_COLUMNS,
|
||||
};
|
||||
Grid::new(widths).show(ui, |ui, _| {
|
||||
for (column, models) in columns.iter().enumerate() {
|
||||
FieldGroup::new(words.channels.as_str().to_owned()).show(ui, |ui, _| {
|
||||
for model in models {
|
||||
self.model_fields(ui, pass, *model, ModelChoice { visible, offered: &offered }, words, got);
|
||||
}
|
||||
if column == 0 {
|
||||
let label = SideLabel::new().kind(LabelKind::Glyph(GlyphLabel::text("#")));
|
||||
Field::new(words.hex.as_str().to_owned()).side(label).show(ui, |ui, _| self.hex_field(ui, pass, words, got));
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
})
|
||||
.output;
|
||||
if let Some(mode) = picked.value() {
|
||||
got.mode_pick = Some(*mode);
|
||||
}
|
||||
}
|
||||
|
||||
/// The rows of one model's channels.
|
||||
fn model_fields(
|
||||
&self,
|
||||
ui: &mut Ui,
|
||||
pass: &Pass<'a>,
|
||||
model: &'a dyn ColorModel,
|
||||
choice: ModelChoice<'_>,
|
||||
words: &ColorPickerWords,
|
||||
got: &mut Collected,
|
||||
) {
|
||||
let ModelChoice { visible, offered } = choice;
|
||||
let values = pass.shown.values_in(model);
|
||||
for (i, channel) in model.channels().iter().enumerate() {
|
||||
let name = channel_name(model, i, visible);
|
||||
let short = words.grid_label.fill(&[("label", channel.label)]);
|
||||
let short: &str = &short;
|
||||
let label = SideLabel::new().kind(LabelKind::Glyph(GlyphLabel::text(Label::from(short.to_owned()))));
|
||||
let mode = offered.iter().find(|mode| mode.model().id() == model.id() && mode.strip() == i).copied();
|
||||
let rule = ChannelRule::of(channel);
|
||||
let unit = ChannelUnit::of(channel.unit);
|
||||
let value = f64::from(values.values[i]);
|
||||
let edit = Field::new(name.clone())
|
||||
.side(label)
|
||||
.show(ui, |ui, _| {
|
||||
Row::new()
|
||||
.show(ui, |ui, _| {
|
||||
if let Some(mode) = mode {
|
||||
Radio::new(mode).label(name.clone()).show(ui);
|
||||
}
|
||||
let field = NumberField::new(name.clone(), Bind::given(pass.shows(Some(value))))
|
||||
.range(rule.range.clone())
|
||||
.step(rule.step)
|
||||
.snap_typed(true)
|
||||
.commit_decimals(usize::from(rule.decimals));
|
||||
let field = match unit {
|
||||
ChannelUnit::None => field,
|
||||
ChannelUnit::Percent => field.unit_kind(craft_ui::runtime::env::UnitKind::Percent),
|
||||
ChannelUnit::Degrees => field.unit_kind(craft_ui::runtime::env::UnitKind::Degrees),
|
||||
ChannelUnit::Text(text) => field.unit(Label::from(text)),
|
||||
};
|
||||
field.show(ui).edit
|
||||
})
|
||||
.inner
|
||||
})
|
||||
.inner
|
||||
.flatten();
|
||||
if let Some(edit) = edit {
|
||||
got.adopt(edit, pass.shown, |v, mine| {
|
||||
if let Some(v) = v {
|
||||
*mine = mine.with_channel(model, i, *v, &pass.rules);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,552 @@
|
||||
//! `ColorPicker`: the colour picker's body, the area and strip with the channel rows, the hex field and the hooks a
|
||||
//! host adds. A container: its body lays the parts out with the form layouts, the "Field shows" choice is a
|
||||
//! `RadioGroup` and the channel rows share one label column.
|
||||
|
||||
mod channel;
|
||||
mod compact;
|
||||
mod full;
|
||||
mod screen_pick;
|
||||
#[cfg(feature = "screen-testing")]
|
||||
mod stories;
|
||||
mod value;
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft_behavior::{EditEvent, EditEvents, GestureId, Mixed, Value};
|
||||
use craft_theme::{ColorModel, ModelValues, Srgba, builtin_models};
|
||||
use craft_ui::contract::{Bind, BindMut, BodyCx, EditResponse, Outcome, Props as _, Remember as _, ShowContainer};
|
||||
use craft_ui::layout_components::Stack;
|
||||
use craft_ui::runtime::env::Label;
|
||||
use egui::{Pos2, Response, Ui};
|
||||
|
||||
use super::AreaMode;
|
||||
pub(crate) use channel::{ChannelRow, ChannelRule, channel_name};
|
||||
pub use full::{ColorWarning, ColorWarningChip, ColorWarningChipOutput};
|
||||
pub use value::ColorConstraint;
|
||||
use value::Rules;
|
||||
|
||||
/// What a [`ColorPicker`] reports: the colour, and the values of the model the user edited it in while they still
|
||||
/// give it, so a host can keep a CMYK colour CMYK.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct PickedColor {
|
||||
/// Encoded sRGB with straight alpha, after the host's [`constrain`](ColorPicker::constrain).
|
||||
pub color: Srgba,
|
||||
/// The values of the model edited, as the user set them: a typed Lab or CMYK colour outside sRGB stays as typed.
|
||||
/// `None` for a colour set as such (hex, a sample) and for one the constraint moved away from its values.
|
||||
pub model: Option<ModelValues>,
|
||||
}
|
||||
|
||||
impl PickedColor {
|
||||
/// A colour set as such (hex, a sample): `color` is encoded sRGB with straight alpha and no model values stay
|
||||
/// with it.
|
||||
pub fn rgb(color: Srgba) -> PickedColor {
|
||||
PickedColor { color, model: None }
|
||||
}
|
||||
|
||||
/// A colour picked in the model of `values`, which stay with it as typed. `color` is what `values` give in
|
||||
/// encoded sRGB; the caller converts it, as the model decides.
|
||||
pub fn in_model(color: Srgba, values: ModelValues) -> PickedColor {
|
||||
PickedColor { color, model: Some(values) }
|
||||
}
|
||||
|
||||
/// A colour picked as CMYK `inks` in percent (cyan, magenta, yellow, black, each 0 to 100, the units of the
|
||||
/// picker's fields). `color` is the sRGB the inks convert to under the host's CMYK converter.
|
||||
pub fn cmyk(color: Srgba, inks: [f32; 4]) -> PickedColor {
|
||||
PickedColor::in_model(color, ModelValues::new("cmyk", &inks))
|
||||
}
|
||||
}
|
||||
|
||||
/// How a [`ColorPicker`] lays out its parts.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
|
||||
#[non_exhaustive]
|
||||
pub enum ColorPickerLayout {
|
||||
/// The Color panel and compact popup: the area over the channel slider rows of one model, a model switch, the hex
|
||||
/// row and the optional alpha row.
|
||||
#[default]
|
||||
Compact,
|
||||
/// The Color Picker dialog: the square area and the strip, the compare swatch and the host's warnings beside them
|
||||
/// over the channel grid, every model's channels at once with radios choosing what the area shows, and the hex
|
||||
/// field.
|
||||
Full,
|
||||
}
|
||||
|
||||
/// The screen-pick button's press, for the host that samples the screen.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub enum ScreenPickGesture {
|
||||
/// The button was clicked: the host starts sampling and answers with [`ColorPicker::sampled`].
|
||||
Clicked,
|
||||
/// The button is held and the pointer moved to `at`: Photoshop's press and drag.
|
||||
#[non_exhaustive]
|
||||
Held {
|
||||
/// The pointer, in the picker's points.
|
||||
at: Pos2,
|
||||
},
|
||||
/// The held button was released at `at`.
|
||||
#[non_exhaustive]
|
||||
Released {
|
||||
/// The pointer, in the picker's points.
|
||||
at: Pos2,
|
||||
},
|
||||
}
|
||||
|
||||
/// What [`ColorPicker`] reports.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
#[must_use = "the host applies the edit event"]
|
||||
pub struct ColorPickerOutput {
|
||||
/// The picker's response.
|
||||
pub response: Response,
|
||||
/// The picker's edits of its colour in this pass, in order, each with the whole colour as its value; empty when
|
||||
/// nothing was edited. A colour bound by reference has taken them; a given one needs the host to apply them.
|
||||
pub events: EditEvents<PickedColor>,
|
||||
/// The screen-pick button's press this pass.
|
||||
pub screen_pick: Option<ScreenPickGesture>,
|
||||
}
|
||||
|
||||
impl Outcome for ColorPickerOutput {
|
||||
type Value = PickedColor;
|
||||
|
||||
fn response(&self) -> &Response {
|
||||
&self.response
|
||||
}
|
||||
|
||||
#[cfg(feature = "screen-testing")]
|
||||
fn story_facts(&self) -> craft_ui::testing::StoryOutput {
|
||||
let mut facts = craft_ui::testing::StoryOutput::default();
|
||||
facts.id = Some(self.response.id);
|
||||
facts.clicked = craft_ui::contract::clicked(&self.response);
|
||||
facts.edits = self.events.iter().filter_map(craft_ui::testing::EditKind::of).collect();
|
||||
facts
|
||||
}
|
||||
}
|
||||
|
||||
craft_ui::words! {
|
||||
/// The picker's words, English by default. The words of the colour models and their channels are the models'.
|
||||
#[non_exhaustive]
|
||||
pub struct ColorPickerWords {
|
||||
/// The opacity row's name.
|
||||
opacity: "colorPicker.opacity" = "Opacity";
|
||||
/// The hex field's accessible name.
|
||||
hex: "colorPicker.hex" = "Hex color";
|
||||
/// The model switch's accessible name; `{model}` is the model's name.
|
||||
color_model: template "colorPicker.colorModel" = "Color model: {model}";
|
||||
/// The Full layout's radios.
|
||||
field_shows: "colorPicker.fieldShows" = "Field shows";
|
||||
/// The caption over the compare swatch's new half.
|
||||
new_caption: "colorPicker.newCaption" = "new";
|
||||
/// The caption under the compare swatch's current half.
|
||||
current_caption: "colorPicker.currentCaption" = "current";
|
||||
/// The new half's accessible name.
|
||||
new_color: "colorPicker.newColor" = "New color";
|
||||
/// The current half's accessible name and tooltip.
|
||||
restore: "colorPicker.restore" = "Restore current color";
|
||||
/// A channel's label in the Full grid; `{label}` is the channel's short label.
|
||||
grid_label: template "colorPicker.gridLabel" = "{label}:";
|
||||
/// The check box under the Full strip.
|
||||
only_web_colors: "colorPicker.onlyWebColors" = "Only Web Colors";
|
||||
/// The screen-pick button's name and tooltip.
|
||||
sample_screen: "colorPicker.sampleScreen" = "Sample color from the screen";
|
||||
/// The channel rows' group name.
|
||||
channels: "colorPicker.channels" = "Channels";
|
||||
}
|
||||
}
|
||||
|
||||
/// What the picker keeps between passes.
|
||||
#[derive(Clone, Default)]
|
||||
struct Memo {
|
||||
/// The model of the Compact rows.
|
||||
model: Option<&'static str>,
|
||||
/// What the area and strip show while the host holds no mode.
|
||||
mode: AreaMode,
|
||||
/// The Full layout has taken the focus for the hex field.
|
||||
opened: bool,
|
||||
/// The running gesture of a child and the colour when it began, for the `before` of its end.
|
||||
gesture: Option<(GestureId, PickedColor)>,
|
||||
}
|
||||
|
||||
/// What the children of one pass reported.
|
||||
#[derive(Default)]
|
||||
struct Collected {
|
||||
/// The children's edits as edits of the colour shown, in the order they were made.
|
||||
edits: EditEvents<PickedColor>,
|
||||
/// Colours the compare swatch and the warning chips set.
|
||||
clicks: Vec<Srgba>,
|
||||
screen_pick: Option<ScreenPickGesture>,
|
||||
model_pick: Option<&'static str>,
|
||||
/// The mode the "Field shows" group picked.
|
||||
mode_pick: Option<AreaMode>,
|
||||
/// The Only Web Colors check box was set to this.
|
||||
web_pick: Option<bool>,
|
||||
/// The picker held no colour when the pass began: its edits begin from Mixed.
|
||||
empty: bool,
|
||||
}
|
||||
|
||||
impl Collected {
|
||||
/// Adopts `edit` of a child as an edit of the picker's colour: `map` applies the child's value to a copy of `shown`,
|
||||
/// the colour the pass showed.
|
||||
fn adopt<V: Value>(&mut self, edit: EditResponse<V>, shown: PickedColor, map: impl Fn(&V, &mut PickedColor)) {
|
||||
let before = if self.empty { Mixed::Mixed } else { Mixed::Same(shown) };
|
||||
let made = |value: &V| {
|
||||
let mut colour = shown;
|
||||
map(value, &mut colour);
|
||||
colour
|
||||
};
|
||||
for event in &edit.events {
|
||||
let adopted = match event {
|
||||
EditEvent::Begin { id, label, doc_key, .. } => EditEvent::begin(*id, before, label.clone(), *doc_key),
|
||||
EditEvent::Update { id, value, .. } => EditEvent::update(*id, made(value)),
|
||||
EditEvent::Commit { id, after, .. } => EditEvent::commit(*id, before, made(after)),
|
||||
EditEvent::Cancel { id, reason, .. } => EditEvent::cancel(*id, *reason, Some(before)),
|
||||
EditEvent::Set { after, label, doc_key, .. } => EditEvent::set(before, made(after), label.clone(), *doc_key),
|
||||
_ => continue,
|
||||
};
|
||||
self.edits.push(adopted);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What the body settled before it showed its children: the colour shown and the rules its edits go through.
|
||||
#[derive(Clone)]
|
||||
struct Pass<'a> {
|
||||
shown: PickedColor,
|
||||
/// The bound value is Mixed: no colour yet. The fields and the new half of the compare swatch show Mixed until the
|
||||
/// first edit; `shown` is the base the edit starts from.
|
||||
empty: bool,
|
||||
rules: Rules<'a>,
|
||||
mode: AreaMode,
|
||||
/// The model of the Compact rows.
|
||||
model: Option<&'static str>,
|
||||
/// Only Web Colors, as the host holds it.
|
||||
web: bool,
|
||||
/// Whether the hex field takes the focus in this pass: the Full layout's first show.
|
||||
focus_hex: bool,
|
||||
}
|
||||
|
||||
impl Pass<'_> {
|
||||
/// `value`, or Mixed while the picker holds no colour yet.
|
||||
fn shows<T>(&self, value: T) -> Mixed<T> {
|
||||
if self.empty { Mixed::Mixed } else { Mixed::Same(value) }
|
||||
}
|
||||
}
|
||||
|
||||
/// A colour picker's body: a [`ColorArea`](super::ColorArea) and a [`ColorStrip`](super::ColorStrip), the channel
|
||||
/// fields of its [`ColorModel`]s, the hex field and the host's hooks, in the Color panel and compact popup layout
|
||||
/// ([`ColorPickerLayout::Compact`]) or the Color Picker dialog's ([`ColorPickerLayout::Full`]).
|
||||
///
|
||||
/// - Compact: the area over the channel rows of one model (a label that scrubs, a slider whose track shows the
|
||||
/// channel's colours, a number field), a model switch, the hex row with the screen-pick button, and with
|
||||
/// [`alpha`](ColorPicker::alpha) an "Opacity" row over the checkerboard.
|
||||
/// - Full: the area square, the strip at its reading end, the opacity row and the screen-pick button under them.
|
||||
/// Beside them the [`compare`](ColorPicker::compare) swatch (new over current) and the host's
|
||||
/// [`warnings`](ColorPicker::warnings), over the channel grid: H S B, R G B, then "#" and the hex field; L a b and
|
||||
/// the host's models; OKLCH in a column of its own when the host turns it on. A radio before each built-in
|
||||
/// channel's label chooses the [`AreaMode`]; it edits no colour. The hex field takes the focus, its text selected,
|
||||
/// when the layout first shows ([`focus_on_open`](ColorPicker::focus_on_open)).
|
||||
/// - Edits: every child's gesture is the picker's, with the whole colour as its value: an area or strip drag, a slider
|
||||
/// drag, a scrub or a typing run is one Begin to Commit (or Cancel); keys, the wheel, Enter, a sample, a compare or
|
||||
/// warning click are `Set`s.
|
||||
/// - Kept components: the picker keeps the values the user last edited, in that model, while they still give the
|
||||
/// colour's 8-bit sRGB: greys keep their hue, black its hue and saturation, a typed Lab colour outside sRGB its
|
||||
/// values. [`PickedColor::model`] carries them, and the host's binding holds them between passes.
|
||||
/// - Only Web Colors ([`web_colors`](ColorPicker::web_colors)): every colour reported has each of red, green and blue
|
||||
/// on a multiple of 0x33, whichever child made it. The Full layout shows the check box.
|
||||
///
|
||||
/// AccessKit: a `Group` named by the label; channel fields and sliders are named by the channel's name ("Hue"), or
|
||||
/// `<model> <channel>` ("OKLCH hue") while another shown model has a channel of that name.
|
||||
#[must_use = "show the picker with `show`"]
|
||||
#[derive(craft_ui::contract::Pattern, craft_ui::contract::Props)]
|
||||
pub struct ColorPicker<'a> {
|
||||
label: Label,
|
||||
value: Bind<'a, PickedColor>,
|
||||
/// The layout; Compact by default.
|
||||
#[prop]
|
||||
layout: ColorPickerLayout,
|
||||
models: Option<Vec<&'a dyn ColorModel>>,
|
||||
/// What the area and the strip show, held by the host; kept per picker without it.
|
||||
#[prop]
|
||||
mode: Option<Bind<'a, AreaMode>>,
|
||||
/// Only Web Colors, held by the host (kept across opens). The Full layout shows its check box; the Compact layout
|
||||
/// has none, the host sets it.
|
||||
#[prop]
|
||||
web_colors: Option<Bind<'a, bool>>,
|
||||
/// Whether the picker edits the alpha: an "Opacity" row, and eight hex digits.
|
||||
#[prop]
|
||||
alpha: bool,
|
||||
/// Whether the channel sliders' tracks show the channel's colours with the others fixed (Dynamic Color Sliders).
|
||||
#[prop]
|
||||
dynamic_tracks: bool,
|
||||
/// Shows the screen-pick button.
|
||||
#[prop]
|
||||
eyedropper: bool,
|
||||
/// Disables the screen-pick button while the host samples.
|
||||
#[prop]
|
||||
eyedropper_busy: bool,
|
||||
/// The Full layout's compare swatch: the colour being edited over this one, the colour the host started from; a
|
||||
/// click on it sets it again.
|
||||
#[prop(into)]
|
||||
compare: Option<Mixed<Srgba>>,
|
||||
warnings: Vec<ColorWarning>,
|
||||
/// Applied to every colour before it is reported, after Only Web Colors' snap.
|
||||
#[prop(func = "Fn(Srgba) -> Srgba")]
|
||||
constrain: Option<ColorConstraint<'a>>,
|
||||
/// The host's answer to a screen or canvas pick, for this pass; a `Set` that keeps the picker's alpha.
|
||||
#[prop]
|
||||
sampled: Option<Srgba>,
|
||||
/// Whether the Full layout focuses its hex field when it first shows; on by default.
|
||||
#[prop]
|
||||
focus_on_open: bool,
|
||||
}
|
||||
|
||||
impl<'a> ColorPicker<'a> {
|
||||
/// A picker named `label` editing `value`.
|
||||
pub fn new(label: impl Into<craft_ui::runtime::env::Label>, value: Bind<'a, PickedColor>) -> Self {
|
||||
ColorPicker {
|
||||
label: label.into(),
|
||||
value,
|
||||
layout: ColorPickerLayout::default(),
|
||||
models: None,
|
||||
mode: None,
|
||||
web_colors: None,
|
||||
alpha: false,
|
||||
dynamic_tracks: true,
|
||||
eyedropper: false,
|
||||
eyedropper_busy: false,
|
||||
compare: None,
|
||||
warnings: Vec::new(),
|
||||
constrain: None,
|
||||
sampled: None,
|
||||
focus_on_open: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Every key a picker offering `models` may ask the host's catalogue for, each once: the area's names
|
||||
/// ([`AreaMode::name`]), and for the built-in models and `models` the model's name and each channel's name,
|
||||
/// qualified name ("OKLCH hue") and short label.
|
||||
pub fn keys<'m>(models: impl IntoIterator<Item = &'m dyn ColorModel>) -> Vec<&'static str> {
|
||||
let builtin: [&dyn ColorModel; 4] = builtin_models();
|
||||
let models: Vec<&dyn ColorModel> = builtin.into_iter().chain(models).collect();
|
||||
let words = models.iter().flat_map(|m| std::iter::once(m.name()).chain(m.channels().iter().flat_map(|ch| [ch.name, ch.qualified, ch.label])));
|
||||
let mut keys: Vec<&'static str> = Vec::new();
|
||||
for key in AreaMode::ALL.map(AreaMode::name).into_iter().chain(words) {
|
||||
if !keys.contains(&key) {
|
||||
keys.push(key);
|
||||
}
|
||||
}
|
||||
keys
|
||||
}
|
||||
|
||||
/// The models offered, in order, the host's own among them; the built-in models on by default in the layout
|
||||
/// without it.
|
||||
pub fn models(mut self, models: impl IntoIterator<Item = &'a dyn ColorModel>) -> Self {
|
||||
self.models = Some(models.into_iter().collect());
|
||||
self
|
||||
}
|
||||
|
||||
/// The warnings beside the Full layout's compare swatch (out-of-gamut and web-colour warnings); a click on one
|
||||
/// sets its nearest passing colour. The host gives this pass's warnings for the colour it shows.
|
||||
pub fn warnings(mut self, warnings: impl IntoIterator<Item = ColorWarning>) -> Self {
|
||||
self.warnings = warnings.into_iter().collect();
|
||||
self
|
||||
}
|
||||
|
||||
/// The modes the Full layout's radios offer.
|
||||
pub(super) fn offered(models: &[&dyn ColorModel]) -> Vec<AreaMode> {
|
||||
AreaMode::PHOTOSHOP.into_iter().chain(AreaMode::OKLCH).filter(|mode| models.iter().any(|m| m.id() == mode.model().id())).collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> ColorPicker<'a> {
|
||||
/// Shows the picker.
|
||||
pub fn show(self, ui: &mut Ui) -> ColorPickerOutput {
|
||||
let ColorPicker {
|
||||
label,
|
||||
mut value,
|
||||
layout,
|
||||
models,
|
||||
mut mode,
|
||||
mut web_colors,
|
||||
alpha,
|
||||
dynamic_tracks,
|
||||
eyedropper,
|
||||
eyedropper_busy,
|
||||
compare,
|
||||
warnings,
|
||||
constrain,
|
||||
sampled,
|
||||
focus_on_open,
|
||||
} = self;
|
||||
let full = layout == ColorPickerLayout::Full;
|
||||
let models: Vec<&'a dyn ColorModel> = models
|
||||
.unwrap_or_else(|| builtin_models().into_iter().filter(|m| if full { m.default_on().full } else { m.default_on().compact }).collect());
|
||||
let parts = compact::Body {
|
||||
layout,
|
||||
models: models.clone(),
|
||||
warnings,
|
||||
compare,
|
||||
alpha,
|
||||
dynamic_tracks,
|
||||
eyedropper,
|
||||
eyedropper_busy,
|
||||
has_web_check: web_colors.is_some(),
|
||||
};
|
||||
let mut run = Run {
|
||||
name: Arc::from(label.as_str()),
|
||||
full,
|
||||
models: &models,
|
||||
value: value.reborrow(),
|
||||
mode: mode.as_mut().map(|held| held.reborrow()),
|
||||
web: web_colors.as_mut().map(|held| held.reborrow()),
|
||||
constrain,
|
||||
sampled,
|
||||
focus_on_open,
|
||||
parts: &parts,
|
||||
latest: PickedColor::rgb(Srgba::BLACK),
|
||||
empty: false,
|
||||
events: EditEvents::new(),
|
||||
};
|
||||
let shown = Stack::new().label(label).show(ui, |ui, body| run.show(ui, body));
|
||||
let (events, screen_pick) = shown.inner.unwrap_or_default();
|
||||
ColorPickerOutput { response: shown.output, events, screen_pick }
|
||||
}
|
||||
}
|
||||
|
||||
/// One pass of the picker: its body settles the rules, shows the children and applies each child's output to the
|
||||
/// bound colour in the same pass.
|
||||
struct Run<'s, 'a> {
|
||||
/// The picker's name, the label of the edits it makes itself.
|
||||
name: Arc<str>,
|
||||
full: bool,
|
||||
models: &'s [&'a dyn ColorModel],
|
||||
value: BindMut<'s, PickedColor>,
|
||||
mode: Option<BindMut<'s, AreaMode>>,
|
||||
web: Option<BindMut<'s, bool>>,
|
||||
constrain: Option<ColorConstraint<'a>>,
|
||||
sampled: Option<Srgba>,
|
||||
focus_on_open: bool,
|
||||
parts: &'s compact::Body<'a>,
|
||||
/// The colour after the edits landed so far.
|
||||
latest: PickedColor,
|
||||
/// No edit has landed on a colour-less picker yet.
|
||||
empty: bool,
|
||||
/// The edits landed, in order.
|
||||
events: EditEvents<PickedColor>,
|
||||
}
|
||||
|
||||
impl<'a> Run<'_, 'a> {
|
||||
fn show(&mut self, ui: &mut Ui, body: &mut BodyCx<'_>) -> (EditEvents<PickedColor>, Option<ScreenPickGesture>) {
|
||||
let memo = body.memory::<Memo>().clone();
|
||||
let held_mode = self.mode.as_ref().and_then(|held| held.read(&mut *body)).and_then(|held| held.same().copied());
|
||||
let mut mode = held_mode.unwrap_or(memo.mode);
|
||||
let held_web = self.web.as_ref().and_then(|held| held.read(&mut *body)).and_then(|held| held.same().copied()).unwrap_or(false);
|
||||
let rules = Rules { web: held_web, constrain: self.constrain.clone() };
|
||||
|
||||
// The Full layout shows a mode its models offer.
|
||||
if self.full {
|
||||
let offered = ColorPicker::offered(self.models);
|
||||
let wanted = offered.first().copied().filter(|first| !offered.contains(&mode) && *first != mode);
|
||||
if let Some(next) = wanted {
|
||||
self.write_mode(body, mode, next);
|
||||
mode = next;
|
||||
}
|
||||
}
|
||||
|
||||
let first_show = !memo.opened;
|
||||
let model = memo.model.filter(|id| self.models.iter().any(|m| m.id() == *id)).or_else(|| self.models.first().map(|m| m.id()));
|
||||
{
|
||||
let memo = body.memory::<Memo>();
|
||||
memo.mode = mode;
|
||||
memo.model = model;
|
||||
memo.opened = true;
|
||||
}
|
||||
let focus_hex = self.full && self.focus_on_open && first_show && body.resolved.enabled;
|
||||
let held = self.value.read(&mut *body).and_then(|held| held.same().copied());
|
||||
let empty = held.is_none();
|
||||
self.empty = empty;
|
||||
self.latest = held.unwrap_or(PickedColor::rgb(Srgba::BLACK));
|
||||
if let Some(color) = self.sampled {
|
||||
let next = self.latest.with_color(color.with_alpha(self.latest.color.a), &rules);
|
||||
self.set(body, next);
|
||||
}
|
||||
|
||||
let pass = Pass { shown: self.latest, empty, rules: rules.clone(), mode, model, web: held_web, focus_hex };
|
||||
let mut got = Collected { empty, ..Collected::default() };
|
||||
self.parts.run(ui, &pass, &mut got);
|
||||
|
||||
for edit in got.edits {
|
||||
self.land(body, edit);
|
||||
}
|
||||
for color in got.clicks {
|
||||
let next = self.latest.with_color(color, &rules);
|
||||
self.set(body, next);
|
||||
}
|
||||
if let Some(next) = got.mode_pick.filter(|next| *next != mode) {
|
||||
self.write_mode(body, mode, next);
|
||||
body.memory::<Memo>().mode = next;
|
||||
}
|
||||
if let Some(on) = got.web_pick.filter(|on| *on != held_web) {
|
||||
if let Some(held) = self.web.as_mut() {
|
||||
let event = EditEvent::set(Mixed::Same(held_web), on, Arc::from("Only Web Colors"), None);
|
||||
let _ = held.write(&mut *body, &event);
|
||||
}
|
||||
if on {
|
||||
let snapped_rules = Rules { web: true, constrain: self.constrain.clone() };
|
||||
let snapped = snapped_rules.apply(self.latest.color);
|
||||
if !snapped.same_rgb8(self.latest.color) {
|
||||
let next = self.latest.with_color(snapped, &snapped_rules);
|
||||
self.set(body, next);
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(model) = got.model_pick {
|
||||
body.memory::<Memo>().model = Some(model);
|
||||
}
|
||||
(std::mem::take(&mut self.events), got.screen_pick)
|
||||
}
|
||||
|
||||
/// Lands `event`, an edit of the colour: a gesture's end takes the colour it began from, the binding takes the
|
||||
/// event, and the pass reports it.
|
||||
fn land(&mut self, body: &mut BodyCx<'_>, mut event: EditEvent<PickedColor>) {
|
||||
match &mut event {
|
||||
EditEvent::Begin { id, before: Mixed::Same(start), .. } => body.memory::<Memo>().gesture = Some((*id, *start)),
|
||||
EditEvent::Commit { id, before, .. } => {
|
||||
if let Some((_, start)) = body.memory::<Memo>().gesture.take().filter(|(running, _)| *running == *id) {
|
||||
*before = Mixed::Same(start);
|
||||
}
|
||||
}
|
||||
EditEvent::Cancel { id, before, .. } => {
|
||||
if let Some((_, start)) = body.memory::<Memo>().gesture.take().filter(|(running, _)| *running == *id) {
|
||||
*before = Some(Mixed::Same(start));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
match &event {
|
||||
EditEvent::Update { value, .. } | EditEvent::Commit { after: value, .. } | EditEvent::Set { after: value, .. } => self.latest = *value,
|
||||
EditEvent::Cancel { before: Some(Mixed::Same(start)), .. } => self.latest = *start,
|
||||
_ => {}
|
||||
}
|
||||
let _ = self.value.write(&mut *body, &event);
|
||||
self.empty = false;
|
||||
self.events.push(event);
|
||||
}
|
||||
|
||||
/// A one-shot change of the colour to `next`.
|
||||
fn set(&mut self, body: &mut BodyCx<'_>, next: PickedColor) {
|
||||
if next == self.latest {
|
||||
return;
|
||||
}
|
||||
let before = if self.empty { Mixed::Mixed } else { Mixed::Same(self.latest) };
|
||||
let event = EditEvent::set(before, next, self.name.clone(), None);
|
||||
self.land(body, event);
|
||||
}
|
||||
|
||||
/// Sets the mode the host holds, if it holds one.
|
||||
fn write_mode(&mut self, body: &mut BodyCx<'_>, from: AreaMode, to: AreaMode) {
|
||||
if let Some(held) = self.mode.as_mut() {
|
||||
let event = EditEvent::set(Mixed::Same(from), to, Arc::from("Field shows"), None);
|
||||
let _ = held.write(&mut *body, &event);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
//! The screen-pick button: an icon button that also reports the press and drag that follow it, for Photoshop's
|
||||
//! press-and-drag sampling.
|
||||
|
||||
use craft_behavior::{IconId, Metrics, PressPhase, Sense};
|
||||
use craft_theme::{Stateful, States, variant::Tone};
|
||||
use craft_ui::contract::{Common, Component, Cx, MeasureCx, NoValue, Outcome, PaintUi, Pointer as _, Role, Styled as _};
|
||||
use craft_ui::primitives::IconSpec;
|
||||
use craft_ui::style::{ComponentStyle, FocusLook, IconLook, Ink, StyleCx};
|
||||
use egui::{Rect, Response, Vec2};
|
||||
|
||||
use super::ScreenPickGesture;
|
||||
|
||||
/// The style of the screen-pick button: the glyph and the focus ring.
|
||||
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
|
||||
#[non_exhaustive]
|
||||
pub(super) struct ScreenPickButtonStyle {
|
||||
#[style(metrics)]
|
||||
metrics: Metrics,
|
||||
#[style(focus)]
|
||||
focus: FocusLook,
|
||||
/// The glyph: its side, and its colour per state.
|
||||
#[style(icon)]
|
||||
glyph: IconLook,
|
||||
}
|
||||
|
||||
/// What the button reports.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
pub(super) struct ScreenPickOutput {
|
||||
pub response: Response,
|
||||
/// The press of this pass.
|
||||
pub gesture: Option<ScreenPickGesture>,
|
||||
}
|
||||
|
||||
impl Outcome for ScreenPickOutput {
|
||||
type Value = NoValue;
|
||||
|
||||
fn response(&self) -> &Response {
|
||||
&self.response
|
||||
}
|
||||
}
|
||||
|
||||
/// The eyedropper button; its label is its accessible name.
|
||||
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
|
||||
pub(super) struct ScreenPickButton {
|
||||
#[common]
|
||||
common: Common,
|
||||
gesture: Option<ScreenPickGesture>,
|
||||
}
|
||||
|
||||
impl ScreenPickButton {
|
||||
pub(super) fn new() -> Self {
|
||||
ScreenPickButton { common: Common::new(), gesture: None }
|
||||
}
|
||||
}
|
||||
|
||||
impl Component for ScreenPickButton {
|
||||
const ROLE: Role = Role::BUTTON;
|
||||
const PARTS: bool = false;
|
||||
const SHOWS_LABEL: bool = false;
|
||||
const OVERLAYS: bool = false;
|
||||
type Style = ScreenPickButtonStyle;
|
||||
type Output = ScreenPickOutput;
|
||||
|
||||
fn style(cx: &StyleCx<'_>, _: ScreenPickButtonStyleKey) -> ScreenPickButtonStyle {
|
||||
let control = cx.control();
|
||||
let (rest, accent) = (cx.ink(Ink::OnPanel), cx.tone(Tone::Accent));
|
||||
let disabled = cx.color(cx.tokens.color.text.disabled);
|
||||
ScreenPickButtonStyle {
|
||||
metrics: Metrics::new().min_size(Vec2::splat(control.height)),
|
||||
focus: cx.focus_look(),
|
||||
glyph: IconLook::new(control.icon, Stateful::new(rest).off(States::new(rest, accent, accent, disabled))),
|
||||
}
|
||||
}
|
||||
|
||||
fn measure(&mut self, cx: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
Vec2::splat(cx.style.glyph.side)
|
||||
}
|
||||
|
||||
fn sense(&self) -> Sense {
|
||||
Sense::CLICK | Sense::DRAG | Sense::FOCUS
|
||||
}
|
||||
|
||||
/// A drag past the slop is the held press; its release outside a click ends it; a click or Enter is a click.
|
||||
fn update(&mut self, cx: &mut Cx<'_, Self>) {
|
||||
self.gesture = match cx.press().phase {
|
||||
PressPhase::DragStart { pos, .. } | PressPhase::Drag { pos, .. } => Some(ScreenPickGesture::Held { at: pos }),
|
||||
PressPhase::Release { pos, click: false, .. } => Some(ScreenPickGesture::Released { at: pos }),
|
||||
_ => cx.activation().map(|_| ScreenPickGesture::Clicked),
|
||||
};
|
||||
}
|
||||
|
||||
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
|
||||
let glyph = Rect::from_center_size(cx.rect.center(), Vec2::splat(cx.style.glyph.side));
|
||||
let icon = IconSpec::svg(IconId::new("eyedropper")).color(cx.resolve(&cx.style.glyph.color));
|
||||
ui.draw().icon(glyph, &icon);
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> ScreenPickOutput {
|
||||
ScreenPickOutput { response: cx.response.clone(), gesture: self.gesture }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,123 @@
|
||||
//! Stories of `ColorPicker` and `ColorWarningChip`: Compact with alpha, Compact with Only Web Colors, Full with the
|
||||
//! compare swatch and a warning, and Full with the host's CMYK model and OKLCH.
|
||||
|
||||
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::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use egui::Ui;
|
||||
|
||||
use super::channel::{ChannelRow, ChannelRule, TrackRamp};
|
||||
use super::screen_pick::ScreenPickButton;
|
||||
use super::{ColorPicker, ColorPickerLayout, ColorWarning, ColorWarningChip, PickedColor};
|
||||
use crate::ui::AreaMode;
|
||||
|
||||
/// A naive CMYK in percent, without a working space: a host's model for the stories. A real host converts through its
|
||||
/// CMYK profile.
|
||||
struct NaiveCmyk;
|
||||
|
||||
const CMYK: [Channel; 4] = [
|
||||
Channel { name: "Cyan", qualified: "CMYK cyan", label: "C", min: 0.0, max: 100.0, unit: "%", decimals: 0, step: 1.0, track_stops: 2 },
|
||||
Channel { name: "Magenta", qualified: "CMYK magenta", label: "M", min: 0.0, max: 100.0, unit: "%", decimals: 0, step: 1.0, track_stops: 2 },
|
||||
Channel { name: "Yellow", qualified: "CMYK yellow", label: "Y", min: 0.0, max: 100.0, unit: "%", decimals: 0, step: 1.0, track_stops: 2 },
|
||||
Channel { name: "Black", qualified: "CMYK black", label: "K", min: 0.0, max: 100.0, unit: "%", decimals: 0, step: 1.0, track_stops: 2 },
|
||||
];
|
||||
|
||||
impl ColorModel for NaiveCmyk {
|
||||
fn id(&self) -> &'static str {
|
||||
"story-cmyk"
|
||||
}
|
||||
|
||||
fn name(&self) -> &'static str {
|
||||
"CMYK"
|
||||
}
|
||||
|
||||
fn channels(&self) -> &[Channel] {
|
||||
&CMYK
|
||||
}
|
||||
|
||||
fn from_srgb(&self, c: Srgba) -> ModelValues {
|
||||
let k = 1.0 - c.r.max(c.g).max(c.b);
|
||||
let ink = |v: f32| if k >= 1.0 { 0.0 } else { 100.0 * (1.0 - v - k) / (1.0 - k) };
|
||||
ModelValues::new("story-cmyk", &[ink(c.r), ink(c.g), ink(c.b), 100.0 * k])
|
||||
}
|
||||
|
||||
fn to_srgb(&self, v: &[f32; MAX_CHANNELS]) -> Srgba {
|
||||
let k = 1.0 - v[3] / 100.0;
|
||||
Srgba::rgb((1.0 - v[0] / 100.0) * k, (1.0 - v[1] / 100.0) * k, (1.0 - v[2] / 100.0) * k)
|
||||
}
|
||||
|
||||
fn default_on(&self) -> DefaultOn {
|
||||
DefaultOn { full: true, compact: false }
|
||||
}
|
||||
}
|
||||
|
||||
static CMYK_MODEL: NaiveCmyk = NaiveCmyk;
|
||||
|
||||
fn start() -> PickedColor {
|
||||
PickedColor::rgb(Srgba::rgb(0.2, 0.5, 0.8))
|
||||
}
|
||||
|
||||
#[story(ColorPicker<'static>, covers = [Default], drive = Drive::Never)]
|
||||
fn color_picker_compact(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let color = data.value("color", start());
|
||||
ColorPicker::new("Foreground color", Bind::bound(color)).alpha(true).eyedropper(true).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(ColorPicker<'static>, covers = [], drive = Drive::Never)]
|
||||
fn color_picker_web_colors(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let web = *data.value("web", true);
|
||||
let mut web = web;
|
||||
let color = data.value("color", start());
|
||||
ColorPicker::new("Foreground color", Bind::bound(color)).web_colors(Bind::bound(&mut web)).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(ColorPicker<'static>, covers = [], drive = Drive::Never)]
|
||||
fn color_picker_full(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let mut mode = *data.value("mode", AreaMode::default());
|
||||
let current = Srgba::rgb(0.9, 0.2, 0.1);
|
||||
let color = data.value("color", PickedColor::rgb(Srgba::rgb(1.0, 0.0, 1.0)));
|
||||
ColorPicker::new("Foreground color", Bind::bound(color))
|
||||
.layout(ColorPickerLayout::Full)
|
||||
.mode(Bind::bound(&mut mode))
|
||||
.compare(current)
|
||||
.warnings([ColorWarning::new("Out of gamut for printing", Srgba::rgb(0.9, 0.1, 0.9))])
|
||||
.eyedropper(true)
|
||||
.show(ui)
|
||||
.into()
|
||||
}
|
||||
|
||||
#[story(ColorPicker<'static>, covers = [Many], drive = Drive::Never)]
|
||||
fn color_picker_full_models(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let color = data.value("color", start());
|
||||
let models: [&'static dyn ColorModel; 5] = [&HsbModel, &RgbModel, &LabModel, &CMYK_MODEL, &OklchModel];
|
||||
ColorPicker::new("Foreground color", Bind::bound(color)).layout(ColorPickerLayout::Full).models(models).alpha(true).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(ColorWarningChip<'static>, covers = [Default], drive = Drive::Never)]
|
||||
fn color_warning_chip(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
static WARNING: std::sync::LazyLock<ColorWarning> =
|
||||
std::sync::LazyLock::new(|| ColorWarning::new("Out of gamut for printing", Srgba::rgb(0.9, 0.1, 0.9)));
|
||||
ColorWarningChip::new(&WARNING).show(ui).into()
|
||||
}
|
||||
|
||||
#[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()
|
||||
}
|
||||
|
||||
#[story(TrackRamp, covers = [Default], drive = Drive::Never)]
|
||||
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()
|
||||
}
|
||||
|
||||
#[story(ChannelRow<'static>, covers = [], drive = Drive::Never)]
|
||||
fn channel_row(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let value = data.value("value", 40.0_f64);
|
||||
let channel = HsbModel.channels()[1];
|
||||
let row = ChannelRow::new("Saturation", Bind::bound(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(),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
//! The picker's colour logic: the values a colour is shown in, and each edit as a new [`PickedColor`].
|
||||
|
||||
use std::rc::Rc;
|
||||
|
||||
use craft_theme::{ColorModel, ModelValues, Rgba, Srgba};
|
||||
|
||||
use super::PickedColor;
|
||||
use crate::ui::channels::{WEB_LEVELS, snapped};
|
||||
|
||||
/// The host's constraint on every colour the picker reports.
|
||||
#[derive(Clone)]
|
||||
pub struct ColorConstraint<'a>(Rc<dyn Fn(Srgba) -> Srgba + 'a>);
|
||||
|
||||
impl<'a> ColorConstraint<'a> {
|
||||
/// A constraint that maps every colour through `constrain`.
|
||||
pub fn new(constrain: impl Fn(Srgba) -> Srgba + 'a) -> Self {
|
||||
ColorConstraint(Rc::new(constrain))
|
||||
}
|
||||
}
|
||||
|
||||
/// What every colour an edit makes goes through: Only Web Colors' snap, then the host's constraint.
|
||||
#[derive(Clone)]
|
||||
pub(super) struct Rules<'a> {
|
||||
pub web: bool,
|
||||
pub constrain: Option<ColorConstraint<'a>>,
|
||||
}
|
||||
|
||||
impl Rules<'_> {
|
||||
pub(super) fn apply(&self, color: Srgba) -> Srgba {
|
||||
let color = if self.web { snapped(color, WEB_LEVELS) } else { color };
|
||||
self.constrain.as_ref().map_or(color, |constrain| (constrain.0)(color))
|
||||
}
|
||||
}
|
||||
|
||||
impl PickedColor {
|
||||
/// The colour in `model`: the kept values while they are of `model` and still give the colour's 8-bit sRGB (greys
|
||||
/// keep their hue, black its hue and saturation, a typed Lab colour outside sRGB its values), otherwise converted.
|
||||
pub(super) fn values_in(&self, model: &dyn ColorModel) -> ModelValues {
|
||||
match self.model {
|
||||
Some(values) if values.model == model.id() && model.to_srgb(&values.values).same_rgb8(self.color) => values,
|
||||
_ => model.from_srgb(self.color),
|
||||
}
|
||||
}
|
||||
|
||||
/// The colour `values` of `model` give, with this alpha, through the rules. The values stay with the colour while
|
||||
/// the rules left it alone.
|
||||
pub(super) fn with_values(&self, values: &ModelValues, model: &dyn ColorModel, rules: &Rules<'_>) -> PickedColor {
|
||||
let made = model.to_srgb(&values.values).with_alpha(self.color.a);
|
||||
let color = rules.apply(made);
|
||||
PickedColor { color, model: color.same_rgb8(made).then_some(*values) }
|
||||
}
|
||||
|
||||
/// Channel `channel` of `model` set to `value`.
|
||||
pub(super) fn with_channel(&self, model: &dyn ColorModel, channel: usize, value: f64, rules: &Rules<'_>) -> PickedColor {
|
||||
let mut values = self.values_in(model);
|
||||
values.values[channel] = value as f32;
|
||||
self.with_values(&values, model, rules)
|
||||
}
|
||||
|
||||
/// The alpha set to `percent`.
|
||||
pub(super) fn with_alpha(&self, percent: f64, rules: &Rules<'_>) -> PickedColor {
|
||||
PickedColor { color: rules.apply(self.color.with_alpha((percent / 100.0) as f32)), model: self.model }
|
||||
}
|
||||
|
||||
/// A colour set as such (a sample, a click on a swatch): no model values stay with it.
|
||||
pub(super) fn with_color(&self, color: Srgba, rules: &Rules<'_>) -> PickedColor {
|
||||
PickedColor { color: rules.apply(color), model: None }
|
||||
}
|
||||
|
||||
/// The hex field's colour; this value itself while the field shows it.
|
||||
pub(super) fn with_hex(&self, rgba: Rgba, rules: &Rules<'_>) -> PickedColor {
|
||||
if rgba == self.color.to_rgba() { *self } else { self.with_color(rgba.into(), rules) }
|
||||
}
|
||||
|
||||
/// The alpha in percent.
|
||||
pub(super) fn alpha_percent(&self) -> f64 {
|
||||
f64::from(self.color.a) * 100.0
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,483 @@
|
||||
//! `ColorPickerDialog` (F04.03): Photoshop's Color Picker as one value an app opens on its `DialogHost` and one result
|
||||
//! it reads back.
|
||||
//!
|
||||
//! ```ignore
|
||||
//! dialogs.open(ColorPickerDialog::foreground(foreground));
|
||||
//! dialogs.run(ui);
|
||||
//! if let Some(DialogResult::Ok(ColorPickerResult { picked, .. })) = dialogs.take::<ColorPickerDialog>() {
|
||||
//! foreground = picked.color;
|
||||
//! }
|
||||
//! ```
|
||||
|
||||
use craft_behavior::Mixed;
|
||||
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::contract::{Bind, Sampler as _, ShowContainer as _};
|
||||
use craft_ui::dialog::{Dialog, DialogId, DialogResult, DialogStack, StackDialog, dialog_id};
|
||||
use craft_ui::patterns::form_dialogs::{HostRequests, ResetFooter};
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
use craft_ui::runtime::focus::Initial;
|
||||
use craft_ui::runtime::overlay::CloseReason;
|
||||
use craft_ui::runtime::requests::{ColorRequest, EyedropperRequest, HostAnswer};
|
||||
use craft_ui::runtime::words::CommonWords;
|
||||
use craft_ui::sections::{DialogRole, FooterButton};
|
||||
use egui::{Context, Id, Ui};
|
||||
use std::sync::Arc;
|
||||
|
||||
use super::{ColorPicker, ColorPickerLayout, ColorWarning, PickedColor, ScreenPickGesture};
|
||||
use crate::{AreaMode, CmykModel, not_web_safe, web_safe};
|
||||
|
||||
craft_ui::words! {
|
||||
/// The Color Picker dialog's own words, English by default. The picker body's words are `ColorPickerWords`; OK and
|
||||
/// Cancel are the common words.
|
||||
#[non_exhaustive]
|
||||
pub struct ColorPickerDialogWords {
|
||||
/// The title when a component's request gives none.
|
||||
title: "colorPickerDialog.title" = "Color Picker";
|
||||
foreground_title: "colorPickerDialog.foregroundTitle" = "Color Picker (Foreground Color)";
|
||||
background_title: "colorPickerDialog.backgroundTitle" = "Color Picker (Background Color)";
|
||||
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";
|
||||
}
|
||||
}
|
||||
|
||||
/// What the picker keeps across opens and runs (`Remembered` under the scope `colorPicker.memory`): the component the
|
||||
/// field shows and Only Web Colors, as Photoshop. Stored when the dialog closes with OK.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub struct ColorPickerMemory {
|
||||
/// The component the area and strip edit.
|
||||
pub mode: AreaMode,
|
||||
/// Only Web Colors: snap to the 216 web-safe colours.
|
||||
pub web_colors: bool,
|
||||
}
|
||||
|
||||
/// The remembered scope of [`ColorPickerMemory`].
|
||||
const MEMORY_SCOPE: &str = "colorPicker.memory";
|
||||
|
||||
/// What a [`ColorPickerDialog`] answers with OK: the key it was opened with (which colour it was for) and the colour.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct ColorPickerResult {
|
||||
/// The dialog's key: `"foreground"`, `"background"`, or the app's own.
|
||||
pub key: String,
|
||||
/// The colour, with the model values the user typed while they still give it (CMYK inks, Lab values outside sRGB).
|
||||
pub picked: PickedColor,
|
||||
}
|
||||
|
||||
/// The dialog's title: given by the app, or one of the two the library words.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
enum Title {
|
||||
Default,
|
||||
Foreground,
|
||||
Background,
|
||||
Given(Label),
|
||||
}
|
||||
|
||||
/// Photoshop's Color Picker dialog on the `DialogHost`: the Full `ColorPicker` with the compare swatch, the
|
||||
/// out-of-gamut and web-colour warnings, Only Web Colors and the eyedroppers, and OK, Cancel and Add to Swatches as the
|
||||
/// dialog's buttons.
|
||||
///
|
||||
/// - **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
|
||||
/// 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.
|
||||
/// - **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
|
||||
/// picker's screen-pick press is kept for the host ([`take_screen_pick`](Self::take_screen_pick)), which drives
|
||||
/// its `ScreenPick` and answers with [`set_color`](Self::set_color).
|
||||
/// - **Buttons:** Enter is OK and Esc is Cancel (not while a popup is open or a gesture runs). Alt turns Cancel into
|
||||
/// Reset: the colour from when the dialog opened, and the dialog stays open. Add to Swatches keeps the dialog open;
|
||||
/// the app takes the colour with [`take_add_to_swatches`](Self::take_add_to_swatches).
|
||||
/// - **Preview:** [`current`](Self::current) follows every edit, so an app that previews reads it each pass through
|
||||
/// `DialogHost::get_by_id` and shows it live; Cancel is the app's cue to put the old colour back.
|
||||
pub struct ColorPickerDialog {
|
||||
id: DialogId,
|
||||
key: String,
|
||||
title: Title,
|
||||
title_args: Vec<(String, String)>,
|
||||
/// The colour the dialog opened with; `None` for a request whose items have different colours.
|
||||
opening: Option<PickedColor>,
|
||||
/// The colour as it stands; `None` until the first pick when the dialog opened without one.
|
||||
current: Option<PickedColor>,
|
||||
compare: bool,
|
||||
remember: bool,
|
||||
add_to_swatches: bool,
|
||||
cmyk: Option<CmykConverter>,
|
||||
eyedropper: bool,
|
||||
canvas_samples: bool,
|
||||
canvas: Option<Id>,
|
||||
screen_busy: bool,
|
||||
memory: ColorPickerMemory,
|
||||
pending_swatch: Option<PickedColor>,
|
||||
pending_screen: Option<ScreenPickGesture>,
|
||||
requests: HostRequests,
|
||||
sampling: bool,
|
||||
sample: Option<Srgba>,
|
||||
host: Option<Arc<Host>>,
|
||||
started: bool,
|
||||
open: bool,
|
||||
}
|
||||
|
||||
impl ColorPickerDialog {
|
||||
/// A picker for what a component's `ColorRequest` asked: its key, its title (the default title when it has none)
|
||||
/// 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 title = title.map_or(Title::Default, Title::Given);
|
||||
ColorPickerDialog::with_title(key, title, color)
|
||||
}
|
||||
|
||||
/// A picker for the colour `key` names, titled `title`, opening on `color`.
|
||||
pub fn new(key: impl Into<String>, title: impl Into<Label>, color: Srgba) -> ColorPickerDialog {
|
||||
ColorPickerDialog::with_title(key.into(), Title::Given(title.into()), Some(color))
|
||||
}
|
||||
|
||||
/// The foreground colour's picker: key `"foreground"`, "Color Picker (Foreground Color)".
|
||||
pub fn foreground(color: Srgba) -> ColorPickerDialog {
|
||||
ColorPickerDialog::with_title("foreground".into(), Title::Foreground, Some(color))
|
||||
}
|
||||
|
||||
/// The background colour's picker: key `"background"`, "Color Picker (Background Color)".
|
||||
pub fn background(color: Srgba) -> ColorPickerDialog {
|
||||
ColorPickerDialog::with_title("background".into(), Title::Background, Some(color))
|
||||
}
|
||||
|
||||
fn with_title(key: String, title: Title, color: Option<Srgba>) -> ColorPickerDialog {
|
||||
let opening = color.map(PickedColor::rgb);
|
||||
ColorPickerDialog {
|
||||
id: dialog_id(("color-picker", key.as_str())),
|
||||
key,
|
||||
title,
|
||||
title_args: Vec::new(),
|
||||
opening,
|
||||
current: opening,
|
||||
compare: true,
|
||||
remember: true,
|
||||
add_to_swatches: true,
|
||||
cmyk: None,
|
||||
eyedropper: true,
|
||||
canvas_samples: true,
|
||||
canvas: None,
|
||||
screen_busy: false,
|
||||
memory: ColorPickerMemory::default(),
|
||||
pending_swatch: None,
|
||||
pending_screen: None,
|
||||
requests: HostRequests::new(),
|
||||
sampling: false,
|
||||
sample: None,
|
||||
host: None,
|
||||
started: false,
|
||||
open: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Fills `{name}` in a given title with `value`, after the title is translated: the title follows a language
|
||||
/// switch while the dialog is open. The value is shown as given, never translated.
|
||||
#[must_use]
|
||||
pub fn arg(mut self, name: impl Into<String>, value: impl Into<String>) -> ColorPickerDialog {
|
||||
self.title_args.push((name.into(), value.into()));
|
||||
self
|
||||
}
|
||||
|
||||
/// The model values the colour was picked in (a CMYK fill's inks): the fields show them as they were typed, not
|
||||
/// what the sRGB colour converts to (storytold/photocraft#4196).
|
||||
#[must_use]
|
||||
pub fn kept(mut self, values: craft_theme::ModelValues) -> ColorPickerDialog {
|
||||
for held in [&mut self.opening, &mut self.current].into_iter().flatten() {
|
||||
held.model = Some(values);
|
||||
}
|
||||
self
|
||||
}
|
||||
|
||||
/// The compare swatch beside the field; on by default.
|
||||
#[must_use]
|
||||
pub fn compare(mut self, on: bool) -> ColorPickerDialog {
|
||||
self.compare = on;
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether the field's component and Only Web Colors are recalled on open and stored on OK
|
||||
/// ([`ColorPickerMemory`]); on by default. A picker opened by a feature that wants its own start turns it off.
|
||||
#[must_use]
|
||||
pub fn web_colors_remembered(mut self, on: bool) -> ColorPickerDialog {
|
||||
self.remember = on;
|
||||
self
|
||||
}
|
||||
|
||||
/// The Add to Swatches button; on by default.
|
||||
#[must_use]
|
||||
pub fn add_to_swatches(mut self, on: bool) -> ColorPickerDialog {
|
||||
self.add_to_swatches = on;
|
||||
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.
|
||||
#[must_use]
|
||||
pub fn cmyk(mut self, converter: &CmykConverter) -> ColorPickerDialog {
|
||||
self.cmyk = Some(converter.clone());
|
||||
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 {
|
||||
self.eyedropper = on;
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether the canvas samples into the dialog while it is the top dialog; on by default.
|
||||
#[must_use]
|
||||
pub fn canvas_samples(mut self, on: bool) -> ColorPickerDialog {
|
||||
self.canvas_samples = on;
|
||||
self
|
||||
}
|
||||
|
||||
/// The canvas whose presses pass through the dialog's modal layer while the dropper is armed
|
||||
/// (`Sampler::arm_sampler`), and whose view stays usable (`keep_view_open`).
|
||||
#[must_use]
|
||||
pub fn canvas(mut self, canvas: Id) -> ColorPickerDialog {
|
||||
self.canvas = Some(canvas);
|
||||
self
|
||||
}
|
||||
|
||||
/// Whether a screen pick is running; the picker's screen-pick button is disabled meanwhile. The host sets it each
|
||||
/// pass from its `ScreenPick`.
|
||||
pub fn screen_busy(&mut self, busy: bool) {
|
||||
self.screen_busy = busy;
|
||||
}
|
||||
|
||||
/// The key the dialog was opened with.
|
||||
pub fn key(&self) -> &str {
|
||||
&self.key
|
||||
}
|
||||
|
||||
/// The colour as it stands this pass.
|
||||
pub fn current(&self) -> Option<PickedColor> {
|
||||
self.current
|
||||
}
|
||||
|
||||
/// The colour the dialog opened with: as given, until the first pass; then, with Only Web Colors on, snapped to the
|
||||
/// nearest web colour, which is what the compare swatch's "current" half shows and what Reset returns to.
|
||||
pub fn opening(&self) -> Option<PickedColor> {
|
||||
self.opening
|
||||
}
|
||||
|
||||
/// Sets the colour as an edit would, for automation, scripts and the host's screen pick: the fields show `picked`'s
|
||||
/// model values when it has them, and the colour is what OK answers. The compare swatch keeps the opening colour.
|
||||
pub fn set_color(&mut self, picked: PickedColor) {
|
||||
self.current = Some(picked);
|
||||
}
|
||||
|
||||
/// The colour Add to Swatches was pressed for, once; `None` otherwise.
|
||||
pub fn take_add_to_swatches(&mut self) -> Option<PickedColor> {
|
||||
self.pending_swatch.take()
|
||||
}
|
||||
|
||||
/// The picker's screen-pick press, once: the host starts or feeds its `ScreenPick` with it.
|
||||
pub fn take_screen_pick(&mut self) -> Option<ScreenPickGesture> {
|
||||
self.pending_screen.take()
|
||||
}
|
||||
|
||||
/// What the dialog asks of the host (the canvas eyedropper) and the host's answers.
|
||||
pub fn requests(&mut self) -> &mut HostRequests {
|
||||
&mut self.requests
|
||||
}
|
||||
|
||||
/// What OK does: stores the remembered field component and Only Web Colors, and answers with the colour.
|
||||
fn accept(&mut self, ctx: &Context) -> Option<ColorPickerResult> {
|
||||
let picked = self.current?;
|
||||
self.requests.cancel();
|
||||
if self.remember
|
||||
&& let Some(host) = self.host.clone().or_else(|| Host::try_of_ctx(ctx))
|
||||
{
|
||||
Remembered::<ColorPickerMemory>::new(MEMORY_SCOPE).store(&host, &self.memory);
|
||||
}
|
||||
Some(ColorPickerResult { key: self.key.clone(), picked })
|
||||
}
|
||||
|
||||
/// The first pass: recalls the remembered field component and Only Web Colors, and with Only Web Colors on snaps
|
||||
/// the opening colour, which the compare swatch's current half follows (storytold/photocraft#4995).
|
||||
fn start(&mut self, host: Option<&Arc<Host>>) {
|
||||
self.started = true;
|
||||
self.host = host.cloned();
|
||||
if self.remember
|
||||
&& let Some(host) = &self.host
|
||||
&& let Some(memory) = Remembered::<ColorPickerMemory>::new(MEMORY_SCOPE).recall(host)
|
||||
{
|
||||
self.memory = memory;
|
||||
}
|
||||
if self.memory.web_colors
|
||||
&& let Some(opening) = self.opening
|
||||
{
|
||||
let [r, g, b] = web_safe([opening.color.r, opening.color.g, opening.color.b]);
|
||||
self.opening = Some(PickedColor { color: Srgba { r, g, b, a: opening.color.a }, model: None });
|
||||
self.current = self.opening;
|
||||
}
|
||||
}
|
||||
|
||||
/// Files or withdraws the canvas eyedropper request as the dialog gains or loses the top.
|
||||
fn follow_top(&mut self, top: bool) {
|
||||
let sampling = self.canvas_samples && top;
|
||||
if sampling && !self.sampling {
|
||||
self.requests.request_eyedropper(EyedropperRequest::new(self.key.clone()));
|
||||
} else if !sampling && self.sampling {
|
||||
self.requests.cancel_eyedropper();
|
||||
}
|
||||
self.sampling = sampling;
|
||||
}
|
||||
}
|
||||
|
||||
impl StackDialog for ColorPickerDialog {
|
||||
type Result = ColorPickerResult;
|
||||
|
||||
fn id(&self) -> DialogId {
|
||||
self.id
|
||||
}
|
||||
|
||||
fn key(&self) -> Option<&str> {
|
||||
Some(&self.key)
|
||||
}
|
||||
|
||||
/// Answers OK as the OK button would, without drawing: the dialog's start (recalled memory, the Only Web Colors
|
||||
/// snap) has run, the memory is stored, and the colour is the current one.
|
||||
fn confirm(&mut self, ctx: &Context) -> Option<ColorPickerResult> {
|
||||
if !self.started {
|
||||
let host = Host::try_of_ctx(ctx);
|
||||
self.start(host.as_ref());
|
||||
}
|
||||
self.accept(ctx)
|
||||
}
|
||||
|
||||
/// The host closed the dialog from outside: its dropper ends with it.
|
||||
fn cancelled(&mut self, _: &Context) {
|
||||
self.requests.cancel();
|
||||
}
|
||||
|
||||
fn show(&mut self, ui: &mut Ui, stack: &DialogStack) -> Option<DialogResult<ColorPickerResult>> {
|
||||
let env = Env::of(ui);
|
||||
let words = env.words::<ColorPickerDialogWords>();
|
||||
let common = env.words::<CommonWords>();
|
||||
if !self.started {
|
||||
self.start(env.view().host());
|
||||
}
|
||||
self.follow_top(stack.is_top(self.id));
|
||||
let answered = self.requests.take_answers().into_iter().rev().find_map(|answer| match answer {
|
||||
HostAnswer::Eyedropper { key, color, .. } if key == self.key => Some(color),
|
||||
_ => None,
|
||||
});
|
||||
self.sample = answered.or(self.sample.take());
|
||||
|
||||
let title = match &self.title {
|
||||
Title::Default => words.title.clone(),
|
||||
Title::Foreground => words.foreground_title.clone(),
|
||||
Title::Background => words.background_title.clone(),
|
||||
Title::Given(label) => {
|
||||
let resolved = env.view().resolve(label);
|
||||
if self.title_args.is_empty() {
|
||||
resolved
|
||||
} else {
|
||||
let args: Vec<(&str, &str)> = self.title_args.iter().map(|(name, value)| (name.as_str(), value.as_str())).collect();
|
||||
Label::from(craft_i18n::fmt(resolved.as_str(), &args))
|
||||
}
|
||||
}
|
||||
};
|
||||
let cmyk = CmykModel::new(self.cmyk.clone().unwrap_or_else(|| CmykConverter::coated().clone()));
|
||||
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 {
|
||||
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 && env.view().shell().caps.contains(Caps::SCREEN_CAPTURE);
|
||||
let Self { current, opening, compare, memory, screen_busy, sample, pending_screen, open, .. } = self;
|
||||
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, |opening| Mixed::Same(opening.color))));
|
||||
let color = current.map(|current| current.color);
|
||||
let web_only = memory.web_colors;
|
||||
let shown = Dialog::new(title.clone())
|
||||
.opened(Bind::bound(open))
|
||||
.buttons(buttons)
|
||||
.close_on_enter(true)
|
||||
.initial_focus(Initial::Keep)
|
||||
.roomy(true)
|
||||
.show(ui, |ui, cx| {
|
||||
if let Some(canvas) = keep_open {
|
||||
cx.keep_view_open(canvas);
|
||||
}
|
||||
if let Some(canvas) = arm {
|
||||
cx.arm_sampler(canvas);
|
||||
}
|
||||
let mut models: Vec<&dyn ColorModel> = builtin_models().into_iter().filter(|model| model.default_on().full).collect();
|
||||
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 !web_only && let Some(nearest) = not_web_safe(rgb) {
|
||||
warnings.push(ColorWarning::web_colors(
|
||||
words.not_web_color.clone(),
|
||||
Srgba { r: nearest[0], g: nearest[1], b: nearest[2], a: color.a },
|
||||
));
|
||||
}
|
||||
}
|
||||
let mut picker = ColorPicker::new(title.clone(), Bind::bound_mixed(&mut held))
|
||||
.layout(ColorPickerLayout::Full)
|
||||
.models(models)
|
||||
.mode(Bind::bound(&mut memory.mode))
|
||||
.web_colors(Bind::bound(&mut memory.web_colors))
|
||||
.warnings(warnings)
|
||||
.eyedropper(screen)
|
||||
.eyedropper_busy(busy)
|
||||
.focus_on_open(true);
|
||||
if let Some(sampled) = sampled {
|
||||
picker = picker.sampled(sampled);
|
||||
}
|
||||
if let Some(compare) = compare_with {
|
||||
picker = picker.compare(compare);
|
||||
}
|
||||
if let Some(gesture) = picker.show(ui).screen_pick {
|
||||
*pending_screen = Some(gesture);
|
||||
}
|
||||
});
|
||||
self.current = held.same().copied();
|
||||
|
||||
let (picked, closed) = (shown.output.picked, shown.output.closed);
|
||||
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) {
|
||||
self.pending_swatch = self.current;
|
||||
return None;
|
||||
}
|
||||
match (ok, closed) {
|
||||
(true, _) => self.accept(ui.ctx()).map(DialogResult::Ok),
|
||||
(false, Some(_)) => {
|
||||
self.requests.cancel();
|
||||
Some(DialogResult::Cancel)
|
||||
}
|
||||
(false, None) => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,150 @@
|
||||
//! `ColorPopover`: a colour well that opens a Compact colour picker in a popover.
|
||||
|
||||
use craft_behavior::EditEvents;
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::choice::Swatch;
|
||||
use craft_ui::contract::{Bind, Outcome, Pattern, Remember as _, Show as _, ShowContainer as _};
|
||||
use craft_ui::layout_components::Stack;
|
||||
use craft_ui::popover::Popover;
|
||||
use craft_ui::runtime::env::Label;
|
||||
use egui::{Response, Ui};
|
||||
|
||||
use super::{ColorPicker, ColorPickerLayout, ColorPickerOutput, PickedColor, ScreenPickGesture};
|
||||
|
||||
#[cfg(feature = "screen-testing")]
|
||||
mod stories;
|
||||
|
||||
/// The setup closure of the picker in the popover.
|
||||
type Setup<'a> = Box<dyn for<'b> FnOnce(ColorPicker<'b>) -> ColorPicker<'b> + 'a>;
|
||||
|
||||
/// The popover's own state while its well is shown.
|
||||
#[derive(Clone, Default)]
|
||||
struct Session {
|
||||
open: bool,
|
||||
}
|
||||
|
||||
/// A [`ColorPicker`] (Compact) in a popover under a colour well, as PhotoCraft's colour button.
|
||||
///
|
||||
/// - The well is a `Swatch` named `label`; a click, Enter or Space opens the popover and the hex field takes the
|
||||
/// focus with its text selected.
|
||||
/// - The popover hangs below the well, or above it when there is no room, and keeps that side while it is open. It is
|
||||
/// as wide as the picker.
|
||||
/// - It closes on a press outside, a click on the well and Escape while no gesture runs (an Escape that cancels a
|
||||
/// gesture is the picker's). The colour stays as edited, and the focus returns to the well unless it moved to
|
||||
/// another control.
|
||||
/// - Edits are the picker's: one step per gesture, so the popover edits live.
|
||||
/// - A caller that draws its own opener (a gradient stop) hands it over with [`anchor`](ColorPopover::anchor); the
|
||||
/// caller closes the popover by writing `false` to the binding it gave.
|
||||
#[must_use = "show the popover with `show`"]
|
||||
#[derive(Pattern)]
|
||||
pub struct ColorPopover<'a> {
|
||||
label: Label,
|
||||
value: Bind<'a, PickedColor>,
|
||||
setup: Option<Setup<'a>>,
|
||||
anchor: Option<(Response, Bind<'a, bool>)>,
|
||||
}
|
||||
|
||||
/// What [`ColorPopover::show`] reports.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
#[must_use = "the host applies the edit"]
|
||||
pub struct ColorPopoverOutput {
|
||||
/// The well's response, or the anchor's.
|
||||
pub response: Response,
|
||||
/// The edits of the picker in the popover, in order; empty while the popover is closed.
|
||||
pub events: EditEvents<PickedColor>,
|
||||
/// The picker's screen-pick button was pressed; the app drives its `ScreenPick`.
|
||||
pub screen_pick: Option<ScreenPickGesture>,
|
||||
/// Whether the popover is open after this pass.
|
||||
pub open: bool,
|
||||
}
|
||||
|
||||
impl Outcome for ColorPopoverOutput {
|
||||
type Value = PickedColor;
|
||||
|
||||
fn response(&self) -> &Response {
|
||||
&self.response
|
||||
}
|
||||
|
||||
#[cfg(feature = "screen-testing")]
|
||||
fn story_facts(&self) -> craft_ui::testing::StoryOutput {
|
||||
self.response.story_facts()
|
||||
}
|
||||
}
|
||||
|
||||
impl<'a> ColorPopover<'a> {
|
||||
/// A well named `label` (its accessible name, translated: "Fill colour") over `value`, opening a picker.
|
||||
pub fn new(label: impl Into<Label>, value: Bind<'a, PickedColor>) -> Self {
|
||||
ColorPopover { label: label.into(), value, setup: None, anchor: None }
|
||||
}
|
||||
|
||||
/// Sets up the picker in the popover (alpha, eyedropper, constraint, models): `setup` gets the Compact picker the
|
||||
/// popover made.
|
||||
pub fn picker(mut self, setup: impl for<'b> FnOnce(ColorPicker<'b>) -> ColorPicker<'b> + 'a) -> Self {
|
||||
self.setup = Some(Box::new(setup));
|
||||
self
|
||||
}
|
||||
|
||||
/// Hangs the popover from `opener`, which the caller drew, and opens it while `open` is true. The caller opens it
|
||||
/// on the opener's click and closes it by writing `false`.
|
||||
pub fn anchor(mut self, opener: &Response, open: Bind<'a, bool>) -> Self {
|
||||
self.anchor = Some((opener.clone(), open));
|
||||
self
|
||||
}
|
||||
|
||||
/// Shows the well and, while open, the popover.
|
||||
pub fn show(self, ui: &mut Ui) -> ColorPopoverOutput {
|
||||
let ColorPopover { label, mut value, mut setup, anchor } = self;
|
||||
if let Some((opener, mut open)) = anchor {
|
||||
let (events, screen_pick, shown) = popover(ui, &label, &mut value, &mut setup, &opener, open.reborrowed());
|
||||
return ColorPopoverOutput { response: opener, events, screen_pick, open: shown };
|
||||
}
|
||||
let shown = Stack::new().show(ui, |ui, cx| {
|
||||
let color = value.reborrow().read(cx).and_then(|held| held.same().map(|picked| picked.color)).unwrap_or(Srgba::rgb(0.0, 0.0, 0.0));
|
||||
let well = Swatch::new(label.clone(), color).show(ui);
|
||||
let state = cx.memory::<Session>();
|
||||
if well.clicked {
|
||||
state.open = !state.open;
|
||||
}
|
||||
let (events, screen_pick, open) = popover(ui, &label, &mut value, &mut setup, &well.response, Bind::bound(&mut state.open));
|
||||
ColorPopoverOutput { response: well.response, events, screen_pick, open }
|
||||
});
|
||||
match shown.inner {
|
||||
Some(output) => output,
|
||||
None => ColorPopoverOutput { response: shown.output, events: EditEvents::new(), screen_pick: None, open: false },
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The popover under `opener` while `open` is true: its picker's edit and screen pick, and whether it stays open.
|
||||
fn popover(
|
||||
ui: &mut Ui,
|
||||
label: &Label,
|
||||
value: &mut Bind<'_, PickedColor>,
|
||||
setup: &mut Option<Setup<'_>>,
|
||||
opener: &Response,
|
||||
open: Bind<'_, bool>,
|
||||
) -> (EditEvents<PickedColor>, Option<ScreenPickGesture>, bool) {
|
||||
let shown = Popover::new(label.clone(), open).opened_by(opener).show(ui, |ui, _| {
|
||||
let mut picker = compact_picker(label.clone(), value.reborrowed(), None).focus_on_open(true);
|
||||
if let Some(setup) = setup.take() {
|
||||
picker = setup(picker);
|
||||
}
|
||||
picker.show(ui)
|
||||
});
|
||||
let open = shown.inner.is_some() && shown.output.closed.is_none();
|
||||
match shown.inner {
|
||||
Some(ColorPickerOutput { events, screen_pick, .. }) => (events, screen_pick, open),
|
||||
None => (EditEvents::new(), None, open),
|
||||
}
|
||||
}
|
||||
|
||||
/// The Compact picker every colour popover of the crate shows: [`ColorPopover`] and the overlays of the swatch pair
|
||||
/// and the paint chip build their picker here. `sampled` answers a pending screen pick.
|
||||
pub(super) fn compact_picker<'a>(label: Label, value: Bind<'a, PickedColor>, sampled: Option<Srgba>) -> ColorPicker<'a> {
|
||||
let picker = ColorPicker::new(label, value).layout(ColorPickerLayout::Compact);
|
||||
match sampled {
|
||||
Some(color) => picker.sampled(color),
|
||||
None => picker,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
//! Stories of `ColorPopover`.
|
||||
|
||||
use super::ColorPopover;
|
||||
use crate::ui::PickedColor;
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::buttons::Button;
|
||||
use craft_ui::contract::ShowContainer as _;
|
||||
use craft_ui::contract::{Bind, Show as _};
|
||||
use craft_ui::layout_components::Stack;
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use egui::Ui;
|
||||
|
||||
fn picked() -> PickedColor {
|
||||
PickedColor { color: Srgba::rgb(0.2, 0.5, 0.8), model: None }
|
||||
}
|
||||
|
||||
#[story(ColorPopover<'static>, covers = [Default], drive = Drive::Never)]
|
||||
fn closed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
StoryOutput::from(ColorPopover::new("Fill colour", Bind::bound(data.value("color", picked()))).show(ui))
|
||||
}
|
||||
|
||||
#[story(ColorPopover<'static>, covers = [], drive = Drive::Never)]
|
||||
fn open(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let color = data.value("color", picked());
|
||||
let shown = Stack::new().show(ui, |ui, _| {
|
||||
let opener = Button::new("Stop").show(ui);
|
||||
ColorPopover::new("Stop colour", Bind::bound(&mut *color)).anchor(&opener, Bind::given(true)).show(ui)
|
||||
});
|
||||
match shown.inner {
|
||||
Some(output) => StoryOutput::from(output),
|
||||
None => StoryOutput::from(shown.output),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,310 @@
|
||||
//! Colour profile prompts (F04.12): the Embedded Profile Mismatch and Missing Profile questions
|
||||
//! when a file opens ([`ProfileMismatchDialog`]), and a document's profile as the status bar and
|
||||
//! the document's title say it ([`ProfileStatus`]).
|
||||
//!
|
||||
//! The answer is the app's to carry out (convert, assign, discard) and, with "Remember this
|
||||
//! choice", to store as its Color Settings policy for that colour mode; the dialog only asks.
|
||||
|
||||
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::dialog::{DialogId, DialogResult, DialogStack, Prompt, StackDialog, dialog_id};
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
use craft_ui::runtime::words::CommonWords;
|
||||
use craft_ui::sections::{DialogRole, FooterButton};
|
||||
use egui::Ui;
|
||||
|
||||
use crate::display::MonitorProblem;
|
||||
|
||||
#[cfg(feature = "screen-testing")]
|
||||
mod stories;
|
||||
|
||||
craft_ui::words! {
|
||||
/// The profile prompts' words, English by default.
|
||||
#[non_exhaustive]
|
||||
pub struct ProfileWords {
|
||||
mismatch_title: "profile.mismatchTitle" = "Embedded Profile Mismatch";
|
||||
missing_title: "profile.missingTitle" = "Missing Profile";
|
||||
/// `{name}` the file name, `{mode}` the mode word ("RGB").
|
||||
mismatch_message: template "profile.mismatchMessage" = "The document \u{201c}{name}\u{201d} has an embedded color profile that does not match the current {mode} working space.";
|
||||
missing_message: template "profile.missingMessage" = "The document \u{201c}{name}\u{201d} does not have an embedded {mode} profile.";
|
||||
/// `{working}` is the working space's name.
|
||||
working: template "profile.working" = "Working: {working}";
|
||||
/// `{profile}` is the embedded profile's name.
|
||||
use_embedded: template "profile.useEmbedded" = "Use the embedded profile ({profile})";
|
||||
/// `{profile}` is the working space's name.
|
||||
convert: template "profile.convert" = "Convert to the working space ({profile})";
|
||||
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";
|
||||
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";
|
||||
cmyk: "profile.cmyk" = "CMYK";
|
||||
gray: "profile.gray" = "Gray";
|
||||
/// `{mode}` the mode word.
|
||||
untagged: template "profile.untagged" = "Untagged {mode}";
|
||||
invalid: template "profile.invalid" = "Invalid {mode} profile";
|
||||
unnamed: template "profile.unnamed" = "Unnamed {mode} profile";
|
||||
/// A monitor profile that is not RGB; `{profile}` is its name, `{space}` its colour space.
|
||||
monitor_not_rgb: template "profile.monitorNotRgb" = "\u{201c}{profile}\u{201d} is a {space} profile, not an RGB profile.";
|
||||
/// A monitor profile that cannot be used; `{profile}` is its name, `{reason}` the engine's text.
|
||||
monitor_cannot_link: template "profile.monitorCannotLink" = "\u{201c}{profile}\u{201d} can't be used as a display profile: {reason}";
|
||||
/// A monitor profile that does not parse; `{reason}` is the parser's text.
|
||||
monitor_unreadable: template "profile.monitorUnreadable" = "The display profile can't be read: {reason}";
|
||||
}
|
||||
}
|
||||
|
||||
/// A document's colour mode, as the prompts word it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
#[non_exhaustive]
|
||||
pub enum ProfileMode {
|
||||
#[allow(missing_docs)]
|
||||
Rgb,
|
||||
#[allow(missing_docs)]
|
||||
Cmyk,
|
||||
#[allow(missing_docs)]
|
||||
Gray,
|
||||
}
|
||||
|
||||
impl ProfileMode {
|
||||
fn word(self, words: &ProfileWords) -> &str {
|
||||
match self {
|
||||
ProfileMode::Rgb => words.rgb.as_str(),
|
||||
ProfileMode::Cmyk => words.cmyk.as_str(),
|
||||
ProfileMode::Gray => words.gray.as_str(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl MonitorProblem {
|
||||
/// The reason a monitor profile was not used, in the words.
|
||||
pub fn label(&self, words: &ProfileWords) -> String {
|
||||
match self {
|
||||
MonitorProblem::NotRgb { description, space } => {
|
||||
let space = match space {
|
||||
ColorSpace::Cmyk => words.cmyk.as_str().to_owned(),
|
||||
ColorSpace::Gray => words.gray.as_str().to_owned(),
|
||||
other => format!("{other:?}").to_uppercase(),
|
||||
};
|
||||
words.monitor_not_rgb.fill(&[("profile", description), ("space", &space)])
|
||||
}
|
||||
MonitorProblem::CannotLink { description, reason } => words.monitor_cannot_link.fill(&[("profile", description), ("reason", reason)]),
|
||||
MonitorProblem::Unreadable { reason } => words.monitor_unreadable.fill(&[("reason", reason)]),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A document's profile as Photoshop's status bar (Document Profile) says it: "Untagged RGB" (no
|
||||
/// profile), "Invalid RGB profile" (one that does not parse or link), "Unnamed RGB profile" (no
|
||||
/// description), else the profile's description.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum ProfileStatus {
|
||||
/// The document has no profile.
|
||||
Untagged,
|
||||
/// The profile does not parse or link.
|
||||
Invalid,
|
||||
/// The profile has no description.
|
||||
Unnamed,
|
||||
/// The profile's description.
|
||||
Named(String),
|
||||
}
|
||||
|
||||
impl ProfileStatus {
|
||||
/// The status of a document whose embedded profile bytes are `icc` (`None` without one).
|
||||
pub fn of(icc: Option<&[u8]>) -> ProfileStatus {
|
||||
let Some(bytes) = icc else { return ProfileStatus::Untagged };
|
||||
let Ok(profile) = Profile::parse(bytes) else { return ProfileStatus::Invalid };
|
||||
let name: String = profile.description.chars().filter(|c| !c.is_control()).take(128).collect();
|
||||
let name = name.trim();
|
||||
if name.is_empty() { ProfileStatus::Unnamed } else { ProfileStatus::Named(name.to_owned()) }
|
||||
}
|
||||
|
||||
/// The text: the words' template with the mode word, or the name.
|
||||
pub fn label(&self, mode: ProfileMode, words: &ProfileWords) -> String {
|
||||
let template = match self {
|
||||
ProfileStatus::Untagged => &words.untagged,
|
||||
ProfileStatus::Invalid => &words.invalid,
|
||||
ProfileStatus::Unnamed => &words.unnamed,
|
||||
ProfileStatus::Named(name) => return name.clone(),
|
||||
};
|
||||
template.fill(&[("mode", mode.word(words))])
|
||||
}
|
||||
}
|
||||
|
||||
/// What the file asks.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum ProfileQuestion {
|
||||
/// The embedded profile differs from the working space; both names shown.
|
||||
#[non_exhaustive]
|
||||
Mismatch {
|
||||
/// The name of the profile embedded in the file.
|
||||
embedded: String,
|
||||
/// The name of the working space.
|
||||
working: String,
|
||||
},
|
||||
/// The file has no profile.
|
||||
#[non_exhaustive]
|
||||
Missing {
|
||||
/// The name of the working space.
|
||||
working: String,
|
||||
},
|
||||
}
|
||||
|
||||
impl ProfileQuestion {
|
||||
/// The embedded profile `embedded` differs from the working space `working`.
|
||||
pub fn mismatch(embedded: impl Into<String>, working: impl Into<String>) -> Self {
|
||||
ProfileQuestion::Mismatch { embedded: embedded.into(), working: working.into() }
|
||||
}
|
||||
|
||||
/// The file has no profile; `working` is the working space.
|
||||
pub fn missing(working: impl Into<String>) -> Self {
|
||||
ProfileQuestion::Missing { working: working.into() }
|
||||
}
|
||||
}
|
||||
|
||||
/// The user's choice.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
#[non_exhaustive]
|
||||
pub enum ProfileAction {
|
||||
/// Mismatch: keep the embedded profile.
|
||||
UseEmbedded,
|
||||
/// Mismatch: convert the pixels to the working space.
|
||||
ConvertToWorking,
|
||||
/// Mismatch: drop the profile (not colour managed).
|
||||
Discard,
|
||||
/// Missing: leave it untagged.
|
||||
LeaveAsIs,
|
||||
/// Missing: tag it with the working space.
|
||||
AssignWorking,
|
||||
}
|
||||
|
||||
/// 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)]
|
||||
#[non_exhaustive]
|
||||
pub struct ProfileAnswer {
|
||||
/// What the user chose.
|
||||
pub action: ProfileAction,
|
||||
/// Whether to apply the choice to later files of the same mode without asking.
|
||||
pub remember: bool,
|
||||
}
|
||||
|
||||
/// Photoshop's Embedded Profile Mismatch and Missing Profile prompt on the
|
||||
/// [`DialogHost`](craft_ui::dialog::DialogHost).
|
||||
///
|
||||
/// - The message (the file name last, so nothing in it reads as a placeholder; the missing form
|
||||
/// adds "Working: …" on its own line), then a radio group: Use the embedded profile (name),
|
||||
/// Convert to the working space (name), Discard the embedded profile; or for a missing
|
||||
/// profile Leave as is, Assign working space. The first is chosen at open unless the app
|
||||
/// gives its policy's action ([`action`](Self::action)).
|
||||
/// - With [`rememberable`](Self::rememberable) (a mismatch in a mode that has a policy), the
|
||||
/// "Remember this choice for future images" check box under the radios, with its tooltip.
|
||||
/// - OK answers [`ProfileAnswer`]; Cancel answers `DialogResult::Cancel`: the app stops opening
|
||||
/// this file and every file queued behind it (PhotoCraft).
|
||||
/// - Keyboard: arrows move in the radio group, Space toggles the box, Enter is OK, Esc Cancel.
|
||||
#[derive(craft_ui::contract::Pattern)]
|
||||
pub struct ProfileMismatchDialog {
|
||||
id: DialogId,
|
||||
file_name: String,
|
||||
mode: ProfileMode,
|
||||
question: ProfileQuestion,
|
||||
action: ProfileAction,
|
||||
rememberable: bool,
|
||||
remember: bool,
|
||||
open: bool,
|
||||
}
|
||||
|
||||
impl ProfileMismatchDialog {
|
||||
/// The prompt for `file_name` in `mode`.
|
||||
pub fn new(file_name: impl Into<String>, mode: ProfileMode, question: ProfileQuestion) -> ProfileMismatchDialog {
|
||||
let action = match question {
|
||||
ProfileQuestion::Mismatch { .. } => ProfileAction::UseEmbedded,
|
||||
ProfileQuestion::Missing { .. } => ProfileAction::LeaveAsIs,
|
||||
};
|
||||
ProfileMismatchDialog {
|
||||
id: dialog_id("profile-mismatch"),
|
||||
file_name: file_name.into(),
|
||||
mode,
|
||||
question,
|
||||
action,
|
||||
rememberable: false,
|
||||
remember: false,
|
||||
open: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// The action chosen at open (the app's policy for this mode).
|
||||
#[must_use]
|
||||
pub fn action(mut self, action: ProfileAction) -> ProfileMismatchDialog {
|
||||
self.action = action;
|
||||
self
|
||||
}
|
||||
|
||||
/// Offers "Remember this choice"; only for a mismatch (ignored for a missing profile).
|
||||
#[must_use]
|
||||
pub fn rememberable(mut self, on: bool) -> ProfileMismatchDialog {
|
||||
self.rememberable = on;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl StackDialog for ProfileMismatchDialog {
|
||||
type Result = ProfileAnswer;
|
||||
|
||||
fn id(&self) -> DialogId {
|
||||
self.id
|
||||
}
|
||||
|
||||
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 Self { file_name, mode, question, action, rememberable, remember, open, .. } = self;
|
||||
let mode_word = mode.word(&words);
|
||||
let name = file_name.as_str();
|
||||
let (title, message, choices, can_remember) = match &*question {
|
||||
ProfileQuestion::Mismatch { embedded, working } => {
|
||||
let message = words.mismatch_message.fill(&[("mode", mode_word), ("name", name)]);
|
||||
let choices = vec![
|
||||
(ProfileAction::UseEmbedded, Label::from(words.use_embedded.fill(&[("profile", embedded)]))),
|
||||
(ProfileAction::ConvertToWorking, Label::from(words.convert.fill(&[("profile", working)]))),
|
||||
(ProfileAction::Discard, words.discard.clone()),
|
||||
];
|
||||
(words.mismatch_title.clone(), message, choices, *rememberable)
|
||||
}
|
||||
ProfileQuestion::Missing { working } => {
|
||||
let what = words.missing_message.fill(&[("mode", mode_word), ("name", name)]);
|
||||
let message = format!("{what}\n{}", words.working.fill(&[("working", working)]));
|
||||
let choices = vec![(ProfileAction::LeaveAsIs, words.leave.clone()), (ProfileAction::AssignWorking, words.assign_working.clone())];
|
||||
(words.missing_title.clone(), message, choices, false)
|
||||
}
|
||||
};
|
||||
let group_label = title.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 shown = Prompt::new(title, message)
|
||||
.answers(answers)
|
||||
.extras(move |ui| {
|
||||
RadioGroup::new(group_label.clone(), Bind::bound(&mut *held)).show(ui, |ui, _| {
|
||||
for (value, text) in choices.iter().cloned() {
|
||||
Radio::new(value).label(text).show(ui);
|
||||
}
|
||||
});
|
||||
if can_remember {
|
||||
Checkbox::new(Bind::bound(&mut *ticked)).label(remember_label.clone()).tooltip(remember_tip.clone()).show(ui);
|
||||
}
|
||||
})
|
||||
.opened(Bind::bound(open))
|
||||
.show(ui);
|
||||
match shown.picked {
|
||||
Some(0) => Some(DialogResult::Ok(ProfileAnswer { action: *action, remember: *remember && can_remember })),
|
||||
Some(_) => Some(DialogResult::Cancel),
|
||||
None => None,
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
//! Stories of the profile prompts.
|
||||
|
||||
use super::{ProfileMismatchDialog, ProfileMode, ProfileQuestion};
|
||||
use craft_ui::dialog::{DialogStack, StackDialog as _};
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use egui::Ui;
|
||||
|
||||
fn shown(ui: &mut Ui, mut dialog: ProfileMismatchDialog) -> StoryOutput {
|
||||
let mut stack = DialogStack::default();
|
||||
stack.push(dialog.id(), None);
|
||||
let _ = dialog.show(ui, &stack);
|
||||
StoryOutput::default()
|
||||
}
|
||||
|
||||
#[story(ProfileMismatchDialog, covers = [Default], drive = Drive::Never)]
|
||||
fn profile_mismatch(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
let question = ProfileQuestion::Mismatch { embedded: "Display P3".into(), working: "sRGB IEC61966-2.1".into() };
|
||||
shown(ui, ProfileMismatchDialog::new("photo.psd", ProfileMode::Rgb, question).rememberable(true))
|
||||
}
|
||||
|
||||
#[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() };
|
||||
shown(ui, ProfileMismatchDialog::new("photo.psd", ProfileMode::Rgb, question))
|
||||
}
|
||||
@@ -0,0 +1,523 @@
|
||||
//! [`ColorRamp`]: the bar under a colour panel's slider rows, with white and black boxes at its end.
|
||||
|
||||
use super::channels::primary;
|
||||
use craft_behavior::{Axis, Metrics, NavMove, PartKey, PressPhase, Sense};
|
||||
use craft_theme::{Hsb, Srgba};
|
||||
use craft_ui::canvas::context_click;
|
||||
use craft_ui::contract::{
|
||||
Access, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Focus as _, Input, Name, Outcome, PaintUi, PartsCx, Pointer as _,
|
||||
Props as _, Remember as _, Role, WordSetCx as _,
|
||||
};
|
||||
use craft_ui::primitives::{PaintShape, StrokeWidth};
|
||||
use craft_ui::runtime::commands::FireSource;
|
||||
use craft_ui::runtime::env::Label;
|
||||
use craft_ui::runtime::focus::{KeepKeys, KeyUse};
|
||||
use craft_ui::style::{ComponentStyle, DataColor, FocusLook, StyleColor, StyleCx};
|
||||
use egui::{Color32, CornerRadius, Mesh, Pos2, Rect, Response, Vec2, pos2};
|
||||
use std::hash::{DefaultHasher, Hash, Hasher};
|
||||
use std::sync::Arc;
|
||||
|
||||
#[cfg(feature = "screen-testing")]
|
||||
mod stories;
|
||||
|
||||
/// The bar: a press picks the colour under the pointer.
|
||||
const BAR: PartKey = PartKey::new("bar");
|
||||
/// The white box at the end.
|
||||
const WHITE: PartKey = PartKey::new("white");
|
||||
/// The black box at the end.
|
||||
const BLACK: PartKey = PartKey::new("black");
|
||||
|
||||
/// Columns of the ramp grid.
|
||||
const CELLS_X: usize = 48;
|
||||
/// Rows of the ramp grid.
|
||||
const CELLS_Y: usize = 8;
|
||||
/// Cells a Shift arrow moves.
|
||||
const FAR: i64 = 10;
|
||||
|
||||
craft_ui::words! {
|
||||
/// The words of colour ramps.
|
||||
pub struct ColorRampWords {
|
||||
white: "colorRamp.white" = "White";
|
||||
black: "colorRamp.black" = "Black";
|
||||
}
|
||||
}
|
||||
|
||||
/// The style of a colour ramp.
|
||||
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
|
||||
#[non_exhaustive]
|
||||
pub struct ColorRampStyle {
|
||||
#[style(metrics)]
|
||||
metrics: Metrics,
|
||||
#[style(focus)]
|
||||
focus: FocusLook,
|
||||
/// The edge round the bar and the boxes.
|
||||
edge: StyleColor,
|
||||
/// The side of an end box.
|
||||
boxes: f32,
|
||||
/// The gap between the bar and the boxes.
|
||||
boxes_gap: f32,
|
||||
/// The diameter of the cursor cell's marker.
|
||||
marker: f32,
|
||||
}
|
||||
|
||||
/// Which colours the ramp shows.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
#[non_exhaustive]
|
||||
pub enum RampKind {
|
||||
/// Hue across; white at the top through the full colour in the middle to black at the bottom.
|
||||
#[default]
|
||||
Spectrum,
|
||||
/// The [`Spectrum`](RampKind::Spectrum) in the host's CMYK gamut: each colour goes through
|
||||
/// [`gamut`](ColorRamp::gamut) (a CMYK round trip). Without a `gamut` it is the spectrum.
|
||||
CmykSpectrum,
|
||||
/// White at the left to black at the right.
|
||||
Grayscale,
|
||||
/// From one colour at the left to another at the right, in encoded sRGB ([`ends`](ColorRamp::ends)).
|
||||
Between,
|
||||
}
|
||||
|
||||
/// A colour the ramp picked.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct RampPick {
|
||||
/// The picked colour.
|
||||
pub color: Srgba,
|
||||
/// Alt was held at the press (or at the click or box press): the host sets the colour it is not editing.
|
||||
pub other: bool,
|
||||
}
|
||||
|
||||
impl RampPick {
|
||||
/// A pick of `color`, with `other` when Alt was held.
|
||||
pub const fn new(color: Srgba, other: bool) -> Self {
|
||||
RampPick { color, other }
|
||||
}
|
||||
}
|
||||
|
||||
/// Maps a spectrum colour to the host's gamut: `ColorRamp::gamut`.
|
||||
pub struct Gamut<'a>(Box<dyn Fn(Srgba) -> Srgba + 'a>);
|
||||
|
||||
impl<'a> Gamut<'a> {
|
||||
/// The gamut that runs `map`.
|
||||
pub fn new(map: impl Fn(Srgba) -> Srgba + 'a) -> Self {
|
||||
Gamut(Box::new(map))
|
||||
}
|
||||
}
|
||||
|
||||
/// What [`ColorRamp`] returns.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
pub struct ColorRampOutput {
|
||||
/// The pick, through the edit lifecycle. The ramp has no value of the host's to compare with, so every pick is a
|
||||
/// change.
|
||||
pub edit: EditResponse<RampPick>,
|
||||
/// A click with Shift: the host moves to its next ramp. Nothing was picked.
|
||||
pub cycle: bool,
|
||||
/// A secondary click that began and ended on the bar: where the host opens its menu.
|
||||
pub menu_at: Option<Pos2>,
|
||||
}
|
||||
|
||||
impl Outcome for ColorRampOutput {
|
||||
type Value = RampPick;
|
||||
|
||||
fn response(&self) -> &Response {
|
||||
&self.edit.response
|
||||
}
|
||||
|
||||
#[cfg(feature = "screen-testing")]
|
||||
fn story_facts(&self) -> craft_ui::testing::StoryOutput {
|
||||
self.edit.story_facts()
|
||||
}
|
||||
}
|
||||
|
||||
/// What a press began with, kept for its gesture.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct Held {
|
||||
shift: bool,
|
||||
alt: bool,
|
||||
/// The ends of a Between ramp at the press.
|
||||
ends: Option<[Srgba; 2]>,
|
||||
}
|
||||
|
||||
/// The cursor cell: column and row.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct Cursor(Option<(usize, usize)>);
|
||||
|
||||
/// The colours of the mesh, with what they were computed for.
|
||||
#[derive(Clone, Default)]
|
||||
struct Cache {
|
||||
signature: u64,
|
||||
colors: Arc<Vec<Color32>>,
|
||||
}
|
||||
|
||||
/// The bar under the Color panel's slider rows (Photoshop's colour ramp): a spectrum, a grey ramp or a ramp between
|
||||
/// two colours, with a white and a black box at its end.
|
||||
///
|
||||
/// The bar is 48 by 8 cells, shaded between the vertices of a 49 by 9 grid; a [`web_safe`](ColorRamp::web_safe) ramp
|
||||
/// is flat cells coloured at their centres. Hue is a function of x only, so a pick carries hue and saturation. The
|
||||
/// colours are computed when the kind, ends, web flag or [`gamut_revision`](ColorRamp::gamut_revision) change, and
|
||||
/// kept.
|
||||
///
|
||||
/// - Pointer: a click picks the colour under the pointer (the cell's centre on a web-safe ramp); a drag picks while it
|
||||
/// 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
|
||||
/// [`menu_at`](ColorRampOutput::menu_at).
|
||||
/// - Boxes: a click on the white or the black box (also by keyboard) is a `Set` of that colour; they are Tab stops of
|
||||
/// their own.
|
||||
/// - Keys, with the bar focused: it has a cursor cell, starting at the left end of the middle row. Arrows move it one
|
||||
/// cell (Shift ten), Home and End to the row's ends, Page Up and Page Down to the top and bottom rows. Enter or Space picks the cursor cell. A press moves the cursor to its cell.
|
||||
/// - AccessKit: the bar is a `Group` named `label` whose value is [`kind_name`](ColorRamp::kind_name); the boxes are
|
||||
/// `Button`s.
|
||||
/// - Nothing mirrors right to left; the boxes stay at the right.
|
||||
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
|
||||
#[component(content_painter)]
|
||||
pub struct ColorRamp<'a> {
|
||||
#[common]
|
||||
common: Common,
|
||||
kind: RampKind,
|
||||
pick: Bind<'a, RampPick>,
|
||||
/// The colours at the left and the right of a [`Between`](RampKind::Between) ramp; black and white without them.
|
||||
#[prop]
|
||||
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")]
|
||||
gamut: Option<Gamut<'a>>,
|
||||
/// The host's counter for the working space `gamut` maps into; a change recomputes the colours.
|
||||
#[prop]
|
||||
gamut_revision: u64,
|
||||
/// Whether every channel is rounded to the nearest of 0, 0.2, ... 1 and the ramp is flat cells.
|
||||
#[prop]
|
||||
web_safe: bool,
|
||||
/// Whether the white and black boxes follow the bar; on by default.
|
||||
#[prop]
|
||||
boxes: bool,
|
||||
/// The ramp's kind as the host names it ("RGB Spectrum"), the bar's accessible value.
|
||||
#[prop(into)]
|
||||
kind_name: Option<Label>,
|
||||
colors: Arc<Vec<Color32>>,
|
||||
shown_ends: [Srgba; 2],
|
||||
cursor: (usize, usize),
|
||||
cycle: bool,
|
||||
menu_at: Option<Pos2>,
|
||||
}
|
||||
|
||||
impl<'a> ColorRamp<'a> {
|
||||
/// A ramp named `label` ("Color ramp") of `kind`, reporting its picks through `pick`.
|
||||
pub fn new(label: impl Into<Label>, kind: RampKind, pick: Bind<'a, RampPick>) -> Self {
|
||||
let ends = Self::default_ends();
|
||||
ColorRamp {
|
||||
common: Common::new(),
|
||||
kind,
|
||||
pick,
|
||||
ends: None,
|
||||
gamut: None,
|
||||
gamut_revision: 0,
|
||||
web_safe: false,
|
||||
boxes: true,
|
||||
kind_name: None,
|
||||
colors: Arc::default(),
|
||||
shown_ends: ends,
|
||||
cursor: (0, CELLS_Y / 2),
|
||||
cycle: false,
|
||||
menu_at: None,
|
||||
}
|
||||
.label(label)
|
||||
.ltr_axis()
|
||||
}
|
||||
|
||||
fn default_ends() -> [Srgba; 2] {
|
||||
[Srgba::rgb(0.0, 0.0, 0.0), Srgba::rgb(1.0, 1.0, 1.0)]
|
||||
}
|
||||
|
||||
/// The colour at (`x`, `y`) as fractions of the bar, `y` down. A non-finite or outside fraction is clamped into
|
||||
/// the bar. Spectrum: hue `x` (below 360), white at the top through the full colour at the middle to black at the
|
||||
/// bottom, through `gamut` when given; grayscale: white to black; between: `ends` from the left to the right.
|
||||
/// `web_safe` rounds each channel.
|
||||
pub fn color_at(kind: RampKind, web_safe: bool, gamut: Option<&dyn Fn(Srgba) -> Srgba>, ends: [Srgba; 2], x: f32, y: f32) -> Srgba {
|
||||
let unit = |v: f32| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
|
||||
let (x, y) = (unit(x), unit(y));
|
||||
let color = match kind {
|
||||
RampKind::Spectrum | RampKind::CmykSpectrum => {
|
||||
let (s, b) = if y < 0.5 { (y * 2.0, 1.0) } else { (1.0, 1.0 - (y - 0.5) * 2.0) };
|
||||
let color = Srgba::from_hsb(Hsb { h: x.min(0.9999) * 360.0, s, b });
|
||||
gamut.map_or(color, |g| g(color))
|
||||
}
|
||||
RampKind::Grayscale => Srgba::new(1.0 - x, 1.0 - x, 1.0 - x, 1.0),
|
||||
RampKind::Between => {
|
||||
let [a, b] = ends;
|
||||
let mix = |from: f32, to: f32| from + (to - from) * x;
|
||||
Srgba::new(mix(a.r, b.r), mix(a.g, b.g), mix(a.b, b.b), mix(a.a, b.a))
|
||||
}
|
||||
};
|
||||
let web = |v: f32| if web_safe { (unit(v) * 5.0).round() / 5.0 } else { unit(v) };
|
||||
Srgba::new(web(color.r), web(color.g), web(color.b), unit(color.a))
|
||||
}
|
||||
|
||||
fn gamut_fn(&self) -> Option<&dyn Fn(Srgba) -> Srgba> {
|
||||
self.gamut.as_ref().map(|gamut| &*gamut.0)
|
||||
}
|
||||
|
||||
/// The pick at the fractions (`fx`, `fy`) of the bar.
|
||||
fn pick_at(&self, ends: [Srgba; 2], fx: f32, fy: f32, other: bool) -> RampPick {
|
||||
let (fx, fy) = if self.web_safe { cell_centre(fx, fy) } else { (fx, fy) };
|
||||
RampPick::new(Self::color_at(self.kind, self.web_safe, self.gamut_fn(), ends, fx, fy), other)
|
||||
}
|
||||
|
||||
/// The bar's rect and the boxes' in the room `rect`.
|
||||
fn layout(&self, rect: Rect, style: &ColorRampStyle) -> (Rect, Rect) {
|
||||
let boxes_width = if self.boxes { style.boxes.min(rect.width() / 2.0) } else { 0.0 };
|
||||
let gap = if self.boxes { style.boxes_gap } else { 0.0 };
|
||||
let bar = Rect::from_min_max(rect.min, pos2((rect.right() - boxes_width - gap).max(rect.left()), rect.bottom()));
|
||||
(bar, Rect::from_min_max(pos2(rect.right() - boxes_width, rect.top()), rect.max))
|
||||
}
|
||||
|
||||
/// The colours of the mesh for `ends`: 49 by 9 vertices, or 48 by 8 cell centres for a web-safe ramp.
|
||||
fn colors(&self, cache: &mut Cache, ends: [Srgba; 2]) -> Arc<Vec<Color32>> {
|
||||
let mut hasher = DefaultHasher::new();
|
||||
(self.kind, self.web_safe).hash(&mut hasher);
|
||||
if self.kind == RampKind::Between {
|
||||
ends.iter().for_each(|c| [c.r, c.g, c.b, c.a].map(f32::to_bits).hash(&mut hasher));
|
||||
}
|
||||
if matches!(self.kind, RampKind::Spectrum | RampKind::CmykSpectrum) {
|
||||
(self.gamut.is_some(), self.gamut_revision).hash(&mut hasher);
|
||||
}
|
||||
let signature = hasher.finish();
|
||||
if cache.signature == signature && !cache.colors.is_empty() {
|
||||
return cache.colors.clone();
|
||||
}
|
||||
let (cols, rows, half) = if self.web_safe { (CELLS_X, CELLS_Y, 0.5) } else { (CELLS_X + 1, CELLS_Y + 1, 0.0) };
|
||||
let mut colors = Vec::with_capacity(cols * rows);
|
||||
for row in 0..rows {
|
||||
for col in 0..cols {
|
||||
let (x, y) = ((col as f32 + half) / CELLS_X as f32, (row as f32 + half) / CELLS_Y as f32);
|
||||
colors.push(Color32::from(Self::color_at(self.kind, self.web_safe, self.gamut_fn(), ends, x, y)));
|
||||
}
|
||||
}
|
||||
*cache = Cache { signature, colors: Arc::new(colors) };
|
||||
cache.colors.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// `pos` as fractions of `bar`, kept inside it.
|
||||
fn fractions(bar: Rect, pos: Pos2) -> (f32, f32) {
|
||||
let along = |p: f32, from: f32, length: f32| if length > 0.0 && p.is_finite() { ((p - from) / length).clamp(0.0, 1.0) } else { 0.0 };
|
||||
(along(pos.x, bar.left(), bar.width()), along(pos.y, bar.top(), bar.height()))
|
||||
}
|
||||
|
||||
/// The cell of the grid under the fractions (`fx`, `fy`).
|
||||
fn cell_of(fx: f32, fy: f32) -> (usize, usize) {
|
||||
(((fx * CELLS_X as f32) as usize).min(CELLS_X - 1), ((fy * CELLS_Y as f32) as usize).min(CELLS_Y - 1))
|
||||
}
|
||||
|
||||
/// The centre of the cell holding the fractions (`fx`, `fy`).
|
||||
fn cell_centre(fx: f32, fy: f32) -> (f32, f32) {
|
||||
let (col, row) = cell_of(fx, fy);
|
||||
centre_of((col, row))
|
||||
}
|
||||
|
||||
/// The centre of `cell` as fractions of the bar.
|
||||
fn centre_of(cell: (usize, usize)) -> (f32, f32) {
|
||||
((cell.0 as f32 + 0.5) / CELLS_X as f32, (cell.1 as f32 + 0.5) / CELLS_Y as f32)
|
||||
}
|
||||
|
||||
/// The cursor after the key `mv`: arrows one cell (ten with `far`), Home and End the row's ends, Page Up and Page Down
|
||||
/// the top and bottom rows.
|
||||
fn moved(cursor: (usize, usize), mv: NavMove, far: bool) -> (usize, usize) {
|
||||
let by = if far { FAR } else { 1 };
|
||||
let along = |at: usize, delta: i64, n: usize| (at as i64 + delta).clamp(0, n as i64 - 1) as usize;
|
||||
match mv {
|
||||
NavMove::Forward => (along(cursor.0, by, CELLS_X), cursor.1),
|
||||
NavMove::Back => (along(cursor.0, -by, CELLS_X), cursor.1),
|
||||
NavMove::Down => (cursor.0, along(cursor.1, by, CELLS_Y)),
|
||||
NavMove::Up => (cursor.0, along(cursor.1, -by, CELLS_Y)),
|
||||
NavMove::Start => (0, cursor.1),
|
||||
NavMove::End => (CELLS_X - 1, cursor.1),
|
||||
NavMove::PageUp => (cursor.0, 0),
|
||||
NavMove::PageDown => (cursor.0, CELLS_Y - 1),
|
||||
_ => cursor,
|
||||
}
|
||||
}
|
||||
|
||||
impl Component for ColorRamp<'_> {
|
||||
const SINGLE_VALUE: bool = true;
|
||||
const ROLE: Role = Role::GROUP;
|
||||
const OVERLAYS: bool = false;
|
||||
const KEYS: KeyUse = KeyUse::of(Input::Pointer).with_keep(KeepKeys::BlockArrows);
|
||||
type Style = ColorRampStyle;
|
||||
type Output = ColorRampOutput;
|
||||
|
||||
fn style(cx: &StyleCx<'_>, _: ColorRampStyleKey) -> ColorRampStyle {
|
||||
let tokens = cx.tokens;
|
||||
ColorRampStyle {
|
||||
metrics: Metrics::new().min_size(Vec2::new(tokens.size.length.track, tokens.size.thumb.lg)),
|
||||
focus: cx.focus_look(),
|
||||
edge: cx.color(tokens.color.line.control_edge),
|
||||
boxes: tokens.size.icon.lg,
|
||||
boxes_gap: tokens.space.gap.tight,
|
||||
marker: tokens.size.handle.md,
|
||||
}
|
||||
}
|
||||
|
||||
fn fills(&self) -> Option<Axis> {
|
||||
Some(Axis::X)
|
||||
}
|
||||
|
||||
fn sense(&self) -> Sense {
|
||||
Sense::empty()
|
||||
}
|
||||
|
||||
fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) {
|
||||
let (bar, boxes) = self.layout(rect, cx.style);
|
||||
cx.part(BAR, bar).sense(Sense::DRAG | Sense::CLICK).focusable().value_part();
|
||||
if self.boxes {
|
||||
let half = boxes.center().y;
|
||||
cx.part(WHITE, Rect::from_min_max(boxes.min, pos2(boxes.right(), half))).sense(Sense::CLICK).focusable();
|
||||
cx.part(BLACK, Rect::from_min_max(pos2(boxes.left(), half), boxes.max)).sense(Sense::CLICK).focusable();
|
||||
}
|
||||
}
|
||||
|
||||
fn bind(&mut self) -> Option<BindMut<'_, RampPick>> {
|
||||
Some(self.pick.reborrow())
|
||||
}
|
||||
|
||||
fn update(&mut self, cx: &mut Cx<'_, Self>) {
|
||||
let (bar, _) = self.layout(cx.rect, cx.style);
|
||||
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) };
|
||||
}
|
||||
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) {
|
||||
let at = |pos: Pos2| fractions(bar, pos);
|
||||
match press.phase {
|
||||
PressPhase::DragStart { pos, .. } if !held.shift => {
|
||||
let (fx, fy) = at(pos);
|
||||
cursor = cell_of(fx, fy);
|
||||
cx.begin();
|
||||
cx.propose(self.pick_at(ends, fx, fy, held.alt));
|
||||
}
|
||||
PressPhase::Drag { pos, .. } if !held.shift && cx.gesture().is_some() => {
|
||||
let (fx, fy) = at(pos);
|
||||
cursor = cell_of(fx, fy);
|
||||
cx.propose(self.pick_at(ends, fx, fy, held.alt));
|
||||
}
|
||||
PressPhase::Release { pos, click, .. } => {
|
||||
let (fx, fy) = at(pos);
|
||||
if cx.gesture().is_some() {
|
||||
cx.propose(self.pick_at(ends, fx, fy, held.alt));
|
||||
cx.commit();
|
||||
} else if click {
|
||||
cursor = cell_of(fx, fy);
|
||||
if held.shift {
|
||||
self.cycle = true;
|
||||
} else {
|
||||
cx.set(self.pick_at(ends, fx, fy, held.alt));
|
||||
}
|
||||
}
|
||||
if !held.shift {
|
||||
cursor = cell_of(fx, fy);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
self.menu_at = context_click(&press);
|
||||
let bar_active = cx.active_part() == Some(BAR.into());
|
||||
while let Some((mv, mods)) = cx.intents().take_move() {
|
||||
if bar_active && !running {
|
||||
cursor = moved(cursor, mv, mods.extend);
|
||||
}
|
||||
}
|
||||
if !running && matches!(cx.part_activated(BAR), Some(FireSource::Key | FireSource::Access)) {
|
||||
let (fx, fy) = centre_of(cursor);
|
||||
cx.set(self.pick_at(ends, fx, fy, false));
|
||||
}
|
||||
for (key, color) in [(WHITE, Srgba::rgb(1.0, 1.0, 1.0)), (BLACK, Srgba::rgb(0.0, 0.0, 0.0))] {
|
||||
if cx.part_activated(key).is_some() {
|
||||
let other = cx.part(key).press.mods.alt;
|
||||
cx.set(RampPick::new(color, other));
|
||||
}
|
||||
}
|
||||
cx.memory::<Cursor>().0 = Some(cursor);
|
||||
self.cursor = cursor;
|
||||
let mut cache = std::mem::take(cx.memory::<Cache>());
|
||||
self.colors = self.colors(&mut cache, ends);
|
||||
*cx.memory::<Cache>() = cache;
|
||||
}
|
||||
|
||||
fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) {
|
||||
let words = cx.words::<ColorRampWords>();
|
||||
let bar = access.node(BAR, Role::GROUP);
|
||||
bar.name = Name::Text(cx.env.resolve(&cx.label()).as_str().to_owned());
|
||||
if let Some(kind) = &self.kind_name {
|
||||
bar.value(cx.env.resolve(kind).as_str().to_owned());
|
||||
}
|
||||
if self.boxes {
|
||||
access.node(WHITE, Role::BUTTON).name = Name::Text(words.white.as_str().to_owned());
|
||||
access.node(BLACK, Role::BUTTON).name = Name::Text(words.black.as_str().to_owned());
|
||||
}
|
||||
}
|
||||
|
||||
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
|
||||
let (bar, boxes) = self.layout(cx.rect, cx.style);
|
||||
let painter = ui.content_painter(cx);
|
||||
painter.painter.add(ramp_mesh(bar, &self.colors, self.web_safe));
|
||||
let draw = ui.draw();
|
||||
draw.stroke(&PaintShape::Rect(bar, CornerRadius::ZERO), StrokeWidth::Thin, cx.style.edge);
|
||||
if cx.focus_visible() && cx.active_part() == Some(BAR.into()) {
|
||||
let (fx, fy) = centre_of(self.cursor);
|
||||
let at = pos2(bar.left() + bar.width() * fx, bar.top() + bar.height() * fy);
|
||||
painter.outline(&PaintShape::Circle(at, cx.style.marker / 2.0));
|
||||
}
|
||||
if self.boxes {
|
||||
let half = boxes.center().y;
|
||||
let white = Rect::from_min_max(boxes.min, pos2(boxes.right(), half));
|
||||
let black = Rect::from_min_max(pos2(boxes.left(), half), boxes.max);
|
||||
draw.data_fill(&PaintShape::Rect(white, CornerRadius::ZERO), DataColor::new(Color32::from(Srgba::WHITE)));
|
||||
draw.data_fill(&PaintShape::Rect(black, CornerRadius::ZERO), DataColor::new(Color32::from(Srgba::BLACK)));
|
||||
draw.stroke(&PaintShape::Rect(boxes, CornerRadius::ZERO), StrokeWidth::Thin, cx.style.edge);
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> ColorRampOutput {
|
||||
let (cycle, menu_at) = (self.cycle, self.menu_at);
|
||||
ColorRampOutput { edit: cx.edit_response(), cycle, menu_at }
|
||||
}
|
||||
}
|
||||
|
||||
/// The ramp mesh over `bar`: shaded between the vertices, or flat cells when web safe.
|
||||
fn ramp_mesh(bar: Rect, colors: &[Color32], flat: bool) -> Mesh {
|
||||
let mut mesh = Mesh::default();
|
||||
let at = |i: usize, j: usize| pos2(bar.left() + bar.width() * i as f32 / CELLS_X as f32, bar.top() + bar.height() * j as f32 / CELLS_Y as f32);
|
||||
if flat {
|
||||
for j in 0..CELLS_Y {
|
||||
for i in 0..CELLS_X {
|
||||
let color = colors.get(j * CELLS_X + i).copied().unwrap_or(Color32::from(Srgba::BLACK));
|
||||
mesh.add_colored_rect(Rect::from_min_max(at(i, j), at(i + 1, j + 1)), color);
|
||||
}
|
||||
}
|
||||
return mesh;
|
||||
}
|
||||
for j in 0..=CELLS_Y {
|
||||
for i in 0..=CELLS_X {
|
||||
mesh.colored_vertex(at(i, j), colors.get(j * (CELLS_X + 1) + i).copied().unwrap_or(Color32::from(Srgba::BLACK)));
|
||||
}
|
||||
}
|
||||
let row = (CELLS_X + 1) as u32;
|
||||
for j in 0..CELLS_Y as u32 {
|
||||
for i in 0..CELLS_X as u32 {
|
||||
let a = j * row + i;
|
||||
mesh.add_triangle(a, a + 1, a + row + 1);
|
||||
mesh.add_triangle(a, a + row + 1, a + row);
|
||||
}
|
||||
}
|
||||
mesh
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
//! Stories of `ColorRamp`: the spectrum, a grey ramp, a ramp between two colours and a web-safe one.
|
||||
|
||||
use super::{ColorRamp, RampKind, RampPick};
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::contract::{Bind, Show as _, Validity};
|
||||
use craft_ui::runtime::env::Message;
|
||||
use craft_ui::testing::{Drive, Grip, StoryData, StoryOutput, story};
|
||||
use egui::Ui;
|
||||
|
||||
fn pick() -> RampPick {
|
||||
RampPick::new(Srgba::rgb(0.2, 0.5, 0.8), false)
|
||||
}
|
||||
|
||||
#[story(ColorRamp<'static>, covers = [Default], drive = Drive::Drag(Grip::new(super::BAR)))]
|
||||
fn color_ramp(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
ColorRamp::new("Color ramp", RampKind::Spectrum, Bind::bound(data.value("pick", pick()))).kind_name("RGB Spectrum").show(ui).into()
|
||||
}
|
||||
|
||||
#[story(ColorRamp<'static>, covers = [], drive = Drive::Never)]
|
||||
fn color_ramp_grayscale(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
ColorRamp::new("Color ramp", RampKind::Grayscale, Bind::bound(data.value("pick", pick()))).kind_name("Grayscale").show(ui).into()
|
||||
}
|
||||
|
||||
#[story(ColorRamp<'static>, covers = [], drive = Drive::Never)]
|
||||
fn color_ramp_between(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
ColorRamp::new("Color ramp", RampKind::Between, Bind::bound(data.value("pick", pick())))
|
||||
.ends([Srgba::rgb(0.9, 0.2, 0.1), Srgba::rgb(0.1, 0.3, 0.9)])
|
||||
.kind_name("Foreground to background")
|
||||
.show(ui)
|
||||
.into()
|
||||
}
|
||||
|
||||
#[story(ColorRamp<'static>, covers = [], drive = Drive::Never)]
|
||||
fn color_ramp_web_safe(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
ColorRamp::new("Color ramp", RampKind::Spectrum, Bind::bound(data.value("pick", pick()))).web_safe(true).kind_name("Web colors").show(ui).into()
|
||||
}
|
||||
|
||||
#[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 };
|
||||
let dark = RampPick::new(Srgba::rgb(0.1, 0.1, 0.1), false);
|
||||
ColorRamp::new("Color ramp", RampKind::Spectrum, Bind::bound(data.value("pick", dark)).check(refuse_dark))
|
||||
.kind_name("RGB Spectrum")
|
||||
.show(ui)
|
||||
.into()
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
//! `ColorReadout`: a colour as a hex field and editable R, G and B fields (the readout of a Color panel).
|
||||
|
||||
#[cfg(feature = "screen-testing")]
|
||||
mod stories;
|
||||
|
||||
use craft_behavior::{ColumnWidth, EditEvent, EditEvents, Mixed};
|
||||
use craft_theme::Rgba;
|
||||
use craft_ui::contract::{Bind, Outcome, Pattern, Props as _, Show as _, ShowContainer as _};
|
||||
use craft_ui::layout_components::{Grid, Stack};
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
use craft_ui::text::{NumberField, TextField};
|
||||
use egui::{Response, Ui};
|
||||
|
||||
/// The hex field and the three channel fields share the room equally, so the row fits a narrow panel.
|
||||
const FIELDS: &[ColumnWidth] = &[ColumnWidth::fill(1.0); 4];
|
||||
|
||||
/// The channels the fields edit, in field order.
|
||||
const CHANNELS: [ReadoutChannel; 3] = [ReadoutChannel::Red, ReadoutChannel::Green, ReadoutChannel::Blue];
|
||||
|
||||
craft_ui::words! {
|
||||
/// The readout's words, English by default.
|
||||
#[non_exhaustive]
|
||||
pub struct ColorReadoutWords {
|
||||
/// The hex field's accessible name.
|
||||
hex: "colorReadout.hex" = "Hex color";
|
||||
/// The red field's accessible name.
|
||||
red: "colorReadout.red" = "Red";
|
||||
/// The green field's accessible name.
|
||||
green: "colorReadout.green" = "Green";
|
||||
/// The blue field's accessible name.
|
||||
blue: "colorReadout.blue" = "Blue";
|
||||
}
|
||||
}
|
||||
|
||||
/// A channel of the readout.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum ReadoutChannel {
|
||||
/// Red.
|
||||
Red,
|
||||
/// Green.
|
||||
Green,
|
||||
/// Blue.
|
||||
Blue,
|
||||
}
|
||||
|
||||
impl ReadoutChannel {
|
||||
/// The channel's place in an [`Rgba`].
|
||||
pub const fn index(self) -> usize {
|
||||
self as usize
|
||||
}
|
||||
}
|
||||
|
||||
/// An edit of one channel of a mixed colour: the host sets that channel of every item and keeps their other channels
|
||||
/// and their alpha. The value is `None` while the field holds text that is not a number.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
pub struct ChannelEdit {
|
||||
/// The channel the field edits.
|
||||
pub channel: ReadoutChannel,
|
||||
/// The field's edit, as the field reports it.
|
||||
pub event: EditEvent<Option<u8>>,
|
||||
}
|
||||
|
||||
/// What a [`ColorReadout`] reports.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
#[must_use = "the host applies the edit"]
|
||||
pub struct ColorReadoutOutput {
|
||||
/// The readout's response.
|
||||
pub response: Response,
|
||||
/// The pass's edits of the whole colour, in order; empty when nothing was edited. A channel field edits the
|
||||
/// whole colour only while the value is the same for every item; the hex field always does.
|
||||
pub events: EditEvents<Rgba>,
|
||||
/// The pass's edits of one channel while the value is mixed, in order; empty when no channel field was edited or
|
||||
/// the value is the same for every item.
|
||||
pub channel: Vec<ChannelEdit>,
|
||||
}
|
||||
|
||||
impl Outcome for ColorReadoutOutput {
|
||||
type Value = Rgba;
|
||||
|
||||
fn response(&self) -> &Response {
|
||||
&self.response
|
||||
}
|
||||
|
||||
#[cfg(feature = "screen-testing")]
|
||||
fn story_facts(&self) -> craft_ui::testing::StoryOutput {
|
||||
let mut facts = craft_ui::testing::StoryOutput::default();
|
||||
facts.id = Some(self.response.id);
|
||||
facts.edits = self
|
||||
.events
|
||||
.iter()
|
||||
.filter_map(craft_ui::testing::EditKind::of)
|
||||
.chain(self.channel.iter().filter_map(|edit| craft_ui::testing::EditKind::of(&edit.event)))
|
||||
.collect();
|
||||
facts
|
||||
}
|
||||
}
|
||||
|
||||
/// A colour as a hex field and three number fields (R, G, B, each 0 to 255), in one row. An edit in any field
|
||||
/// reports the whole colour, with the other channels and the alpha as given. While the value is mixed, the hex field
|
||||
/// still sets the whole colour and a channel field reports that channel alone ([`ColorReadoutOutput::channel`]), for
|
||||
/// the host to set on each item. Each field's gesture is the readout's.
|
||||
///
|
||||
/// AccessKit: a group named by the label, the hex field "Hex color" and a spin button per channel named by its
|
||||
/// colour.
|
||||
#[must_use = "show the readout with `show`"]
|
||||
#[derive(Pattern)]
|
||||
pub struct ColorReadout<'a> {
|
||||
label: Label,
|
||||
value: Bind<'a, Rgba>,
|
||||
shared: [Mixed<u8>; 3],
|
||||
}
|
||||
|
||||
impl<'a> ColorReadout<'a> {
|
||||
/// A readout of `value` named `label`.
|
||||
pub fn new(label: impl Into<Label>, value: Bind<'a, Rgba>) -> Self {
|
||||
ColorReadout { label: label.into(), value, shared: [Mixed::Mixed; 3] }
|
||||
}
|
||||
|
||||
/// The channels (red, green, blue, in [`Rgba`] order) that are the same in every item while the value is mixed,
|
||||
/// computed by the host: a channel field shows its shared number and the others show Mixed, as Photoshop's Info
|
||||
/// and Color panels do. Ignored while the value is the same for every item.
|
||||
pub fn shared_channels(mut self, shared: [Mixed<u8>; 3]) -> Self {
|
||||
self.shared = shared;
|
||||
self
|
||||
}
|
||||
|
||||
/// Shows the readout.
|
||||
pub fn show(self, ui: &mut Ui) -> ColorReadoutOutput {
|
||||
let ColorReadout { label, mut value, shared } = self;
|
||||
let words = Env::of(ui).words::<ColorReadoutWords>();
|
||||
let shown = Stack::new().label(label).show(ui, |ui, body| {
|
||||
let held: Mixed<Rgba> = value.reborrow().read(&mut *body).unwrap_or(Mixed::Mixed);
|
||||
let mut events: Vec<EditEvent<Rgba>> = Vec::new();
|
||||
let mut channel_edits = Vec::new();
|
||||
Grid::new(FIELDS).show(ui, |ui, _| {
|
||||
events.clear();
|
||||
channel_edits.clear();
|
||||
events.extend(TextField::hex(words.hex.as_str().to_owned(), Bind::given(held)).show(ui).events);
|
||||
let names = [&words.red, &words.green, &words.blue];
|
||||
for (i, name) in names.into_iter().enumerate() {
|
||||
let field = NumberField::new(
|
||||
name.as_str().to_owned(),
|
||||
Bind::given(match held {
|
||||
Mixed::Same(color) => Mixed::Same(Some(f64::from(color.0[i]))),
|
||||
Mixed::Mixed => match shared[i] {
|
||||
Mixed::Same(byte) => Mixed::Same(Some(f64::from(byte))),
|
||||
Mixed::Mixed => Mixed::Mixed,
|
||||
},
|
||||
}),
|
||||
)
|
||||
.range(0.0..=255.0)
|
||||
.step(1.0)
|
||||
.snap_typed(true)
|
||||
.commit_decimals(0);
|
||||
let byte = |number: Option<f64>| number.map(|number| number.round().clamp(0.0, 255.0) as u8);
|
||||
let out = field.show(ui);
|
||||
for event in &out.events {
|
||||
match held {
|
||||
Mixed::Same(base) => events.push(event.clone().map(move |number| {
|
||||
let mut mine = base;
|
||||
if let Some(byte) = byte(number) {
|
||||
mine.0[i] = byte;
|
||||
}
|
||||
mine
|
||||
})),
|
||||
Mixed::Mixed => channel_edits.push(ChannelEdit { channel: CHANNELS[i], event: event.clone().map(byte) }),
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
for event in &events {
|
||||
let _ = value.reborrow().write(&mut *body, event);
|
||||
}
|
||||
(events.into_iter().collect::<EditEvents<_>>(), channel_edits)
|
||||
});
|
||||
let (events, channel) = shown.inner.unwrap_or_default();
|
||||
ColorReadoutOutput { response: shown.output, events, channel }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
//! Stories of the readout's container, shown through `ColorReadout`.
|
||||
|
||||
use craft_behavior::Mixed;
|
||||
use craft_theme::Rgba;
|
||||
use craft_ui::contract::{Bind, Validity};
|
||||
use craft_ui::runtime::env::Message;
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use egui::Ui;
|
||||
|
||||
use super::ColorReadout;
|
||||
|
||||
#[story(ColorReadout<'static>, covers = [Default], drive = Drive::Never)]
|
||||
fn color_readout(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let color = data.value("color", Rgba::rgb(0x33, 0x66, 0x99));
|
||||
ColorReadout::new("Color", Bind::bound(color)).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(ColorReadout<'static>, covers = [], drive = Drive::Never)]
|
||||
fn color_readout_mixed(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let color = data.value("mixed", Mixed::<Rgba>::Mixed);
|
||||
ColorReadout::new("Color", Bind::bound_mixed(color)).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(ColorReadout<'static>, covers = [Invalid], drive = Drive::Never)]
|
||||
fn color_readout_invalid(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let refuse_dark = |color: &Rgba| if color.0[2] < 0x80 { Validity::Refuse(Message::new("Too dark")) } else { Validity::Ok };
|
||||
let color = data.value("dark", Rgba::rgb(0x33, 0x33, 0x33));
|
||||
ColorReadout::new("Color", Bind::bound(color).check(refuse_dark)).show(ui).into()
|
||||
}
|
||||
@@ -0,0 +1,498 @@
|
||||
//! Colour samplers (F04.04): up to ten numbered points on the document whose colours a panel reads. `ColorSamplers` is
|
||||
//! the data, `ColorSamplerMarks` paints the points on the canvas, `ColorSamplerTool` places, moves and removes them,
|
||||
//! `SamplerOptions` is the options bar's member and `SamplerReadouts` reads the colours under the points.
|
||||
//!
|
||||
//! ```ignore
|
||||
//! Canvas::new("Document", ColorSamplerTool::new(&mut samplers, size).command_form()).show(ui, |ui, body| {
|
||||
//! ColorSamplerMarks::new("Color samplers", &samplers).show_at(ui, body.rect);
|
||||
//! });
|
||||
//! let readouts = SamplerReadouts::new(&samplers, |at| composite_color(at)).revision(document.revision()).get(&mut cache);
|
||||
//! ```
|
||||
|
||||
use std::hash::Hash;
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft_behavior::kurbo::Point;
|
||||
use craft_behavior::{CancelReason, Cursor, Input, Metrics, PaintedCursor};
|
||||
use craft_cms::convert::CmykConverter;
|
||||
use craft_theme::variant::Tone;
|
||||
use craft_theme::{Srgba, TypeRole};
|
||||
use craft_ui::buttons::Button;
|
||||
use craft_ui::canvas::{CanvasTool, ToolAction, ToolContext, ToolPath, ToolPointer, canvas_space};
|
||||
use craft_ui::contract::{Access, CommandSet, Common, Component, Cx, MeasureCx, NoValue, Outcome, PaintUi, Props as _, Role, Show as _};
|
||||
use craft_ui::display::Text;
|
||||
use craft_ui::primitives::{PaintShape, StrokeWidth, TextRun};
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
use craft_ui::runtime::toast::Toast;
|
||||
use craft_ui::style::{ComponentStyle, StyleColor, StyleCx};
|
||||
use egui::{Pos2, Response, Ui, Vec2, vec2};
|
||||
|
||||
#[cfg(feature = "screen-testing")]
|
||||
mod stories;
|
||||
|
||||
craft_ui::words! {
|
||||
/// The colour samplers' words, English by default.
|
||||
#[non_exhaustive]
|
||||
pub struct SamplerWords {
|
||||
/// The options bar's count; `{n}` points of at most `{max}`.
|
||||
count: template "colorSampler.count" = "{n} of {max} sample points";
|
||||
clear_all: "colorSampler.clearAll" = "Clear All";
|
||||
hint: "colorSampler.hint" = "Click to place · Alt-click or drag off-canvas to remove";
|
||||
/// The notice when a point is refused for the limit.
|
||||
limit: template "colorSampler.limit" = "Color Sampler limit reached: at most {max} points per document";
|
||||
}
|
||||
}
|
||||
|
||||
/// The most points a document holds.
|
||||
pub const MAX_SAMPLERS: usize = 10;
|
||||
|
||||
/// A sampler command that did not apply.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum SamplerError {
|
||||
/// Ten points are placed already.
|
||||
Full,
|
||||
/// The position is off the canvas.
|
||||
Outside,
|
||||
/// No point has this index.
|
||||
NoSuchPoint,
|
||||
}
|
||||
|
||||
/// The commands of the colour samplers (11). They are app commands: the app owns the points, and runs them with
|
||||
/// [`ColorSamplers::apply`]; New opens the app's form of X and Y in document pixels.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, CommandSet)]
|
||||
#[command(prefix = "colorSampler")]
|
||||
#[non_exhaustive]
|
||||
pub enum ColorSamplerCommand {
|
||||
/// Place a point by its numbers.
|
||||
#[command(label = "New Color Sampler…")]
|
||||
New,
|
||||
/// Remove the focused point, else the last one.
|
||||
#[command(label = "Delete Color Sampler")]
|
||||
Delete,
|
||||
/// Remove every point.
|
||||
#[command(label = "Clear All Color Samplers")]
|
||||
Clear,
|
||||
}
|
||||
|
||||
/// The sample points of a document, in document pixels, at most [`MAX_SAMPLERS`], numbered by their order.
|
||||
#[derive(Clone, Debug, Default, PartialEq)]
|
||||
pub struct ColorSamplers {
|
||||
points: Vec<[f64; 2]>,
|
||||
}
|
||||
|
||||
impl ColorSamplers {
|
||||
/// No points.
|
||||
pub fn new() -> ColorSamplers {
|
||||
ColorSamplers::default()
|
||||
}
|
||||
|
||||
/// The points in number order (the first is number 1).
|
||||
pub fn points(&self) -> &[[f64; 2]] {
|
||||
&self.points
|
||||
}
|
||||
|
||||
/// Places a point at the pixel under `pos` on a document of `size` pixels; the new point's index.
|
||||
pub fn add(&mut self, pos: [f64; 2], size: [u32; 2]) -> Result<usize, SamplerError> {
|
||||
let pixel = pixel(pos, size).ok_or(SamplerError::Outside)?;
|
||||
if self.points.len() >= MAX_SAMPLERS {
|
||||
return Err(SamplerError::Full);
|
||||
}
|
||||
self.points.push(pixel);
|
||||
Ok(self.points.len() - 1)
|
||||
}
|
||||
|
||||
/// Moves the point `index` to the pixel under `pos`; dropped off the canvas it is removed and the later points
|
||||
/// move up one number.
|
||||
pub fn move_point(&mut self, index: usize, pos: [f64; 2], size: [u32; 2]) -> Result<(), SamplerError> {
|
||||
if index >= self.points.len() {
|
||||
return Err(SamplerError::NoSuchPoint);
|
||||
}
|
||||
match pixel(pos, size) {
|
||||
Some(pixel) => self.points[index] = pixel,
|
||||
None => {
|
||||
self.points.remove(index);
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Removes the point `index`; the later points move up one number.
|
||||
pub fn remove(&mut self, index: usize) -> Result<(), SamplerError> {
|
||||
if index >= self.points.len() {
|
||||
return Err(SamplerError::NoSuchPoint);
|
||||
}
|
||||
self.points.remove(index);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Removes every point.
|
||||
pub fn clear(&mut self) {
|
||||
self.points.clear();
|
||||
}
|
||||
|
||||
/// The point nearest `at` within `tolerance` document units.
|
||||
pub fn hit(&self, at: [f64; 2], tolerance: f64) -> Option<usize> {
|
||||
let distance = |p: &[f64; 2]| (p[0] - at[0]).hypot(p[1] - at[1]);
|
||||
self.points
|
||||
.iter()
|
||||
.enumerate()
|
||||
.filter(|(_, p)| distance(p) <= tolerance)
|
||||
.min_by(|a, b| distance(a.1).total_cmp(&distance(b.1)))
|
||||
.map(|(index, _)| index)
|
||||
}
|
||||
|
||||
/// Runs `command`: Delete removes `focused`, else the last point; Clear removes every point. New changes nothing
|
||||
/// here: the form that takes the numbers is the app's.
|
||||
pub fn apply(&mut self, command: ColorSamplerCommand, focused: Option<usize>) {
|
||||
match command {
|
||||
ColorSamplerCommand::New => {}
|
||||
ColorSamplerCommand::Delete => {
|
||||
if let Some(last) = self.points.len().checked_sub(1) {
|
||||
let _ = self.remove(focused.unwrap_or(last));
|
||||
}
|
||||
}
|
||||
ColorSamplerCommand::Clear => self.clear(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The pixel under `pos`, if it is on a document of `size` pixels.
|
||||
fn pixel(pos: [f64; 2], size: [u32; 2]) -> Option<[f64; 2]> {
|
||||
let [x, y] = pos.map(f64::floor);
|
||||
(x >= 0.0 && y >= 0.0 && x < f64::from(size[0]) && y < f64::from(size[1])).then_some([x, y])
|
||||
}
|
||||
|
||||
/// The style of the sampler marks.
|
||||
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
|
||||
#[non_exhaustive]
|
||||
pub struct ColorSamplerMarksStyle {
|
||||
#[style(metrics)]
|
||||
metrics: Metrics,
|
||||
/// The reticle and its number.
|
||||
ink: StyleColor,
|
||||
/// The outline under the reticle and the number's shadow, so the marks read on any image.
|
||||
halo: StyleColor,
|
||||
/// The reticle's radius.
|
||||
radius: f32,
|
||||
/// How far the ticks reach past the circle.
|
||||
tick: f32,
|
||||
/// The number's offset from the reticle's centre, and its shadow's offset from the number.
|
||||
shadow: f32,
|
||||
}
|
||||
|
||||
/// The numbered reticles of the points on a canvas. Paint only: a press never lands on it.
|
||||
#[derive(craft_ui::contract::Component)]
|
||||
#[component(canvas_control)]
|
||||
pub struct ColorSamplerMarks<'a> {
|
||||
#[common]
|
||||
common: Common,
|
||||
samplers: &'a ColorSamplers,
|
||||
}
|
||||
|
||||
impl<'a> ColorSamplerMarks<'a> {
|
||||
/// The marks of `samplers`, named `label`.
|
||||
pub fn new(label: impl Into<Label>, samplers: &'a ColorSamplers) -> Self {
|
||||
ColorSamplerMarks { common: Common::new(), samplers }.label(label)
|
||||
}
|
||||
}
|
||||
|
||||
impl Component for ColorSamplerMarks<'_> {
|
||||
const ROLE: Role = Role::GRAPHICS_OBJECT;
|
||||
const ALT_ROLES: &'static [Role] = &[Role::None];
|
||||
const INPUT: Input = Input::Display;
|
||||
const PARTS: bool = false;
|
||||
const STOPS: bool = false;
|
||||
const OVERLAYS: bool = false;
|
||||
type Style = ColorSamplerMarksStyle;
|
||||
type Output = Response;
|
||||
|
||||
fn style(cx: &StyleCx<'_>, _: ColorSamplerMarksStyleKey) -> ColorSamplerMarksStyle {
|
||||
let tokens = cx.tokens;
|
||||
ColorSamplerMarksStyle {
|
||||
metrics: Metrics::new(),
|
||||
ink: cx.color(tokens.color.overlay.stroke),
|
||||
halo: cx.color(tokens.color.overlay.halo),
|
||||
radius: tokens.size.handle.md,
|
||||
tick: tokens.space.gap.tight,
|
||||
shadow: tokens.stroke.thin,
|
||||
}
|
||||
}
|
||||
|
||||
fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
Vec2::ZERO
|
||||
}
|
||||
|
||||
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
|
||||
let Some(space) = canvas_space(&cx.env) else { return };
|
||||
let draw = ui.draw();
|
||||
let style = &cx.style;
|
||||
for (index, point) in self.samplers.points.iter().enumerate() {
|
||||
let at = space.view.to_screen(Point::new(point[0], point[1]));
|
||||
let reticle = |width: StrokeWidth, color: StyleColor| {
|
||||
draw.stroke(&PaintShape::Circle(at, style.radius), width, color);
|
||||
for direction in [Vec2::X, -Vec2::X, Vec2::Y, -Vec2::Y] {
|
||||
let line = vec![at + direction * style.radius, at + direction * (style.radius + style.tick)];
|
||||
draw.stroke(&PaintShape::Path(line), width, color);
|
||||
}
|
||||
};
|
||||
reticle(StrokeWidth::Medium, style.halo);
|
||||
reticle(StrokeWidth::Hairline, style.ink);
|
||||
let number = (index + 1).to_string();
|
||||
let anchor = at + vec2(style.radius, -style.radius);
|
||||
for (offset, color) in [(Vec2::splat(style.shadow), style.halo), (Vec2::ZERO, style.ink)] {
|
||||
let run = TextRun::new(number.as_str()).role(TypeRole::Caption).color(color);
|
||||
let layout = draw.layout(&run, f32::INFINITY);
|
||||
let size = layout.size();
|
||||
draw.galley(anchor + offset - vec2(0.0, size.y), &layout);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn access(&self, access: &mut Access, _: &Cx<'_, Self>) {
|
||||
access.role(Role::None);
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> Response {
|
||||
cx.response.clone()
|
||||
}
|
||||
}
|
||||
|
||||
/// The Color Sampler tool: a press on empty canvas places a point and the drag that follows carries it until the
|
||||
/// release (the eleventh reports [`SamplerError::Full`] as a toast through [`take_error`](Self::take_error)), a drag
|
||||
/// on a point moves it, a point dropped off the canvas is removed, and Alt-click removes a point and renumbers the rest.
|
||||
pub struct ColorSamplerTool<'a> {
|
||||
samplers: &'a mut ColorSamplers,
|
||||
size: [u32; 2],
|
||||
/// The point being carried: its index, the press position and where the press found the point.
|
||||
moving: Option<(usize, [f64; 2], [f64; 2])>,
|
||||
full: Option<Toast>,
|
||||
}
|
||||
|
||||
impl<'a> ColorSamplerTool<'a> {
|
||||
/// A tool over `samplers` on a document of `size` pixels.
|
||||
pub fn new(samplers: &'a mut ColorSamplers, size: [u32; 2]) -> Self {
|
||||
ColorSamplerTool { samplers, size, moving: None, full: None }
|
||||
}
|
||||
|
||||
/// The points the tool edits.
|
||||
pub fn samplers(&self) -> &ColorSamplers {
|
||||
self.samplers
|
||||
}
|
||||
|
||||
/// The notice of a press that was refused, once.
|
||||
pub fn take_error(&mut self) -> Option<Toast> {
|
||||
self.full.take()
|
||||
}
|
||||
|
||||
fn doc_at(cx: &ToolContext<'_>, pos: Pos2) -> Option<[f64; 2]> {
|
||||
let Point { x, y } = cx.space()?.view.to_doc(pos);
|
||||
Some([x, y])
|
||||
}
|
||||
}
|
||||
|
||||
impl CanvasTool for ColorSamplerTool<'_> {
|
||||
fn press(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) -> ToolAction {
|
||||
let (Some(at), Some(space)) = (Self::doc_at(cx, pointer.pos), cx.space()) else { return ToolAction::Ignored };
|
||||
let tolerance = space.view.doc_len(cx.reach());
|
||||
self.moving = None;
|
||||
match self.samplers.hit(at, tolerance) {
|
||||
Some(index) if pointer.mods.alt => {
|
||||
let _ = self.samplers.remove(index);
|
||||
ToolAction::Done
|
||||
}
|
||||
Some(index) => {
|
||||
self.moving = Some((index, at, self.samplers.points()[index]));
|
||||
ToolAction::Claimed
|
||||
}
|
||||
None if pointer.mods.alt => ToolAction::Done,
|
||||
None => match self.samplers.add(at, self.size) {
|
||||
Ok(index) => {
|
||||
self.moving = Some((index, at, self.samplers.points()[index]));
|
||||
ToolAction::Claimed
|
||||
}
|
||||
Err(error) => {
|
||||
if error == SamplerError::Full {
|
||||
let words = cx.words::<SamplerWords>();
|
||||
let text = words.limit.fill(&[("max", &MAX_SAMPLERS.to_string())]);
|
||||
self.full = Some(Toast::new(Label::from(text)).tone(Tone::Bad));
|
||||
}
|
||||
ToolAction::Done
|
||||
}
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn drag(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) {
|
||||
let (Some((index, ..)), Some(to)) = (self.moving, Self::doc_at(cx, pointer.pos)) else { return };
|
||||
// Off the canvas the point stays at its last position; the release removes it.
|
||||
if pixel(to, self.size).is_some() {
|
||||
let _ = self.samplers.move_point(index, to, self.size);
|
||||
}
|
||||
}
|
||||
|
||||
fn release(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) {
|
||||
let Some((index, from, _)) = self.moving.take() else { return };
|
||||
let Some(to) = Self::doc_at(cx, pointer.pos) else { return };
|
||||
if (to[0] - from[0]).hypot(to[1] - from[1]) <= 0.5 {
|
||||
return;
|
||||
}
|
||||
let _ = self.samplers.move_point(index, to, self.size);
|
||||
}
|
||||
|
||||
fn cancel(&mut self, _: CancelReason, _: &mut ToolContext<'_>) {
|
||||
if let Some((index, _, start)) = self.moving.take() {
|
||||
let _ = self.samplers.move_point(index, start, self.size);
|
||||
}
|
||||
}
|
||||
|
||||
fn paint(&self, _: &craft_ui::primitives::Draw<'_>, _: &ToolContext<'_>) {}
|
||||
|
||||
fn cursor(&self, _: &ToolContext<'_>) -> Cursor {
|
||||
PaintedCursor::Crosshair.into()
|
||||
}
|
||||
|
||||
fn autoscrolls(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
fn command_form(&self) -> ToolPath {
|
||||
ToolPath::Command("the New Color Sampler… command")
|
||||
}
|
||||
}
|
||||
|
||||
/// The colour under a point, as a panel shows it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub struct SamplerReadout {
|
||||
/// The point's number (1 to 10).
|
||||
pub number: usize,
|
||||
/// The pixel it is on.
|
||||
pub position: [i64; 2],
|
||||
/// The colour in 8-bit sRGB.
|
||||
pub rgb: [u8; 3],
|
||||
/// The colour in CMYK percent through the document's converter.
|
||||
pub cmyk: [u8; 4],
|
||||
}
|
||||
|
||||
impl SamplerReadout {
|
||||
/// The readout of point `index` at `position` with `color`, CMYK through `cmyk`. A channel that is not finite
|
||||
/// reads as 0 and the rest is clamped.
|
||||
pub fn new(index: usize, position: [f64; 2], color: Srgba, cmyk: &CmykConverter) -> SamplerReadout {
|
||||
let unit = |v: f32| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 };
|
||||
let rgb = [color.r, color.g, color.b].map(unit);
|
||||
SamplerReadout {
|
||||
number: index + 1,
|
||||
position: position.map(|v| v.floor() as i64),
|
||||
rgb: rgb.map(|v| (v * 255.0).round() as u8),
|
||||
cmyk: cmyk.from_srgb(rgb).map(|v| (unit(v) * 100.0).round() as u8),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The options bar's members: the count, Clear All and the hint.
|
||||
#[must_use = "show the options with `show`"]
|
||||
#[derive(craft_ui::contract::Pattern)]
|
||||
pub struct SamplerOptions {
|
||||
count: usize,
|
||||
}
|
||||
|
||||
/// What [`SamplerOptions::show`] reports.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
pub struct SamplerOptionsOutput {
|
||||
/// The Clear All button.
|
||||
pub response: Response,
|
||||
/// Clear All was pressed.
|
||||
pub clear_all: bool,
|
||||
}
|
||||
|
||||
impl Outcome for SamplerOptionsOutput {
|
||||
type Value = NoValue;
|
||||
|
||||
fn response(&self) -> &Response {
|
||||
&self.response
|
||||
}
|
||||
}
|
||||
|
||||
impl SamplerOptions {
|
||||
/// The members for a document with `count` points.
|
||||
pub fn new(count: usize) -> Self {
|
||||
SamplerOptions { count }
|
||||
}
|
||||
|
||||
/// Shows the members inside the options `Bar`.
|
||||
pub fn show(self, ui: &mut Ui) -> SamplerOptionsOutput {
|
||||
let words = Env::of(ui).words::<SamplerWords>();
|
||||
let counted = words.count.fill(&[("n", &self.count.to_string()), ("max", &MAX_SAMPLERS.to_string())]);
|
||||
Text::new(Label::from(counted)).show(ui);
|
||||
let clear = Button::new(words.clear_all.clone()).enabled(self.count > 0).show(ui);
|
||||
Text::new(words.hint.clone()).show(ui);
|
||||
SamplerOptionsOutput { clear_all: craft_ui::contract::clicked(&clear), response: clear.response }
|
||||
}
|
||||
}
|
||||
|
||||
type Cached = (u64, u64, usize, Vec<[f64; 2]>, Arc<Vec<SamplerReadout>>);
|
||||
|
||||
/// The readouts a host cached: keyed by the revision, the points and the CMYK profile.
|
||||
#[derive(Clone, Default)]
|
||||
pub struct SamplerCache {
|
||||
cached: Option<Cached>,
|
||||
}
|
||||
|
||||
/// The readouts of every point, cached by the host between passes.
|
||||
pub struct SamplerReadouts<'a, F> {
|
||||
samplers: &'a ColorSamplers,
|
||||
read: F,
|
||||
revision: u64,
|
||||
document: u64,
|
||||
cmyk: Option<&'a CmykConverter>,
|
||||
}
|
||||
|
||||
impl<'a, F: Fn([f64; 2]) -> Srgba> SamplerReadouts<'a, F> {
|
||||
/// The readouts of `samplers`, reading the colour under a point with `read`.
|
||||
pub fn new(samplers: &'a ColorSamplers, read: F) -> Self {
|
||||
SamplerReadouts { samplers, read, revision: 0, document: 0, cmyk: None }
|
||||
}
|
||||
|
||||
/// The document's revision: a new one reads again.
|
||||
#[must_use]
|
||||
pub fn revision(mut self, revision: u64) -> Self {
|
||||
self.revision = revision;
|
||||
self
|
||||
}
|
||||
|
||||
/// Which document is read: another document at the same revision reads again.
|
||||
#[must_use]
|
||||
pub fn document(mut self, document: impl Hash) -> Self {
|
||||
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
||||
document.hash(&mut hasher);
|
||||
self.document = std::hash::Hasher::finish(&hasher);
|
||||
self
|
||||
}
|
||||
|
||||
/// The document's CMYK converter; the built-in coated one without it.
|
||||
#[must_use]
|
||||
pub fn cmyk(mut self, converter: &'a CmykConverter) -> Self {
|
||||
self.cmyk = Some(converter);
|
||||
self
|
||||
}
|
||||
|
||||
/// The readouts, from `cache` while the revision, the document, the points and the CMYK profile are as they were.
|
||||
pub fn get(self, cache: &mut SamplerCache) -> Arc<Vec<SamplerReadout>> {
|
||||
let cmyk = self.cmyk.unwrap_or_else(|| CmykConverter::coated());
|
||||
let profile = Arc::as_ptr(cmyk.profile()) as usize;
|
||||
if let Some((revision, document, cached_profile, points, readouts)) = &cache.cached
|
||||
&& *revision == self.revision
|
||||
&& *document == self.document
|
||||
&& *cached_profile == profile
|
||||
&& *points == self.samplers.points
|
||||
{
|
||||
return Arc::clone(readouts);
|
||||
}
|
||||
let readouts: Arc<Vec<SamplerReadout>> =
|
||||
Arc::new(self.samplers.points.iter().enumerate().map(|(i, p)| SamplerReadout::new(i, *p, (self.read)(*p), cmyk)).collect());
|
||||
cache.cached = Some((self.revision, self.document, profile, self.samplers.points.clone(), Arc::clone(&readouts)));
|
||||
readouts
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
//! Stories of `ColorSamplerMarks` and `SamplerOptions`.
|
||||
|
||||
use super::{ColorSamplerMarks, ColorSamplers, SamplerOptions};
|
||||
use craft_behavior::CanvasView;
|
||||
use craft_behavior::kurbo::Point;
|
||||
use craft_ui::bars::{Bar, BarKind};
|
||||
use craft_ui::canvas::Canvas;
|
||||
use craft_ui::contract::{Show as _, ShowContainer as _};
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use egui::Ui;
|
||||
|
||||
/// The document pixels of the story's canvas.
|
||||
const SIZE: [u32; 2] = [300, 200];
|
||||
|
||||
#[story(ColorSamplerMarks<'static>, covers = [Default], drive = Drive::Never)]
|
||||
fn three_points(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
let mut samplers = ColorSamplers::new();
|
||||
for at in [[40.0, 30.0], [120.0, 90.0], [200.0, 60.0]] {
|
||||
let _ = samplers.add(at, SIZE);
|
||||
}
|
||||
let at = ui.available_rect_before_wrap();
|
||||
let center = Point::new(f64::from(at.width()) / 2.0, f64::from(at.height()) / 2.0);
|
||||
let view = CanvasView::new(at, center, 1.0);
|
||||
let shown = Canvas::new("Document").view(view).show(ui, |ui, body| ColorSamplerMarks::new("Color samplers", &samplers).show_at(ui, body.rect));
|
||||
shown.inner.map(StoryOutput::from).unwrap_or_default()
|
||||
}
|
||||
|
||||
#[story(SamplerOptions, covers = [], drive = Drive::Never)]
|
||||
fn options(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
let shown = Bar::new("Color sampler options", BarKind::Options).show(ui, |ui, _| SamplerOptions::new(3).show(ui));
|
||||
match shown.inner {
|
||||
Some(output) => StoryOutput::from(output),
|
||||
None => StoryOutput::from(shown.output),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,505 @@
|
||||
//! Screen colour picking (F04.05): one pick at a time, owned by the key that asked, with its state in an app-owned
|
||||
//! [`ScreenPick`]. The press-and-drag from the picker's button inside the app's windows samples the app's last frame
|
||||
//! through the runtime's screenshot slot; a click, or a release outside the app's windows, captures the screen
|
||||
//! ([`craft_platform::screen`]). A release outside takes the colour under it; after a click the capture shows over
|
||||
//! each monitor ([`ScreenColorPicker`]) and a click there takes the colour under it.
|
||||
//!
|
||||
//! ```ignore
|
||||
//! let mut pick = ScreenPick::new();
|
||||
//! // In the pass that got the picker's `ScreenPickGesture`:
|
||||
//! if let Some(color) = pick.hold(ctx, "fill", gesture) { /* live sample while the button is held */ }
|
||||
//! // Once per pass, after the app's UI:
|
||||
//! pick.tick(ctx, window_generation);
|
||||
//! ScreenColorPicker::new(&mut pick, "PhotoCraft").show(ui);
|
||||
//! if let Some(color) = pick.take("fill") { /* the picked colour */ }
|
||||
//! if let Some(toast) = pick.take_notice(&words) { /* a capture failure */ }
|
||||
//! ```
|
||||
|
||||
use std::hash::{Hash, Hasher};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use craft_cms::{Builtin, Intent, Profile, Transform};
|
||||
use craft_host::Wake;
|
||||
use craft_host::target::Caps;
|
||||
use craft_platform::screen::{self, Capture, CaptureHandle, ScreenError, ScreenImage};
|
||||
use craft_theme::Srgba;
|
||||
use craft_theme::variant::Tone;
|
||||
use craft_ui::contract::{Pattern, Props as _, Show as _, ShowContainer as _};
|
||||
use craft_ui::runtime::env::{Env, Label};
|
||||
use craft_ui::runtime::toast::Toast;
|
||||
use craft_ui::runtime::windows::{ScreenshotSlot, WindowHost};
|
||||
use egui::{Color32, Context, Pos2, Rect, Ui, ViewportId, pos2, vec2};
|
||||
|
||||
use super::ScreenPickGesture;
|
||||
|
||||
mod capture;
|
||||
#[cfg(feature = "screen-testing")]
|
||||
mod stories;
|
||||
|
||||
use capture::{CaptureView, CaptureWindow};
|
||||
|
||||
craft_ui::words! {
|
||||
/// The screen picker's words, English by default.
|
||||
#[non_exhaustive]
|
||||
pub struct ScreenPickerWords {
|
||||
window_title: template "screenPicker.windowTitle" = "{app} — Screen Color Picker";
|
||||
click_to_pick: "screenPicker.clickToPick" = "Click to pick · Esc to cancel";
|
||||
scroll_to_zoom: "screenPicker.scrollToZoom" = "Scroll to zoom";
|
||||
denied: "screenPicker.denied" = "Screen capture was not allowed. Allow screen recording for this app in the system settings.";
|
||||
unsupported: "screenPicker.unsupported" = "Screen capture is not available here.";
|
||||
invalid_capture: "screenPicker.invalidCapture" = "The screen capture is not valid.";
|
||||
texture_limit: "screenPicker.textureLimit" = "This display is larger than the graphics card can show.";
|
||||
not_rgb_profile: "screenPicker.notRgbProfile" = "The screen profile must describe RGB pixels.";
|
||||
nothing_captured: "screenPicker.nothingCaptured" = "No screen was captured.";
|
||||
failed: template "screenPicker.failed" = "Screen capture failed: {reason}";
|
||||
}
|
||||
}
|
||||
|
||||
/// The loupe shows this many pixels on each side (odd, so one is in the middle).
|
||||
pub const LOUPE_PIXELS: usize = 11;
|
||||
|
||||
/// The loupe's zoom in screen pixels per pixel: the least, the first and the most; the wheel steps between them.
|
||||
pub const LOUPE_ZOOM: (usize, usize, usize) = (4, 12, 24);
|
||||
|
||||
/// How far one wheel notch steps the loupe's zoom.
|
||||
const ZOOM_STEP: usize = 2;
|
||||
|
||||
/// The most bytes one frame of the app's own windows may take when sampled during a held drag.
|
||||
const FRAME_BYTES: usize = 256 * 1024 * 1024;
|
||||
|
||||
/// What a capture ends in.
|
||||
pub type CaptureResult = Result<Capture, ScreenError>;
|
||||
|
||||
/// Where a capture's result comes from; the platform capture in the app, a fixed one in stories and tests.
|
||||
pub trait CaptureSource: Send {
|
||||
/// The result, once, when it is ready.
|
||||
fn poll(&self) -> Option<CaptureResult>;
|
||||
}
|
||||
|
||||
impl CaptureSource for CaptureHandle {
|
||||
fn poll(&self) -> Option<CaptureResult> {
|
||||
self.try_take()
|
||||
}
|
||||
}
|
||||
|
||||
/// A capture that is ready at once: a result given in advance.
|
||||
pub struct StillCapture(Mutex<Option<CaptureResult>>);
|
||||
|
||||
impl StillCapture {
|
||||
/// A capture that ends in `result`.
|
||||
pub fn new(result: CaptureResult) -> StillCapture {
|
||||
StillCapture(Mutex::new(Some(result)))
|
||||
}
|
||||
|
||||
/// A capture that picks `color` at once, with no capture windows (a platform that picks natively).
|
||||
pub fn color(color: Srgba) -> StillCapture {
|
||||
StillCapture::new(Ok(Capture::Color([color.r, color.g, color.b])))
|
||||
}
|
||||
}
|
||||
|
||||
impl CaptureSource for StillCapture {
|
||||
fn poll(&self) -> Option<CaptureResult> {
|
||||
self.0.lock().unwrap_or_else(|e| e.into_inner()).take()
|
||||
}
|
||||
}
|
||||
|
||||
/// Why a pick ended without a colour; worded when the app takes the notice.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
enum Failure {
|
||||
NothingCaptured,
|
||||
InvalidCapture,
|
||||
NotRgb,
|
||||
Denied,
|
||||
Unsupported,
|
||||
Failed(String),
|
||||
}
|
||||
|
||||
/// Why a captured image cannot be shown.
|
||||
enum SnapshotError {
|
||||
Invalid,
|
||||
NotRgb,
|
||||
Profile(String),
|
||||
}
|
||||
|
||||
/// One monitor's capture with the conversion from its profile to sRGB.
|
||||
#[derive(Clone)]
|
||||
pub(super) struct Snapshot {
|
||||
image: ScreenImage,
|
||||
conversion: Option<Arc<Transform>>,
|
||||
}
|
||||
|
||||
impl Snapshot {
|
||||
fn new(image: ScreenImage) -> Result<Snapshot, SnapshotError> {
|
||||
let [w, h] = image.size.map(|n| n as usize);
|
||||
let pixels = w.checked_mul(h).filter(|&n| n > 0 && n <= screen::MAX_PIXELS);
|
||||
if pixels.and_then(|n| n.checked_mul(4)) != Some(image.rgba.len()) || !image.scale.is_finite() || image.scale <= 0.0 {
|
||||
return Err(SnapshotError::Invalid);
|
||||
}
|
||||
let conversion = match &image.icc_profile {
|
||||
None => None,
|
||||
Some(bytes) => {
|
||||
let source = Profile::parse(bytes).map_err(|e| SnapshotError::Profile(e.to_string()))?;
|
||||
if source.color_space != craft_cms::ColorSpace::Rgb {
|
||||
return Err(SnapshotError::NotRgb);
|
||||
}
|
||||
Some(Arc::new(
|
||||
Transform::new(&source, Builtin::Srgb.profile(), Intent::RelativeColorimetric, true)
|
||||
.map_err(|e| SnapshotError::Profile(e.to_string()))?,
|
||||
))
|
||||
}
|
||||
};
|
||||
Ok(Snapshot { image, conversion })
|
||||
}
|
||||
|
||||
/// The pixel `x`, `y` in 8-bit RGB.
|
||||
pub(super) fn pixel(&self, x: usize, y: usize) -> Option<Color32> {
|
||||
let [w, h] = self.image.size.map(|n| n as usize);
|
||||
if x >= w || y >= h {
|
||||
return None;
|
||||
}
|
||||
let at = (y * w + x) * 4;
|
||||
let p = self.image.rgba.get(at..at + 3)?;
|
||||
Some(Color32::from_rgb(p[0], p[1], p[2]))
|
||||
}
|
||||
|
||||
/// The pixel `x`, `y` converted from the monitor's profile to sRGB.
|
||||
pub(super) fn sample(&self, x: usize, y: usize) -> Result<Srgba, String> {
|
||||
let p = self.pixel(x, y).ok_or("The pixel is outside the capture")?;
|
||||
let mut rgb = [p.r(), p.g(), p.b()].map(|v| f32::from(v) / 255.0);
|
||||
if let Some(t) = &self.conversion {
|
||||
t.apply(&mut rgb, 3).map_err(|e| e.to_string())?;
|
||||
}
|
||||
Ok(Srgba::from_rgb_array(rgb.map(|v| v.clamp(0.0, 1.0))))
|
||||
}
|
||||
}
|
||||
|
||||
/// The app's own frame, grabbed through the screenshot slot while the button is held.
|
||||
struct Hold {
|
||||
owner: u64,
|
||||
slot: Option<ScreenshotSlot>,
|
||||
frame: Option<Arc<egui::ColorImage>>,
|
||||
}
|
||||
|
||||
/// The state of the screen picker. The app keeps one, and ticks and [`show`](Self::show)s it once per pass after its UI.
|
||||
///
|
||||
/// - One pick runs at a time, owned by the key that asked: only the owner [`take`](Self::take)s its colour, even
|
||||
/// after the popover that asked has closed.
|
||||
/// - [`tick`](Self::tick) starts a requested capture and settles a finished one; [`cancel`](Self::cancel) ends a
|
||||
/// running pick.
|
||||
/// - After a click on the picker's button the capture of each monitor shows in a window over that monitor until the
|
||||
/// pick ends.
|
||||
#[derive(Default)]
|
||||
pub struct ScreenPick {
|
||||
request: Option<u64>,
|
||||
owner: Option<u64>,
|
||||
source: Option<Box<dyn CaptureSource>>,
|
||||
images: Vec<Snapshot>,
|
||||
answer: Option<Result<Option<Srgba>, Failure>>,
|
||||
completed: Option<(u64, Srgba)>,
|
||||
notice: Option<Failure>,
|
||||
unsupported: bool,
|
||||
target: Option<u64>,
|
||||
hold: Option<Hold>,
|
||||
monitor: Option<(u64, Option<Arc<Transform>>)>,
|
||||
/// Where a drag released outside the app's windows, in physical pixels of the virtual desktop: the captured
|
||||
/// monitor under it gives the colour.
|
||||
release: Option<Pos2>,
|
||||
/// The loupe's zoom in the capture windows, in screen pixels per captured pixel.
|
||||
zoom: usize,
|
||||
/// Counts the picks, so each pick's capture windows are new windows.
|
||||
generation: u64,
|
||||
}
|
||||
|
||||
fn key_of(owner: impl Hash) -> u64 {
|
||||
let mut hasher = std::collections::hash_map::DefaultHasher::new();
|
||||
owner.hash(&mut hasher);
|
||||
hasher.finish()
|
||||
}
|
||||
|
||||
/// The capture windows of a running pick, one over each captured monitor. Show it once per pass, after the app's UI.
|
||||
#[must_use = "show the windows with `show`"]
|
||||
#[derive(Pattern)]
|
||||
pub struct ScreenColorPicker<'a> {
|
||||
pick: &'a mut ScreenPick,
|
||||
app: &'a str,
|
||||
}
|
||||
|
||||
impl<'a> ScreenColorPicker<'a> {
|
||||
/// The windows of `pick`; `app` is the app's name, for the windows' title.
|
||||
pub fn new(pick: &'a mut ScreenPick, app: &'a str) -> Self {
|
||||
ScreenColorPicker { pick, app }
|
||||
}
|
||||
|
||||
/// Shows the capture windows of `pick`'s running pick, one over each captured monitor, borderless and above every other
|
||||
/// window; `app` is the app's name, for the windows' title. A click picks the pixel under it, as a release outside
|
||||
/// the app's windows does; Escape, a right-click or closing a window cancels. The wheel steps the loupe's zoom
|
||||
/// ([`LOUPE_ZOOM`]). Every window closes when the pick ends.
|
||||
pub fn show(self, ui: &mut Ui) {
|
||||
let ScreenColorPicker { pick, app } = self;
|
||||
if pick.images.is_empty() || pick.answer.is_some() {
|
||||
return;
|
||||
}
|
||||
let words = Env::of(ui).words::<ScreenPickerWords>();
|
||||
let title = Label::from(words.window_title.fill(&[("app", app)]));
|
||||
let hints = [words.click_to_pick.clone(), words.scroll_to_zoom.clone()];
|
||||
let (mut picked, mut cancelled, mut notches) = (None, false, 0);
|
||||
for (n, snapshot) in pick.images.iter().enumerate() {
|
||||
let [x, y, w, h] = capture::area(snapshot).cover();
|
||||
let key = key_of((pick.generation, n));
|
||||
let window = CaptureWindow::new(title.clone(), Rect::from_min_size(pos2(x, y), vec2(w, h))).id_salt((
|
||||
"craft-color screen pick",
|
||||
pick.generation,
|
||||
n,
|
||||
));
|
||||
let mut shown = window.show(ui, |ui, _| {
|
||||
let rect = ui.max_rect();
|
||||
CaptureView::new(snapshot.image.name.clone(), snapshot, key, pick.zoom, hints.clone()).show_at(ui, rect)
|
||||
});
|
||||
cancelled |= shown.output.closed.is_some();
|
||||
if let Some((at, right_click, wheel)) = shown.settle(|_, view| (view.picked, view.cancelled, view.notches)) {
|
||||
picked = picked.or(at);
|
||||
cancelled |= right_click;
|
||||
notches += wheel;
|
||||
}
|
||||
}
|
||||
let step = notches.unsigned_abs() as usize * ZOOM_STEP;
|
||||
pick.zoom = if notches > 0 { pick.zoom + step } else { pick.zoom.saturating_sub(step) }.clamp(LOUPE_ZOOM.0, LOUPE_ZOOM.2);
|
||||
if let Some(at) = picked {
|
||||
pick.answer = Some(sample_desktop(&pick.images, at).map_err(Failure::Failed));
|
||||
} else if cancelled {
|
||||
pick.answer = Some(Ok(None));
|
||||
}
|
||||
pick.settle(ui.ctx());
|
||||
}
|
||||
}
|
||||
|
||||
impl ScreenPick {
|
||||
/// No pick.
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
/// Asks for a pick for `owner`; nothing happens while another pick runs.
|
||||
pub fn start(&mut self, owner: impl Hash) {
|
||||
if self.owner.is_none() && self.request.is_none() {
|
||||
self.request = Some(key_of(owner));
|
||||
}
|
||||
}
|
||||
|
||||
/// Runs the pick for one pass: starts the requested capture through the platform, waking the app when it
|
||||
/// finishes, and settles the answer. `target` identifies the window the pick belongs to: a pick whose target
|
||||
/// changed is cancelled.
|
||||
pub fn tick(&mut self, ctx: &Context, target: u64) {
|
||||
let scale = ctx.native_pixels_per_point().unwrap_or(1.0);
|
||||
let repaint = ctx.clone();
|
||||
self.tick_with(ctx, target, &|| {
|
||||
let repaint = repaint.clone();
|
||||
Box::new(screen::capture(scale, Wake::new(move || repaint.request_repaint())))
|
||||
});
|
||||
}
|
||||
|
||||
/// [`tick`](Self::tick) with the capture `start` makes, for stories and tests.
|
||||
pub fn tick_with(&mut self, ctx: &Context, target: u64, start: &dyn Fn() -> Box<dyn CaptureSource>) {
|
||||
if self.completed.is_some() && self.target != Some(target) {
|
||||
self.completed = None;
|
||||
}
|
||||
if let Some(owner) = self.request.take() {
|
||||
self.completed = None;
|
||||
self.notice = None;
|
||||
self.source = Some(start());
|
||||
self.owner = Some(owner);
|
||||
self.target = Some(target);
|
||||
self.zoom = LOUPE_ZOOM.1;
|
||||
self.generation = self.generation.wrapping_add(1);
|
||||
}
|
||||
if self.owner.is_none() {
|
||||
return;
|
||||
}
|
||||
if self.target != Some(target) {
|
||||
self.answer = Some(Ok(None));
|
||||
}
|
||||
if self.answer.is_none()
|
||||
&& let Some(result) = self.source.as_ref().and_then(|source| source.poll())
|
||||
{
|
||||
self.source = None;
|
||||
self.answer = Some(match result {
|
||||
Ok(Capture::Color([r, g, b])) => Ok(Some(Srgba::rgb(r, g, b))),
|
||||
Ok(Capture::Images(images)) => match images.into_iter().map(Snapshot::new).collect::<Result<Vec<_>, _>>() {
|
||||
Ok(images) if !images.is_empty() => match self.release.take() {
|
||||
Some(at) => sample_desktop(&images, at).map_err(Failure::Failed),
|
||||
None => {
|
||||
self.images = images;
|
||||
return;
|
||||
}
|
||||
},
|
||||
Ok(_) => Err(Failure::NothingCaptured),
|
||||
Err(SnapshotError::Invalid) => Err(Failure::InvalidCapture),
|
||||
Err(SnapshotError::NotRgb) => Err(Failure::NotRgb),
|
||||
Err(SnapshotError::Profile(reason)) => Err(Failure::Failed(reason)),
|
||||
},
|
||||
Err(ScreenError::Cancelled) => Ok(None),
|
||||
Err(ScreenError::Denied) => Err(Failure::Denied),
|
||||
Err(ScreenError::Unsupported) => {
|
||||
self.unsupported = true;
|
||||
Err(Failure::Unsupported)
|
||||
}
|
||||
Err(ScreenError::Failed(reason)) => Err(Failure::Failed(reason)),
|
||||
});
|
||||
}
|
||||
self.settle(ctx);
|
||||
}
|
||||
|
||||
/// Ends the pick with the answer it has.
|
||||
fn settle(&mut self, ctx: &Context) {
|
||||
let Some(answer) = self.answer.take() else { return };
|
||||
let owner = self.owner.take();
|
||||
self.source = None;
|
||||
self.release = None;
|
||||
if !self.images.is_empty() {
|
||||
capture::store(ctx).clear(ctx);
|
||||
}
|
||||
self.images.clear();
|
||||
match answer {
|
||||
Ok(Some(color)) => self.completed = owner.map(|owner| (owner, color)),
|
||||
Ok(None) => {}
|
||||
Err(notice) => self.notice = Some(notice),
|
||||
}
|
||||
ctx.request_repaint();
|
||||
}
|
||||
|
||||
/// Whether a pick runs or waits for its capture; the picker's button is disabled meanwhile.
|
||||
pub fn busy(&self) -> bool {
|
||||
self.owner.is_some() || self.request.is_some()
|
||||
}
|
||||
|
||||
/// Whether the platform can capture the screen (`caps` are the shell's) and has not said it cannot.
|
||||
pub fn available(&self, caps: Caps) -> bool {
|
||||
caps.contains(Caps::SCREEN_CAPTURE) && !self.unsupported
|
||||
}
|
||||
|
||||
/// Cancels a running or requested pick: Esc, a closed capture window and a right-click all end here.
|
||||
pub fn cancel(&mut self) {
|
||||
if self.owner.is_some() {
|
||||
self.answer = Some(Ok(None));
|
||||
} else {
|
||||
self.request = None;
|
||||
self.release = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// The colour `owner` picked, once. Only the owner takes it.
|
||||
pub fn take(&mut self, owner: impl Hash) -> Option<Srgba> {
|
||||
let key = key_of(owner);
|
||||
if self.completed.as_ref().is_some_and(|(id, _)| *id == key) { self.completed.take().map(|(_, color)| color) } else { None }
|
||||
}
|
||||
|
||||
/// A capture failure, once, as a toast worded with `words`.
|
||||
pub fn take_notice(&mut self, words: &ScreenPickerWords) -> Option<Toast> {
|
||||
let text = match self.notice.take()? {
|
||||
Failure::NothingCaptured => words.nothing_captured.clone(),
|
||||
Failure::InvalidCapture => words.invalid_capture.clone(),
|
||||
Failure::NotRgb => words.not_rgb_profile.clone(),
|
||||
Failure::Denied => words.denied.clone(),
|
||||
Failure::Unsupported => words.unsupported.clone(),
|
||||
Failure::Failed(reason) => Label::from(words.failed.fill(&[("reason", reason.as_str())])),
|
||||
};
|
||||
Some(Toast::new(text).tone(Tone::Bad))
|
||||
}
|
||||
|
||||
/// The profile of the monitor the app's own windows show on: a frame sampled during a held drag converts from it
|
||||
/// to sRGB.
|
||||
pub fn set_monitor(&mut self, monitor: &Profile) {
|
||||
let hash = monitor.content_hash();
|
||||
if self.monitor.as_ref().is_some_and(|(known, _)| *known == hash) {
|
||||
return;
|
||||
}
|
||||
let back = if monitor.same_colors(Builtin::Srgb.profile()) {
|
||||
None
|
||||
} else {
|
||||
Transform::new(monitor, Builtin::Srgb.profile(), Intent::RelativeColorimetric, true).ok().map(Arc::new)
|
||||
};
|
||||
self.monitor = Some((hash, back));
|
||||
}
|
||||
|
||||
/// Follows the picker button's press for `owner`: a click starts the capture; a held drag inside the app's windows
|
||||
/// samples the app's last frame each pass (the colour returned); a release inside takes the colour under it, and
|
||||
/// a release outside the app's windows starts the capture.
|
||||
pub fn hold(&mut self, ctx: &Context, owner: impl Hash, gesture: ScreenPickGesture) -> Option<Srgba> {
|
||||
let key = key_of(&owner);
|
||||
if self.busy() {
|
||||
self.hold = None;
|
||||
return None;
|
||||
}
|
||||
let (at, released) = match gesture {
|
||||
ScreenPickGesture::Held { at } => (at, false),
|
||||
ScreenPickGesture::Released { at } => (at, true),
|
||||
_ => {
|
||||
self.hold = None;
|
||||
self.start(owner);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
let windows = WindowHost::of(ctx);
|
||||
let size = windows.screenshot_facts();
|
||||
let inside = at.x >= 0.0 && at.y >= 0.0 && at.x < size.size_points.x && at.y < size.size_points.y;
|
||||
let back = self.monitor.as_ref().and_then(|(_, back)| back.clone());
|
||||
let hold = self.hold.get_or_insert_with(|| Hold { owner: key, slot: None, frame: None });
|
||||
if hold.owner != key {
|
||||
*hold = Hold { owner: key, slot: None, frame: None };
|
||||
}
|
||||
if let Some(Ok(frame)) = hold.slot.as_ref().and_then(ScreenshotSlot::take) {
|
||||
hold.frame = Some(frame);
|
||||
hold.slot = None;
|
||||
}
|
||||
let sampled = hold.frame.as_ref().filter(|_| inside).and_then(|frame| sample_frame(frame, size.pixels_per_point, at, back.as_deref()));
|
||||
if !released {
|
||||
if hold.slot.is_none() {
|
||||
hold.slot = Some(windows.screenshot(ViewportId::ROOT, FRAME_BYTES));
|
||||
}
|
||||
ctx.request_repaint();
|
||||
return sampled;
|
||||
}
|
||||
self.hold = None;
|
||||
if !inside {
|
||||
// A window with no reported position (a host with no desktop) sits at the desktop's origin.
|
||||
let window = ctx.input(|input| input.viewport().inner_rect).map_or(Pos2::ZERO, |inner| inner.min);
|
||||
self.start(owner);
|
||||
if self.request.is_some() {
|
||||
let native = size.pixels_per_point / size.zoom;
|
||||
self.release = Some(Pos2::new(
|
||||
(window.x * native + at.x * size.pixels_per_point).round(),
|
||||
(window.y * native + at.y * size.pixels_per_point).round(),
|
||||
));
|
||||
}
|
||||
}
|
||||
sampled
|
||||
}
|
||||
}
|
||||
|
||||
/// The colour under the desktop pixel `at` (physical pixels): the pixel of the monitor that holds it, converted from
|
||||
/// the monitor's profile to sRGB. `Ok(None)` when no captured monitor holds it.
|
||||
fn sample_desktop(images: &[Snapshot], at: Pos2) -> Result<Option<Srgba>, String> {
|
||||
for snapshot in images {
|
||||
let [w, h] = snapshot.image.size.map(|n| n as f32);
|
||||
let (dx, dy) = (at.x - snapshot.image.origin[0] as f32, at.y - snapshot.image.origin[1] as f32);
|
||||
if dx >= 0.0 && dy >= 0.0 && dx < w && dy < h {
|
||||
return snapshot.sample(dx as usize, dy as usize).map(Some);
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
/// The colour of `image` under `at` (points of the viewport), converted with `back` when the monitor is not sRGB.
|
||||
fn sample_frame(image: &egui::ColorImage, pixels_per_point: f32, at: Pos2, back: Option<&Transform>) -> Option<Srgba> {
|
||||
let [w, h] = image.size;
|
||||
let (x, y) = ((at.x * pixels_per_point) as usize, (at.y * pixels_per_point) as usize);
|
||||
if x >= w || y >= h {
|
||||
return None;
|
||||
}
|
||||
let c = image.pixels.get(y * w + x)?;
|
||||
let mut rgb = [c.r(), c.g(), c.b()].map(|v| f32::from(v) / 255.0);
|
||||
if let Some(back) = back {
|
||||
back.apply(&mut rgb, 3).ok()?;
|
||||
}
|
||||
Some(Srgba::from_rgb_array(rgb.map(|v| v.clamp(0.0, 1.0))))
|
||||
}
|
||||
@@ -0,0 +1,280 @@
|
||||
//! The capture windows of a screen pick: one over each captured monitor, showing its capture with a crosshair, a
|
||||
//! loupe and the hint, and reporting the pixel a click picks.
|
||||
|
||||
use craft_behavior::{Cursor, CursorIcon, CursorPriority, Metrics, PointerButton, PressPhase, Sense};
|
||||
use craft_host::target::{WindowChrome, WindowKind};
|
||||
use craft_theme::TypeRole;
|
||||
use craft_ui::contract::{
|
||||
Common, Component, Container, ContainerProps, Cx, MeasureCx, Mount, NoValue, Outcome, Overlay, Pad, PaintUi, Pointer as _, Props as _, Role,
|
||||
Sizing,
|
||||
};
|
||||
use craft_ui::primitives::{PaintShape, Revision, StrokeWidth, TextRun, TextureStore, TextureStoreOptions};
|
||||
use craft_ui::runtime::env::Label;
|
||||
use craft_ui::runtime::overlay::CloseReason;
|
||||
use craft_ui::runtime::windows::{WindowLevel, WindowSpec};
|
||||
use craft_ui::style::{ComponentStyle, DataColor, StyleColor, StyleCx, SurfaceKind};
|
||||
use craft_window::capture::MonitorArea;
|
||||
use egui::{ColorImage, Context, CornerRadius, Pos2, Rect, Response, Vec2, pos2, vec2};
|
||||
|
||||
use super::{LOUPE_PIXELS, Snapshot};
|
||||
|
||||
/// The texture store the captures are shown from; emptied when a pick ends.
|
||||
const STORE: &str = "craft-color screen pick";
|
||||
|
||||
/// The store the capture textures live in.
|
||||
pub(super) fn store(ctx: &Context) -> TextureStore<u64> {
|
||||
TextureStore::in_context(ctx, STORE, TextureStoreOptions::pages())
|
||||
}
|
||||
|
||||
/// The capture's area in the virtual desktop.
|
||||
pub(super) fn area(snapshot: &Snapshot) -> MonitorArea {
|
||||
MonitorArea::new(snapshot.image.origin, snapshot.image.size, snapshot.image.scale)
|
||||
}
|
||||
|
||||
/// The style of a capture window and its view: no padding, and the loupe's inner margin.
|
||||
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
|
||||
#[non_exhaustive]
|
||||
pub(super) struct CaptureStyle {
|
||||
#[style(metrics)]
|
||||
metrics: Metrics,
|
||||
/// The loupe's inner margin.
|
||||
pad: f32,
|
||||
/// How far the loupe sits down and across from the pointer.
|
||||
offset: f32,
|
||||
/// The centre pixel's outline: the mark over its halo, so it reads on any image.
|
||||
mark: StyleColor,
|
||||
halo: StyleColor,
|
||||
}
|
||||
|
||||
impl CaptureStyle {
|
||||
fn of(cx: &StyleCx<'_>) -> Self {
|
||||
let overlay = &cx.tokens.color.overlay;
|
||||
CaptureStyle {
|
||||
metrics: Metrics::new(),
|
||||
pad: cx.tokens.space.gap.inline,
|
||||
offset: cx.tokens.size.hit.target,
|
||||
mark: cx.color(overlay.stroke),
|
||||
halo: cx.color(overlay.halo),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// What a capture window reports: how it closed, if it did.
|
||||
#[derive(Debug)]
|
||||
pub(super) struct CaptureWindowOutput {
|
||||
response: Response,
|
||||
/// Escape or the OS closing the window.
|
||||
pub closed: Option<CloseReason>,
|
||||
}
|
||||
|
||||
impl Outcome for CaptureWindowOutput {
|
||||
type Value = NoValue;
|
||||
|
||||
fn response(&self) -> &Response {
|
||||
&self.response
|
||||
}
|
||||
}
|
||||
|
||||
/// A borderless, always-on-top window over one monitor, with no taskbar entry, shown once its first frame is painted.
|
||||
/// Where OS windows are unavailable it is a modal layer at the same rect.
|
||||
#[derive(craft_ui::contract::Component)]
|
||||
#[component(container)]
|
||||
pub(super) struct CaptureWindow {
|
||||
#[common]
|
||||
common: Common,
|
||||
#[container]
|
||||
props: ContainerProps,
|
||||
closed: Option<CloseReason>,
|
||||
}
|
||||
|
||||
impl CaptureWindow {
|
||||
/// A window titled `title` at `over`, the monitor's rect in its own points.
|
||||
pub(super) fn new(title: Label, over: Rect) -> Self {
|
||||
let fallback = Overlay::modal().placed(over).body_scroll(false);
|
||||
let spec = WindowSpec::dialog()
|
||||
.kind(WindowKind::Tool)
|
||||
.chrome(WindowChrome::Integrated)
|
||||
.captions(None)
|
||||
.level(WindowLevel::AlwaysOnTop)
|
||||
.taskbar(false)
|
||||
.shown_after_first_paint(true);
|
||||
let props =
|
||||
ContainerProps::new().surface(SurfaceKind::Canvas).pad(Pad::None).sizing(Sizing::Fill).mount(Mount::viewport_with(fallback, spec));
|
||||
CaptureWindow { common: Common::new(), props, closed: None }.label(title)
|
||||
}
|
||||
}
|
||||
|
||||
impl Component for CaptureWindow {
|
||||
const ROLE: Role = Role::GROUP;
|
||||
type Style = CaptureStyle;
|
||||
type Output = CaptureWindowOutput;
|
||||
|
||||
fn style(cx: &StyleCx<'_>, _: CaptureWindowStyleKey) -> CaptureStyle {
|
||||
CaptureStyle::of(cx)
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> CaptureWindowOutput {
|
||||
CaptureWindowOutput { response: cx.response.clone(), closed: self.closed }
|
||||
}
|
||||
}
|
||||
|
||||
impl Container for CaptureWindow {
|
||||
fn closed(&mut self, why: CloseReason) {
|
||||
self.closed = Some(why);
|
||||
}
|
||||
}
|
||||
|
||||
/// What a capture view reports in one pass.
|
||||
#[derive(Debug)]
|
||||
pub(super) struct CaptureViewOutput {
|
||||
response: Response,
|
||||
/// A primary click picked this desktop pixel (physical pixels).
|
||||
pub picked: Option<Pos2>,
|
||||
/// A secondary click asked to cancel.
|
||||
pub cancelled: bool,
|
||||
/// Wheel notches up (positive) or down this pass.
|
||||
pub notches: i32,
|
||||
}
|
||||
|
||||
impl Outcome for CaptureViewOutput {
|
||||
type Value = NoValue;
|
||||
|
||||
fn response(&self) -> &Response {
|
||||
&self.response
|
||||
}
|
||||
}
|
||||
|
||||
/// One monitor's capture stretched over the view, with a crosshair pointer and the loupe beside it.
|
||||
#[derive(craft_ui::contract::Component)]
|
||||
#[component(content_painter)]
|
||||
pub(super) struct CaptureView<'a> {
|
||||
#[common]
|
||||
common: Common,
|
||||
snapshot: &'a Snapshot,
|
||||
/// The capture's key in the texture store.
|
||||
key: u64,
|
||||
/// Screen pixels per captured pixel in the loupe.
|
||||
zoom: usize,
|
||||
hints: [Label; 2],
|
||||
picked: Option<Pos2>,
|
||||
cancelled: bool,
|
||||
notches: i32,
|
||||
}
|
||||
|
||||
impl<'a> CaptureView<'a> {
|
||||
/// The view of `snapshot`, stored under `key`, its loupe at `zoom`, with the click and wheel `hints`.
|
||||
pub(super) fn new(label: impl Into<Label>, snapshot: &'a Snapshot, key: u64, zoom: usize, hints: [Label; 2]) -> Self {
|
||||
CaptureView { common: Common::new(), snapshot, key, zoom, hints, picked: None, cancelled: false, notches: 0 }.label(label)
|
||||
}
|
||||
|
||||
/// The captured pixel (x, y) shown at `at`, a point of the view at `rect`.
|
||||
fn pixel(&self, rect: Rect, at: Pos2) -> Option<(usize, usize)> {
|
||||
let area = area(self.snapshot);
|
||||
let local = at - rect.min;
|
||||
let [x, y] = area.pixel_at([rect.width(), rect.height()], [local.x, local.y])?;
|
||||
Some(((x - area.origin[0]) as usize, (y - area.origin[1]) as usize))
|
||||
}
|
||||
}
|
||||
|
||||
impl Component for CaptureView<'_> {
|
||||
const ROLE: Role = Role::IMAGE;
|
||||
const PARTS: bool = false;
|
||||
const STOPS: bool = false;
|
||||
const OVERLAYS: bool = false;
|
||||
const SHOWS_LABEL: bool = false;
|
||||
type Style = CaptureStyle;
|
||||
type Output = CaptureViewOutput;
|
||||
|
||||
fn style(cx: &StyleCx<'_>, _: CaptureViewStyleKey) -> CaptureStyle {
|
||||
CaptureStyle::of(cx)
|
||||
}
|
||||
|
||||
/// The capture's size in points: the monitor's own, as it is shown over it.
|
||||
fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
let [_, _, w, h] = area(self.snapshot).cover();
|
||||
vec2(w, h)
|
||||
}
|
||||
|
||||
fn sense(&self) -> Sense {
|
||||
Sense::HOVER | Sense::CLICK | Sense::CONTEXT_CLICK | Sense::WHEEL_Y
|
||||
}
|
||||
|
||||
fn update(&mut self, cx: &mut Cx<'_, Self>) {
|
||||
cx.cursor(Cursor::System(CursorIcon::Crosshair), CursorPriority::Hover);
|
||||
if let Some(wheel) = cx.take_wheel() {
|
||||
self.notches = if wheel.scroll.y > 0.0 {
|
||||
1
|
||||
} else if wheel.scroll.y < 0.0 {
|
||||
-1
|
||||
} else {
|
||||
0
|
||||
};
|
||||
}
|
||||
if let PressPhase::Release { start, pos, click: true, .. } = cx.press().phase {
|
||||
match start.button {
|
||||
PointerButton::Primary => {
|
||||
let area = area(self.snapshot);
|
||||
self.picked = self.pixel(cx.rect, pos).map(|(x, y)| pos2((area.origin[0] + x as i32) as f32, (area.origin[1] + y as i32) as f32));
|
||||
}
|
||||
PointerButton::Secondary => self.cancelled = true,
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
|
||||
let image = &self.snapshot.image;
|
||||
let ctx = &cx.response.ctx;
|
||||
let texture = store(ctx)
|
||||
.get_or_put(ctx, self.key, Revision::default(), || ColorImage::from_rgba_unmultiplied(image.size.map(|n| n as usize), &image.rgba));
|
||||
let whole = Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0));
|
||||
ui.draw().texture(cx.rect, texture.id, whole);
|
||||
let Some(pointer) = cx.response.hover_pos().filter(|at| cx.rect.contains(*at)) else { return };
|
||||
let Some((x, y)) = self.pixel(cx.rect, pointer) else { return };
|
||||
self.loupe(ui, cx, pointer, (x, y));
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> CaptureViewOutput {
|
||||
CaptureViewOutput { response: cx.response.clone(), picked: self.picked, cancelled: self.cancelled, notches: self.notches }
|
||||
}
|
||||
}
|
||||
|
||||
impl CaptureView<'_> {
|
||||
/// The loupe beside `pointer`, kept inside the view: the captured pixels round `pixel`, `zoom` screen pixels to
|
||||
/// each, the centre one outlined black outside white, then the hex and zoom and the two hints.
|
||||
fn loupe(&self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>, pointer: Pos2, (x, y): (usize, usize)) {
|
||||
let draw = ui.draw();
|
||||
let cell = self.zoom as f32 / cx.response.ctx.pixels_per_point();
|
||||
let pad = cx.style.pad;
|
||||
let grid = LOUPE_PIXELS as f32 * cell;
|
||||
let hex = self.snapshot.pixel(x, y).map(|c| format!("#{:02X}{:02X}{:02X}", c.r(), c.g(), c.b())).unwrap_or_default();
|
||||
let readout = TextRun::new(format!("{hex} {}\u{d7}", self.zoom)).role(TypeRole::Mono);
|
||||
let hints = self.hints.each_ref().map(|hint| TextRun::new(cx.env.resolve(hint).as_str().to_owned()).role(TypeRole::Caption));
|
||||
let layouts: Vec<_> = std::iter::once(&readout).chain(hints.iter()).map(|run| draw.layout(run, f32::INFINITY)).collect();
|
||||
let text_width = layouts.iter().map(|layout| layout.size().x).fold(0.0, f32::max);
|
||||
let text_height: f32 = layouts.iter().map(|layout| layout.size().y).sum();
|
||||
let size = vec2(grid.max(text_width) + 2.0 * pad, pad + grid + pad + text_height + pad);
|
||||
let wanted = pointer + Vec2::splat(cx.style.offset);
|
||||
let at = pos2(wanted.x.min(cx.rect.right() - size.x).max(cx.rect.left()), wanted.y.min(cx.rect.bottom() - size.y).max(cx.rect.top()));
|
||||
let area = Rect::from_min_size(at, size);
|
||||
draw.surface(area, SurfaceKind::Popup, Default::default());
|
||||
let origin = at + vec2((size.x - grid) / 2.0, pad);
|
||||
let half = LOUPE_PIXELS / 2;
|
||||
for row in 0..LOUPE_PIXELS {
|
||||
for col in 0..LOUPE_PIXELS {
|
||||
let pixel = (x + col).checked_sub(half).zip((y + row).checked_sub(half)).and_then(|(px, py)| self.snapshot.pixel(px, py));
|
||||
let Some(color) = pixel else { continue };
|
||||
let rect = Rect::from_min_size(origin + vec2(col as f32, row as f32) * cell, Vec2::splat(cell));
|
||||
draw.data_fill(&PaintShape::Rect(rect, CornerRadius::ZERO), DataColor::new(color));
|
||||
}
|
||||
}
|
||||
let centre = Rect::from_min_size(origin + Vec2::splat(half as f32 * cell), Vec2::splat(cell));
|
||||
draw.stroke(&PaintShape::Rect(centre.expand(1.0), CornerRadius::ZERO), StrokeWidth::Hairline, cx.style.halo);
|
||||
draw.stroke(&PaintShape::Rect(centre, CornerRadius::ZERO), StrokeWidth::Hairline, cx.style.mark);
|
||||
let mut line = at + vec2(pad, pad + grid + pad);
|
||||
for layout in &layouts {
|
||||
draw.galley(line, layout);
|
||||
line.y += layout.size().y;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
//! Stories of the screen picker: its pattern and the capture window and view it shows.
|
||||
|
||||
use super::capture::{CaptureView, CaptureWindow};
|
||||
use super::{LOUPE_ZOOM, ScreenColorPicker, ScreenPick, Snapshot, StillCapture, capture};
|
||||
use craft_platform::screen::{Capture, ScreenImage};
|
||||
use craft_ui::contract::{Show as _, ShowContainer as _};
|
||||
use craft_ui::runtime::env::Label;
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use egui::{Rect, Ui, pos2, vec2};
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
/// A monitor of `size` pixels at `origin`, a gradient that tells its pixels apart.
|
||||
fn monitor(origin: [i32; 2], size: [u32; 2], tag: u8) -> ScreenImage {
|
||||
let rgba = (0..size[1]).flat_map(|y| (0..size[0]).flat_map(move |x| [(x * 4) as u8, (y * 4) as u8, tag, 255])).collect();
|
||||
ScreenImage { origin, size, scale: 1.0, rgba: Arc::new(rgba), icc_profile: None, name: format!("monitor {tag}") }
|
||||
}
|
||||
|
||||
/// The story's pick: story values are `Clone + PartialEq + Sync`, which `ScreenPick` is not.
|
||||
#[derive(Clone)]
|
||||
struct SharedPick(Arc<Mutex<ScreenPick>>);
|
||||
|
||||
impl PartialEq for SharedPick {
|
||||
fn eq(&self, other: &Self) -> bool {
|
||||
Arc::ptr_eq(&self.0, &other.0)
|
||||
}
|
||||
}
|
||||
|
||||
/// Shows the capture windows of a pick over a small monitor while the story's `open` value is on; the pick's end turns
|
||||
/// it off.
|
||||
fn captures(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
if !*data.value("open", true) {
|
||||
return StoryOutput::default();
|
||||
}
|
||||
let shared = data.value("pick", SharedPick(Arc::new(Mutex::new(ScreenPick::new())))).0.clone();
|
||||
let mut pick = shared.lock().unwrap_or_else(|e| e.into_inner());
|
||||
if !pick.busy() {
|
||||
pick.start("story");
|
||||
}
|
||||
let image = monitor([0, 0], [96, 72], 1);
|
||||
pick.tick_with(ui.ctx(), 1, &move || Box::new(StillCapture::new(Ok(Capture::Images(vec![image.clone()])))));
|
||||
ScreenColorPicker::new(&mut pick, "Story").show(ui);
|
||||
*data.value("open", true) = pick.busy();
|
||||
StoryOutput::default()
|
||||
}
|
||||
|
||||
#[story(ScreenColorPicker<'static>, covers = [Default], drive = Drive::Never)]
|
||||
fn screen_color_picker(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
captures(ui, data)
|
||||
}
|
||||
|
||||
#[story(CaptureWindow, covers = [Default], drive = Drive::Never)]
|
||||
fn capture_window(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let open = data.value("open", true);
|
||||
if !*open {
|
||||
return StoryOutput::default();
|
||||
}
|
||||
let image = Snapshot::new(monitor([0, 0], [96, 72], 1)).ok().expect("a valid monitor");
|
||||
let [x, y, w, h] = capture::area(&image).cover();
|
||||
let rect = Rect::from_min_size(pos2(x, y), vec2(w, h));
|
||||
let hints = [Label::from("Click to pick"), Label::from("Scroll to zoom")];
|
||||
let shown = CaptureWindow::new(Label::from("Story"), rect).show(ui, |ui, _| {
|
||||
let rect = ui.max_rect();
|
||||
CaptureView::new("monitor 1", &image, 1, LOUPE_ZOOM.1, hints.clone()).show_at(ui, rect)
|
||||
});
|
||||
*open = shown.output.closed.is_none();
|
||||
match shown.inner {
|
||||
Some(output) => StoryOutput::from(output),
|
||||
None => StoryOutput::from(shown.output),
|
||||
}
|
||||
}
|
||||
|
||||
#[story(CaptureView<'static>, covers = [Default], drive = Drive::Never)]
|
||||
fn capture_view(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
let image = Snapshot::new(monitor([0, 0], [96, 72], 1)).ok().expect("a valid monitor");
|
||||
let hints = [Label::from("Click to pick"), Label::from("Scroll to zoom")];
|
||||
StoryOutput::from(CaptureView::new("monitor 1", &image, 1, LOUPE_ZOOM.1, hints).show(ui))
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
//! [`ColorStrip`]: one component of a colour along a vertical strip, the others fixed.
|
||||
|
||||
use super::channels::{QUANTIZE_CELLS, channel_range, channel_step, primary, quantized, settled, snapped};
|
||||
use crate::AreaMode;
|
||||
use craft_behavior::nav::{LARGE_STEPS, StepResult, ValueAxes, ValueSteps, step_value};
|
||||
use craft_behavior::{Axis, Metrics, NavMove, PartKey, PressPhase, Sense, ValueDrag};
|
||||
use craft_theme::ModelValues;
|
||||
use craft_ui::contract::{
|
||||
Access, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Focus as _, Input, Numeric, PaintUi, PartsCx, Pointer as _, Props as _,
|
||||
Remember as _, Role,
|
||||
};
|
||||
use craft_ui::primitives::{PaintShape, StrokeWidth};
|
||||
use craft_ui::runtime::env::Label;
|
||||
use craft_ui::runtime::focus::{ActivateKeys, KeepKeys, KeyUse};
|
||||
use craft_ui::style::{ComponentStyle, DataColor, FocusLook, StyleColor, StyleCx, UiTokens};
|
||||
use egui::{CornerRadius, Mesh, Pos2, Rect, Vec2, pos2};
|
||||
|
||||
#[cfg(feature = "screen-testing")]
|
||||
mod stories;
|
||||
|
||||
/// The strip itself: a press on it sets the value there.
|
||||
const STRIP: PartKey = PartKey::new("strip");
|
||||
|
||||
/// The stops of the strip's colour ramp (PhotoCraft's 24 steps).
|
||||
const RAMP_STEPS: usize = 24;
|
||||
|
||||
/// The style of a colour strip.
|
||||
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
|
||||
#[non_exhaustive]
|
||||
pub struct ColorStripStyle {
|
||||
#[style(metrics)]
|
||||
metrics: Metrics,
|
||||
#[style(focus)]
|
||||
focus: FocusLook,
|
||||
/// The edge round the strip.
|
||||
edge: StyleColor,
|
||||
/// The pointers' fill.
|
||||
pointer: StyleColor,
|
||||
/// The side of the square a pointer triangle fills.
|
||||
pointer_size: f32,
|
||||
}
|
||||
|
||||
/// The value at the start of the running drag.
|
||||
#[derive(Clone, Default)]
|
||||
struct DragStart(f64);
|
||||
|
||||
/// The component strip beside a colour picker's [`ColorArea`](super::ColorArea): the [`AreaMode`]'s strip component
|
||||
/// from its lowest value at the bottom to its highest at the top, the others fixed (PhotoCraft's component strip; hue
|
||||
/// runs from 360 degrees at the top to 0 at the bottom). The HSB hue strip shows pure hues; the others show the
|
||||
/// colour's own values.
|
||||
///
|
||||
/// It edits the mode's model values and changes only its component:
|
||||
///
|
||||
/// - Pointer: a press sets the value under the pointer; a drag moves it (the pointer may leave the strip); Esc during
|
||||
/// a drag cancels it. Values snap to the channel's step.
|
||||
/// - Keys, while focused: Up and Right step the value up, Down and Left down; Shift steps ten; Page Up and Page Down
|
||||
/// move a tenth of the range, Home and End go to its ends. The wheel scrolls the panel. Right to left the strip
|
||||
/// keeps its directions.
|
||||
/// - AccessKit: a `Slider` named `label` ("Hue") with its value, bounds and step, which takes increment, decrement
|
||||
/// and set-value requests.
|
||||
///
|
||||
/// The pointer triangles on both sides are drawn outside its rect.
|
||||
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
|
||||
#[component(content_painter)]
|
||||
pub struct ColorStrip<'a> {
|
||||
#[common]
|
||||
common: Common,
|
||||
mode: AreaMode,
|
||||
values: Bind<'a, ModelValues>,
|
||||
/// Puts the colour the strip reports on this many levels (at least two) per red, green and blue channel, whatever
|
||||
/// the mode: a web-safe strip has 6. The pointer takes the nearest such colour and a key steps to the next
|
||||
/// different one. The strip shows flat rows of the snapped colours.
|
||||
#[prop]
|
||||
quantize: Option<usize>,
|
||||
}
|
||||
|
||||
impl<'a> ColorStrip<'a> {
|
||||
/// A strip named `label` ("Hue") showing `values`, values of `mode`'s model.
|
||||
pub fn new(label: impl Into<Label>, mode: AreaMode, values: Bind<'a, ModelValues>) -> Self {
|
||||
ColorStrip { common: Common::new(), mode, values, quantize: None }.label(label).ltr_axis()
|
||||
}
|
||||
|
||||
fn levels(&self) -> Option<usize> {
|
||||
self.quantize.map(|levels| levels.max(2))
|
||||
}
|
||||
|
||||
/// `values` with the strip's component set to `value`, on its step and the quantised colour.
|
||||
fn with(&self, values: &ModelValues, value: f64) -> ModelValues {
|
||||
let model = self.mode.model();
|
||||
let channel = self.mode.strip();
|
||||
let mut out = *values;
|
||||
out.values[channel] = settled(model, channel, value as f32);
|
||||
match self.levels() {
|
||||
Some(levels) => quantized(model, &out, levels),
|
||||
None => out,
|
||||
}
|
||||
}
|
||||
|
||||
/// The value after the key `mv` held with `mods`, from `values`; a quantising strip steps again until the colour
|
||||
/// is a different one or the component can go no further.
|
||||
fn stepped(&self, values: &ModelValues, mv: NavMove, mods: craft_behavior::MoveMods) -> ModelValues {
|
||||
let model = self.mode.model();
|
||||
let channel = self.mode.strip();
|
||||
let range = channel_range(model, channel);
|
||||
let (min, max) = (*range.start(), *range.end());
|
||||
let step = channel_step(model, channel);
|
||||
let mv = match mv {
|
||||
NavMove::Forward => NavMove::Up,
|
||||
NavMove::Back => NavMove::Down,
|
||||
other => other,
|
||||
};
|
||||
let large = if matches!(mv, NavMove::PageUp | NavMove::PageDown) { (max - min) / LARGE_STEPS } else { step * LARGE_STEPS };
|
||||
let once = |from: f64| match step_value(&ValueSteps::new(from, min, max, step, large), ValueAxes::Vertical, mv, mods) {
|
||||
StepResult::Set(next) => next,
|
||||
_ => from,
|
||||
};
|
||||
let mut next = f64::from(values.values[channel]);
|
||||
let from = self.levels().map(|levels| quantized(model, values, levels));
|
||||
loop {
|
||||
let after = once(next);
|
||||
let moved = after != next;
|
||||
next = after;
|
||||
let unchanged = from.is_some_and(|from| quantized(model, &self.with(values, next), self.levels().unwrap_or(2)) == from);
|
||||
if !(moved && unchanged) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
self.with(values, next)
|
||||
}
|
||||
|
||||
/// The colour of the strip at `value` of its component.
|
||||
fn color_at(&self, base: &ModelValues, value: f32) -> craft_theme::Srgba {
|
||||
let model = self.mode.model();
|
||||
let mut values = *base;
|
||||
values.values[self.mode.strip()] = value;
|
||||
model.to_srgb(&values.values)
|
||||
}
|
||||
}
|
||||
|
||||
impl Component for ColorStrip<'_> {
|
||||
const SINGLE_VALUE: bool = true;
|
||||
const ROLE: Role = Role::SLIDER;
|
||||
const OVERLAYS: bool = false;
|
||||
const KEYS: KeyUse = KeyUse::of(Input::Pointer).with_keep(KeepKeys::BlockArrows).with_activate(ActivateKeys::Neither);
|
||||
type Style = ColorStripStyle;
|
||||
type Output = EditResponse<ModelValues>;
|
||||
|
||||
fn style(cx: &StyleCx<'_>, _: ColorStripStyleKey) -> ColorStripStyle {
|
||||
let tokens = cx.tokens;
|
||||
ColorStripStyle {
|
||||
metrics: Metrics::new().min_size(Vec2::new(tokens.size.icon.lg, tokens.size.plot.height)),
|
||||
focus: cx.focus_look(),
|
||||
edge: cx.color(tokens.color.line.control_edge),
|
||||
pointer: cx.color(tokens.color.text.normal),
|
||||
pointer_size: tokens.size.handle.md,
|
||||
}
|
||||
}
|
||||
|
||||
fn paint_outset(tokens: &UiTokens) -> f32 {
|
||||
tokens.size.handle.md
|
||||
}
|
||||
|
||||
fn sense(&self) -> Sense {
|
||||
Sense::FOCUS
|
||||
}
|
||||
|
||||
fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) {
|
||||
cx.part(STRIP, rect).sense(Sense::CLICK | Sense::DRAG | Sense::TAKE_FOCUS).value_part().pointer_only("the arrow keys step the value");
|
||||
}
|
||||
|
||||
fn bind(&mut self) -> Option<BindMut<'_, ModelValues>> {
|
||||
Some(self.values.reborrow())
|
||||
}
|
||||
|
||||
fn update(&mut self, cx: &mut Cx<'_, Self>) {
|
||||
let model = self.mode.model();
|
||||
let channel = self.mode.strip();
|
||||
let drag = ValueDrag::absolute(cx.rect.bottom()..cx.rect.top(), channel_range(model, channel)).axis(Axis::Y);
|
||||
let start_values = ModelValues::new(model.id(), &[]);
|
||||
let current = |cx: &Cx<'_, Self>| cx.value().copied().unwrap_or(start_values);
|
||||
let press = cx.part(STRIP).press;
|
||||
match press.phase {
|
||||
PressPhase::DragStart { .. } if primary(&press) => {
|
||||
cx.memory::<DragStart>().0 = f64::from(current(&*cx).values[channel]);
|
||||
cx.begin();
|
||||
}
|
||||
PressPhase::Drag { .. } if primary(&press) => {
|
||||
let from = cx.memory::<DragStart>().0;
|
||||
if let Some(next) = drag.value(from, &press, false) {
|
||||
cx.propose(self.with(¤t(&*cx), next));
|
||||
}
|
||||
}
|
||||
PressPhase::Release { click, .. } if primary(&press) => {
|
||||
if cx.gesture().is_some() {
|
||||
let from = cx.memory::<DragStart>().0;
|
||||
if let Some(next) = drag.value(from, &press, false) {
|
||||
cx.propose(self.with(¤t(&*cx), next));
|
||||
}
|
||||
cx.commit();
|
||||
} else if click && let Some(next) = drag.value(0.0, &press.mods(craft_keymap::Mods::NONE), false) {
|
||||
cx.set(self.with(¤t(&*cx), next));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
// A running drag is one edit: keys and SetValue wait for it, and are still taken.
|
||||
let running = cx.gesture().is_some();
|
||||
while let Some((mv, mods)) = cx.intents().take_move() {
|
||||
if !running {
|
||||
let next = self.stepped(¤t(&*cx), mv, mods);
|
||||
cx.set(next);
|
||||
}
|
||||
}
|
||||
if let Some(value) = cx.intents().take_set_value().filter(|value| value.is_finite() && !running) {
|
||||
cx.set(self.with(¤t(&*cx), value));
|
||||
}
|
||||
}
|
||||
|
||||
fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) {
|
||||
let model = self.mode.model();
|
||||
let channel = self.mode.strip();
|
||||
let range = channel_range(model, channel);
|
||||
let numeric = match cx.value() {
|
||||
Some(values) => Numeric::new(f64::from(values.values[channel]), range),
|
||||
None => Numeric::empty(range),
|
||||
};
|
||||
access.numeric(numeric.step(channel_step(model, channel)));
|
||||
}
|
||||
|
||||
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
|
||||
let model = self.mode.model();
|
||||
let channel = self.mode.strip();
|
||||
let range = channel_range(model, channel);
|
||||
let (min, max) = (*range.start() as f32, *range.end() as f32);
|
||||
let rect = cx.rect;
|
||||
let shown = cx.value().copied().unwrap_or_else(|| ModelValues::new(model.id(), &[]));
|
||||
let base = self.mode.strip_base(&shown);
|
||||
let painter = ui.content_painter(cx);
|
||||
match self.levels() {
|
||||
Some(levels) => {
|
||||
let height = rect.height() / QUANTIZE_CELLS as f32;
|
||||
let mut mesh = Mesh::default();
|
||||
for row in 0..QUANTIZE_CELLS {
|
||||
let t = (row as f32 + 0.5) / QUANTIZE_CELLS as f32;
|
||||
let top = rect.top() + row as f32 * height;
|
||||
let color = snapped(self.color_at(&base, egui::lerp(max..=min, t)), levels);
|
||||
mesh.add_colored_rect(Rect::from_min_max(pos2(rect.left(), top), pos2(rect.right(), top + height)), color.into());
|
||||
}
|
||||
painter.painter.add(mesh);
|
||||
}
|
||||
None => {
|
||||
let stops: Vec<(f32, DataColor)> = (0..=RAMP_STEPS)
|
||||
.map(|k| {
|
||||
let t = k as f32 / RAMP_STEPS as f32;
|
||||
(t, DataColor::new(self.color_at(&base, egui::lerp(max..=min, t)).into()))
|
||||
})
|
||||
.collect();
|
||||
painter.ramp(rect, &stops, Axis::Y);
|
||||
}
|
||||
}
|
||||
let draw = ui.draw();
|
||||
draw.stroke(&PaintShape::Rect(rect, CornerRadius::ZERO), StrokeWidth::Thin, cx.style.edge);
|
||||
if cx.value().is_none() {
|
||||
return;
|
||||
}
|
||||
let span = max - min;
|
||||
let share = if span > 0.0 { ((shown.values[channel] - min) / span).clamp(0.0, 1.0) } else { 0.0 };
|
||||
let y = egui::lerp(rect.bottom()..=rect.top(), share);
|
||||
let (depth, half) = (cx.style.pointer_size / 2.0, cx.style.pointer_size / 2.0);
|
||||
for (tip, direction) in [(rect.left(), -1.0), (rect.right(), 1.0)] {
|
||||
let base_x = tip + direction * depth;
|
||||
let points: Vec<Pos2> = vec![pos2(tip, y), pos2(base_x, y - half), pos2(base_x, y + half)];
|
||||
let triangle = PaintShape::Polygon(points);
|
||||
draw.fill(&triangle, cx.style.pointer);
|
||||
draw.stroke(&triangle, StrokeWidth::Thin, cx.style.edge);
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> EditResponse<ModelValues> {
|
||||
cx.edit_response()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
//! Stories of `ColorStrip`: a hue strip and a web-safe one.
|
||||
|
||||
use super::ColorStrip;
|
||||
use crate::AreaMode;
|
||||
use craft_theme::{ColorModel, HsbModel, Srgba};
|
||||
use craft_ui::contract::{Bind, Show as _, Validity};
|
||||
use craft_ui::runtime::env::Message;
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use egui::Ui;
|
||||
|
||||
#[story(ColorStrip<'static>, covers = [Default], drive = Drive::Step)]
|
||||
fn color_strip(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let values = data.value("values", HsbModel.from_srgb(Srgba::rgb(0.2, 0.5, 0.8)));
|
||||
ColorStrip::new("Hue", AreaMode::Hue, Bind::bound(values)).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(ColorStrip<'static>, covers = [], drive = Drive::Never)]
|
||||
fn color_strip_web_safe(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let values = data.value("values", HsbModel.from_srgb(Srgba::rgb(0.2, 0.6, 0.8)));
|
||||
ColorStrip::new("Hue", AreaMode::Hue, Bind::bound(values)).quantize(6).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(ColorStrip<'static>, covers = [Invalid], drive = Drive::Never)]
|
||||
fn color_strip_invalid(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let refuse_dim =
|
||||
|values: &craft_theme::ModelValues| if values.values[2] < 50.0 { Validity::Refuse(Message::new("Too dim")) } else { Validity::Ok };
|
||||
let values = data.value("values", HsbModel.from_srgb(Srgba::rgb(0.1, 0.2, 0.3)));
|
||||
ColorStrip::new("Hue", AreaMode::Hue, Bind::bound(values).check(refuse_dim)).show(ui).into()
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
//! `SwatchesPanel`: the Swatches panel on a [`SwatchLibrary`]: groups of flat touching squares, click to use, the panel
|
||||
//! menu for new swatches, groups and swatch files.
|
||||
|
||||
mod library;
|
||||
mod menu;
|
||||
mod panel;
|
||||
#[cfg(feature = "screen-testing")]
|
||||
mod stories;
|
||||
|
||||
pub use library::{SwatchAt, SwatchKey, SwatchLibrary, SwatchesState};
|
||||
pub use menu::{SwatchesCommand, SwatchesFileOutput, SwatchesMenu, SwatchesMenuOutput};
|
||||
pub use panel::{SwatchesPanel, SwatchesPanelOutput};
|
||||
|
||||
/// The most swatches a library holds (PhotoCraft's `MAX_SWATCHES`).
|
||||
pub const MAX_SWATCHES: usize = 100_000;
|
||||
|
||||
/// The most groups a library holds (PhotoCraft's `MAX_GROUPS`).
|
||||
pub const MAX_GROUPS: usize = 10_000;
|
||||
|
||||
craft_ui::words! {
|
||||
/// The Swatches panel's words.
|
||||
#[non_exhaustive]
|
||||
pub struct SwatchesWords {
|
||||
title: "swatches.title" = "Swatches";
|
||||
/// The name of a new group.
|
||||
group: "swatches.group" = "Group";
|
||||
/// A new swatch's name; `{n}` numbers it.
|
||||
swatch_n: template "swatches.swatchN" = "Color Swatch {n}";
|
||||
/// The name of the file filter of the swatch pickers, and of an exported file.
|
||||
file: "swatches.file" = "Swatches";
|
||||
/// The start of the toast after an import that changed something; the notes follow.
|
||||
notice_import: "swatches.noticeImport" = "Swatches imported with changes";
|
||||
/// The start of the toast after an export that changed something.
|
||||
notice_export: "swatches.noticeExport" = "Swatches exported with changes";
|
||||
/// The toast when a swatch file could not be imported; `{reason}` says why.
|
||||
import_failed: template "swatches.importFailed" = "Swatches could not be imported: {reason}";
|
||||
/// The toast when swatches could not be exported; `{reason}` says why.
|
||||
export_failed: template "swatches.exportFailed" = "Swatches could not be exported: {reason}";
|
||||
groups_flattened: "swatches.groupsFlattened" = "The format has no groups; the swatches were written as one list.";
|
||||
book_read: count "swatches.bookRead" = "{n} color-book color was read as black." | "{n} color-book colors were read as black.";
|
||||
book_left_out: count "swatches.bookLeftOut" = "{n} color-book color was left out." | "{n} color-book colors were left out.";
|
||||
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.";
|
||||
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.";
|
||||
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.";
|
||||
/// The value read for a colour-book colour, which the panel cannot show.
|
||||
book_color: "swatches.bookColor" = "Color book color";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,342 @@
|
||||
//! The swatch library model: keys, state, groups and their editing.
|
||||
|
||||
use std::collections::HashSet;
|
||||
|
||||
use craft_ui::contract::ReorderMove;
|
||||
use craft_ui::patterns::presets::PresetState;
|
||||
|
||||
use super::{MAX_GROUPS, MAX_SWATCHES, SwatchesWords};
|
||||
use crate::palette::{SwatchColor, SwatchEntry, SwatchGroup, SwatchReport};
|
||||
use crate::ui::PickedColor;
|
||||
|
||||
/// What the browser names its rows by. Swatch names are unique across the library and group names among groups, so
|
||||
/// both survive reordering.
|
||||
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
|
||||
#[non_exhaustive]
|
||||
pub enum SwatchKey {
|
||||
/// A group, by name.
|
||||
Group(String),
|
||||
/// A swatch, by name.
|
||||
Swatch(String),
|
||||
}
|
||||
|
||||
/// What the Swatches panel keeps between passes, owned by the host: the browser's view, the selected row, the row to
|
||||
/// rename in place next, and the notes of an export in flight.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct SwatchesState {
|
||||
/// The browser's view settings: thumbnail size, open groups.
|
||||
pub browser: PresetState<SwatchKey>,
|
||||
/// The selected row.
|
||||
pub selected: Option<SwatchKey>,
|
||||
/// A row to open the rename on in the next pass.
|
||||
pub rename: Option<SwatchKey>,
|
||||
/// The notes of the export whose file the host is writing.
|
||||
pub(super) export_notes: Option<SwatchReport>,
|
||||
}
|
||||
|
||||
impl Default for SwatchesState {
|
||||
fn default() -> Self {
|
||||
SwatchesState { browser: PresetState::new(), selected: None, rename: None, export_notes: None }
|
||||
}
|
||||
}
|
||||
|
||||
/// The app's swatches: groups of named swatches, names unique across the library. Kept by the
|
||||
/// app (a settings section or its presets store).
|
||||
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
|
||||
#[serde(default)]
|
||||
#[non_exhaustive]
|
||||
pub struct SwatchLibrary {
|
||||
/// The groups, in display order.
|
||||
pub groups: Vec<SwatchGroup>,
|
||||
}
|
||||
|
||||
impl Default for SwatchLibrary {
|
||||
/// The default swatches ([`default_swatches`](crate::palette::default_swatches)).
|
||||
fn default() -> Self {
|
||||
SwatchLibrary { groups: crate::palette::default_swatches() }
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a swatch is: its group's index and its index in the group.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
#[non_exhaustive]
|
||||
pub struct SwatchAt {
|
||||
/// Index of the group.
|
||||
pub group: usize,
|
||||
/// Index of the swatch within its group.
|
||||
pub index: usize,
|
||||
}
|
||||
|
||||
impl SwatchAt {
|
||||
/// The swatch at `index` of group `group`.
|
||||
pub const fn new(group: usize, index: usize) -> Self {
|
||||
SwatchAt { group, index }
|
||||
}
|
||||
}
|
||||
|
||||
impl SwatchLibrary {
|
||||
/// A library of `groups`.
|
||||
pub fn new(groups: Vec<SwatchGroup>) -> Self {
|
||||
SwatchLibrary { groups }
|
||||
}
|
||||
|
||||
/// Every swatch, in order.
|
||||
pub fn total(&self) -> usize {
|
||||
self.groups.iter().map(|g| g.entries.len()).sum()
|
||||
}
|
||||
|
||||
/// The swatch named `name`.
|
||||
pub fn find(&self, name: &str) -> Option<SwatchAt> {
|
||||
self.groups.iter().enumerate().find_map(|(group, g)| g.entries.iter().position(|e| e.name == name).map(|index| SwatchAt { group, index }))
|
||||
}
|
||||
|
||||
/// The swatch at `at`, or `None` when out of range.
|
||||
pub fn get(&self, at: SwatchAt) -> Option<&SwatchEntry> {
|
||||
self.groups.get(at.group)?.entries.get(at.index)
|
||||
}
|
||||
|
||||
/// Adds `color` to group `group` (the first group when `None`, a new "Swatches" group when
|
||||
/// the library is empty) under a free name ("Color Swatch N" when `name` is `None` or taken);
|
||||
/// where it went, or `None` when the library holds [`MAX_SWATCHES`].
|
||||
// pc: crates/engine/src/cmd/swatch_cmds.rs:150-171 (`swatches.add`: the cap, the name, group 0).
|
||||
pub fn add(&mut self, color: SwatchColor, name: Option<&str>, group: Option<usize>) -> Option<SwatchAt> {
|
||||
self.add_numbered(color, name, group, SwatchesWords::default().swatch_n.as_str())
|
||||
}
|
||||
|
||||
/// [`add`](SwatchLibrary::add) with the template (`{n}`) that names a swatch left without one.
|
||||
pub(super) fn add_numbered(&mut self, color: SwatchColor, name: Option<&str>, group: Option<usize>, template: &str) -> Option<SwatchAt> {
|
||||
if self.groups.iter().map(|g| g.entries.len()).sum::<usize>() >= MAX_SWATCHES {
|
||||
return None;
|
||||
}
|
||||
let name = name.map(str::trim).filter(|n| !n.is_empty() && self.find(n).is_none()).map_or_else(|| self.free_name(template), str::to_owned);
|
||||
if self.groups.is_empty() {
|
||||
self.groups.push(SwatchGroup { name: "Swatches".to_owned(), entries: Vec::new() });
|
||||
}
|
||||
let group = group.unwrap_or(0).min(self.groups.len() - 1);
|
||||
let entries = &mut self.groups[group].entries;
|
||||
entries.push(SwatchEntry::new(name, color));
|
||||
Some(SwatchAt { group, index: entries.len() - 1 })
|
||||
}
|
||||
|
||||
/// The first free name of `template`, numbered from 1.
|
||||
fn free_name(&self, template: &str) -> String {
|
||||
let taken: HashSet<&str> = self.groups.iter().flat_map(|g| g.entries.iter().map(|e| e.name.as_str())).collect();
|
||||
(1..).map(|n| craft_i18n::fmt_plain(template, &[("n", &n.to_string())])).find(|name| !taken.contains(name.as_str())).unwrap_or_default()
|
||||
}
|
||||
|
||||
/// Add to Swatches from the picker: in the model the user typed (CMYK inks or Lab values the
|
||||
/// picker kept), else RGB; `None` when the library is full.
|
||||
// pc: crates/ui-egui/src/panels/swatches_ui.rs:260 `add_from_picker`.
|
||||
pub fn add_picked(&mut self, picked: &PickedColor) -> Option<SwatchAt> {
|
||||
let color = match picked.model {
|
||||
Some(m) if m.model == "cmyk" => SwatchColor::Cmyk([0, 1, 2, 3].map(|i| (m.values[i] / 100.0).clamp(0.0, 1.0))),
|
||||
Some(m) if m.model == "lab" => SwatchColor::Lab([m.values[0], m.values[1], m.values[2]]),
|
||||
_ => SwatchColor::Rgb(picked.color.to_rgb_array().map(|v| v.clamp(0.0, 1.0))),
|
||||
};
|
||||
self.add(color, None, None)
|
||||
}
|
||||
|
||||
/// Renames a swatch; `false` when the name is empty or taken.
|
||||
pub fn rename(&mut self, at: SwatchAt, name: &str) -> bool {
|
||||
let name = name.trim();
|
||||
if name.is_empty() || self.get(at).is_none() {
|
||||
return false;
|
||||
}
|
||||
if self.find(name).is_some_and(|other| other != at) {
|
||||
return false;
|
||||
}
|
||||
self.groups[at.group].entries[at.index].name = name.to_owned();
|
||||
true
|
||||
}
|
||||
|
||||
/// Removes and returns the swatch at `at`, or `None` when out of range.
|
||||
pub fn remove(&mut self, at: SwatchAt) -> Option<SwatchEntry> {
|
||||
let entries = &mut self.groups.get_mut(at.group)?.entries;
|
||||
(at.index < entries.len()).then(|| entries.remove(at.index))
|
||||
}
|
||||
|
||||
/// Moves a swatch to the end of group `to`.
|
||||
pub fn move_to(&mut self, at: SwatchAt, to: usize) {
|
||||
if to >= self.groups.len() {
|
||||
return;
|
||||
}
|
||||
if let Some(entry) = self.remove(at) {
|
||||
self.groups[to].entries.push(entry);
|
||||
}
|
||||
}
|
||||
|
||||
/// Adds an empty group named `name` (made unique); its index, or `None` when the library
|
||||
/// holds [`MAX_GROUPS`].
|
||||
pub fn new_group(&mut self, name: &str) -> Option<usize> {
|
||||
if self.groups.len() >= MAX_GROUPS {
|
||||
return None;
|
||||
}
|
||||
let name = self.unique_group_name(name.trim());
|
||||
self.groups.push(SwatchGroup { name, entries: Vec::new() });
|
||||
Some(self.groups.len() - 1)
|
||||
}
|
||||
|
||||
/// `base`, or `base 1`, `base 2`… when a group has it.
|
||||
fn unique_group_name(&self, base: &str) -> String {
|
||||
let taken = |n: &str| self.groups.iter().any(|g| g.name == n);
|
||||
if !taken(base) { base.to_owned() } else { (1..).map(|i| format!("{base} {i}")).find(|n| !taken(n)).unwrap_or_default() }
|
||||
}
|
||||
|
||||
/// Renames a group; `false` when the name is empty or another group has it.
|
||||
pub(super) fn rename_group(&mut self, group: usize, name: &str) -> bool {
|
||||
let name = name.trim();
|
||||
if name.is_empty() || group >= self.groups.len() || self.groups.iter().enumerate().any(|(i, g)| i != group && g.name == name) {
|
||||
return false;
|
||||
}
|
||||
self.groups[group].name = name.to_owned();
|
||||
true
|
||||
}
|
||||
|
||||
/// Appends the groups read from a file (names made unique), or replaces the library with
|
||||
/// them.
|
||||
// pc: crates/ui-egui/src/panels/swatches_ui.rs:155 `import_bytes` (`mode: append | replace`).
|
||||
pub fn import(&mut self, groups: Vec<SwatchGroup>, replace: bool) {
|
||||
if replace {
|
||||
self.groups.clear();
|
||||
}
|
||||
let mut taken: HashSet<String> = self.groups.iter().flat_map(|g| g.entries.iter().map(|e| e.name.clone())).collect();
|
||||
let mut group_taken: HashSet<String> = self.groups.iter().map(|g| g.name.clone()).collect();
|
||||
for mut group in groups {
|
||||
if group_taken.contains(&group.name) {
|
||||
group.name = (1..).map(|i| format!("{} {i}", group.name)).find(|n| !group_taken.contains(n)).unwrap_or_default();
|
||||
}
|
||||
group_taken.insert(group.name.clone());
|
||||
for entry in &mut group.entries {
|
||||
if taken.contains(&entry.name) {
|
||||
entry.name = (2..).map(|i| format!("{} {i}", entry.name)).find(|n| !taken.contains(n)).unwrap_or_default();
|
||||
}
|
||||
taken.insert(entry.name.clone());
|
||||
}
|
||||
self.groups.push(group);
|
||||
}
|
||||
}
|
||||
|
||||
/// Applies a reorder of the browser: swatches go into a group at a place, or groups to a place among the
|
||||
/// groups. `to` counts in the flat rows (a header, then its swatches) that remain once the moved ones are
|
||||
/// taken out. Anything else leaves the library as it is.
|
||||
pub fn apply_reorder(&mut self, mv: &ReorderMove<SwatchKey>) -> bool {
|
||||
if mv.copy {
|
||||
return false;
|
||||
}
|
||||
let swatches: Option<Vec<&str>> = mv.keys.iter().map(|k| if let SwatchKey::Swatch(n) = k { Some(n.as_str()) } else { None }).collect();
|
||||
let groups: Option<Vec<&str>> = mv.keys.iter().map(|k| if let SwatchKey::Group(n) = k { Some(n.as_str()) } else { None }).collect();
|
||||
if let Some(names) = swatches {
|
||||
return self.move_swatches(&names, mv.to, mv.parent.as_ref());
|
||||
}
|
||||
groups.is_some_and(|names| self.move_groups(&names, mv.to))
|
||||
}
|
||||
|
||||
/// The flat rows of the browser: each group's header, then its swatches.
|
||||
fn flat(&self) -> Vec<SwatchKey> {
|
||||
let mut rows = Vec::new();
|
||||
for group in &self.groups {
|
||||
rows.push(SwatchKey::Group(group.name.clone()));
|
||||
rows.extend(group.entries.iter().map(|e| SwatchKey::Swatch(e.name.clone())));
|
||||
}
|
||||
rows
|
||||
}
|
||||
|
||||
fn move_swatches(&mut self, names: &[&str], to: usize, parent: Option<&SwatchKey>) -> bool {
|
||||
let moved = |e: &SwatchEntry| names.contains(&e.name.as_str());
|
||||
let remaining: Vec<SwatchKey> =
|
||||
self.flat().into_iter().filter(|k| !matches!(k, SwatchKey::Swatch(n) if names.contains(&n.as_str()))).collect();
|
||||
let before = &remaining[..to.min(remaining.len())];
|
||||
// The slot is counted in the entries that stay, so it survives taking the moved ones out.
|
||||
let (group, slot) = match before.last() {
|
||||
Some(SwatchKey::Swatch(n)) => {
|
||||
let Some(at) = self.find(n) else { return false };
|
||||
let entries = &self.groups[at.group].entries;
|
||||
let slot = entries[..=at.index].iter().filter(|e| !moved(e)).count();
|
||||
match parent {
|
||||
Some(SwatchKey::Group(g)) if self.groups[at.group].name != *g => match self.groups.iter().position(|x| x.name == *g) {
|
||||
Some(group) => (group, 0),
|
||||
None => return false,
|
||||
},
|
||||
_ => (at.group, slot),
|
||||
}
|
||||
}
|
||||
Some(SwatchKey::Group(g)) => match self.groups.iter().position(|x| x.name == *g) {
|
||||
Some(group) => (group, 0),
|
||||
None => return false,
|
||||
},
|
||||
None => (0, 0),
|
||||
};
|
||||
if group >= self.groups.len() {
|
||||
return false;
|
||||
}
|
||||
let mut taken = Vec::new();
|
||||
for g in &mut self.groups {
|
||||
let (out, keep): (Vec<_>, Vec<_>) = std::mem::take(&mut g.entries).into_iter().partition(|e| moved(e));
|
||||
g.entries = keep;
|
||||
taken.extend(out);
|
||||
}
|
||||
if taken.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let entries = &mut self.groups[group].entries;
|
||||
let slot = slot.min(entries.len());
|
||||
entries.splice(slot..slot, taken);
|
||||
true
|
||||
}
|
||||
|
||||
fn move_groups(&mut self, names: &[&str], to: usize) -> bool {
|
||||
let moved = |g: &SwatchGroup| names.contains(&g.name.as_str());
|
||||
let remaining: Vec<SwatchKey> = {
|
||||
let mut rows = Vec::new();
|
||||
for group in self.groups.iter().filter(|g| !moved(g)) {
|
||||
rows.push(SwatchKey::Group(group.name.clone()));
|
||||
rows.extend(group.entries.iter().map(|e| SwatchKey::Swatch(e.name.clone())));
|
||||
}
|
||||
rows
|
||||
};
|
||||
let slot = remaining[..to.min(remaining.len())].iter().filter(|k| matches!(k, SwatchKey::Group(_))).count();
|
||||
let (taken, keep): (Vec<_>, Vec<_>) = std::mem::take(&mut self.groups).into_iter().partition(|g| moved(g));
|
||||
self.groups = keep;
|
||||
if taken.is_empty() {
|
||||
return false;
|
||||
}
|
||||
let slot = slot.min(self.groups.len());
|
||||
self.groups.splice(slot..slot, taken);
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
impl SwatchLibrary {
|
||||
/// The index of the group `key` is, or is in.
|
||||
pub(super) fn group_of(&self, key: &SwatchKey) -> Option<usize> {
|
||||
match key {
|
||||
SwatchKey::Swatch(name) => self.find(name).map(|at| at.group),
|
||||
SwatchKey::Group(name) => self.groups.iter().position(|g| g.name == *name),
|
||||
}
|
||||
}
|
||||
|
||||
/// Whether `key` names a row of the library.
|
||||
pub(super) fn has(&self, key: &SwatchKey) -> bool {
|
||||
match key {
|
||||
SwatchKey::Swatch(name) => self.find(name).is_some(),
|
||||
SwatchKey::Group(name) => self.groups.iter().any(|g| g.name == *name),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A swatch's value in its own model, for the tooltip and a screen reader.
|
||||
pub(super) fn value_text(color: &SwatchColor, book: &str) -> String {
|
||||
let pct = |v: f32| (v * 100.0).round();
|
||||
match *color {
|
||||
SwatchColor::Rgb(v) => {
|
||||
let [r, g, b] = v.map(|c| (c.clamp(0.0, 1.0) * 255.0).round() as u8);
|
||||
format!("#{r:02x}{g:02x}{b:02x}")
|
||||
}
|
||||
SwatchColor::Hsb([h, s, b]) => format!("H {} S {}% B {}%", h.round(), pct(s), pct(b)),
|
||||
SwatchColor::Cmyk([c, m, y, k]) => format!("C {}% M {}% Y {}% K {}%", pct(c), pct(m), pct(y), pct(k)),
|
||||
SwatchColor::Lab([l, a, b]) => format!("L {} a {} b {}", l.round(), a.round(), b.round()),
|
||||
SwatchColor::Gray(k) => format!("K {}%", pct(k)),
|
||||
SwatchColor::Book { .. } => book.to_owned(),
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
//! The Swatches panel menu, its commands and file import and export.
|
||||
|
||||
use craft_behavior::EditEvent;
|
||||
use craft_cms::convert::CmykConverter;
|
||||
use craft_theme::Srgba;
|
||||
use craft_theme::variant::Tone;
|
||||
use craft_ui::contract::CommandSet;
|
||||
use craft_ui::menu::PanelRow;
|
||||
use craft_ui::patterns::presets::{PresetCommands, PresetEvent, PresetExport, PresetFileRequest, PresetFiles, PresetFooterEvent};
|
||||
use craft_ui::runtime::commands::{CommandRef, CommandState};
|
||||
use craft_ui::runtime::toast::Toast;
|
||||
|
||||
use super::{SwatchAt, SwatchKey, SwatchLibrary, SwatchesState, SwatchesWords};
|
||||
use crate::palette::{SwatchColor, SwatchFormat, SwatchReport};
|
||||
|
||||
/// The purpose of the swatch file pickers: their folder is remembered under it.
|
||||
const PICK_PURPOSE: &str = "swatches";
|
||||
|
||||
/// What [`SwatchesPanel::apply_file`] did.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
#[must_use = "the host saves a changed library and posts the toast"]
|
||||
pub struct SwatchesFileOutput {
|
||||
/// The library changed: the app saves it.
|
||||
pub changed: bool,
|
||||
/// The notes of the swatch file that was read or written, once the panel has handled it.
|
||||
pub report: Option<SwatchReport>,
|
||||
/// The toast for the notes that lost something or for a failure.
|
||||
pub toast: Option<Toast>,
|
||||
}
|
||||
|
||||
/// The commands of the Swatches panel menu, in Photoshop's words.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, CommandSet)]
|
||||
#[command(prefix = "swatches")]
|
||||
#[non_exhaustive]
|
||||
pub enum SwatchesCommand {
|
||||
/// Add the foreground colour as a swatch.
|
||||
#[command(label = "New Swatch…")]
|
||||
NewSwatch,
|
||||
/// Add an empty group.
|
||||
#[command(label = "New Swatch Group…")]
|
||||
NewGroup,
|
||||
/// Add the swatches of a file.
|
||||
#[command(label = "Import Swatches…")]
|
||||
Import,
|
||||
/// Replace the swatches with those of a file.
|
||||
#[command(label = "Replace Swatches…")]
|
||||
Replace,
|
||||
/// Write the swatches to a Photoshop swatch file.
|
||||
#[command(label = "Export Swatches…")]
|
||||
Export,
|
||||
/// Write the swatches to an exchange file with their groups.
|
||||
#[command(label = "Export Swatches for Exchange…")]
|
||||
ExportExchange,
|
||||
/// Put the default swatches back.
|
||||
#[command(label = "Reset Swatches")]
|
||||
Reset,
|
||||
}
|
||||
|
||||
impl SwatchesCommand {
|
||||
/// Every command, in menu order.
|
||||
pub const ALL: [SwatchesCommand; 7] = [
|
||||
SwatchesCommand::NewSwatch,
|
||||
SwatchesCommand::NewGroup,
|
||||
SwatchesCommand::Import,
|
||||
SwatchesCommand::Replace,
|
||||
SwatchesCommand::Export,
|
||||
SwatchesCommand::ExportExchange,
|
||||
SwatchesCommand::Reset,
|
||||
];
|
||||
}
|
||||
|
||||
/// What [`SwatchesMenu::run_command`] did.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
#[must_use = "the app saves a changed library and answers the file request"]
|
||||
pub struct SwatchesMenuOutput {
|
||||
/// The library changed: the app saves it.
|
||||
pub changed: bool,
|
||||
/// The file dialog the command asks the host for; the host answers with [`SwatchesPanel::apply_file`].
|
||||
pub file: Option<PresetFileRequest>,
|
||||
/// A toast for a command that failed before it asked for a file.
|
||||
pub toast: Option<Toast>,
|
||||
}
|
||||
|
||||
/// The Swatches panel menu: the rows for the dock's panel menu, the states the host publishes, and the carrying out
|
||||
/// of a fired command.
|
||||
pub struct SwatchesMenu;
|
||||
|
||||
impl SwatchesMenu {
|
||||
/// The rows: New Swatch…, New Swatch Group…, a separator, Import, Replace, Export and Export for Exchange, a
|
||||
/// separator, Reset Swatches.
|
||||
pub fn rows() -> Vec<PanelRow> {
|
||||
let row = |command: SwatchesCommand| PanelRow::Command(CommandRef::from(command));
|
||||
vec![
|
||||
row(SwatchesCommand::NewSwatch),
|
||||
row(SwatchesCommand::NewGroup),
|
||||
PanelRow::Separator,
|
||||
row(SwatchesCommand::Import),
|
||||
row(SwatchesCommand::Replace),
|
||||
row(SwatchesCommand::Export),
|
||||
row(SwatchesCommand::ExportExchange),
|
||||
PanelRow::Separator,
|
||||
row(SwatchesCommand::Reset),
|
||||
]
|
||||
}
|
||||
|
||||
/// The state of each command: both exports are disabled while the library has no swatch.
|
||||
pub fn states(library: &SwatchLibrary) -> Vec<(SwatchesCommand, CommandState)> {
|
||||
let exports = library.total() > 0;
|
||||
SwatchesCommand::ALL
|
||||
.into_iter()
|
||||
.map(|command| {
|
||||
let enabled = !matches!(command, SwatchesCommand::Export | SwatchesCommand::ExportExchange) || exports;
|
||||
(command, CommandState::new().enabled(enabled))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// Carries out `command`. New Swatch adds the foreground to the selected swatch's (or group's) group, as the
|
||||
/// footer's New does, and the panel selects it and opens its name for editing in its next pass; New Swatch Group
|
||||
/// and Reset Swatches act on `library`. Import, Replace and the two exports give the file request for the host.
|
||||
pub fn run_command(
|
||||
library: &mut SwatchLibrary,
|
||||
state: &mut SwatchesState,
|
||||
command: SwatchesCommand,
|
||||
foreground: Srgba,
|
||||
words: &SwatchesWords,
|
||||
) -> SwatchesMenuOutput {
|
||||
let mut output = SwatchesMenuOutput { changed: false, file: None, toast: None };
|
||||
let readable: Vec<&str> = SwatchFormat::ALL.iter().filter(|f| f.can_read()).map(|f| f.extension()).collect();
|
||||
let import = || PresetFiles::<SwatchKey>::new(PICK_PURPOSE, words.file.as_str(), &readable).replace(true);
|
||||
match command {
|
||||
SwatchesCommand::NewSwatch => {
|
||||
let group = state.selected.as_ref().and_then(|key| library.group_of(key));
|
||||
let color = SwatchColor::Rgb(foreground.to_rgb_array().map(|v| v.clamp(0.0, 1.0)));
|
||||
let at = library.add_numbered(color, None, group, words.swatch_n.as_str());
|
||||
output.changed = at.is_some();
|
||||
if let Some(entry) = at.and_then(|at| library.get(at)) {
|
||||
let key = SwatchKey::Swatch(entry.name.clone());
|
||||
state.selected = Some(key.clone());
|
||||
state.rename = Some(key);
|
||||
}
|
||||
}
|
||||
SwatchesCommand::NewGroup => {
|
||||
let at = library.new_group(words.group.as_str());
|
||||
output.changed = at.is_some();
|
||||
if let Some(at) = at {
|
||||
state.rename = Some(SwatchKey::Group(library.groups[at].name.clone()));
|
||||
}
|
||||
}
|
||||
SwatchesCommand::Reset => {
|
||||
library.groups = crate::palette::default_swatches();
|
||||
output.changed = true;
|
||||
}
|
||||
SwatchesCommand::Import => output.file = import().request(PresetCommands::Load, None),
|
||||
SwatchesCommand::Replace => output.file = import().request(PresetCommands::Replace, None),
|
||||
SwatchesCommand::Export => Self::export(library, state, SwatchFormat::Aco, words, &mut output),
|
||||
SwatchesCommand::ExportExchange => Self::export(library, state, SwatchFormat::Ase, words, &mut output),
|
||||
}
|
||||
output
|
||||
}
|
||||
|
||||
/// The file request that writes the library as `format`; a library the format cannot hold is a toast.
|
||||
fn export(library: &SwatchLibrary, state: &mut SwatchesState, format: SwatchFormat, words: &SwatchesWords, output: &mut SwatchesMenuOutput) {
|
||||
match crate::palette::write_swatches(&library.groups, format) {
|
||||
Ok((bytes, report)) => {
|
||||
let file_name = format!("{}.{}", words.file.as_str(), format.extension());
|
||||
let files = PresetFiles::<SwatchKey>::new(PICK_PURPOSE, words.file.as_str(), &[format.extension()])
|
||||
.export(move |_| Some(PresetExport::new(file_name.clone(), bytes.clone())));
|
||||
output.file = files.request(PresetCommands::Save, None);
|
||||
state.export_notes = Some(report);
|
||||
}
|
||||
Err(error) => output.toast = Some(Toast::new(words.export_failed.fill(&[("reason", &error.to_string())])).tone(Tone::Bad)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The events of one pass applied to the library and the panel's state.
|
||||
pub(super) struct Actions<'a> {
|
||||
pub(super) library: &'a mut SwatchLibrary,
|
||||
pub(super) st: &'a mut SwatchesState,
|
||||
pub(super) used: &'a mut Option<(SwatchAt, Srgba, bool)>,
|
||||
pub(super) changed: &'a mut bool,
|
||||
pub(super) foreground: Srgba,
|
||||
pub(super) template: &'a str,
|
||||
pub(super) group_name: &'a str,
|
||||
pub(super) cmyk: &'a CmykConverter,
|
||||
}
|
||||
|
||||
impl Actions<'_> {
|
||||
pub(super) fn event(&mut self, event: PresetEvent<SwatchKey>) {
|
||||
match event {
|
||||
PresetEvent::Select { key: SwatchKey::Swatch(name), mods, .. } => {
|
||||
self.st.selected = Some(SwatchKey::Swatch(name.clone()));
|
||||
if let Some(at) = self.library.find(&name)
|
||||
&& let Some(entry) = self.library.get(at)
|
||||
{
|
||||
let background = mods.alt || mods.cmd || mods.ctrl;
|
||||
*self.used = Some((at, entry.color.to_srgb(self.cmyk), background));
|
||||
}
|
||||
}
|
||||
PresetEvent::Select { key, .. } | PresetEvent::Activate { key, .. } => {
|
||||
self.st.selected = Some(key).filter(|k| matches!(k, SwatchKey::Swatch(_)))
|
||||
}
|
||||
PresetEvent::Rename { key: SwatchKey::Swatch(old), text, .. } => {
|
||||
if let Some(at) = self.library.find(&old)
|
||||
&& self.library.rename(at, &text)
|
||||
{
|
||||
*self.changed = true;
|
||||
if self.st.selected == Some(SwatchKey::Swatch(old)) {
|
||||
self.st.selected = Some(SwatchKey::Swatch(text.trim().to_owned()));
|
||||
}
|
||||
}
|
||||
}
|
||||
PresetEvent::Rename { key: SwatchKey::Group(old), text, .. } => {
|
||||
if let Some(group) = self.library.groups.iter().position(|g| g.name == old)
|
||||
&& self.library.rename_group(group, &text)
|
||||
{
|
||||
*self.changed = true;
|
||||
}
|
||||
}
|
||||
PresetEvent::Delete(key) => self.delete(&key),
|
||||
PresetEvent::MoveTo { key: SwatchKey::Swatch(name), group: SwatchKey::Group(to), .. } => {
|
||||
if let (Some(at), Some(to)) = (self.library.find(&name), self.library.groups.iter().position(|g| g.name == to)) {
|
||||
self.library.move_to(at, to);
|
||||
*self.changed = true;
|
||||
}
|
||||
}
|
||||
PresetEvent::Reorder(EditEvent::Commit { after, .. } | EditEvent::Set { after, .. }) => {
|
||||
*self.changed |= self.library.apply_reorder(&after);
|
||||
}
|
||||
PresetEvent::Footer(footer) => self.footer(footer),
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
fn footer(&mut self, event: PresetFooterEvent<SwatchKey>) {
|
||||
match event {
|
||||
PresetFooterEvent::New => self.new_swatch(),
|
||||
PresetFooterEvent::NewGroup => {
|
||||
if let Some(at) = self.library.new_group(self.group_name) {
|
||||
self.st.rename = Some(SwatchKey::Group(self.library.groups[at].name.clone()));
|
||||
*self.changed = true;
|
||||
}
|
||||
}
|
||||
PresetFooterEvent::Delete => {
|
||||
if let Some(key) = self.st.selected.clone() {
|
||||
self.delete(&key);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
/// The foreground colour into the selected swatch's group, named and selected, then renamed in place.
|
||||
fn new_swatch(&mut self) {
|
||||
let group = self.st.selected.as_ref().and_then(|key| self.library.group_of(key));
|
||||
let color = SwatchColor::Rgb(self.foreground.to_rgb_array().map(|v| v.clamp(0.0, 1.0)));
|
||||
let Some(at) = self.library.add_numbered(color, None, group, self.template) else {
|
||||
return;
|
||||
};
|
||||
if let Some(entry) = self.library.get(at) {
|
||||
let key = SwatchKey::Swatch(entry.name.clone());
|
||||
self.st.selected = Some(key.clone());
|
||||
self.st.rename = Some(key);
|
||||
}
|
||||
*self.changed = true;
|
||||
}
|
||||
|
||||
fn delete(&mut self, key: &SwatchKey) {
|
||||
let removed = match key {
|
||||
SwatchKey::Swatch(name) => self.library.find(name).and_then(|at| self.library.remove(at)).is_some(),
|
||||
SwatchKey::Group(name) => match self.library.groups.iter().position(|g| g.name == *name) {
|
||||
Some(group) => {
|
||||
self.library.groups.remove(group);
|
||||
true
|
||||
}
|
||||
None => false,
|
||||
},
|
||||
};
|
||||
if removed {
|
||||
*self.changed = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
//! `SwatchesPanel`: the panel body, its state and what it reports.
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
use craft_cms::convert::CmykConverter;
|
||||
use craft_i18n::Format;
|
||||
use craft_theme::Srgba;
|
||||
use craft_theme::variant::Tone;
|
||||
use craft_ui::choice::SwatchFace;
|
||||
use craft_ui::contract::{Bind, Held, NoValue, Outcome, Pattern, ShowContainer as _, request_rename};
|
||||
use craft_ui::layout_components::Stack;
|
||||
use craft_ui::patterns::presets::{PresetBrowser, PresetFileEvent, PresetFooterOptions, PresetReorder, PresetRow, PresetWords, ThumbInfo};
|
||||
use craft_ui::primitives::ContentPainterCx;
|
||||
use craft_ui::runtime::env::{Count, Env};
|
||||
use craft_ui::runtime::toast::Toast;
|
||||
use egui::{Rect, Response, Ui};
|
||||
|
||||
use super::library::value_text;
|
||||
use super::menu::Actions;
|
||||
use super::{SwatchAt, SwatchKey, SwatchLibrary, SwatchesFileOutput, SwatchesState, SwatchesWords};
|
||||
use crate::palette::{SwatchColor, SwatchNote, SwatchReport};
|
||||
|
||||
/// What [`SwatchesPanel::show`] reports.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
#[must_use = "the host applies the swatch"]
|
||||
pub struct SwatchesPanelOutput {
|
||||
/// The panel's response.
|
||||
pub response: Response,
|
||||
/// A swatch was clicked: its colour (through the document's converter) for the foreground, or for the background
|
||||
/// when Alt (Ctrl or Cmd too, as PhotoCraft) was held.
|
||||
pub used: Option<(SwatchAt, Srgba, bool)>,
|
||||
/// The library changed (new, rename, delete, move, group edits): the app saves it.
|
||||
pub changed: bool,
|
||||
}
|
||||
|
||||
impl Outcome for SwatchesPanelOutput {
|
||||
type Value = NoValue;
|
||||
|
||||
fn response(&self) -> &Response {
|
||||
&self.response
|
||||
}
|
||||
}
|
||||
|
||||
/// The Swatches panel on a [`SwatchLibrary`], built on `PresetBrowser`: groups as folders, swatches as flat touching
|
||||
/// squares with no gap or corner radius (Photoshop), the size the browser's zoom chooses.
|
||||
///
|
||||
/// - Click uses the swatch for the foreground; Alt-click (or Ctrl or Cmd) for the background. The swatch is selected.
|
||||
/// Double-click or F2 renames in place; Delete removes; dragging onto a group moves it. Swatches do not drop onto
|
||||
/// the canvas.
|
||||
/// - The footer's + is New Swatch: the foreground colour into the selected swatch's group, named "Color Swatch N", then
|
||||
/// renamed in place.
|
||||
/// - Tooltips name the swatch and its value; AccessKit as the preset browser's grid, each swatch named.
|
||||
/// - The files of Import, Replace and Export go out as [`PresetFileRequest`]s from the panel menu; the host answers
|
||||
/// them with [`SwatchesPanel::apply_file`].
|
||||
#[must_use = "show the panel with `show`"]
|
||||
#[derive(Pattern)]
|
||||
pub struct SwatchesPanel<'a> {
|
||||
library: Bind<'a, SwatchLibrary>,
|
||||
state: Bind<'a, SwatchesState>,
|
||||
cmyk: Option<&'a CmykConverter>,
|
||||
foreground: Srgba,
|
||||
}
|
||||
|
||||
/// What the body decided; `show` stores it after the real run.
|
||||
struct Settled {
|
||||
before: SwatchLibrary,
|
||||
lib: SwatchLibrary,
|
||||
before_state: SwatchesState,
|
||||
st: SwatchesState,
|
||||
used: Option<(SwatchAt, Srgba, bool)>,
|
||||
changed: bool,
|
||||
}
|
||||
|
||||
impl<'a> SwatchesPanel<'a> {
|
||||
/// The panel over `library` and the host-owned `state`; `foreground` is what New Swatch adds.
|
||||
pub fn new(library: Bind<'a, SwatchLibrary>, state: Bind<'a, SwatchesState>, foreground: Srgba) -> Self {
|
||||
SwatchesPanel { library, state, cmyk: None, foreground }
|
||||
}
|
||||
|
||||
/// The document's CMYK converter, which draws CMYK swatches and gives their colours when used; without it they
|
||||
/// use the built-in coated CMYK.
|
||||
pub fn cmyk(mut self, converter: &'a CmykConverter) -> Self {
|
||||
self.cmyk = Some(converter);
|
||||
self
|
||||
}
|
||||
|
||||
/// Draws the panel and returns the user's actions this pass.
|
||||
pub fn show(self, ui: &mut Ui) -> SwatchesPanelOutput {
|
||||
let SwatchesPanel { library, state, cmyk, foreground } = self;
|
||||
let cmyk = cmyk.unwrap_or_else(|| CmykConverter::coated());
|
||||
let words = Env::of(ui).words::<SwatchesWords>();
|
||||
let mut held_library = Held::new(library);
|
||||
let mut held_state = Held::new(state);
|
||||
let ctx = ui.ctx().clone();
|
||||
let rename_scope = ui.scope_id().with("browser-rows");
|
||||
let mut shown = Stack::new().show(ui, |ui, cx| {
|
||||
let (Some(before), Some(before_state)) = (held_library.read(cx), held_state.read(cx)) else { return None };
|
||||
let (mut used, mut changed) = (None, false);
|
||||
let (mut lib, mut st) = (before.clone(), before_state.clone());
|
||||
if st.selected.as_ref().is_some_and(|k| !lib.has(k)) {
|
||||
st.selected = None;
|
||||
}
|
||||
let mut rows = Vec::with_capacity(lib.total() + lib.groups.len());
|
||||
for group in &lib.groups {
|
||||
rows.push(PresetRow::group(SwatchKey::Group(group.name.clone()), group.name.as_str(), 0).count(group.entries.len()));
|
||||
for entry in &group.entries {
|
||||
let named = format!("{}, {}", entry.name, value_text(&entry.color, words.book_color.as_str()));
|
||||
rows.push(
|
||||
PresetRow::item(SwatchKey::Swatch(entry.name.clone()), entry.name.as_str(), 1).tooltip(named.clone()).accessible_name(named),
|
||||
);
|
||||
}
|
||||
}
|
||||
let out = {
|
||||
let colors: HashMap<&str, &SwatchColor> =
|
||||
lib.groups.iter().flat_map(|g| g.entries.iter().map(|e| (e.name.as_str(), &e.color))).collect();
|
||||
let mut browser = PresetBrowser::new(words.title.clone(), Bind::bound(&mut st.browser), &rows)
|
||||
.toolbar(true)
|
||||
.reorder(PresetReorder::items_and_groups())
|
||||
.footer(PresetFooterOptions::new().can_delete(st.selected.is_some()))
|
||||
.thumb(|cx: &ContentPainterCx<'_>, rect: Rect, info: ThumbInfo<'_, SwatchKey>| {
|
||||
if let SwatchKey::Swatch(name) = info.key
|
||||
&& let Some(color) = colors.get(name.as_str())
|
||||
{
|
||||
SwatchFace::new(color.to_srgb(cmyk)).selected(info.selected).paint(cx, rect);
|
||||
}
|
||||
});
|
||||
if let Some(key) = &st.selected {
|
||||
browser = browser.selected(key.clone());
|
||||
}
|
||||
browser.show(ui)
|
||||
};
|
||||
let mut actions = Actions {
|
||||
library: &mut lib,
|
||||
st: &mut st,
|
||||
used: &mut used,
|
||||
changed: &mut changed,
|
||||
foreground,
|
||||
template: words.swatch_n.as_str(),
|
||||
group_name: words.group.as_str(),
|
||||
cmyk,
|
||||
};
|
||||
for event in out.events {
|
||||
actions.event(event);
|
||||
}
|
||||
Some(Settled { before, lib, before_state, st, used, changed })
|
||||
});
|
||||
// Once per pass, after the real run: the rename request and the edited library and state are stored.
|
||||
let (used, changed) = shown
|
||||
.settle(|cx, settled| {
|
||||
let Settled { before, lib, before_state, mut st, used, changed } = settled.take()?;
|
||||
if let Some(key) = st.rename.take() {
|
||||
request_rename(&ctx, rename_scope, &key);
|
||||
}
|
||||
if changed {
|
||||
held_library.write(cx, &before, lib, words.title.as_str());
|
||||
}
|
||||
if st != before_state {
|
||||
held_state.write(cx, &before_state, st, words.title.as_str());
|
||||
}
|
||||
Some((used, changed))
|
||||
})
|
||||
.flatten()
|
||||
.unwrap_or_default();
|
||||
SwatchesPanelOutput { response: shown.output, used, changed }
|
||||
}
|
||||
|
||||
/// Carries out the host's answer to a file request of the panel menu: Import and Replace read the file into
|
||||
/// `library`, a finished export reports the notes it kept, and a failure says why. Returns what changed and the
|
||||
/// toast the host posts, if any.
|
||||
pub fn apply_file(
|
||||
library: &mut SwatchLibrary,
|
||||
state: &mut SwatchesState,
|
||||
event: &PresetFileEvent,
|
||||
words: &SwatchesWords,
|
||||
presets: &PresetWords,
|
||||
format: &Format,
|
||||
) -> SwatchesFileOutput {
|
||||
let mut output = SwatchesFileOutput { changed: false, report: None, toast: None };
|
||||
match event {
|
||||
PresetFileEvent::Loaded { file_name, bytes, replace, .. } => match crate::palette::read_swatches(bytes, file_name) {
|
||||
Ok((groups, report)) => {
|
||||
library.import(groups, *replace);
|
||||
output.changed = true;
|
||||
output.toast = Self::notes_toast(&report, false, words, format);
|
||||
output.report = Some(report);
|
||||
}
|
||||
Err(error) => {
|
||||
output.toast = Some(Toast::new(words.import_failed.fill(&[("reason", &error.to_string())])).tone(Tone::Bad));
|
||||
}
|
||||
},
|
||||
PresetFileEvent::Saved { .. } => {
|
||||
if let Some(report) = state.export_notes.take() {
|
||||
output.toast = Self::notes_toast(&report, true, words, format);
|
||||
output.report = Some(report);
|
||||
}
|
||||
}
|
||||
PresetFileEvent::Failed { .. } => {
|
||||
state.export_notes = None;
|
||||
output.toast = Some(Toast::new(event.status(presets)).tone(Tone::Bad));
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
output
|
||||
}
|
||||
|
||||
/// The notes of a swatch file read or written as sentences; counts follow the locale's plural rules. `writing`
|
||||
/// tells an export's notes from an import's, which word a colour-book colour differently.
|
||||
pub fn note_lines(report: &SwatchReport, writing: bool, words: &SwatchesWords, format: &Format) -> Vec<String> {
|
||||
let count = |row: &Count, n: usize| row.text(n as u64, &format.integer(n as u64));
|
||||
report
|
||||
.notes
|
||||
.iter()
|
||||
.map(|note| match *note {
|
||||
SwatchNote::BookColors(n) if writing => count(&words.book_left_out, n),
|
||||
SwatchNote::BookColors(n) => count(&words.book_read, n),
|
||||
SwatchNote::Skipped(n) => count(&words.skipped, n),
|
||||
SwatchNote::GroupsFlattened => words.groups_flattened.as_str().to_owned(),
|
||||
SwatchNote::ConvertedToRgb(n) => count(&words.converted, n),
|
||||
SwatchNote::KindsDropped(n) => count(&words.kinds_dropped, n),
|
||||
SwatchNote::Truncated(n) => count(&words.truncated, n),
|
||||
SwatchNote::NamesCut(n) => count(&words.names_cut, n),
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// The toast for the notes of an import (or, with `writing`, an export): the title and the notes in one line, as
|
||||
/// a warning; `None` when there is nothing to say.
|
||||
fn notes_toast(report: &SwatchReport, writing: bool, words: &SwatchesWords, format: &Format) -> Option<Toast> {
|
||||
let lines = Self::note_lines(report, writing, words, format);
|
||||
if lines.is_empty() {
|
||||
return None;
|
||||
}
|
||||
let title = if writing { &words.notice_export } else { &words.notice_import };
|
||||
Some(Toast::new(format!("{}: {}", title.as_str(), lines.join(" "))).tone(Tone::Warn))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
//! Stories of `SwatchesPanel`.
|
||||
|
||||
use super::{SwatchLibrary, SwatchesPanel, SwatchesState};
|
||||
use craft_ui::contract::Bind;
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use egui::Ui;
|
||||
|
||||
#[story(SwatchesPanel<'static>, covers = [], drive = Drive::Never)]
|
||||
fn swatches_panel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let (library, state) = data.value("panel", (SwatchLibrary::default(), SwatchesState::default()));
|
||||
SwatchesPanel::new(Bind::bound(library), Bind::bound(state), craft_theme::Srgba::rgb(0.2, 0.4, 0.6)).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(SwatchesPanel<'static>, covers = [], drive = Drive::Never)]
|
||||
fn swatches_panel_empty(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let (library, state) = data.value("empty", (SwatchLibrary { groups: Vec::new() }, SwatchesState::default()));
|
||||
SwatchesPanel::new(Bind::bound(library), Bind::bound(state), craft_theme::Srgba::rgb(0.2, 0.4, 0.6)).show(ui).into()
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
craft_ui::testing_registered!();
|
||||
@@ -0,0 +1,459 @@
|
||||
//! [`ColorWheel`]: a hue ring round a saturation and brightness triangle that turns with the hue, as PhotoCraft's
|
||||
//! Color Wheel.
|
||||
|
||||
use super::channels::{channel_step, finite, primary, settled, spoken};
|
||||
use craft_behavior::{HitLevel, HitPriority, HitShape, Metrics, NavMove, PartKey, PressPhase, Sense};
|
||||
use craft_theme::{ColorModel, HsbModel, ModelValues};
|
||||
use craft_ui::contract::{
|
||||
Access, Bind, BindMut, Common, Component, Cx, Edit as _, EditResponse, Focus as _, Input, Name, Numeric, PaintUi, PartsCx, Pointer as _,
|
||||
Props as _, Remember as _, Role, WordSetCx as _,
|
||||
};
|
||||
use craft_ui::primitives::{PaintShape, StrokeWidth};
|
||||
use craft_ui::runtime::env::Label;
|
||||
use craft_ui::runtime::focus::{ActivateKeys, FocusShape, KeepKeys, KeyUse};
|
||||
use craft_ui::style::{ComponentStyle, FocusLook, StyleColor, StyleCx};
|
||||
use egui::{Mesh, Pos2, Rect, Vec2, vec2};
|
||||
use std::f32::consts::TAU;
|
||||
|
||||
#[cfg(feature = "screen-testing")]
|
||||
mod stories;
|
||||
|
||||
/// The hue ring: a press on it sets the hue to the pointer's angle.
|
||||
const RING: PartKey = PartKey::new("ring");
|
||||
/// The triangle: a press on it sets saturation and brightness.
|
||||
const TRIANGLE: PartKey = PartKey::new("triangle");
|
||||
|
||||
/// Steps round the hue ring's mesh (PhotoCraft's 96).
|
||||
const RING_STEPS: u32 = 96;
|
||||
/// Cells along each side of the triangle's mesh (PhotoCraft's 16).
|
||||
const TRIANGLE_CELLS: usize = 16;
|
||||
/// The ring's width as a proportion of the outer radius.
|
||||
const RING_RATIO: f32 = 0.09;
|
||||
/// Degrees a Page key moves the hue.
|
||||
const HUE_PAGE: f32 = 36.0;
|
||||
/// Percents a Page key moves the brightness.
|
||||
const BRIGHTNESS_PAGE: f32 = 10.0;
|
||||
/// A Shift arrow moves ten steps.
|
||||
const FAR: f32 = 10.0;
|
||||
/// The last hue a key reaches: the hue wraps at 360 and has no 360 of its own.
|
||||
const HUE_LAST: f32 = 359.0;
|
||||
|
||||
craft_ui::words! {
|
||||
/// The words of colour wheels.
|
||||
pub struct ColorWheelWords {
|
||||
hue: "colorWheel.hue" = "Hue";
|
||||
triangle: "colorWheel.saturationBrightness" = "Saturation and brightness";
|
||||
saturation: "colorWheel.saturation" = "Saturation";
|
||||
brightness: "colorWheel.brightness" = "Brightness";
|
||||
}
|
||||
}
|
||||
|
||||
/// The hue ring and the triangle: where a press began decides which one a drag edits.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
#[non_exhaustive]
|
||||
pub enum WheelPart {
|
||||
/// The ring: a press or drag sets the hue to the pointer's angle.
|
||||
Ring,
|
||||
/// The triangle: a press or drag sets saturation and brightness.
|
||||
Triangle,
|
||||
}
|
||||
|
||||
/// Where a wheel lies in its area: pure numbers, shared with the colour disc.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct WheelGeometry {
|
||||
/// Centre of the wheel.
|
||||
pub center: Pos2,
|
||||
/// Radius of the ring's inner edge.
|
||||
pub inner: f32,
|
||||
/// Radius of the ring's outer edge.
|
||||
pub outer: f32,
|
||||
/// Radius of the circle round the triangle's corners.
|
||||
pub triangle: f32,
|
||||
}
|
||||
|
||||
impl WheelGeometry {
|
||||
/// The wheel in `area`: the outer radius is half the shorter side less `outer_inset`; the
|
||||
/// ring is `ratio` of it wide, between `ring_min` and `ring_max` and at most half the
|
||||
/// radius; the triangle's circle lies `triangle_inset` inside the ring.
|
||||
pub fn new(area: Rect, outer_inset: f32, ring: (f32, f32), ratio: f32, triangle_inset: f32) -> Self {
|
||||
let outer = (area.width().min(area.height()) / 2.0 - outer_inset).max(1.0);
|
||||
let width = (outer * ratio).max(ring.0).min(ring.1).min(outer * 0.5);
|
||||
let inner = outer - width;
|
||||
Self { center: area.center(), inner, outer, triangle: (inner - triangle_inset).max(0.0) }
|
||||
}
|
||||
|
||||
/// The part a press at `pos` takes: nothing beyond the ring's outer edge plus `grab_outer`,
|
||||
/// the ring from `grab_inner` inside its inner edge, the triangle within.
|
||||
pub fn part_at(&self, pos: Pos2, grab_outer: f32, grab_inner: f32) -> Option<WheelPart> {
|
||||
let d = pos.distance(self.center);
|
||||
if !d.is_finite() || d > self.outer + grab_outer {
|
||||
None
|
||||
} else if d >= self.inner - grab_inner {
|
||||
Some(WheelPart::Ring)
|
||||
} else {
|
||||
Some(WheelPart::Triangle)
|
||||
}
|
||||
}
|
||||
|
||||
/// The middle of the ring at `hue` degrees: where its knob sits.
|
||||
pub fn ring_knob(&self, hue: f32) -> Pos2 {
|
||||
self.center + hue_direction(hue) * ((self.inner + self.outer) / 2.0)
|
||||
}
|
||||
|
||||
/// The triangle's corners at `hue`, as `triangle_corners`, grown by `by` points.
|
||||
pub fn corners(&self, hue: f32, by: f32) -> [Pos2; 3] {
|
||||
triangle_corners(self.center, self.triangle + by, hue)
|
||||
}
|
||||
}
|
||||
|
||||
/// The unit vector on screen at `hue` degrees: red (0) to the right, growing counter-clockwise.
|
||||
pub fn hue_direction(hue: f32) -> Vec2 {
|
||||
let a = hue.to_radians();
|
||||
vec2(a.cos(), -a.sin())
|
||||
}
|
||||
|
||||
/// The hue in whole degrees, 0 to 359, of the direction from `center` to `p`; `None` for a point
|
||||
/// that isn't finite.
|
||||
pub fn hue_at(center: Pos2, p: Pos2) -> Option<f32> {
|
||||
let a = (center.y - p.y).atan2(p.x - center.x);
|
||||
a.is_finite().then(|| (a.rem_euclid(TAU).to_degrees().round()).rem_euclid(360.0))
|
||||
}
|
||||
|
||||
/// The triangle's corners for `hue` degrees inside radius `r`: the pure hue at the hue's angle,
|
||||
/// white 120 degrees on and black 240 degrees on.
|
||||
pub fn triangle_corners(center: Pos2, r: f32, hue: f32) -> [Pos2; 3] {
|
||||
[0.0, 120.0, 240.0].map(|turn| center + hue_direction(hue + turn) * r)
|
||||
}
|
||||
|
||||
/// The point of saturation `s` and brightness `b` (0 to 1) in the triangle: black + b (white -
|
||||
/// black) + b s (hue - white).
|
||||
pub fn triangle_point([hue, white, black]: [Pos2; 3], s: f32, b: f32) -> Pos2 {
|
||||
black + (white - black) * b + (hue - white) * (b * s)
|
||||
}
|
||||
|
||||
/// Saturation and brightness (0 to 1) at `p`, kept inside the triangle; `None` for a degenerate
|
||||
/// triangle or a point that isn't finite.
|
||||
pub fn triangle_sv([hue, white, black]: [Pos2; 3], p: Pos2) -> Option<(f32, f32)> {
|
||||
let (a, c, d) = (white - black, hue - white, p - black);
|
||||
let det = a.x * c.y - a.y * c.x;
|
||||
if det.abs() < 1e-6 {
|
||||
return None;
|
||||
}
|
||||
let (b, bs) = ((d.x * c.y - d.y * c.x) / det, (a.x * d.y - a.y * d.x) / det);
|
||||
if !b.is_finite() || !bs.is_finite() {
|
||||
return None;
|
||||
}
|
||||
let b = b.clamp(0.0, 1.0);
|
||||
let bs = bs.clamp(0.0, b);
|
||||
Some((if b > 0.0 { bs / b } else { 0.0 }, b))
|
||||
}
|
||||
|
||||
/// The style of a colour wheel.
|
||||
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
|
||||
#[non_exhaustive]
|
||||
pub struct ColorWheelStyle {
|
||||
#[style(metrics)]
|
||||
metrics: Metrics,
|
||||
#[style(focus)]
|
||||
focus: FocusLook,
|
||||
/// The least ring width, and the largest.
|
||||
ring_min: f32,
|
||||
ring_max: f32,
|
||||
/// The gap between the area's edge and the ring.
|
||||
outer_inset: f32,
|
||||
/// The gap between the ring's inner edge and the triangle's circle.
|
||||
triangle_inset: f32,
|
||||
/// A press this far outside the ring still takes it, and this far inside its inner edge.
|
||||
grab: f32,
|
||||
/// The edge round the ring and the triangle.
|
||||
edge: StyleColor,
|
||||
/// The diameter of the knobs.
|
||||
knob: f32,
|
||||
}
|
||||
|
||||
/// The part a press began in, for its whole drag.
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct Held(Option<WheelPart>);
|
||||
|
||||
/// A hue ring round a saturation and brightness triangle, editing a colour's HSB values.
|
||||
///
|
||||
/// The host gives the colour as HSB [`ModelValues`] and gets them back with only the picked components changed: the
|
||||
/// ring changes the hue, the triangle saturation and brightness. A host that keeps the values it was sent keeps the
|
||||
/// hue of a grey and the hue and saturation of black.
|
||||
///
|
||||
/// - Pointer (primary button): the part under the press is kept for the whole drag, so a drag that leaves the ring
|
||||
/// keeps turning the hue; a press further outside the ring than `size.hit.target` starts nothing. A press sets the
|
||||
/// value under the pointer (whole degrees, whole percents) and a drag follows it; Esc cancels. A press focuses the
|
||||
/// part.
|
||||
/// - Keys on the focused ring: Left and Down lower the hue by 1 degree, Right and Up raise it, wrapping at 360;
|
||||
/// Shift steps ten; Page Up and Page Down 36 degrees; Home 0, End 359. On the triangle: Left and Right saturation,
|
||||
/// Up and Down brightness; Shift ten; Page keys a tenth of brightness; Home and End saturation 0 and 100. The
|
||||
/// directions are not screen directions: the triangle turns with the hue.
|
||||
/// - Two Tab stops, the ring and then the triangle.
|
||||
/// - AccessKit: a `Group` named `label` holding a `Slider` for the hue (0 to 360, step 1, increment, decrement and
|
||||
/// set value) and a `Slider` for saturation and brightness (value text, no numeric value).
|
||||
/// - Right to left nothing mirrors: red stays at 3 o'clock.
|
||||
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
|
||||
#[component(content_painter)]
|
||||
pub struct ColorWheel<'a> {
|
||||
#[common]
|
||||
common: Common,
|
||||
values: Bind<'a, ModelValues>,
|
||||
}
|
||||
|
||||
impl<'a> ColorWheel<'a> {
|
||||
/// A wheel named `label` ("Color wheel") showing `values`, HSB values.
|
||||
pub fn new(label: impl Into<Label>, values: Bind<'a, ModelValues>) -> Self {
|
||||
ColorWheel { common: Common::new(), values }.label(label).ltr_axis()
|
||||
}
|
||||
|
||||
/// Where the wheel lies in `area`.
|
||||
pub fn geometry(style: &ColorWheelStyle, area: Rect) -> WheelGeometry {
|
||||
WheelGeometry::new(area, style.outer_inset, (style.ring_min, style.ring_max), RING_RATIO, style.triangle_inset)
|
||||
}
|
||||
}
|
||||
|
||||
/// The HSB values the wheel shows when the host gives none.
|
||||
fn blank() -> ModelValues {
|
||||
ModelValues::new(HsbModel.id(), &[])
|
||||
}
|
||||
|
||||
/// `base` with what a press at `pos` in `part` picks: the hue for the ring, saturation and brightness for the
|
||||
/// triangle (turned to `base`'s hue); `base` when `pos` picks nothing.
|
||||
fn value_at(geometry: &WheelGeometry, base: &ModelValues, part: WheelPart, pos: Pos2) -> ModelValues {
|
||||
let mut out = *base;
|
||||
match part {
|
||||
WheelPart::Ring => {
|
||||
if let Some(hue) = hue_at(geometry.center, pos) {
|
||||
out.values[0] = hue;
|
||||
}
|
||||
}
|
||||
WheelPart::Triangle => {
|
||||
if let Some((s, b)) = triangle_sv(geometry.corners(finite(base.values[0]), 0.0), pos) {
|
||||
out.values[1] = (s * 100.0).round();
|
||||
out.values[2] = (b * 100.0).round();
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// `values` after the key `mv` on the focused `part`.
|
||||
fn keyed(values: &ModelValues, part: WheelPart, mv: NavMove, far: bool) -> Option<ModelValues> {
|
||||
let by = if far { FAR } else { 1.0 };
|
||||
let mut out = *values;
|
||||
match part {
|
||||
WheelPart::Ring => {
|
||||
let hue = finite(values.values[0]);
|
||||
let next = match mv {
|
||||
NavMove::Forward => hue + by,
|
||||
NavMove::Back => hue - by,
|
||||
NavMove::Up => hue + by,
|
||||
NavMove::Down => hue - by,
|
||||
NavMove::PageUp => hue + HUE_PAGE,
|
||||
NavMove::PageDown => hue - HUE_PAGE,
|
||||
NavMove::Start => 0.0,
|
||||
NavMove::End => HUE_LAST,
|
||||
_ => return None,
|
||||
};
|
||||
out.values[0] = next.round().rem_euclid(360.0);
|
||||
}
|
||||
WheelPart::Triangle => {
|
||||
let step = channel_step(&HsbModel, 1) as f32;
|
||||
let (s, b) = (finite(values.values[1]), finite(values.values[2]));
|
||||
let (s, b) = match mv {
|
||||
NavMove::Forward => (s + by * step, b),
|
||||
NavMove::Back => (s - by * step, b),
|
||||
NavMove::Up => (s, b + by * step),
|
||||
NavMove::Down => (s, b - by * step),
|
||||
NavMove::PageUp => (s, b + BRIGHTNESS_PAGE),
|
||||
NavMove::PageDown => (s, b - BRIGHTNESS_PAGE),
|
||||
NavMove::Start => (0.0, b),
|
||||
NavMove::End => (100.0, b),
|
||||
_ => return None,
|
||||
};
|
||||
out.values[1] = settled(&HsbModel, 1, s);
|
||||
out.values[2] = settled(&HsbModel, 2, b);
|
||||
}
|
||||
}
|
||||
Some(out)
|
||||
}
|
||||
|
||||
impl Component for ColorWheel<'_> {
|
||||
const SINGLE_VALUE: bool = true;
|
||||
const ROLE: Role = Role::GROUP;
|
||||
const KEYS: KeyUse = KeyUse::of(Input::Pointer).with_keep(KeepKeys::BlockArrows).with_activate(ActivateKeys::Neither);
|
||||
const OVERLAYS: bool = false;
|
||||
type Style = ColorWheelStyle;
|
||||
type Output = EditResponse<ModelValues>;
|
||||
|
||||
fn style(cx: &StyleCx<'_>, _: ColorWheelStyleKey) -> ColorWheelStyle {
|
||||
let tokens = cx.tokens;
|
||||
ColorWheelStyle {
|
||||
metrics: Metrics::new().min_size(Vec2::new(tokens.size.plot.width, tokens.size.plot.height)),
|
||||
focus: cx.focus_look(),
|
||||
ring_min: tokens.size.icon.sm,
|
||||
ring_max: tokens.size.control.md,
|
||||
outer_inset: tokens.space.gap.tight,
|
||||
triangle_inset: tokens.stroke.thin,
|
||||
grab: tokens.size.hit.target,
|
||||
edge: cx.color(tokens.color.line.control_edge),
|
||||
knob: tokens.size.handle.md,
|
||||
}
|
||||
}
|
||||
|
||||
fn sense(&self) -> Sense {
|
||||
Sense::empty()
|
||||
}
|
||||
|
||||
fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) {
|
||||
let geometry = ColorWheel::geometry(cx.style, rect);
|
||||
let reach = cx.style.grab;
|
||||
// The ring takes every press within its reach; the triangle takes the circle inside the ring's reach.
|
||||
cx.part(RING, HitShape::circle(geometry.center, geometry.outer + reach))
|
||||
.sense(Sense::DRAG | Sense::CLICK)
|
||||
.focusable()
|
||||
.focus_shape(FocusShape::Circle);
|
||||
cx.part(TRIANGLE, HitShape::circle(geometry.center, (geometry.inner - reach).max(0.0)))
|
||||
.sense(Sense::DRAG | Sense::CLICK)
|
||||
.priority(HitPriority::new(HitLevel::Handle, 0))
|
||||
.focusable()
|
||||
.focus_shape(FocusShape::Circle);
|
||||
}
|
||||
|
||||
fn bind(&mut self) -> Option<BindMut<'_, ModelValues>> {
|
||||
Some(self.values.reborrow())
|
||||
}
|
||||
|
||||
fn update(&mut self, cx: &mut Cx<'_, Self>) {
|
||||
let geometry = ColorWheel::geometry(cx.style, cx.rect);
|
||||
let current = |cx: &Cx<'_, Self>| cx.value().copied().unwrap_or_else(blank);
|
||||
for (key, part) in [(RING, WheelPart::Ring), (TRIANGLE, WheelPart::Triangle)] {
|
||||
let press = cx.part(key).press;
|
||||
if !primary(&press) {
|
||||
continue;
|
||||
}
|
||||
if matches!(press.phase, PressPhase::Down { .. }) {
|
||||
cx.focus_part(key);
|
||||
}
|
||||
match press.phase {
|
||||
PressPhase::DragStart { pos, .. } => {
|
||||
cx.memory::<Held>().0 = Some(part);
|
||||
cx.begin();
|
||||
cx.propose(value_at(&geometry, ¤t(&*cx), part, pos));
|
||||
}
|
||||
PressPhase::Drag { pos, .. } if cx.gesture().is_some() && cx.memory::<Held>().0 == Some(part) => {
|
||||
cx.propose(value_at(&geometry, ¤t(&*cx), part, pos));
|
||||
}
|
||||
PressPhase::Release { pos, click, .. } => {
|
||||
if cx.gesture().is_some() {
|
||||
cx.propose(value_at(&geometry, ¤t(&*cx), part, pos));
|
||||
cx.commit();
|
||||
} else if click {
|
||||
cx.set(value_at(&geometry, ¤t(&*cx), part, pos));
|
||||
}
|
||||
cx.memory::<Held>().0 = None;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
let running = cx.gesture().is_some();
|
||||
let focused = match cx.active_part() {
|
||||
Some(active) if active == RING.into() => Some(WheelPart::Ring),
|
||||
Some(active) if active == TRIANGLE.into() => Some(WheelPart::Triangle),
|
||||
_ => None,
|
||||
};
|
||||
let mut now = current(&*cx);
|
||||
while let Some((mv, mods)) = cx.intents().take_move() {
|
||||
if let Some(part) = focused.filter(|_| !running)
|
||||
&& let Some(next) = keyed(&now, part, mv, mods.extend)
|
||||
{
|
||||
now = next;
|
||||
cx.set(now);
|
||||
}
|
||||
}
|
||||
if let Some(value) = cx.intents().take_set_value_at(RING).filter(|value| value.is_finite() && !running) {
|
||||
now.values[0] = value.round().rem_euclid(360.0) as f32;
|
||||
cx.set(now);
|
||||
}
|
||||
}
|
||||
|
||||
fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) {
|
||||
let words = cx.words::<ColorWheelWords>();
|
||||
let values = cx.value().copied().unwrap_or_else(blank);
|
||||
let [hue, saturation, brightness] = [0, 1, 2].map(|channel| finite(values.values[channel]));
|
||||
let ring = access.node(RING, Role::SLIDER);
|
||||
ring.name = Name::Text(words.hue.as_str().to_owned());
|
||||
ring.numeric = Some(Numeric::new(f64::from(hue.rem_euclid(360.0)), 0.0..=360.0).step(1.0).wraps(true));
|
||||
let model = &HsbModel as &dyn ColorModel;
|
||||
let text =
|
||||
format!("{}, {}", spoken(words.saturation.as_str(), model, 1, saturation), spoken(words.brightness.as_str(), model, 2, brightness));
|
||||
let triangle = access.node(TRIANGLE, Role::GROUP);
|
||||
triangle.name = Name::Text(words.triangle.as_str().to_owned());
|
||||
triangle.value(text);
|
||||
}
|
||||
|
||||
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
|
||||
let geometry = ColorWheel::geometry(cx.style, cx.rect);
|
||||
let values = cx.value().copied().unwrap_or_else(blank);
|
||||
let [hue, saturation, brightness] = [0, 1, 2].map(|channel| finite(values.values[channel]));
|
||||
let corners = geometry.corners(hue, 0.0);
|
||||
let painter = ui.content_painter(cx);
|
||||
painter.painter.add(ring_mesh(&geometry));
|
||||
painter.painter.add(triangle_mesh(corners, hue));
|
||||
let draw = ui.draw();
|
||||
draw.stroke(&PaintShape::Circle(geometry.center, geometry.outer), StrokeWidth::Thin, cx.style.edge);
|
||||
draw.stroke(&PaintShape::Polygon(corners.to_vec()), StrokeWidth::Thin, cx.style.edge);
|
||||
let knobs = [geometry.ring_knob(hue), triangle_point(corners, saturation / 100.0, brightness / 100.0)];
|
||||
for at in knobs {
|
||||
painter.outline(&PaintShape::Circle(at, cx.style.knob / 2.0));
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> EditResponse<ModelValues> {
|
||||
cx.edit_response()
|
||||
}
|
||||
}
|
||||
|
||||
/// The colour of HSB `[h, s, b]` (degrees and percents) as a vertex colour.
|
||||
pub(super) fn vertex(h: f32, s: f32, b: f32) -> egui::Color32 {
|
||||
HsbModel.to_srgb(&ModelValues::new("hsb", &[h, s, b]).values).into()
|
||||
}
|
||||
|
||||
fn ring_mesh(geometry: &WheelGeometry) -> Mesh {
|
||||
let mut mesh = Mesh::default();
|
||||
for k in 0..=RING_STEPS {
|
||||
let hue = k as f32 / RING_STEPS as f32 * 360.0;
|
||||
let color = vertex(hue, 100.0, 100.0);
|
||||
let dir = hue_direction(hue);
|
||||
mesh.colored_vertex(geometry.center + dir * geometry.inner, color);
|
||||
mesh.colored_vertex(geometry.center + dir * geometry.outer, color);
|
||||
}
|
||||
for k in 0..RING_STEPS {
|
||||
let a = k * 2;
|
||||
mesh.add_triangle(a, a + 1, a + 3);
|
||||
mesh.add_triangle(a, a + 3, a + 2);
|
||||
}
|
||||
mesh
|
||||
}
|
||||
|
||||
fn triangle_mesh(corners: [Pos2; 3], hue: f32) -> Mesh {
|
||||
let n = TRIANGLE_CELLS;
|
||||
let mut mesh = Mesh::default();
|
||||
for j in 0..=n {
|
||||
for i in 0..=n {
|
||||
let (s, b) = (i as f32 / n as f32, j as f32 / n as f32);
|
||||
mesh.colored_vertex(triangle_point(corners, s, b), vertex(hue, s * 100.0, b * 100.0));
|
||||
}
|
||||
}
|
||||
let row = (n + 1) as u32;
|
||||
for j in 0..n as u32 {
|
||||
for i in 0..n as u32 {
|
||||
let a = j * row + i;
|
||||
mesh.add_triangle(a, a + 1, a + row + 1);
|
||||
mesh.add_triangle(a, a + row + 1, a + row);
|
||||
}
|
||||
}
|
||||
mesh
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
//! Stories of `ColorWheel`.
|
||||
|
||||
use super::ColorWheel;
|
||||
use craft_theme::{ColorModel, HsbModel, Srgba};
|
||||
use craft_ui::contract::{Bind, Show as _, Validity};
|
||||
use craft_ui::runtime::env::Message;
|
||||
use craft_ui::testing::{Drive, Grip, StoryData, StoryOutput, story};
|
||||
use egui::Ui;
|
||||
|
||||
#[story(ColorWheel<'static>, covers = [Default], drive = Drive::Drag(Grip::new(super::RING)))]
|
||||
fn color_wheel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let values = data.value("values", HsbModel.from_srgb(Srgba::rgb(0.2, 0.5, 0.8)));
|
||||
ColorWheel::new("Color wheel", Bind::bound(values)).show(ui).into()
|
||||
}
|
||||
|
||||
#[story(ColorWheel<'static>, covers = [Invalid], drive = Drive::Never)]
|
||||
fn color_wheel_invalid(ui: &mut Ui, data: &mut StoryData) -> StoryOutput {
|
||||
let refuse_dim =
|
||||
|values: &craft_theme::ModelValues| if values.values[2] < 50.0 { Validity::Refuse(Message::new("Too dim")) } else { Validity::Ok };
|
||||
let values = data.value("values", HsbModel.from_srgb(Srgba::rgb(0.1, 0.2, 0.3)));
|
||||
ColorWheel::new("Color wheel", Bind::bound(values).check(refuse_dim)).show(ui).into()
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
//! Web-safe colours: each channel on 0, 0.2, ... 1 (`00`, `33`, `66`, `99`, `CC`, `FF`).
|
||||
|
||||
/// `color` with each channel (clamped to `0..=1`) on the nearest web-safe level.
|
||||
pub fn web_safe(color: [f32; 3]) -> [f32; 3] {
|
||||
color.map(|v| (v.clamp(0.0, 1.0) * 5.0).round() / 5.0)
|
||||
}
|
||||
|
||||
/// The nearest web colour of `color`, when `color` is not one; `None` for a web colour. It is
|
||||
/// what a "not a web colour" warning offers.
|
||||
pub fn not_web_safe(color: [f32; 3]) -> Option<[f32; 3]> {
|
||||
let near = web_safe(color);
|
||||
let hex = |c: [f32; 3]| craft_theme::Srgba::from_rgb_array(c).to_hex();
|
||||
(hex(near) != hex(color)).then_some(near)
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
//! The colour area, strip, ramp, disc and wheel: the colour maths and the edits they report.
|
||||
|
||||
use craft_color::ui::{WheelGeometry, hue_at, triangle_corners, triangle_point, triangle_sv};
|
||||
use craft_ui::testing::trial;
|
||||
use egui::{Pos2, Rect, pos2, vec2};
|
||||
|
||||
fn within(a: f32, b: f32) -> bool {
|
||||
(a - b).abs() < 1e-3
|
||||
}
|
||||
|
||||
/// The wheel's pure geometry: a triangle point reads back as its saturation and brightness, and the ring hue is whole
|
||||
/// degrees counter-clockwise from the right.
|
||||
#[trial]
|
||||
fn the_wheel_geometry_round_trips() {
|
||||
let center = pos2(100.0, 100.0);
|
||||
let corners = triangle_corners(center, 60.0, 210.0);
|
||||
for (s, b) in [(0.0, 1.0), (1.0, 1.0), (0.4, 0.7), (0.9, 0.2)] {
|
||||
let (read_s, read_b) = triangle_sv(corners, triangle_point(corners, s, b)).expect("a triangle point reads back");
|
||||
assert!(within(read_s, s) && within(read_b, b), "({s}, {b}) read as ({read_s}, {read_b})");
|
||||
}
|
||||
assert_eq!(hue_at(center, center + vec2(10.0, 0.0)), Some(0.0));
|
||||
assert_eq!(hue_at(center, center + vec2(0.0, -10.0)), Some(90.0), "up is 90 degrees");
|
||||
assert_eq!(hue_at(center, Pos2::new(f32::NAN, 0.0)), None);
|
||||
let geometry = WheelGeometry::new(Rect::from_min_size(Pos2::ZERO, vec2(200.0, 200.0)), 4.0, (8.0, 24.0), 0.09, 1.0);
|
||||
assert!(geometry.inner < geometry.outer && geometry.triangle < geometry.inner);
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
//! The screen tests of craft-color, folded into the lib's test target.
|
||||
|
||||
mod color_parts;
|
||||
mod panels;
|
||||
mod picker;
|
||||
mod sampling;
|
||||
@@ -0,0 +1,143 @@
|
||||
//! The colour panels through the fixture: the Color panel, the Swatches panel, the Color Guide and the swatch
|
||||
//! palette and table.
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
use std::rc::Rc;
|
||||
|
||||
use craft_behavior::EditEvent;
|
||||
use craft_color::ui::{ColorPanel, ColorPanelMode, ColorPanelState, PanelTarget, PickedColor, SwatchPalette};
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::contract::{Bind, Show as _};
|
||||
use craft_ui::runtime::env::Label;
|
||||
use craft_ui::runtime::requests::ColorRequest;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::{Key, Modifiers, Vec2};
|
||||
|
||||
const RED: Srgba = Srgba::rgb(1.0, 0.0, 0.0);
|
||||
const BLUE: Srgba = Srgba::rgb(0.0, 0.0, 1.0);
|
||||
|
||||
/// The rooms the panels are shown in.
|
||||
const COLOR_ROOM: Vec2 = Vec2::new(320.0, 600.0);
|
||||
const PALETTE_WIDE: Vec2 = Vec2::new(600.0, 300.0);
|
||||
|
||||
type Edits = Rc<RefCell<Vec<(PanelTarget, EditEvent<PickedColor>)>>>;
|
||||
|
||||
/// The Color panel on a state and two colours the test can change, collecting what it reports.
|
||||
struct PanelRig {
|
||||
fixture: Fixture,
|
||||
colors: Rc<Cell<[Srgba; 2]>>,
|
||||
edits: Edits,
|
||||
}
|
||||
|
||||
impl PanelRig {
|
||||
fn new(mode: ColorPanelMode) -> Self {
|
||||
let mut start = ColorPanelState::default();
|
||||
start.mode = mode;
|
||||
let state = Rc::new(RefCell::new(start));
|
||||
let colors = Rc::new(Cell::new([RED, BLUE]));
|
||||
type Shared = (Edits, Rc<RefCell<Vec<ColorRequest>>>, Rc<RefCell<Vec<PanelTarget>>>);
|
||||
let (edits, opened, added): Shared = Default::default();
|
||||
let (s, c, e, o, a) = (state, colors.clone(), edits.clone(), opened, added);
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut current = *s.borrow();
|
||||
let shown = ColorPanel::new(Bind::bound(&mut current), c.get()).show(ui);
|
||||
*s.borrow_mut() = current;
|
||||
e.borrow_mut().extend(shown.edits);
|
||||
o.borrow_mut().extend(shown.pick_color);
|
||||
a.borrow_mut().extend(shown.add_to_swatches);
|
||||
});
|
||||
fixture.room(COLOR_ROOM);
|
||||
fixture.settle();
|
||||
PanelRig { fixture, colors, edits }
|
||||
}
|
||||
|
||||
fn set_colors(&mut self, colors: [Srgba; 2]) {
|
||||
self.colors.set(colors);
|
||||
self.fixture.settle();
|
||||
}
|
||||
}
|
||||
|
||||
/// A saturated colour dragged to the cube's bottom right (black) keeps the remembered hue and saturation: the knob stays
|
||||
/// in the corner and the strip keeps its hue.
|
||||
#[trial]
|
||||
fn dragging_to_the_bottom_right_keeps_the_knob_there() {
|
||||
let mut rig = PanelRig::new(ColorPanelMode::HueCube);
|
||||
rig.set_colors([Srgba::rgb(0.2, 0.4, 0.6), BLUE]);
|
||||
let area = rig.fixture.by_label("Saturation and brightness").expect("the area");
|
||||
rig.fixture.drag(&area, area.rect.size());
|
||||
let picked = rig.edits.borrow().iter().rev().find_map(|(_, e)| e.value().map(|v| v.color)).expect("a picked colour");
|
||||
assert_eq!(picked.to_rgba(), Srgba::rgb(0.0, 0.0, 0.0).to_rgba(), "the corner is black");
|
||||
|
||||
rig.set_colors([picked, BLUE]);
|
||||
let area = rig.fixture.focused().expect("the dragged area keeps the focus");
|
||||
let value = rig.fixture.tree().value(area).expect("the area reports its value");
|
||||
assert!(value.contains("Saturation 100") && value.contains("Brightness 0"), "the knob stays at the corner: {value}");
|
||||
}
|
||||
|
||||
const SWATCHES: [(&str, [f32; 3]); 6] = [
|
||||
("Red", [0.90, 0.28, 0.30]),
|
||||
("Orange", [0.97, 0.42, 0.08]),
|
||||
("Green", [0.19, 0.64, 0.42]),
|
||||
("Teal", [0.07, 0.65, 0.58]),
|
||||
("Blue", [0.24, 0.39, 0.87]),
|
||||
("Violet", [0.56, 0.31, 0.78]),
|
||||
];
|
||||
|
||||
/// A palette over `SWATCHES` choosing the colour the test sets.
|
||||
struct PaletteRig {
|
||||
fixture: Fixture,
|
||||
events: Rc<Cell<usize>>,
|
||||
}
|
||||
|
||||
impl PaletteRig {
|
||||
fn new(start: Srgba, room: Vec2) -> Self {
|
||||
let swatches: Vec<(Label, Srgba)> = SWATCHES.iter().map(|(name, [r, g, b])| (Label::from(*name), Srgba::rgb(*r, *g, *b))).collect();
|
||||
let events = Rc::new(Cell::new(0));
|
||||
let (c, e) = (Rc::new(Cell::new(start)), events.clone());
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut current = c.get();
|
||||
let shown = SwatchPalette::new("Swatches", Bind::bound(&mut current), &swatches).show(ui);
|
||||
// A second Tab stop for the Tab that leaves the palette to land on.
|
||||
let _ = craft_ui::buttons::Button::new("After").show(ui);
|
||||
c.set(current);
|
||||
e.set(e.get() + usize::from(shown.edit.is_some()));
|
||||
});
|
||||
fixture.room(room);
|
||||
fixture.settle();
|
||||
PaletteRig { fixture, events }
|
||||
}
|
||||
|
||||
fn focused(&self) -> Option<String> {
|
||||
let tree = self.fixture.tree();
|
||||
tree.name_of(craft_ui::testing::access::focused_key(tree)).map(str::to_owned)
|
||||
}
|
||||
}
|
||||
|
||||
/// Up and Down walk the wrapped rows of the palette to the swatch in the same column.
|
||||
#[trial]
|
||||
fn the_palette_arrows_walk_the_wrapped_grid() {
|
||||
// Three to a row: Red Orange Green / Teal Blue Violet. The room is three cells and the gaps the wide rig lays out.
|
||||
let wide = PaletteRig::new(Srgba::rgb(0.19, 0.64, 0.42), PALETTE_WIDE);
|
||||
let (first, third) = (wide.fixture.by_label("Red").expect("red").rect, wide.fixture.by_label("Green").expect("green").rect);
|
||||
let narrow = Vec2::new(third.max.x + first.min.x, PALETTE_WIDE.y);
|
||||
let mut rig = PaletteRig::new(Srgba::rgb(0.19, 0.64, 0.42), narrow);
|
||||
let (red, teal) = (rig.fixture.by_label("Red").expect("red").rect, rig.fixture.by_label("Teal").expect("teal").rect);
|
||||
assert!(teal.min.y > red.min.y, "the palette wrapped");
|
||||
rig.fixture.key(Key::Tab, Modifiers::NONE);
|
||||
let steps = [
|
||||
(Key::ArrowDown, "Violet"),
|
||||
(Key::ArrowUp, "Green"),
|
||||
(Key::ArrowUp, "Green"),
|
||||
(Key::ArrowRight, "Teal"),
|
||||
(Key::ArrowLeft, "Green"),
|
||||
(Key::ArrowLeft, "Orange"),
|
||||
(Key::ArrowDown, "Blue"),
|
||||
(Key::ArrowRight, "Violet"),
|
||||
(Key::ArrowRight, "Violet"),
|
||||
];
|
||||
for (key, expected) in steps {
|
||||
rig.fixture.key(key, Modifiers::NONE);
|
||||
assert_eq!(rig.focused().as_deref(), Some(expected), "{key:?}");
|
||||
}
|
||||
assert_eq!(rig.events.get(), 0);
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
//! `ColorPicker`, its hex pair field, `ColorReadout` and `ColorChoice`: the edit rules the picker owns.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
use craft_behavior::Mixed;
|
||||
use craft_color::ui::ColorReadout;
|
||||
use craft_theme::Rgba;
|
||||
use craft_ui::contract::Bind;
|
||||
use craft_ui::testing::{Fixture, trial};
|
||||
use egui::{Key, Modifiers, vec2};
|
||||
|
||||
fn type_into(fixture: &mut Fixture, label: &str, text: &str) {
|
||||
let field = fixture.by_label(label).unwrap_or_else(|| panic!("the picker shows a {label} field"));
|
||||
fixture.click(&field);
|
||||
fixture.key(Key::A, Modifiers::COMMAND);
|
||||
fixture.type_text(text);
|
||||
fixture.key(Key::Enter, Modifiers::NONE);
|
||||
fixture.settle();
|
||||
}
|
||||
|
||||
/// Two items with different G, B and alpha, shown by a readout the way a multi-selection host does.
|
||||
fn mixed_readout(items: Rc<RefCell<[Rgba; 2]>>) -> Fixture {
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut items = items.borrow_mut();
|
||||
let out = ColorReadout::new("Color", Bind::given(Mixed::<Rgba>::Mixed)).show(ui);
|
||||
for edit in &out.channel {
|
||||
if let Some(Some(byte)) = edit.event.value() {
|
||||
for item in items.iter_mut() {
|
||||
item.0[edit.channel.index()] = *byte;
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(color) = out.events.value() {
|
||||
items.fill(*color);
|
||||
}
|
||||
});
|
||||
fixture.room(vec2(480.0, 60.0));
|
||||
fixture.settle();
|
||||
fixture
|
||||
}
|
||||
|
||||
/// A channel typed while the colour is mixed sets that channel of every item and keeps each item's other channels
|
||||
/// and alpha; a hex value sets the whole colour of both.
|
||||
#[trial]
|
||||
fn a_channel_typed_into_a_mixed_readout_keeps_each_items_other_channels() {
|
||||
let items = Rc::new(RefCell::new([Rgba([10, 20, 30, 100]), Rgba([40, 50, 60, 200])]));
|
||||
let mut fixture = mixed_readout(items.clone());
|
||||
type_into(&mut fixture, "Red", "255");
|
||||
assert_eq!(*items.borrow(), [Rgba([255, 20, 30, 100]), Rgba([255, 50, 60, 200])]);
|
||||
type_into(&mut fixture, "Hex color", "336699");
|
||||
let whole = items.borrow()[0];
|
||||
assert_eq!(&whole.0[..3], &[0x33, 0x66, 0x99], "the hex sets the colour");
|
||||
assert_eq!(items.borrow()[1], whole, "and sets it for both items");
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
//! The Color Picker dialog, the droppers, the eyedropper, the colour samplers and the screen pick.
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft_behavior::CanvasView;
|
||||
use craft_behavior::kurbo::Point;
|
||||
use craft_cms::convert::CmykConverter;
|
||||
use craft_color::ui::{
|
||||
CaptureSource, ColorPicker, ColorPickerLayout, ColorSamplerTool, ColorSamplers, PickedColor, SamplerCache, SamplerReadouts, ScreenPick,
|
||||
StillCapture,
|
||||
};
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::contract::Bind;
|
||||
use craft_ui::testing::{Fixture, ToolFixture, trial};
|
||||
use egui::{Context, Rect, vec2};
|
||||
|
||||
const SIZE: [u32; 2] = [300, 200];
|
||||
|
||||
#[trial]
|
||||
fn readouts_are_cached_per_document_and_converter() {
|
||||
use std::cell::Cell;
|
||||
let mut samplers = ColorSamplers::new();
|
||||
samplers.add([1.0, 1.0], [10, 10]).unwrap();
|
||||
let reads = Cell::new(0);
|
||||
let read = |_: [f64; 2]| {
|
||||
reads.set(reads.get() + 1);
|
||||
Srgba { r: 0.0, g: 0.0, b: 1.0, a: 1.0 }
|
||||
};
|
||||
let mut cache = SamplerCache::default();
|
||||
let coated = CmykConverter::coated();
|
||||
let first = SamplerReadouts::new(&samplers, read).revision(3).document("a").cmyk(coated).get(&mut cache);
|
||||
let again = SamplerReadouts::new(&samplers, read).revision(3).document("a").cmyk(coated).get(&mut cache);
|
||||
assert!(Arc::ptr_eq(&first, &again) && reads.get() == 1, "unchanged: from the cache");
|
||||
SamplerReadouts::new(&samplers, read).revision(3).document("b").cmyk(coated).get(&mut cache);
|
||||
assert_eq!(reads.get(), 2, "another document at the same revision reads again");
|
||||
let fogra = CmykConverter::new(Arc::new(craft_cms::Builtin::CoatedFogra39.profile().clone())).unwrap();
|
||||
let other = SamplerReadouts::new(&samplers, read).revision(3).document("a").cmyk(&fogra).get(&mut cache);
|
||||
assert_eq!(reads.get(), 3, "another CMYK working space reads again");
|
||||
assert_ne!(other[0].cmyk, first[0].cmyk);
|
||||
}
|
||||
|
||||
fn sampler_tool(points: &[[f64; 2]]) -> ColorSamplerTool<'static> {
|
||||
let samplers: &'static mut ColorSamplers = Box::leak(Box::new(ColorSamplers::new()));
|
||||
for p in points {
|
||||
samplers.add(*p, SIZE).unwrap();
|
||||
}
|
||||
ColorSamplerTool::new(samplers, SIZE)
|
||||
}
|
||||
|
||||
#[trial]
|
||||
fn the_sampler_tool_meets_the_tool_rules() {
|
||||
let view = |rect: Rect| CanvasView::new(rect, Point::new(f64::from(SIZE[0]) / 2.0, f64::from(SIZE[1]) / 2.0), 1.0);
|
||||
let mut tool = ToolFixture::with_view("Color Sampler", sampler_tool(&[]), view, |_, _| {});
|
||||
tool.check();
|
||||
}
|
||||
|
||||
/// A monitor of `size` pixels at `origin` in the virtual desktop whose pixel (x, y) is (x, y, `tag`), so a pick shows
|
||||
/// which monitor and which pixel it read.
|
||||
fn monitor(origin: [i32; 2], size: [u32; 2], tag: u8) -> craft_platform::screen::ScreenImage {
|
||||
let rgba = (0..size[1]).flat_map(|y| (0..size[0]).flat_map(move |x| [x as u8, y as u8, tag, 255])).collect();
|
||||
craft_platform::screen::ScreenImage { origin, size, scale: 1.0, rgba: Arc::new(rgba), icc_profile: None, name: format!("monitor {tag}") }
|
||||
}
|
||||
|
||||
/// Dragging from the picker's screen button and releasing outside the app's window picks the colour under the pointer on
|
||||
/// whichever monitor it is over, not only inside the window. Guards the capture of every monitor ending without a colour.
|
||||
#[trial]
|
||||
fn a_release_outside_the_window_picks_the_colour_under_the_pointer_on_any_monitor() {
|
||||
let pick = Rc::new(RefCell::new(ScreenPick::new()));
|
||||
let shared = pick.clone();
|
||||
let mut fixture = Fixture::new(move |ui| {
|
||||
let mut color = PickedColor::rgb(Srgba::rgb(0.2, 0.5, 0.8));
|
||||
let out = ColorPicker::new("Foreground color", Bind::bound(&mut color)).layout(ColorPickerLayout::Compact).eyedropper(true).show(ui);
|
||||
if let Some(gesture) = out.screen_pick {
|
||||
shared.borrow_mut().hold(ui.ctx(), "fill", gesture);
|
||||
}
|
||||
});
|
||||
fixture.room(vec2(720.0, 640.0));
|
||||
fixture.settle();
|
||||
let button = fixture.by_label("Sample color from the screen").expect("the screen button");
|
||||
// The window is the first monitor; the second one starts where the first ends.
|
||||
let by = vec2(900.0 - button.center().x, 50.0 - button.center().y);
|
||||
fixture.drag(&button, by);
|
||||
assert!(pick.borrow().busy(), "a release outside the window captures the screen");
|
||||
let monitors = [monitor([0, 0], [720, 700], 1), monitor([720, 0], [400, 700], 2)];
|
||||
let capture = || -> Box<dyn CaptureSource> { Box::new(StillCapture::new(Ok(craft_platform::screen::Capture::Images(monitors.to_vec())))) };
|
||||
pick.borrow_mut().tick_with(&Context::default(), 1, &capture);
|
||||
assert!(!pick.borrow().busy(), "the pick ends with the capture");
|
||||
let color = pick.borrow_mut().take("fill").expect("the colour under the pointer");
|
||||
let released = button.center() + by;
|
||||
let under = |m: &craft_platform::screen::ScreenImage| {
|
||||
let (x, y) = ((released.x as i32 - m.origin[0]) as usize, (released.y as i32 - m.origin[1]) as usize);
|
||||
let at = (y * m.size[0] as usize + x) * 4;
|
||||
Srgba::rgb(f32::from(m.rgba[at]) / 255.0, f32::from(m.rgba[at + 1]) / 255.0, f32::from(m.rgba[at + 2]) / 255.0)
|
||||
};
|
||||
assert_eq!(color, under(&monitors[1]), "the pixel under the pointer on the monitor it is over");
|
||||
assert_ne!(color, under(&monitors[0]), "not the same coordinates on the first monitor");
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
[package]
|
||||
name = "craft-draw"
|
||||
description = "Vector and shape tools for Craft apps: gradient editing, pen, stroke, shapes, crop, free transform, measure, symmetry and brush presets."
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
license.workspace = true
|
||||
rust-version.workspace = true
|
||||
repository.workspace = true
|
||||
autotests = false
|
||||
|
||||
[lib]
|
||||
# The lib's test target is the crate's one test executable: its trials and, with `screen-testing`, the
|
||||
# screen tests in tests/it.
|
||||
harness = false
|
||||
|
||||
[lints]
|
||||
workspace = true
|
||||
|
||||
[features]
|
||||
default = []
|
||||
# The tool widgets (`craft_draw::ui`).
|
||||
ui = ["dep:craft-behavior", "dep:craft-keymap", "dep:craft-ui", "dep:egui", "dep:craft-color", "craft-color/ui", "dep:craft-settings"]
|
||||
# The widgets' stories and trials (`tests/it`).
|
||||
screen-testing = ["ui", "craft-ui/testing", "craft-color/screen-testing"]
|
||||
|
||||
[dependencies]
|
||||
craft-behavior = { workspace = true, optional = true }
|
||||
craft-color = { workspace = true, optional = true }
|
||||
craft-host = { workspace = true }
|
||||
craft-i18n = { workspace = true }
|
||||
craft-keymap = { workspace = true, optional = true }
|
||||
craft-settings = { workspace = true, optional = true }
|
||||
craft-theme = { workspace = true }
|
||||
craft-ui = { workspace = true, optional = true }
|
||||
egui = { workspace = true, optional = true }
|
||||
kurbo = { workspace = true, features = ["serde"] }
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
|
||||
[dev-dependencies]
|
||||
craft-ui = { workspace = true, features = ["testing"] }
|
||||
egui = { workspace = true }
|
||||
@@ -0,0 +1,17 @@
|
||||
# craft-draw
|
||||
|
||||
Vector and shape tools for Craft apps. With the `ui` feature, `craft_draw::ui` has the pen, crop and free transform overlays (below), the gradient tools (`GradientEditor`, `GradientPalette`, `GradientSwatch`, `GradientRamp`, the stop rules in `gradient::stops`, the on-canvas `GradientOverlay` with its `gradient_line` geometry, and the `GradientMapEditor`) and these tools and panels, each in its own module with its labels:
|
||||
|
||||
- `stroke`: `StrokeEditor`, `StrokeButton` and `StrokePreview` over `StrokeStyle`; `corner`: `CornerWidgets` for corner radii;
|
||||
- `shape` and `shape_drag`: `ShapePanel`, `ShapeBar`, `ShapeDragTool` and `CreateShapeDialog`; `slice`: `SliceTool`, `SliceOverlay`, `SliceBar` and the Slice Options and Divide Slices dialogs; `artboard` and `add_beside`: `ArtboardTool`, `ArtboardBar`, `ArtboardProperties` and the add-beside buttons; `connector`: `ConnectorTool`, `ConnectorOverlay` and `ConnectorBar`;
|
||||
- `pattern` and `picture_fill`: `PatternFillEditor`, `PatternFillDialog` and `PictureFillEditor`;
|
||||
- `transform`: `TransformSession` with `TransformOverlay`, `TransformBar` and the Transform menu words; `crop`: `CropTool`, `CropSession` and `CropBar` beside the `CropFrame`; `measure`: `RulerTool`, `RulerBar` and `box_distances`; `symmetry`: `Symmetry` with `SymmetryOverlay`, `SymmetryMenu` and `SymmetryTransform`;
|
||||
- `brush_presets` and `brush_settings`: `BrushPresetPicker`, `BrushPresetChip` and `BrushSettingsPanel` (its answer is `BrushSettingsPanelOutput`).
|
||||
|
||||
The main types of every module are re-exported at `craft_draw::ui`.
|
||||
|
||||
The gradient editor uses the colour picker and wells of `craft-color`.
|
||||
|
||||
`ui::pen`, `ui::crop` and `ui::transform` hold the canvas overlays of the Pen, Crop and Free Transform tools. They sense through `craft_ui::canvas` (`CanvasView`, `Claim`, `PartFocus`, `quad`):
|
||||
|
||||
`TransformBox` draws Free Transform's box over the guides (a bare 1 pt line, 8 square handles, the reference point) and runs its gestures through `quad::drag` (PhotoCraft's rules by default; `BoxRules`, `RotateZone` and `inside_moves` set DesignCraft's, VectorCraft's or a Move tool's): the nearest handle within 12 pt, drags reported as edit gestures, a click outside or a double-click inside or Enter applies, Esc undoes a drag and then discards the box, the arrows move the picked part, an optional readout shows the angle, scale or move; one Tab stop whose Page keys pick the whole box, a corner, an edge or the reference point, each an AccessKit object named by the host's `TransformNames`. A host that runs its own input calls `hit`, `press`, `track` and `release` (canvas points, modifiers, the view; `BoxPress` is the state it keeps between press and release) and gets the box `show` would give; `paint_pivot` draws the reference point for a host that shows one outside the box. `BezierOverlay` draws paths (`EditPath`: subpaths of `Knot`s, each an anchor with in and out handles; `PathSelection` is the host's) with their anchors and direction handles and edits them as Direct Selection (select, ⇧ toggle, ⌥ subpath, drag anchors, handles and segments, a marquee on empty canvas) or Convert Point does, reporting `PathEdit`s for the host to apply; one Tab stop whose Page keys pick anchors and their handles, arrows move them, Insert and Delete report anchors to add and remove; above `MAX_ANCHORS` anchors it draws outlines only. `PenDraft` draws the path being drawn with the Pen and runs its gestures (click for a corner anchor, drag for symmetric handles, ⇧ at 45°, ⌥ breaks the pair, a press on the last anchor retracts its handle, a press on the first closes the path, a press on an open path's end resumes it) and keys (Enter and Esc end the path and keep it, Backspace and `PenDraft::remove_last` take back the last anchor), reporting the whole draft as an `EditSubpath` edit gesture; it is not a Tab stop and its anchors are AccessKit objects named by the host's `PenNames`.
|
||||
@@ -0,0 +1,83 @@
|
||||
//! Artboard rectangles and the rules that size them: [`drawn_rect`], [`moved_rect`],
|
||||
//! [`resized_rect`] and [`resized_keep_ratio`]. No egui.
|
||||
//!
|
||||
//! Artboards are whole document pixels: every rectangle these return has integer edges and is at
|
||||
//! least 1 × 1. A handle is one of [`HANDLES`](super::slice::HANDLES) (−1, 0 or 1 per axis).
|
||||
|
||||
use kurbo::{Point, Rect, Vec2};
|
||||
|
||||
/// The board a drag from `a` to `b` draws: both corners rounded to whole pixels, ordered.
|
||||
pub fn drawn_rect(a: Point, b: Point) -> Rect {
|
||||
// pc: crates/ui-egui/src/tools/artboard_tool.rs:113-115 `drawn`.
|
||||
Rect::new(a.x.min(b.x).round(), a.y.min(b.y).round(), a.x.max(b.x).round(), a.y.max(b.y).round())
|
||||
}
|
||||
|
||||
/// `rect` moved by `by` rounded to whole pixels (a move keeps the size).
|
||||
pub fn moved_rect(rect: Rect, by: Vec2) -> Rect {
|
||||
// pc: crates/ui-egui/src/tools/artboard_tool.rs:118-120 `offset` (each axis rounded), :158-161.
|
||||
rect + Vec2::new(by.x.round(), by.y.round())
|
||||
}
|
||||
|
||||
/// `rect` with handle `handle` dragged by `by` (rounded to whole pixels). An edge dragged past the
|
||||
/// opposite one flips the board, which never gets narrower than one pixel. `about_centre` (⌥)
|
||||
/// moves the opposite edge by the same amount the other way, so the centre stays.
|
||||
pub fn resized_rect(rect: Rect, handle: [i8; 2], by: Vec2, about_centre: bool) -> Rect {
|
||||
// pc: crates/ui-egui/src/tools/artboard_tool.rs:125-139 `resized` (per axis: −1 moves the low
|
||||
// edge, 1 the high one; `(a, b.max(a + 1))`).
|
||||
// new: `about_centre` (⌥, Photoshop's artboard resize; PhotoCraft has none).
|
||||
let (dx, dy) = (by.x.round(), by.y.round());
|
||||
let mut e = [rect.x0, rect.y0, rect.x1, rect.y1];
|
||||
for (h, lo, hi, dv) in [(handle[0], 0, 2, dx), (handle[1], 1, 3, dy)] {
|
||||
match h {
|
||||
-1 => {
|
||||
e[lo] += dv;
|
||||
if about_centre {
|
||||
e[hi] -= dv;
|
||||
}
|
||||
}
|
||||
1 => {
|
||||
e[hi] += dv;
|
||||
if about_centre {
|
||||
e[lo] -= dv;
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
let (a, b) = (e[lo].min(e[hi]), e[lo].max(e[hi]));
|
||||
(e[lo], e[hi]) = (a, b.max(a + 1.0));
|
||||
}
|
||||
Rect::new(e[0], e[1], e[2], e[3])
|
||||
}
|
||||
|
||||
/// `rect` with corner `handle` dragged by `by`, keeping its proportions (⇧ on a corner): the
|
||||
/// opposite corner stays (the centre with `about_centre`), and the board scales by the larger of
|
||||
/// the two axes' factors, each side rounded to whole pixels and at least 1. An edge handle (a 0 in
|
||||
/// `handle`) resizes as [`resized_rect`] does.
|
||||
pub fn resized_keep_ratio(rect: Rect, handle: [i8; 2], by: Vec2, about_centre: bool) -> Rect {
|
||||
// pc: crates/ui-egui/src/tools/artboard_tool.rs:141-153 `resized_keep` (`k = (dw.abs() /
|
||||
// w).max(dh.abs() / h)`, sides `(w * k).round().max(1.0)`, spanning from the fixed corner toward
|
||||
// the drag), :160 (only for a corner).
|
||||
// new: `about_centre`.
|
||||
if handle[0] == 0 || handle[1] == 0 {
|
||||
return resized_rect(rect, handle, by, about_centre);
|
||||
}
|
||||
let (dx, dy) = (by.x.round(), by.y.round());
|
||||
let (w, h) = (rect.width().max(1.0), rect.height().max(1.0));
|
||||
let (cx, cy) = ((rect.x0 + rect.x1) / 2.0, (rect.y0 + rect.y1) / 2.0);
|
||||
// The fixed point: the opposite corner, or the centre with `about_centre`; and the dragged
|
||||
// corner's offset from it.
|
||||
let (ax, ay) =
|
||||
if about_centre { (cx, cy) } else { (if handle[0] > 0 { rect.x0 } else { rect.x1 }, if handle[1] > 0 { rect.y0 } else { rect.y1 }) };
|
||||
let (px, py) = (if handle[0] > 0 { rect.x1 } else { rect.x0 } + dx, if handle[1] > 0 { rect.y1 } else { rect.y0 } + dy);
|
||||
let (dw, dh) = (px - ax, py - ay);
|
||||
let reach = if about_centre { 2.0 } else { 1.0 };
|
||||
let k = (dw.abs() * reach / w).max(dh.abs() * reach / h);
|
||||
let (nw, nh) = ((w * k).round().max(1.0), (h * k).round().max(1.0));
|
||||
if about_centre {
|
||||
let (x0, y0) = ((cx - nw / 2.0).round(), (cy - nh / 2.0).round());
|
||||
return Rect::new(x0, y0, x0 + nw, y0 + nh);
|
||||
}
|
||||
let span = |a: f64, len: f64, toward: f64| if toward < 0.0 { [a - len, a] } else { [a, a + len] };
|
||||
let ([x0, x1], [y0, y1]) = (span(ax, nw, dw), span(ay, nh, dh));
|
||||
Rect::new(x0, y0, x1, y1)
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
//! Tests of artboard rectangles.
|
||||
|
||||
use craft_ui::testing::trial;
|
||||
use kurbo::{Rect, Vec2};
|
||||
|
||||
use super::artboard::resized_rect;
|
||||
|
||||
// `resized_rect` of (0, 0, 100, 100) with the left handle dragged by 150 gives (100, 0, 150, 100);
|
||||
// dragged by exactly 100 it is 1 px wide; ⌥ moves the right edge the other way.
|
||||
#[trial]
|
||||
fn artboard_resize_past_opposite_edge_flips_with_min_one_pixel() {
|
||||
let r = Rect::new(0.0, 0.0, 100.0, 100.0);
|
||||
assert_eq!(resized_rect(r, [-1, 0], Vec2::new(150.0, 0.0), false), Rect::new(100.0, 0.0, 150.0, 100.0));
|
||||
assert_eq!(resized_rect(r, [-1, 0], Vec2::new(100.0, 0.0), false), Rect::new(100.0, 0.0, 101.0, 100.0));
|
||||
assert_eq!(resized_rect(r, [-1, 0], Vec2::new(20.0, 0.0), true), Rect::new(20.0, 0.0, 80.0, 100.0));
|
||||
assert_eq!(resized_rect(r, [1, 1], Vec2::new(10.0, -10.0), true), Rect::new(-10.0, 10.0, 110.0, 90.0));
|
||||
}
|
||||
|
||||
// `drawn_rect` and `moved_rect` round to whole pixels and order the corners.
|
||||
@@ -0,0 +1,360 @@
|
||||
//! Connector routes between objects: [`route`], [`route_along`], [`attached_sides`],
|
||||
//! [`path_handles`] and [`reshaped`], ported from FigCraft's `board_route` (no egui). The
|
||||
//! Connector tool previews with them (`craft_draw::ui::connector`), and an app's engine routes the
|
||||
//! connectors it stores with the same functions, so the two never disagree.
|
||||
//!
|
||||
//! A connector's route is document geometry: [`ROOM`] is a constant, not a theme token, so a
|
||||
//! theme never moves a connector.
|
||||
|
||||
use kurbo::{Point, Rect, Vec2};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// How far an elbow route going around the objects it joins keeps from them, document units
|
||||
/// (FigCraft's `ROOM`).
|
||||
pub const ROOM: f64 = 24.0;
|
||||
|
||||
/// How a connector runs between its ends.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum Routing {
|
||||
/// A direct line between the ends.
|
||||
#[default]
|
||||
Straight,
|
||||
/// Right angles only: out of each end along its side's normal, turning once or twice, around
|
||||
/// the objects it joins when the short way would cross them.
|
||||
Elbow,
|
||||
/// One smooth curve, leaving and arriving along the sides' normals.
|
||||
Curved,
|
||||
}
|
||||
|
||||
/// The side of an object a connector end leaves by.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ConnectionSide {
|
||||
/// The side facing the other end.
|
||||
#[default]
|
||||
Auto,
|
||||
#[allow(missing_docs)]
|
||||
Top,
|
||||
#[allow(missing_docs)]
|
||||
Right,
|
||||
#[allow(missing_docs)]
|
||||
Bottom,
|
||||
#[allow(missing_docs)]
|
||||
Left,
|
||||
}
|
||||
|
||||
impl ConnectionSide {
|
||||
/// The four sides clockwise from the top, the default connection sites' order.
|
||||
pub const ALL: [ConnectionSide; 4] = [ConnectionSide::Top, ConnectionSide::Right, ConnectionSide::Bottom, ConnectionSide::Left];
|
||||
|
||||
/// The side's middle on `bounds`; the centre for [`Auto`](Self::Auto).
|
||||
pub fn point(self, bounds: Rect) -> Point {
|
||||
let c = bounds.center();
|
||||
match self {
|
||||
ConnectionSide::Top => Point::new(c.x, bounds.y0),
|
||||
ConnectionSide::Right => Point::new(bounds.x1, c.y),
|
||||
ConnectionSide::Bottom => Point::new(c.x, bounds.y1),
|
||||
ConnectionSide::Left => Point::new(bounds.x0, c.y),
|
||||
ConnectionSide::Auto => c,
|
||||
}
|
||||
}
|
||||
|
||||
/// Left or right.
|
||||
pub fn horizontal(self) -> bool {
|
||||
matches!(self, ConnectionSide::Left | ConnectionSide::Right)
|
||||
}
|
||||
|
||||
/// The way out of the side (y down); zero for [`Auto`](Self::Auto).
|
||||
pub fn normal(self) -> Vec2 {
|
||||
match self {
|
||||
ConnectionSide::Top => Vec2::new(0.0, -1.0),
|
||||
ConnectionSide::Right => Vec2::new(1.0, 0.0),
|
||||
ConnectionSide::Bottom => Vec2::new(0.0, 1.0),
|
||||
ConnectionSide::Left => Vec2::new(-1.0, 0.0),
|
||||
ConnectionSide::Auto => Vec2::ZERO,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A box edge counts as outside: a run along or out of an edge is not inside, by this much
|
||||
/// (FigCraft's `EDGE`, document units).
|
||||
const EDGE: f64 = 0.5;
|
||||
|
||||
/// A path of more runs than this can't be made by hand ([`reshaped`] refuses another).
|
||||
const MAX_RUNS: usize = 64;
|
||||
|
||||
/// Two control points moved by `d` move a cubic's middle by 3/4 of `d`, so a bow is applied as
|
||||
/// `d * 4/3`.
|
||||
const BOW_GAIN: f64 = 4.0 / 3.0;
|
||||
|
||||
/// A divisor floor that keeps a zero-length division finite.
|
||||
const TINY: f64 = 1e-9;
|
||||
|
||||
/// One end of a route.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub enum RouteEnd {
|
||||
/// A free end at a point.
|
||||
Point(Point),
|
||||
/// Glued to the middle of a side of the box (or the side facing the other end).
|
||||
Box(Rect, ConnectionSide),
|
||||
/// Glued to a point on the object in the box, placed by hand or a numbered site, leaving by the
|
||||
/// side given.
|
||||
On(Rect, ConnectionSide, Point),
|
||||
}
|
||||
|
||||
/// A connector's path as reshaped by hand, measured from the middle of its two ends so the shape
|
||||
/// travels with what it joins.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum ConnectorPath {
|
||||
/// An elbow's straight runs, each at right angles to the one before: whether the first runs
|
||||
/// across (else up or down), and where the runs between the first and last lie (x of one that
|
||||
/// runs up or down, y of one that runs across). The first and last lie on the ends.
|
||||
Runs {
|
||||
/// Whether the first run goes across (else up or down).
|
||||
across: bool,
|
||||
/// Positions of the runs between the first and last, in document units.
|
||||
at: Vec<f64>,
|
||||
},
|
||||
/// How far a curve's middle was moved.
|
||||
Bow {
|
||||
/// Horizontal move of the curve's middle, in document units.
|
||||
x: f64,
|
||||
/// Vertical move of the curve's middle, in document units.
|
||||
y: f64,
|
||||
},
|
||||
}
|
||||
|
||||
impl RouteEnd {
|
||||
fn centre(self) -> Point {
|
||||
match self {
|
||||
RouteEnd::Point(p) | RouteEnd::On(_, _, p) => p,
|
||||
RouteEnd::Box(b, _) => b.center(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The points a connector runs through from `from` to `to`: from the middle of the side of each
|
||||
/// box facing the other end (or the side it names), straight, in right angles keeping [`ROOM`]
|
||||
/// from the joined boxes, or (curved) its two ends with the curve's two control points between
|
||||
/// them. `None` when a point isn't finite.
|
||||
pub fn route(from: RouteEnd, to: RouteEnd, routing: Routing) -> Option<Vec<Point>> {
|
||||
let (p0, s0) = attach(from, to.centre());
|
||||
let (p1, s1) = attach(to, from.centre());
|
||||
let boxes: Vec<Rect> = [from, to].into_iter().filter_map(|e| if let RouteEnd::Box(b, _) = e { Some(b) } else { None }).collect();
|
||||
let pts = match routing {
|
||||
Routing::Straight => tidy(vec![p0, p1]),
|
||||
Routing::Elbow => elbow(p0, s0, p1, s1, &boxes),
|
||||
Routing::Curved => curve(p0, s0, p1, s1),
|
||||
};
|
||||
finite(pts)
|
||||
}
|
||||
|
||||
/// [`route`] for a connector whose `path` may have been reshaped by hand; a path that isn't for
|
||||
/// its `routing` is ignored.
|
||||
pub fn route_along(from: RouteEnd, to: RouteEnd, routing: Routing, path: Option<&ConnectorPath>) -> Option<Vec<Point>> {
|
||||
let (p0, s0) = attach(from, to.centre());
|
||||
let (p1, s1) = attach(to, from.centre());
|
||||
let pts = match (routing, path) {
|
||||
(Routing::Elbow, Some(ConnectorPath::Runs { across, at })) => along_runs(p0, p1, *across, at),
|
||||
(Routing::Curved, Some(ConnectorPath::Bow { x, y })) => {
|
||||
let d = Vec2::new(*x, *y) * BOW_GAIN;
|
||||
let pull = |(i, p): (usize, Point)| if i == 1 || i == 2 { p + d } else { p };
|
||||
curve(p0, s0, p1, s1).into_iter().enumerate().map(pull).collect()
|
||||
}
|
||||
_ => return route(from, to, routing),
|
||||
};
|
||||
finite(pts)
|
||||
}
|
||||
|
||||
/// The sides a connector's ends leave by as routed now; `None` for a free end.
|
||||
pub fn attached_sides(from: RouteEnd, to: RouteEnd) -> (Option<ConnectionSide>, Option<ConnectionSide>) {
|
||||
(attach(from, to.centre()).1, attach(to, from.centre()).1)
|
||||
}
|
||||
|
||||
/// The route's path handles: one per run of an elbow and one for a curve, each with the portion
|
||||
/// of the path it moves and where it sits. None for a straight route.
|
||||
pub fn path_handles(points: &[Point], routing: Routing) -> Vec<(usize, Point)> {
|
||||
match routing {
|
||||
Routing::Straight => Vec::new(),
|
||||
Routing::Curved => curve_middle(points).map(|m| (0, m)).into_iter().collect(),
|
||||
Routing::Elbow => points.windows(2).enumerate().map(|(i, w)| (i, w[0].midpoint(w[1]))).collect(),
|
||||
}
|
||||
}
|
||||
|
||||
/// The path after dragging `portion`'s handle to `at`: an elbow's run moves there, and a first or
|
||||
/// last run stays on its end through an extra run; a curve's middle moves there. `None` for a
|
||||
/// straight connector, a portion it doesn't have, or a path of too many runs (64).
|
||||
pub fn reshaped(from: RouteEnd, to: RouteEnd, routing: Routing, path: Option<&ConnectorPath>, portion: usize, at: Point) -> Option<ConnectorPath> {
|
||||
match routing {
|
||||
Routing::Straight => None,
|
||||
Routing::Curved => {
|
||||
let m = curve_middle(&route(from, to, routing)?)?;
|
||||
Some(ConnectorPath::Bow { x: at.x - m.x, y: at.y - m.y })
|
||||
}
|
||||
Routing::Elbow => reshaped_runs(&route_along(from, to, routing, path)?, portion, at),
|
||||
}
|
||||
}
|
||||
|
||||
/// `pts` when every coordinate is finite.
|
||||
fn finite(pts: Vec<Point>) -> Option<Vec<Point>> {
|
||||
pts.iter().all(|p| p.x.is_finite() && p.y.is_finite()).then_some(pts)
|
||||
}
|
||||
|
||||
/// The runs of the right-angled route `pts` with run `portion` moved to `p`.
|
||||
fn reshaped_runs(pts: &[Point], portion: usize, p: Point) -> Option<ConnectorPath> {
|
||||
let last = pts.len().checked_sub(2)?;
|
||||
let (first, end) = (*pts.first()?, *pts.last()?);
|
||||
if portion > last || last + 3 > MAX_RUNS {
|
||||
return None;
|
||||
}
|
||||
let mid = first.midpoint(end);
|
||||
let across = |i: usize| pts[i].y == pts[i + 1].y;
|
||||
// Run i's place (where it lies), and a point's place along it, from the middle of the ends.
|
||||
let lies = |i: usize, q: Point| if across(i) { q.y - mid.y } else { q.x - mid.x };
|
||||
let along = |i: usize, q: Point| if across(i) { q.x - mid.x } else { q.y - mid.y };
|
||||
// The stretch of run i kept on its end `q`, towards the run's other end `to`.
|
||||
let stub = |i: usize, q: Point, to: Point| {
|
||||
let d = to - q;
|
||||
along(i, q + d * (ROOM.min(d.hypot() / 2.0) / d.hypot().max(TINY)))
|
||||
};
|
||||
let mut at: Vec<f64> = (1..last).map(|i| lies(i, pts[i])).collect();
|
||||
let moved = lies(portion, p);
|
||||
if last == 0 {
|
||||
at = vec![stub(0, first, end), moved, stub(0, end, first)];
|
||||
} else if portion == 0 {
|
||||
at.splice(0..0, [stub(0, first, pts[1]), moved]);
|
||||
} else if portion == last {
|
||||
at.extend([moved, stub(last, end, pts[last])]);
|
||||
} else {
|
||||
*at.get_mut(portion - 1)? = moved;
|
||||
}
|
||||
Some(ConnectorPath::Runs { across: across(0), at })
|
||||
}
|
||||
|
||||
/// The right-angled route from `p0` to `p1` through runs at the places `at` (see
|
||||
/// [`ConnectorPath::Runs`]).
|
||||
fn along_runs(p0: Point, p1: Point, across: bool, at: &[f64]) -> Vec<Point> {
|
||||
let mid = p0.midpoint(p1);
|
||||
let (mut out, mut cur, mut sideways) = (vec![p0], p0, across);
|
||||
for v in at {
|
||||
cur = if sideways { Point::new(mid.x + v, cur.y) } else { Point::new(cur.x, mid.y + v) };
|
||||
out.push(cur);
|
||||
sideways = !sideways;
|
||||
}
|
||||
out.push(if sideways { Point::new(p1.x, cur.y) } else { Point::new(cur.x, p1.y) });
|
||||
out.push(p1);
|
||||
tidy(out)
|
||||
}
|
||||
|
||||
/// The middle of the curve whose ends and control points are `pts`.
|
||||
fn curve_middle(pts: &[Point]) -> Option<Point> {
|
||||
let [a, b, c, d] = pts else { return None };
|
||||
Some(((a.to_vec2() + (b.to_vec2() + c.to_vec2()) * 3.0 + d.to_vec2()) / 8.0).to_point())
|
||||
}
|
||||
|
||||
/// `pts` without repeats or turns that don't turn (three in a line across or down).
|
||||
fn tidy(pts: Vec<Point>) -> Vec<Point> {
|
||||
let mut out: Vec<Point> = Vec::with_capacity(pts.len());
|
||||
for p in pts {
|
||||
if out.last() == Some(&p) {
|
||||
continue;
|
||||
}
|
||||
if let [.., a, b] = out.as_slice()
|
||||
&& ((a.x == b.x && b.x == p.x) || (a.y == b.y && b.y == p.y))
|
||||
{
|
||||
out.pop();
|
||||
}
|
||||
out.push(p);
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// Where end `e` attaches (its point, or the middle of its box's side facing `other`) and that
|
||||
/// side (`None`: a free point).
|
||||
fn attach(e: RouteEnd, other: Point) -> (Point, Option<ConnectionSide>) {
|
||||
match e {
|
||||
RouteEnd::Point(p) => (p, None),
|
||||
RouteEnd::Box(b, side) => {
|
||||
let side = named_or_facing(b, side, other);
|
||||
(side.point(b), Some(side))
|
||||
}
|
||||
RouteEnd::On(b, side, p) => (p, Some(named_or_facing(b, side, other))),
|
||||
}
|
||||
}
|
||||
|
||||
/// `side`, or for [`ConnectionSide::Auto`] the side of `b` facing `other`.
|
||||
fn named_or_facing(b: Rect, side: ConnectionSide, other: Point) -> ConnectionSide {
|
||||
if side != ConnectionSide::Auto {
|
||||
return side;
|
||||
}
|
||||
let d = other - b.center();
|
||||
// Compare against the box's proportions: a wide box takes the sides more.
|
||||
if d.x.abs() * b.height().max(TINY) >= d.y.abs() * b.width().max(TINY) {
|
||||
if d.x >= 0.0 { ConnectionSide::Right } else { ConnectionSide::Left }
|
||||
} else if d.y >= 0.0 {
|
||||
ConnectionSide::Bottom
|
||||
} else {
|
||||
ConnectionSide::Top
|
||||
}
|
||||
}
|
||||
|
||||
/// A curve from `p0` to `p1` leaving and arriving along the sides' normals (a free end pulls no
|
||||
/// way): the ends and the two control points between them.
|
||||
fn curve(p0: Point, s0: Option<ConnectionSide>, p1: Point, s1: Option<ConnectionSide>) -> Vec<Point> {
|
||||
let reach = (p1 - p0).hypot() / 2.0;
|
||||
let pull = |p: Point, s: Option<ConnectionSide>| p + s.map_or(Vec2::ZERO, |s| s.normal() * reach);
|
||||
vec![p0, pull(p0, s0), pull(p1, s1), p1]
|
||||
}
|
||||
|
||||
/// A right-angled route from `p0` to `p1`, leaving and arriving along the sides' normals (`s`; a
|
||||
/// free end follows the other): the short way when it keeps out of the attached objects' `boxes`,
|
||||
/// else the cheapest of a few ways around them (by length, and turns).
|
||||
fn elbow(p0: Point, s0: Option<ConnectionSide>, p1: Point, s1: Option<ConnectionSide>, boxes: &[Rect]) -> Vec<Point> {
|
||||
let direct = tidy(short_elbow(p0, s0.map(ConnectionSide::horizontal), p1, s1.map(ConnectionSide::horizontal)));
|
||||
let Some(all) = boxes.iter().copied().reduce(|a, b| a.union(b)) else { return direct };
|
||||
if !crosses(&direct, boxes) {
|
||||
return direct;
|
||||
}
|
||||
// Out of each end by ROOM, then across on one of a few lines: halfway, or clear of the objects.
|
||||
let out = |p: Point, s: Option<ConnectionSide>| p + s.map_or(Vec2::ZERO, |s| s.normal() * ROOM);
|
||||
let (a, b) = (out(p0, s0), out(p1, s1));
|
||||
let mut ways = vec![vec![p0, a, Point::new(b.x, a.y), b, p1], vec![p0, a, Point::new(a.x, b.y), b, p1]];
|
||||
for x in [(a.x + b.x) / 2.0, all.x0 - ROOM, all.x1 + ROOM] {
|
||||
ways.push(vec![p0, a, Point::new(x, a.y), Point::new(x, b.y), b, p1]);
|
||||
}
|
||||
for y in [(a.y + b.y) / 2.0, all.y0 - ROOM, all.y1 + ROOM] {
|
||||
ways.push(vec![p0, a, Point::new(a.x, y), Point::new(b.x, y), b, p1]);
|
||||
}
|
||||
let cost = |r: &Vec<Point>| r.windows(2).map(|s| (s[1] - s[0]).hypot()).sum::<f64>() + ROOM * r.len() as f64;
|
||||
ways.into_iter().map(tidy).filter(|r| !crosses(r, boxes)).min_by(|x, y| cost(x).total_cmp(&cost(y))).unwrap_or(direct)
|
||||
}
|
||||
|
||||
/// Whether the right-angled route `pts` runs through the inside of any of `boxes` (along an edge,
|
||||
/// or out of one, is outside).
|
||||
fn crosses(pts: &[Point], boxes: &[Rect]) -> bool {
|
||||
pts.windows(2).any(|s| {
|
||||
let (a, b) = (s[0], s[1]);
|
||||
boxes.iter().any(|r| a.x.min(b.x) < r.x1 - EDGE && a.x.max(b.x) > r.x0 + EDGE && a.y.min(b.y) < r.y1 - EDGE && a.y.max(b.y) > r.y0 + EDGE)
|
||||
})
|
||||
}
|
||||
|
||||
/// The short right-angled route from `p0` to `p1` (`h`: the side faces sideways; a free end
|
||||
/// follows the other): halfway across between two sides facing the same way, one turn otherwise.
|
||||
fn short_elbow(p0: Point, h0: Option<bool>, p1: Point, h1: Option<bool>) -> Vec<Point> {
|
||||
let h0 = h0.or(h1).unwrap_or((p1.x - p0.x).abs() >= (p1.y - p0.y).abs());
|
||||
let h1 = h1.unwrap_or(h0);
|
||||
match (h0, h1) {
|
||||
(true, true) => {
|
||||
let mx = (p0.x + p1.x) / 2.0;
|
||||
vec![p0, Point::new(mx, p0.y), Point::new(mx, p1.y), p1]
|
||||
}
|
||||
(false, false) => {
|
||||
let my = (p0.y + p1.y) / 2.0;
|
||||
vec![p0, Point::new(p0.x, my), Point::new(p1.x, my), p1]
|
||||
}
|
||||
(true, false) => vec![p0, Point::new(p1.x, p0.y), p1],
|
||||
(false, true) => vec![p0, Point::new(p0.x, p1.y), p1],
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
//! Tests of connector routes, ported from FigCraft's engine tests (`board_route.rs`).
|
||||
|
||||
use craft_ui::testing::trial;
|
||||
use kurbo::{Point, Rect};
|
||||
|
||||
use super::connector::{ConnectionSide, ConnectorPath, ROOM, RouteEnd, Routing, attached_sides, reshaped, route, route_along};
|
||||
|
||||
fn pt(x: f64, y: f64) -> Point {
|
||||
Point::new(x, y)
|
||||
}
|
||||
|
||||
const A: Rect = Rect::new(0.0, 0.0, 100.0, 100.0);
|
||||
|
||||
// An elbow whose short way would cross a joined box goes around it, keeping `ROOM` from it
|
||||
// (`board_connector_tests.rs:141`).
|
||||
#[trial]
|
||||
fn connector_elbow_goes_around_joined_boxes_by_room() {
|
||||
use ConnectionSide::{Left, Right};
|
||||
let b = Rect::new(300.0, 0.0, 400.0, 100.0);
|
||||
// Out of A's left and B's right: the short way runs through both, so it goes over them, the
|
||||
// nearer way round (the tie between over and under goes to the top).
|
||||
let pts = route(RouteEnd::Box(A, Left), RouteEnd::Box(b, Right), Routing::Elbow);
|
||||
assert_eq!(pts, Some(vec![pt(0.0, 50.0), pt(-ROOM, 50.0), pt(-ROOM, -ROOM), pt(400.0 + ROOM, -ROOM), pt(400.0 + ROOM, 50.0), pt(400.0, 50.0)]));
|
||||
// Facing each other, the short way stays.
|
||||
assert_eq!(route(RouteEnd::Box(A, Right), RouteEnd::Box(b, Left), Routing::Elbow), Some(vec![pt(100.0, 50.0), pt(300.0, 50.0)]));
|
||||
// An end at the bottom of the second box leaving towards the first above it: no run goes
|
||||
// through either box.
|
||||
let pts = route(RouteEnd::Box(A, Left), RouteEnd::Box(b, ConnectionSide::Bottom), Routing::Elbow).unwrap_or_default();
|
||||
assert_eq!(pts.last().copied(), Some(pt(350.0, 100.0)));
|
||||
let inside = |r: Rect| {
|
||||
pts.windows(2).any(|w| {
|
||||
w[0].x.min(w[1].x) < r.x1 - 0.5 && w[0].x.max(w[1].x) > r.x0 + 0.5 && w[0].y.min(w[1].y) < r.y1 - 0.5 && w[0].y.max(w[1].y) > r.y0 + 0.5
|
||||
})
|
||||
};
|
||||
assert!(!inside(A) && !inside(b), "{pts:?}");
|
||||
assert!(pts.windows(2).all(|w| w[0].x == w[1].x || w[0].y == w[1].y), "right angles only");
|
||||
}
|
||||
|
||||
// `reshaped` of a first or last run keeps it on its end through an extra run; a straight route
|
||||
// has no path; `attached_sides` gives the sides it left by (`board_reshape_tests.rs:67`, `:123`,
|
||||
// `:130`; `connector_anywhere_tests.rs:81`).
|
||||
#[trial]
|
||||
fn connector_reshape_keeps_first_and_last_runs_on_their_ends() {
|
||||
use ConnectionSide::{Bottom, Left, Right};
|
||||
let a = Rect::new(0.0, 0.0, 100.0, 100.0);
|
||||
let b = Rect::new(300.0, 200.0, 400.0, 300.0);
|
||||
let (from, to) = (RouteEnd::Box(a, Right), RouteEnd::Box(b, Left));
|
||||
let (s, e) = (pt(100.0, 50.0), pt(300.0, 250.0));
|
||||
let plain = route(from, to, Routing::Elbow);
|
||||
assert_eq!(plain, Some(vec![s, pt(200.0, 50.0), pt(200.0, 250.0), e]));
|
||||
// The first run dragged: it gains a run and stays on its end.
|
||||
let path = reshaped(from, to, Routing::Elbow, None, 0, pt(150.0, 120.0));
|
||||
assert_eq!(
|
||||
route_along(from, to, Routing::Elbow, path.as_ref()),
|
||||
Some(vec![s, pt(124.0, 50.0), pt(124.0, 120.0), pt(200.0, 120.0), pt(200.0, 250.0), e])
|
||||
);
|
||||
// The last run of that path dragged, from the path as it is.
|
||||
let last = 4;
|
||||
let path = reshaped(from, to, Routing::Elbow, path.as_ref(), last, pt(250.0, 200.0));
|
||||
assert_eq!(
|
||||
route_along(from, to, Routing::Elbow, path.as_ref()),
|
||||
Some(vec![s, pt(124.0, 50.0), pt(124.0, 120.0), pt(200.0, 120.0), pt(200.0, 200.0), pt(276.0, 200.0), pt(276.0, 250.0), e])
|
||||
);
|
||||
// A middle run just moves.
|
||||
let mid = reshaped(from, to, Routing::Elbow, None, 1, pt(230.0, 150.0));
|
||||
assert_eq!(route_along(from, to, Routing::Elbow, mid.as_ref()), Some(vec![s, pt(230.0, 50.0), pt(230.0, 250.0), e]));
|
||||
// Two boxes level with each other: the lone run gains a run at each end.
|
||||
let level = RouteEnd::Box(Rect::new(300.0, 0.0, 400.0, 100.0), Left);
|
||||
let lone = reshaped(from, level, Routing::Elbow, None, 0, pt(200.0, -40.0));
|
||||
assert_eq!(
|
||||
route_along(from, level, Routing::Elbow, lone.as_ref()),
|
||||
Some(vec![s, pt(124.0, 50.0), pt(124.0, -40.0), pt(276.0, -40.0), pt(276.0, 50.0), pt(300.0, 50.0)])
|
||||
);
|
||||
// A straight route has no path; a portion it doesn't have is refused; a path is capped.
|
||||
assert_eq!(reshaped(from, to, Routing::Straight, None, 0, pt(1.0, 1.0)), None);
|
||||
assert_eq!(reshaped(from, to, Routing::Elbow, None, 3, pt(1.0, 1.0)), None);
|
||||
let mut path = None;
|
||||
let mut tries = 0;
|
||||
while let Some(next) = reshaped(from, level, Routing::Elbow, path.as_ref(), 0, pt(150.0, 60.0 + f64::from(tries) * 3.0)) {
|
||||
path = Some(next);
|
||||
tries += 1;
|
||||
}
|
||||
assert!((20..40).contains(&tries), "{tries}");
|
||||
assert!(route_along(from, level, Routing::Elbow, path.as_ref()).is_some_and(|r| r.len() <= 66));
|
||||
// A path for another routing is ignored.
|
||||
let bow = ConnectorPath::Bow { x: 5.0, y: 5.0 };
|
||||
assert_eq!(route_along(from, to, Routing::Elbow, Some(&bow)), plain);
|
||||
// The sides as routed now: named, facing the other end, or none for a free end.
|
||||
assert_eq!(attached_sides(RouteEnd::Box(a, Bottom), RouteEnd::Point(pt(0.0, 500.0))), (Some(Bottom), None));
|
||||
assert_eq!(attached_sides(RouteEnd::Box(a, ConnectionSide::Auto), RouteEnd::Box(b, ConnectionSide::Auto)), (Some(Right), Some(Left)));
|
||||
assert_eq!(attached_sides(RouteEnd::Point(pt(0.0, 0.0)), RouteEnd::On(b, Left, pt(310.0, 250.0))), (None, Some(Left)));
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
//! The Curvature Pen's handles through a list of anchors.
|
||||
//!
|
||||
//! One rule draws, previews and edits Curvature paths everywhere: the pen draft's Curvature mode,
|
||||
//! `BezierTool::Curvature` on finished paths, `EditSubpath::reflow`, and an app's engine.
|
||||
|
||||
use std::ops::RangeInclusive;
|
||||
|
||||
use kurbo::Point;
|
||||
|
||||
/// The range a Curvature insert's segment parameter `t` is clamped to, so an anchor added right
|
||||
/// at a segment's end still lands inside it (PhotoCraft's Curvature press). Add Anchor Point and
|
||||
/// Auto Add take the hit's `t` as it is.
|
||||
// pc: crates/ui-egui/src/tools/direct_select.rs:418 (`t.clamp(0.01, 0.99)`).
|
||||
pub const CURVATURE_T_RANGE: RangeInclusive<f64> = 0.01..=0.99;
|
||||
|
||||
/// The Curvature Pen's handles for `anchors`: for each anchor its (in, out) handle points, so the
|
||||
/// curve passes smoothly through every anchor (Catmull-Rom style, PhotoCraft's chordal rule).
|
||||
///
|
||||
/// - An inner anchor (every anchor when `closed`) lies on handles parallel to the chord from its
|
||||
/// previous to its next neighbour (so they are collinear), the in handle a third of the
|
||||
/// distance to the previous anchor long, the out handle a third of the distance to the next.
|
||||
/// When the neighbours coincide, the direction is from the anchor to the next one.
|
||||
/// - An open path's first anchor aims its out handle at the second anchor's in handle, and the
|
||||
/// last anchor its in handle at the second-to-last anchor's out handle, each a third of the
|
||||
/// distance to that neighbour long. The ends' other handles stay on their anchors.
|
||||
/// - `corners[i]` true keeps anchor `i`'s handles on the anchor (a corner point); an index past
|
||||
/// `corners` is smooth.
|
||||
/// - Fewer than three anchors give straight segments: every handle on its anchor.
|
||||
/// - Coincident points give handles on the anchor, never NaN.
|
||||
///
|
||||
/// The result has one entry per anchor.
|
||||
pub fn curvature_handles(anchors: &[Point], corners: &[bool], closed: bool) -> Vec<(Point, Point)> {
|
||||
// pc: crates/vector/src/edit.rs:281-327 `curvature_knots`.
|
||||
const ZERO: f64 = 1e-9;
|
||||
let n = anchors.len();
|
||||
let mut handles: Vec<(Point, Point)> = anchors.iter().map(|&a| (a, a)).collect();
|
||||
let unit = |a: Point, b: Point| {
|
||||
let l = a.distance(b);
|
||||
(l > ZERO).then(|| (b - a) / l)
|
||||
};
|
||||
let corner = |i: usize| corners.get(i).copied().unwrap_or(false);
|
||||
let inner = |i: usize| closed || (i > 0 && i + 1 < n);
|
||||
for (i, &p) in anchors.iter().enumerate() {
|
||||
if n < 3 || corner(i) || !inner(i) {
|
||||
continue;
|
||||
}
|
||||
let prev = anchors[(i + n - 1) % n];
|
||||
let next = anchors[(i + 1) % n];
|
||||
let Some(d) = unit(prev, next).or_else(|| unit(p, next)) else { continue };
|
||||
handles[i] = (p - d * (prev.distance(p) / 3.0), p + d * (p.distance(next) / 3.0));
|
||||
}
|
||||
if !closed && n >= 3 {
|
||||
for (end, neighbour, first) in [(0, 1, true), (n - 1, n - 2, false)] {
|
||||
if corner(end) {
|
||||
continue;
|
||||
}
|
||||
let p = anchors[end];
|
||||
let aim = if first { handles[neighbour].0 } else { handles[neighbour].1 };
|
||||
let Some(d) = unit(p, aim) else { continue };
|
||||
let h = p + d * (p.distance(anchors[neighbour]) / 3.0);
|
||||
if first {
|
||||
handles[end].1 = h;
|
||||
} else {
|
||||
handles[end].0 = h;
|
||||
}
|
||||
}
|
||||
}
|
||||
handles
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
//! Tests of the Curvature Pen's handles.
|
||||
|
||||
use craft_ui::testing::trial;
|
||||
use kurbo::Point;
|
||||
|
||||
use super::curvature::curvature_handles;
|
||||
|
||||
fn p(x: f64, y: f64) -> Point {
|
||||
Point::new(x, y)
|
||||
}
|
||||
|
||||
// An inner anchor's handles are collinear, parallel to the neighbours' chord, and a third of the
|
||||
// distance to each neighbour long (uneven spacing).
|
||||
#[trial]
|
||||
fn curvature_handles_are_collinear_and_one_third_of_the_neighbour_distance() {
|
||||
let a = [p(0.0, 0.0), p(30.0, 40.0), p(120.0, 40.0), p(150.0, 0.0)];
|
||||
let h = curvature_handles(&a, &[], false);
|
||||
assert_eq!(h.len(), 4);
|
||||
let (i, o) = h[1];
|
||||
let chord = a[2] - a[0];
|
||||
let cross = |u: kurbo::Vec2, v: kurbo::Vec2| u.x * v.y - u.y * v.x;
|
||||
assert!(cross(o - a[1], chord).abs() < 1e-9);
|
||||
assert!(cross(i - a[1], chord).abs() < 1e-9);
|
||||
assert!((a[1].distance(i) - a[1].distance(a[0]) / 3.0).abs() < 1e-9);
|
||||
assert!((a[1].distance(o) - a[1].distance(a[2]) / 3.0).abs() < 1e-9);
|
||||
assert!((a[1] - i).dot(o - a[1]) > 0.0);
|
||||
}
|
||||
|
||||
// `corners[i]` keeps anchor i's handles on the anchor; one or two anchors give straight segments,
|
||||
// open or closed.
|
||||
@@ -0,0 +1,79 @@
|
||||
//! Rounded corners of a polygon: where a vertex's circular rounding sits ([`fillet`]).
|
||||
//!
|
||||
//! The corner widgets (`craft_draw::ui::corner`) place, cap and drag their radius with it, and an
|
||||
//! app's engine rounds its polygons and stars with it, so the widget always sits on the arc the
|
||||
//! engine draws.
|
||||
|
||||
use std::f64::consts::FRAC_PI_2;
|
||||
|
||||
use kurbo::{Point, Vec2};
|
||||
|
||||
/// A vertex rounded by a circular arc tangent to both its edges: see [`fillet`].
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct Fillet {
|
||||
/// The arc's centre.
|
||||
pub centre: Point,
|
||||
/// The arc's tangent point on the edge towards the previous vertex.
|
||||
pub from: Point,
|
||||
/// The arc's tangent point on the edge towards the next vertex.
|
||||
pub to: Point,
|
||||
/// The radius used: the one asked for, capped at what the edges allow.
|
||||
pub radius: f64,
|
||||
/// The unit direction from the vertex towards the arc's centre.
|
||||
pub bisector: Vec2,
|
||||
/// Half the vertex's inner angle, in radians, in 1e-6..=π/2 − 1e-6.
|
||||
pub half_angle: f64,
|
||||
}
|
||||
|
||||
impl Fillet {
|
||||
/// How far the arc's centre moves per unit of radius: `bisector / sin(half_angle)`. A right
|
||||
/// angle's is `(±1, ±1)`. The corner widgets project a drag on it.
|
||||
pub fn step(&self) -> Vec2 {
|
||||
// pc: crates/ui-egui/src/tools/corner_radius.rs:75-79 (`bisector / sin`; `half_angle` is
|
||||
// never small enough here for the division to blow up).
|
||||
self.bisector / self.half_angle.sin()
|
||||
}
|
||||
}
|
||||
|
||||
/// Where vertex `vertex` between `prev` and `next` is rounded with radius `radius`: the radius is
|
||||
/// capped so both tangent points stay within half of each edge (`radius.min(min(l1, l2) / 2 *
|
||||
/// tan(half))`, so neighbouring roundings never overlap); the centre is `bisector * radius /
|
||||
/// sin(half)` from the vertex; the tangent points `radius / tan(half)` along each edge. A
|
||||
/// rectangle's cap is `min(w, h) / 2`.
|
||||
///
|
||||
/// `None` for `radius` NaN or `<= 0`, an edge shorter than 1e-9, a half angle outside
|
||||
/// 1e-6..=π/2 − 1e-6 (a straight or folded vertex), or a bisector shorter than 1e-9. Pass a very
|
||||
/// large radius (PhotoCraft passes 1e12) to get the largest one the vertex takes.
|
||||
pub fn fillet(prev: Point, vertex: Point, next: Point, radius: f64) -> Option<Fillet> {
|
||||
// pc: crates/vector/src/shapes.rs:128-165 `fillet` (constants as there).
|
||||
if radius.is_nan() || radius <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let unit = |to: Point| {
|
||||
let d = to - vertex;
|
||||
let len = d.hypot();
|
||||
(len > 1e-9).then(|| (d / len, len))
|
||||
};
|
||||
let (u1, l1) = unit(prev)?;
|
||||
let (u2, l2) = unit(next)?;
|
||||
let half = u1.dot(u2).clamp(-1.0, 1.0).acos() / 2.0;
|
||||
if !(1e-6..=FRAC_PI_2 - 1e-6).contains(&half) {
|
||||
return None;
|
||||
}
|
||||
let radius = radius.min(l1.min(l2) / 2.0 * half.tan());
|
||||
let sum = u1 + u2;
|
||||
let len = sum.hypot();
|
||||
if len < 1e-9 {
|
||||
return None;
|
||||
}
|
||||
let bisector = sum / len;
|
||||
let tangent = radius / half.tan();
|
||||
Some(Fillet {
|
||||
centre: vertex + bisector * (radius / half.sin()),
|
||||
from: vertex + u1 * tangent,
|
||||
to: vertex + u2 * tangent,
|
||||
radius,
|
||||
bisector,
|
||||
half_angle: half,
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
//! Tests of rounded corners.
|
||||
|
||||
use craft_ui::testing::trial;
|
||||
use kurbo::{Point, Vec2};
|
||||
|
||||
use super::fillet::fillet;
|
||||
|
||||
fn near(a: f64, b: f64) -> bool {
|
||||
(a - b).abs() < 1e-9
|
||||
}
|
||||
|
||||
// PhotoCraft's values: a right angle of a 100 × 60 rectangle caps at 30 and steps (1, 1); an
|
||||
// acute triangle vertex; a small radius is kept.
|
||||
#[trial]
|
||||
fn fillet_matches_photocraft() {
|
||||
let (a, b, c) = (Point::new(0.0, 0.0), Point::new(100.0, 0.0), Point::new(0.0, 60.0));
|
||||
let Some(f) = fillet(b, a, c, 1e12) else { panic!("a right angle rounds") };
|
||||
assert!(near(f.radius, 30.0));
|
||||
assert!(near(f.half_angle, std::f64::consts::FRAC_PI_4));
|
||||
assert!((f.centre - Point::new(30.0, 30.0)).hypot() < 1e-9);
|
||||
assert!((f.from - Point::new(30.0, 0.0)).hypot() < 1e-9);
|
||||
assert!((f.to - Point::new(0.0, 30.0)).hypot() < 1e-9);
|
||||
assert!((f.step() - Vec2::new(1.0, 1.0)).hypot() < 1e-9);
|
||||
|
||||
let Some(small) = fillet(b, a, c, 5.0) else { panic!("a small radius rounds") };
|
||||
assert!(near(small.radius, 5.0));
|
||||
assert!((small.centre - Point::new(5.0, 5.0)).hypot() < 1e-9);
|
||||
|
||||
// An acute vertex: 60° at the origin of an equilateral triangle with side 10.
|
||||
let (p, q) = (Point::new(10.0, 0.0), Point::new(5.0, 75f64.sqrt()));
|
||||
let Some(t) = fillet(p, a, q, 1e12) else { panic!("an acute angle rounds") };
|
||||
assert!(near(t.half_angle, std::f64::consts::FRAC_PI_6));
|
||||
assert!(near(t.radius, 5.0 * std::f64::consts::FRAC_PI_6.tan()));
|
||||
assert!(near((t.centre - a).hypot(), t.radius / t.half_angle.sin()));
|
||||
}
|
||||
|
||||
// `None` for a zero radius, NaN, a zero-length edge, a straight and a folded vertex.
|
||||
@@ -0,0 +1,18 @@
|
||||
//! Drawing geometry without egui, shared by the tools and an app's engine.
|
||||
|
||||
pub mod artboard;
|
||||
#[cfg(test)]
|
||||
mod artboard_tests;
|
||||
pub mod connector;
|
||||
#[cfg(test)]
|
||||
mod connector_tests;
|
||||
pub mod curvature;
|
||||
#[cfg(test)]
|
||||
mod curvature_tests;
|
||||
pub mod fillet;
|
||||
#[cfg(test)]
|
||||
mod fillet_tests;
|
||||
pub mod shape;
|
||||
pub mod slice;
|
||||
|
||||
pub use shape::ShapeGeometry;
|
||||
@@ -0,0 +1,273 @@
|
||||
//! Shape outlines and the drag rules that size them: [`ShapeGeometry`] (a live shape's outline as
|
||||
//! a [`BezPath`]), the box drag ([`box_drag`]), the line drag ([`line_drag`]) and the radial drag
|
||||
//! ([`RadialFrame::drag`]). No egui: an engine, importer or exporter builds the same outline the
|
||||
//! Shape tools preview (`craft_draw::ui::shape_drag`).
|
||||
//!
|
||||
//! Document units throughout; y grows downwards. Corner radii run top-left, top-right,
|
||||
//! bottom-right, bottom-left (PhotoCraft's engine order).
|
||||
|
||||
use std::f64::consts::{FRAC_PI_2, PI, TAU};
|
||||
use std::ops::RangeInclusive;
|
||||
|
||||
use kurbo::{BezPath, Ellipse, Point, Rect, RoundedRect, RoundedRectRadii, Shape, Vec2};
|
||||
|
||||
/// The sides a polygon or the points a star may have (PhotoCraft's Sides field, 3–100).
|
||||
pub const SIDES: RangeInclusive<u32> = 3..=100;
|
||||
|
||||
/// The inner radius of a star over its outer radius; 1 is a plain polygon (PhotoCraft's Star
|
||||
/// ratio field, 1–100 %, stored 0.01–1).
|
||||
pub const STAR_RATIO: RangeInclusive<f64> = 0.01..=1.0;
|
||||
|
||||
/// The smallest side a box drag draws and the shortest line, in document units: anything smaller
|
||||
/// draws nothing (PhotoCraft).
|
||||
pub const MIN_SIDE: f64 = 1.0;
|
||||
|
||||
/// A shape's outline: what a Shape tool drag, the Create Shape dialog and the Properties panel
|
||||
/// describe, and what the app's engine draws.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub enum ShapeGeometry {
|
||||
/// A rectangle; `radii` round the corners top-left, top-right, bottom-right, bottom-left (all
|
||||
/// 0 for square corners). Photoshop's Rectangle with a radius and VectorCraft's Rounded
|
||||
/// Rectangle are this with radii.
|
||||
Rect {
|
||||
/// The rectangle's bounds.
|
||||
rect: Rect,
|
||||
/// Corner radii, in document units.
|
||||
radii: [f64; 4],
|
||||
},
|
||||
/// An ellipse inscribed in `rect`.
|
||||
Ellipse {
|
||||
/// The bounds of the ellipse.
|
||||
rect: Rect,
|
||||
},
|
||||
/// A regular polygon or star inscribed in the ellipse of `rect` (the Box frame: PhotoCraft's Triangle and
|
||||
/// Polygon). `sides` in [`SIDES`]; `star_ratio` in [`STAR_RATIO`], 1 for a plain polygon.
|
||||
/// The Triangle tool is 3 sides.
|
||||
Polygon {
|
||||
/// The box whose inscribed ellipse holds the polygon.
|
||||
rect: Rect,
|
||||
/// Number of sides.
|
||||
sides: u32,
|
||||
/// Inner radius over outer radius for a star; 1 for a plain polygon.
|
||||
star_ratio: f64,
|
||||
},
|
||||
/// A regular polygon or star about `center` (the Radial frame: VectorCraft's Polygon and
|
||||
/// Star). `radius` reaches the outer points; `rotation` turns the first point from straight
|
||||
/// up, in radians, clockwise on screen.
|
||||
RadialPolygon {
|
||||
/// The centre of the polygon.
|
||||
center: Point,
|
||||
/// Distance from the centre to the outer points, in document units.
|
||||
radius: f64,
|
||||
/// Turn of the first point from straight up, in radians, clockwise on screen.
|
||||
rotation: f64,
|
||||
/// Number of sides.
|
||||
sides: u32,
|
||||
/// Inner radius over outer radius for a star; 1 for a plain polygon.
|
||||
star_ratio: f64,
|
||||
},
|
||||
/// A line from `from` to `to`, `weight` wide (Photoshop's Line tool: a filled bar).
|
||||
Line {
|
||||
/// The start of the line.
|
||||
from: Point,
|
||||
/// The end of the line.
|
||||
to: Point,
|
||||
/// The bar's width, in document units.
|
||||
weight: f64,
|
||||
},
|
||||
/// A custom shape's box: the app fits its preset path into `rect`, keeping the preset's
|
||||
/// proportions when `keep_proportions` (⇧ held, PhotoCraft's `finish_custom_shape`).
|
||||
Custom {
|
||||
/// The box the preset path is fitted into.
|
||||
rect: Rect,
|
||||
/// Whether the preset keeps its own proportions inside `rect`.
|
||||
keep_proportions: bool,
|
||||
},
|
||||
}
|
||||
|
||||
impl ShapeGeometry {
|
||||
/// The outline as a closed path; `tolerance` (document units) bounds the error where a curve
|
||||
/// is approximated.
|
||||
///
|
||||
/// - `Rect`: the four corners clockwise from the top left, each rounded by its radius (clamped
|
||||
/// to half the shorter side, as kurbo's `RoundedRect` does); all radii 0 is the plain
|
||||
/// rectangle.
|
||||
/// - `Ellipse`: kurbo's `Ellipse::from_rect`.
|
||||
/// - `Polygon`: the outline of [`RadialPolygon`](Self::RadialPolygon) with the first point
|
||||
/// straight up, its outer points on the ellipse inscribed in `rect` (PhotoCraft's engine:
|
||||
/// a triangle's base lies a quarter of the height below the centre, not on the bottom
|
||||
/// edge); a star alternates outer and inner points, the inner ones on the ellipse
|
||||
/// scaled by `star_ratio`.
|
||||
/// - `RadialPolygon`: `sides` outer points on the circle of `radius`, the first at `rotation`
|
||||
/// from straight up; a star (`star_ratio` < 1) puts an inner point between each pair at
|
||||
/// `radius * star_ratio`.
|
||||
/// - `Line`: the bar `weight` wide centred on the segment, square ends at `from` and `to`.
|
||||
/// - `Custom`: the box itself (the app draws the preset).
|
||||
pub fn to_path(&self, tolerance: f64) -> BezPath {
|
||||
// pc: crates/ui-egui/src/tools/vector_ui/shapes.rs:73-79 (the kinds: `roundedRect` with four
|
||||
// equal radii, ellipse, a polygon of 3 sides for the Triangle, `polygon_sides.max(3)`).
|
||||
// new: PhotoCraft's engine draws the outline; here it is kurbo's `RoundedRect`, `Ellipse`
|
||||
// and a point list, so engines without one share it.
|
||||
let tolerance = tolerance.max(f64::EPSILON);
|
||||
match *self {
|
||||
Self::Rect { rect, radii } => {
|
||||
let rect = rect.abs();
|
||||
if radii.iter().all(|r| *r <= 0.0) {
|
||||
rect.to_path(tolerance)
|
||||
} else {
|
||||
RoundedRect::from_rect(rect, RoundedRectRadii::new(radii[0], radii[1], radii[2], radii[3])).to_path(tolerance)
|
||||
}
|
||||
}
|
||||
Self::Ellipse { rect } => Ellipse::from_rect(rect.abs()).to_path(tolerance),
|
||||
Self::Polygon { rect, sides, star_ratio } => {
|
||||
let rect = rect.abs();
|
||||
let (c, rx, ry) = (rect.center(), rect.width() / 2.0, rect.height() / 2.0);
|
||||
let points: Vec<Point> =
|
||||
polygon_points(Point::ZERO, 1.0, 0.0, sides, star_ratio).iter().map(|p| Point::new(c.x + p.x * rx, c.y + p.y * ry)).collect();
|
||||
closed(&points)
|
||||
}
|
||||
Self::RadialPolygon { center, radius, rotation, sides, star_ratio } => {
|
||||
closed(&polygon_points(center, radius, rotation, sides, star_ratio))
|
||||
}
|
||||
Self::Line { from, to, weight } => {
|
||||
let v = to - from;
|
||||
let len = v.hypot();
|
||||
let n = if len > 0.0 { Vec2::new(-v.y, v.x) * (weight / 2.0 / len) } else { Vec2::ZERO };
|
||||
closed(&[from + n, to + n, to - n, from - n])
|
||||
}
|
||||
Self::Custom { rect, .. } => rect.abs().to_path(tolerance),
|
||||
}
|
||||
}
|
||||
|
||||
/// The axis-aligned box the shape occupies: the rect of the box kinds, the circle's box of a
|
||||
/// radial polygon, the box of a line's ends. Space-drag snapping uses it (PhotoCraft's
|
||||
/// `shape_bounds`).
|
||||
pub fn bounds(&self) -> Rect {
|
||||
// pc: crates/ui-egui/src/tools/vector_ui/shapes.rs:85-96 `shape_bounds` (a line's ends' box).
|
||||
match *self {
|
||||
Self::Rect { rect, .. } | Self::Ellipse { rect } | Self::Polygon { rect, .. } | Self::Custom { rect, .. } => rect.abs(),
|
||||
Self::RadialPolygon { center, radius, .. } => Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius),
|
||||
Self::Line { from, to, .. } => Rect::from_points(from, to),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The box a drag from `start` to `end` draws, in whole pixels, or `None` when a side is under
|
||||
/// [`MIN_SIDE`].
|
||||
///
|
||||
/// - `square` (⇧): both sides take the larger absolute extent, each keeping its direction.
|
||||
/// - `from_centre` (⌥): `start` is the centre; the box is twice the extent.
|
||||
/// - The top left and the size round to whole pixels, as PhotoCraft rounds `[x, y, w, h]`.
|
||||
pub fn box_drag(start: Point, end: Point, square: bool, from_centre: bool) -> Option<Rect> {
|
||||
// pc: crates/ui-egui/src/tools/vector_ui/shapes.rs:63-72 (⇧: `m = w.abs().max(h.abs())` with the
|
||||
// signs kept; ⌥: origin `start - (w, h)`, size doubled; `[x0.min(x0 + w).round(), …,
|
||||
// w.abs().round(), …]`; `rect[2] < 1.0 || rect[3] < 1.0` draws nothing).
|
||||
let (mut w, mut h) = (end.x - start.x, end.y - start.y);
|
||||
if square {
|
||||
let m = w.abs().max(h.abs());
|
||||
(w, h) = (m * sign(w), m * sign(h));
|
||||
}
|
||||
let (x0, y0) = if from_centre { (start.x - w, start.y - h) } else { (start.x, start.y) };
|
||||
let (w, h) = if from_centre { (w * 2.0, h * 2.0) } else { (w, h) };
|
||||
let (x, y, w, h) = (x0.min(x0 + w).round(), y0.min(y0 + h).round(), w.abs().round(), h.abs().round());
|
||||
(w >= MIN_SIDE && h >= MIN_SIDE).then(|| Rect::new(x, y, x + w, y + h))
|
||||
}
|
||||
|
||||
/// The end of a line dragged from `from` to `to`, or `None` when it is shorter than
|
||||
/// [`MIN_SIDE`].
|
||||
pub fn line_drag(from: Point, to: Point) -> Option<Point> {
|
||||
// pc: crates/ui-egui/src/tools/vector_ui/shapes.rs:52-61 (shorter than 1 draws nothing).
|
||||
((to - from).hypot() >= MIN_SIDE).then_some(to)
|
||||
}
|
||||
|
||||
/// A radial drag's frame: the press is the centre, the pointer sets the radius and the turn
|
||||
/// (VectorCraft's Polygon and Star tools).
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct RadialFrame {
|
||||
/// The press point, the frame's centre.
|
||||
pub center: Point,
|
||||
/// From the centre to the pointer, document units.
|
||||
pub radius: f64,
|
||||
/// The first point's turn from straight up, radians, clockwise on screen.
|
||||
pub rotation: f64,
|
||||
}
|
||||
|
||||
impl RadialFrame {
|
||||
/// The frame of a drag from `center` to `at`, or `None` when the radius is under
|
||||
/// [`MIN_SIDE`]. The first point follows the pointer; `upright` (⇧) keeps the base
|
||||
/// orientation (rotation 0, the first point straight up).
|
||||
pub fn drag(center: Point, at: Point, upright: bool) -> Option<RadialFrame> {
|
||||
// inv-vectorcraft: crates/tools/src/shape.rs:131-137 (polygon and star: the press is the
|
||||
// centre, `r = v.hypot()`, rotation `(v.atan2().to_degrees() + 90.0) % 360.0`; Shift keeps the
|
||||
// base orientation). VectorCraft's radius floor is 0.01; the library's is `MIN_SIDE`.
|
||||
let v = at - center;
|
||||
let radius = v.hypot();
|
||||
if radius < MIN_SIDE {
|
||||
return None;
|
||||
}
|
||||
let rotation = if upright { 0.0 } else { (v.atan2() + FRAC_PI_2).rem_euclid(TAU) };
|
||||
Some(RadialFrame { center, radius, rotation })
|
||||
}
|
||||
|
||||
/// The shape of this frame with `sides` points and `star_ratio`.
|
||||
pub fn geometry(self, sides: u32, star_ratio: f64) -> ShapeGeometry {
|
||||
ShapeGeometry::RadialPolygon { center: self.center, radius: self.radius, rotation: self.rotation, sides, star_ratio }
|
||||
}
|
||||
|
||||
/// The star ratio that keeps the inner radius `inner` (held when Ctrl/Cmd went down) while
|
||||
/// the outer radius follows the pointer to [`radius`](Self::radius); clamped to
|
||||
/// [`STAR_RATIO`].
|
||||
pub fn ratio_holding(self, inner: f64) -> f64 {
|
||||
// inv-vectorcraft: crates/tools/src/shape.rs:5-7 (Ctrl/Cmd keeps the inner radius while the
|
||||
// outer one follows), :32-33 (`inner` held while Ctrl/Cmd is down).
|
||||
if self.radius > 0.0 { (inner / self.radius).clamp(*STAR_RATIO.start(), *STAR_RATIO.end()) } else { *STAR_RATIO.end() }
|
||||
}
|
||||
|
||||
/// The star ratio whose shoulders are straight (⌥, five points or more): the line between
|
||||
/// two outer points two apart passes through the inner points between them. `None` under five
|
||||
/// points.
|
||||
pub fn straight_shoulders(sides: u32) -> Option<f64> {
|
||||
// inv-vectorcraft: crates/tools/src/shape.rs:42-48 `straight_ratio`: `(points >= 5).then(||
|
||||
// (2π / n).cos() / (π / n).cos())`.
|
||||
(sides >= 5).then(|| {
|
||||
let n = f64::from(sides);
|
||||
(TAU / n).cos() / (PI / n).cos()
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn sign(v: f64) -> f64 {
|
||||
if v < 0.0 { -1.0 } else { 1.0 }
|
||||
}
|
||||
|
||||
/// The corners of a polygon or star about `center`, the first outer point `rotation` clockwise
|
||||
/// from straight up (y down); a star puts an inner point between each pair of outer ones.
|
||||
fn polygon_points(center: Point, radius: f64, rotation: f64, sides: u32, star_ratio: f64) -> Vec<Point> {
|
||||
let n = sides.clamp(*SIDES.start(), *SIDES.end());
|
||||
let step = TAU / f64::from(n);
|
||||
let at = |angle: f64, r: f64| Point::new(center.x + r * (rotation + angle).sin(), center.y - r * (rotation + angle).cos());
|
||||
let star = star_ratio < 1.0;
|
||||
let inner = radius * star_ratio.max(*STAR_RATIO.start());
|
||||
let mut points = Vec::with_capacity(if star { 2 * n as usize } else { n as usize });
|
||||
for i in 0..n {
|
||||
let angle = step * f64::from(i);
|
||||
points.push(at(angle, radius));
|
||||
if star {
|
||||
points.push(at(angle + step / 2.0, inner));
|
||||
}
|
||||
}
|
||||
points
|
||||
}
|
||||
|
||||
fn closed(points: &[Point]) -> BezPath {
|
||||
let mut path = BezPath::new();
|
||||
for (i, p) in points.iter().enumerate() {
|
||||
if i == 0 {
|
||||
path.move_to(*p);
|
||||
} else {
|
||||
path.line_to(*p);
|
||||
}
|
||||
}
|
||||
path.close_path();
|
||||
path
|
||||
}
|
||||
@@ -0,0 +1,99 @@
|
||||
//! Slice rectangles and the rules that size them: [`fixed_ratio_pixels`] (a Fixed Ratio slice
|
||||
//! from a drag) and [`resized_rect`] (a handle drag). No egui. Normal and Fixed Size slices use the
|
||||
//! marquee's rules (`craft_behavior::geometry::{Constraint::corners, marquee_pixels, fixed_size_pixels}`).
|
||||
//!
|
||||
//! Slices are whole document pixels: every rectangle these return has integer edges.
|
||||
|
||||
use kurbo::{Point, Rect, Vec2};
|
||||
|
||||
/// The handles of a rectangle in hit order, corners first, then edge middles: each is the
|
||||
/// direction from the centre per axis (−1 the low edge, 0 the middle, 1 the high edge).
|
||||
/// PhotoCraft's slice handles and the artboard handles use this order.
|
||||
pub const HANDLES: [[i8; 2]; 8] = [[-1, -1], [1, -1], [-1, 1], [1, 1], [0, -1], [0, 1], [-1, 0], [1, 0]];
|
||||
|
||||
/// The Fixed Ratio slice drawn from `start` to `end` with the ratio `(w, h)`: the longer side of
|
||||
/// the ratio follows the drag to within a pixel and the shorter side takes the ratio from it,
|
||||
/// rounded to whole pixels (at least 1). A drag shorter than half a pixel along the longer side is
|
||||
/// a click: a slice of no size. The slice sits on the pixel the press is in: drawn right or down
|
||||
/// it starts at that pixel's top-left edge, drawn left or up at its far edge, so it holds that
|
||||
/// pixel either way.
|
||||
///
|
||||
/// `Constraint::Ratio` is not used: rounding each edge of a fractional drag apart turns 2 : 1
|
||||
/// into 5 × 3 (PhotoCraft test `fixed_ratio_slices_keep_their_ratio_from_a_fractional_drag`).
|
||||
pub fn fixed_ratio_pixels(start: Point, end: Point, ratio: (f64, f64)) -> Rect {
|
||||
// pc: crates/ui-egui/src/tools/slice_ui.rs:113-148 `new_rect` ("fixedRatio": `k = |end.x -
|
||||
// start.x| / w` after `marquee_end`, `follow(long, short)` with `l = (k * long).round()` and
|
||||
// `(l * short / long).round().max(1.0)`; the corner on the press's pixel at :143-147).
|
||||
let (w, h) = ratio;
|
||||
if w <= 0.0 || h <= 0.0 {
|
||||
return pixels(start, end);
|
||||
}
|
||||
let (dx, dy) = (end.x - start.x, end.y - start.y);
|
||||
let k = (dx.abs() / w).max(dy.abs() / h);
|
||||
// A drag shorter than half a pixel along the longer side is a click: no size.
|
||||
let follow = |long: f64, short: f64| {
|
||||
let l = (k * long).round();
|
||||
[l, if l > 0.0 { (l * short / long).round().max(1.0) } else { 0.0 }]
|
||||
};
|
||||
let size = if w >= h {
|
||||
follow(w, h)
|
||||
} else {
|
||||
let [l, s] = follow(h, w);
|
||||
[s, l]
|
||||
};
|
||||
let sign = |d: f64| if d < 0.0 { -1.0 } else { 1.0 };
|
||||
let dir = [sign(dx), sign(dy)];
|
||||
let s = [start.x, start.y];
|
||||
let corner = [0, 1].map(|i| if dir[i] < 0.0 { s[i].ceil() } else { s[i].floor() });
|
||||
pixels(Point::new(corner[0], corner[1]), Point::new(corner[0] + dir[0] * size[0], corner[1] + dir[1] * size[1]))
|
||||
}
|
||||
|
||||
/// `rect` with the edges `handle` grabs (one of [`HANDLES`]) moved by `by`, rounded to whole
|
||||
/// pixels; an edge dragged past the opposite one turns the rectangle the right way round, which
|
||||
/// stays at least 1 × 1.
|
||||
pub fn resized_rect(rect: Rect, handle: [i8; 2], by: Vec2) -> Rect {
|
||||
// pc: crates/ui-egui/src/tools/slice_ui.rs:78-93 `resized` (`x0 + dx` for handle −1, `x1 + dx`
|
||||
// for 1; `(x0.min(x1), x0.max(x1).max(x0.min(x1) + 1))` per axis).
|
||||
let (dx, dy) = (by.x.round(), by.y.round());
|
||||
let (mut x0, mut y0, mut x1, mut y1) = (rect.x0, rect.y0, rect.x1, rect.y1);
|
||||
match handle[0] {
|
||||
-1 => x0 += dx,
|
||||
1 => x1 += dx,
|
||||
_ => {}
|
||||
}
|
||||
match handle[1] {
|
||||
-1 => y0 += dy,
|
||||
1 => y1 += dy,
|
||||
_ => {}
|
||||
}
|
||||
let (x0, x1) = (x0.min(x1), x0.max(x1).max(x0.min(x1) + 1.0));
|
||||
let (y0, y1) = (y0.min(y1), y0.max(y1).max(y0.min(y1) + 1.0));
|
||||
Rect::new(x0, y0, x1, y1)
|
||||
}
|
||||
|
||||
/// The handle of `rect` within `reach` document units of `point`, in [`HANDLES`] order (corners
|
||||
/// win over edge middles), or `None`.
|
||||
pub fn handle_at(rect: Rect, point: Point, reach: f64) -> Option<[i8; 2]> {
|
||||
// pc: crates/ui-egui/src/tools/slice_ui.rs:58-74 `handle_at` (a square reach per axis around each
|
||||
// handle; corners first).
|
||||
let (x0, y0, x1, y1) = (rect.x0, rect.y0, rect.x1, rect.y1);
|
||||
HANDLES.into_iter().find(|h| {
|
||||
let x = match h[0] {
|
||||
-1 => x0,
|
||||
1 => x1,
|
||||
_ => (x0 + x1) / 2.0,
|
||||
};
|
||||
let y = match h[1] {
|
||||
-1 => y0,
|
||||
1 => y1,
|
||||
_ => (y0 + y1) / 2.0,
|
||||
};
|
||||
(point.x - x).abs() <= reach && (point.y - y).abs() <= reach
|
||||
})
|
||||
}
|
||||
|
||||
/// The whole pixels a drag between two corners covers, edges snapped outwards (the marquee's
|
||||
/// rule; craft-ui's `marquee_pixels` is not reachable without the `ui` feature).
|
||||
fn pixels(a: Point, b: Point) -> Rect {
|
||||
Rect::new(a.x.min(b.x).floor(), a.y.min(b.y).floor(), a.x.max(b.x).ceil(), a.y.max(b.y).ceil())
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
//! Vector and shape tools: gradient editing, the Pen and path editing, strokes and corners, shapes, slices, artboards and connectors, Crop and Perspective Crop, Free Transform, measure, symmetry and brush presets.
|
||||
|
||||
pub mod geometry;
|
||||
pub mod stroke;
|
||||
#[cfg(feature = "ui")]
|
||||
pub mod ui;
|
||||
|
||||
#[cfg(feature = "screen-testing")]
|
||||
pub mod testing {
|
||||
//! The registrations of this crate's stories, for the `tests/it` harness.
|
||||
craft_ui::testing_registered!();
|
||||
}
|
||||
|
||||
#[cfg(all(test, feature = "screen-testing"))]
|
||||
extern crate self as craft_draw;
|
||||
#[cfg(all(test, feature = "screen-testing"))]
|
||||
#[path = "../tests/it/main.rs"]
|
||||
mod integration;
|
||||
|
||||
#[cfg(test)]
|
||||
fn main() {
|
||||
craft_ui::testing::run(module_path!(), env!("CARGO_PKG_NAME"), &craft_ui::testing::registered_in(env!("CARGO_PKG_NAME")));
|
||||
}
|
||||
@@ -0,0 +1,315 @@
|
||||
//! The stroke style of a path: width, caps, joins, alignment and dashes, without egui.
|
||||
//!
|
||||
//! [`StrokeStyle`] is the value an app's engine and the stroke editor (`craft_draw::ui::stroke`)
|
||||
//! share: PhotoCraft's `ShapeStroke` without its paint, with PhotoCraft's limits
|
||||
//! ([`StrokeStyle::validate`]) and presets ([`StrokeStyle::with_line_style`]). Colour and paint
|
||||
//! stay with the app (S7-shapes' paints list).
|
||||
|
||||
use std::fmt;
|
||||
use std::ops::RangeInclusive;
|
||||
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
/// Where the stroke sits on the path. Only a closed path aligns; an open one is always centred.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum StrokeAlign {
|
||||
/// The stroke lies inside the path.
|
||||
Inside,
|
||||
/// The stroke is centred on the path.
|
||||
#[default]
|
||||
Center,
|
||||
/// The stroke lies outside the path.
|
||||
Outside,
|
||||
}
|
||||
|
||||
/// The shape at the ends of an open path and of each dash.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum LineCap {
|
||||
/// Butt / Flat: the stroke ends at the end point.
|
||||
#[default]
|
||||
Butt,
|
||||
/// A semicircle past the end point.
|
||||
Round,
|
||||
/// The stroke goes on half its width past the end point.
|
||||
Square,
|
||||
}
|
||||
|
||||
/// The shape of the stroke where two segments meet at a corner.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum LineJoin {
|
||||
/// A sharp point, cut off past [`StrokeStyle::miter_limit`].
|
||||
#[default]
|
||||
Miter,
|
||||
/// A circular arc around the corner point.
|
||||
Round,
|
||||
/// The corner is cut off flat.
|
||||
Bevel,
|
||||
}
|
||||
|
||||
/// The name of a dash pattern, as the stroke editor's presets and its opener show it.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum LineStyle {
|
||||
/// No dashes.
|
||||
Solid,
|
||||
/// Dashes [`StrokeStyle::DASHED`].
|
||||
Dashed,
|
||||
/// Dashes [`StrokeStyle::DOTTED`] with round caps.
|
||||
Dotted,
|
||||
/// Any other pattern.
|
||||
Custom,
|
||||
}
|
||||
|
||||
/// The unit of the dash lengths and the dash offset. It changes what the numbers mean, never the
|
||||
/// stored numbers: the stroke editor shows it as the fields' suffix.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
|
||||
#[serde(rename_all = "camelCase")]
|
||||
pub enum DashUnit {
|
||||
/// Multiples of the stroke width (PhotoCraft, Photoshop).
|
||||
#[default]
|
||||
Widths,
|
||||
/// Document units (VectorCraft).
|
||||
Document,
|
||||
}
|
||||
|
||||
/// Why [`StrokeStyle::validate`] refuses a style. The `Display` text is PhotoCraft's engine
|
||||
/// message, for logs and the app's own errors; the stroke editor shows its own words.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub enum StrokeError {
|
||||
/// The width is not finite or outside [`StrokeStyle::WIDTH_RANGE`].
|
||||
Width,
|
||||
/// The opacity is not finite or outside 0..=1.
|
||||
Opacity,
|
||||
/// The miter limit is not finite or outside [`StrokeStyle::MITER_LIMIT_RANGE`].
|
||||
MiterLimit,
|
||||
/// The dash offset is not finite or its size is over [`StrokeStyle::DASH_OFFSET_MAX`].
|
||||
DashOffset,
|
||||
/// More than [`StrokeStyle::MAX_DASHES`] lengths, or a length not finite or outside
|
||||
/// [`StrokeStyle::DASH_RANGE`].
|
||||
DashPattern,
|
||||
/// A pattern whose lengths add up to less than [`StrokeStyle::DASH_TOTAL_MIN`].
|
||||
DashTotal,
|
||||
}
|
||||
|
||||
impl fmt::Display for StrokeError {
|
||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||
// pc: crates/doc/src/vector.rs:270-290 `ShapeStroke::validate`, the messages verbatim.
|
||||
f.write_str(match self {
|
||||
StrokeError::Width => "stroke width must be finite and between 0 and 1000000 px",
|
||||
StrokeError::Opacity => "stroke opacity must be between 0 and 100%",
|
||||
StrokeError::MiterLimit => "miter limit must be between 1 and 500",
|
||||
StrokeError::DashOffset => "dash offset must be finite and within ±1000000 widths",
|
||||
StrokeError::DashPattern => "dash pattern must contain at most 32 finite lengths between 0 and 10000 widths",
|
||||
StrokeError::DashTotal => "dash pattern total must be at least 0.01 widths",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
impl std::error::Error for StrokeError {}
|
||||
|
||||
/// How a path is stroked, except its paint: width, alignment, caps, corners, dashes and opacity.
|
||||
/// The default is PhotoCraft's `ShapeStroke::default()` without the paint: width 3, centred, butt
|
||||
/// caps, miter corners with limit 100, solid, opacity 1, dashes in widths.
|
||||
///
|
||||
/// Serialised in camelCase with every field optional (missing fields take the default), so an
|
||||
/// app keeps it in its settings and documents.
|
||||
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
|
||||
#[serde(default, rename_all = "camelCase")]
|
||||
pub struct StrokeStyle {
|
||||
/// The width in document units.
|
||||
pub width: f32,
|
||||
/// Where the stroke lies relative to the path.
|
||||
pub align: StrokeAlign,
|
||||
/// The shape of open ends.
|
||||
pub cap: LineCap,
|
||||
/// The shape of corners.
|
||||
pub join: LineJoin,
|
||||
/// The miter limit as a multiple of the width (Photoshop's 100 mitres nearly every corner).
|
||||
pub miter_limit: f32,
|
||||
/// Dash and gap lengths, alternating, in [`dash_unit`](Self::dash_unit); empty is solid.
|
||||
pub dashes: Vec<f32>,
|
||||
/// Where the pattern starts along the path, in [`dash_unit`](Self::dash_unit).
|
||||
pub dash_offset: f32,
|
||||
/// What a dash or gap length counts in.
|
||||
pub dash_unit: DashUnit,
|
||||
/// 0..=1.
|
||||
pub opacity: f32,
|
||||
}
|
||||
|
||||
impl Default for StrokeStyle {
|
||||
fn default() -> Self {
|
||||
// pc: crates/doc/src/vector.rs:251-264 `ShapeStroke::default`.
|
||||
Self {
|
||||
width: 3.0,
|
||||
align: StrokeAlign::Center,
|
||||
cap: LineCap::Butt,
|
||||
join: LineJoin::Miter,
|
||||
miter_limit: 100.0,
|
||||
dashes: Vec::new(),
|
||||
dash_offset: 0.0,
|
||||
dash_unit: DashUnit::Widths,
|
||||
opacity: 1.0,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl StrokeStyle {
|
||||
/// The widths [`validate`](Self::validate) accepts.
|
||||
pub const WIDTH_RANGE: RangeInclusive<f32> = 0.0..=1_000_000.0;
|
||||
/// The miter limits [`validate`](Self::validate) accepts.
|
||||
pub const MITER_LIMIT_RANGE: RangeInclusive<f32> = 1.0..=500.0;
|
||||
/// The dash and gap lengths [`validate`](Self::validate) accepts.
|
||||
pub const DASH_RANGE: RangeInclusive<f32> = 0.0..=10_000.0;
|
||||
/// The largest dash offset, either way.
|
||||
pub const DASH_OFFSET_MAX: f32 = 1_000_000.0;
|
||||
/// The most dash and gap lengths a pattern holds (16 pairs).
|
||||
pub const MAX_DASHES: usize = 32;
|
||||
/// The smallest total of a dashed pattern.
|
||||
pub const DASH_TOTAL_MIN: f32 = 0.01;
|
||||
/// The Dashed preset's pattern.
|
||||
pub const DASHED: [f32; 2] = [4.0, 2.0];
|
||||
/// The Dotted preset's pattern (with round caps).
|
||||
pub const DOTTED: [f32; 2] = [0.0, 2.0];
|
||||
|
||||
/// Whether an engine accepts the style. PhotoCraft's rules, checked in this order, the first
|
||||
/// failure being the error: width finite and in [`WIDTH_RANGE`](Self::WIDTH_RANGE); opacity
|
||||
/// finite and in 0..=1; miter limit finite and in
|
||||
/// [`MITER_LIMIT_RANGE`](Self::MITER_LIMIT_RANGE); dash offset finite with `abs() <=`
|
||||
/// [`DASH_OFFSET_MAX`](Self::DASH_OFFSET_MAX); at most [`MAX_DASHES`](Self::MAX_DASHES)
|
||||
/// lengths, each finite and in [`DASH_RANGE`](Self::DASH_RANGE); a non-empty pattern whose sum
|
||||
/// is at least [`DASH_TOTAL_MIN`](Self::DASH_TOTAL_MIN). The limits are the same in either
|
||||
/// [`DashUnit`].
|
||||
pub fn validate(&self) -> Result<(), StrokeError> {
|
||||
// pc: crates/doc/src/vector.rs:270-290 `ShapeStroke::validate`.
|
||||
if !self.width.is_finite() || !Self::WIDTH_RANGE.contains(&self.width) {
|
||||
return Err(StrokeError::Width);
|
||||
}
|
||||
if !self.opacity.is_finite() || !(0.0..=1.0).contains(&self.opacity) {
|
||||
return Err(StrokeError::Opacity);
|
||||
}
|
||||
if !self.miter_limit.is_finite() || !Self::MITER_LIMIT_RANGE.contains(&self.miter_limit) {
|
||||
return Err(StrokeError::MiterLimit);
|
||||
}
|
||||
if !self.dash_offset.is_finite() || self.dash_offset.abs() > Self::DASH_OFFSET_MAX {
|
||||
return Err(StrokeError::DashOffset);
|
||||
}
|
||||
if self.dashes.len() > Self::MAX_DASHES || self.dashes.iter().any(|d| !d.is_finite() || !Self::DASH_RANGE.contains(d)) {
|
||||
return Err(StrokeError::DashPattern);
|
||||
}
|
||||
if !self.dashes.is_empty() && self.dashes.iter().sum::<f32>() < Self::DASH_TOTAL_MIN {
|
||||
return Err(StrokeError::DashTotal);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// The pattern's name: empty dashes are [`LineStyle::Solid`]; exactly
|
||||
/// [`DASHED`](Self::DASHED) is [`LineStyle::Dashed`]; exactly [`DOTTED`](Self::DOTTED) with
|
||||
/// [`LineCap::Round`] is [`LineStyle::Dotted`]; anything else is [`LineStyle::Custom`]
|
||||
/// (`[0, 2]` with another cap too). The dash offset plays no part.
|
||||
pub fn line_style(&self) -> LineStyle {
|
||||
// pc: crates/ui-egui/src/tools/shape_stroke_ui.rs:53-63 `StrokeOptions::label`.
|
||||
if self.dashes.is_empty() {
|
||||
LineStyle::Solid
|
||||
} else if self.dashes == Self::DASHED {
|
||||
LineStyle::Dashed
|
||||
} else if self.dashes == Self::DOTTED && self.cap == LineCap::Round {
|
||||
LineStyle::Dotted
|
||||
} else {
|
||||
LineStyle::Custom
|
||||
}
|
||||
}
|
||||
|
||||
/// This style with the preset `style`: the dash offset goes to 0 and the dashes become empty
|
||||
/// (Solid), [`DASHED`](Self::DASHED), or [`DOTTED`](Self::DOTTED) with the cap set to
|
||||
/// [`LineCap::Round`]. Every other field is kept. [`LineStyle::Custom`] returns the style
|
||||
/// unchanged.
|
||||
#[must_use]
|
||||
pub fn with_line_style(&self, style: LineStyle) -> StrokeStyle {
|
||||
// pc: crates/ui-egui/src/tools/shape_stroke_ui.rs:65-75 `StrokeOptions::preset`.
|
||||
let mut out = self.clone();
|
||||
match style {
|
||||
LineStyle::Custom => return out,
|
||||
LineStyle::Solid => out.dashes = Vec::new(),
|
||||
LineStyle::Dashed => out.dashes = Self::DASHED.to_vec(),
|
||||
LineStyle::Dotted => {
|
||||
out.dashes = Self::DOTTED.to_vec();
|
||||
out.cap = LineCap::Round;
|
||||
}
|
||||
}
|
||||
out.dash_offset = 0.0;
|
||||
out
|
||||
}
|
||||
|
||||
/// The dashes as (dash, gap) pairs in order. An odd-length pattern's last pair has no gap
|
||||
/// (`None`), as PhotoCraft's editor shows it (one Dash field in the last row).
|
||||
pub fn dash_pairs(&self) -> Vec<(f32, Option<f32>)> {
|
||||
// pc: crates/ui-egui/src/tools/shape_stroke_ui/editor.rs:201-211 (`dashes.chunks_mut(2)`).
|
||||
self.dashes.chunks(2).map(|c| (c[0], c.get(1).copied())).collect()
|
||||
}
|
||||
|
||||
/// This style with its first `pairs.len()` pairs replaced by `pairs` and every later entry of
|
||||
/// the pattern kept, so a host that shows three pairs (VectorCraft, Photoshop) never loses
|
||||
/// pairs four and on. A `None` gap drops the gap when it replaces the pattern's last pair and
|
||||
/// keeps the stored gap anywhere else. Pairs past the stored ones are appended. The result is
|
||||
/// not validated.
|
||||
#[must_use]
|
||||
pub fn with_dash_pairs(&self, pairs: &[(f32, Option<f32>)]) -> StrokeStyle {
|
||||
// new: entries a field row does not show stay unchanged (step7-pen "Stroke editor", Dashes).
|
||||
let mut out = self.clone();
|
||||
for (i, &(dash, gap)) in pairs.iter().enumerate() {
|
||||
let at = i * 2;
|
||||
if at >= out.dashes.len() {
|
||||
out.dashes.push(dash);
|
||||
out.dashes.extend(gap);
|
||||
continue;
|
||||
}
|
||||
out.dashes[at] = dash;
|
||||
let is_last = at + 1 >= out.dashes.len();
|
||||
match (gap, is_last) {
|
||||
(Some(g), false) => out.dashes[at + 1] = g,
|
||||
(Some(g), true) => out.dashes.push(g),
|
||||
(None, true) => {}
|
||||
(None, false) => {
|
||||
// The stored gap stays unless this pair is the pattern's last.
|
||||
if at + 2 >= out.dashes.len() {
|
||||
out.dashes.truncate(at + 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
|
||||
/// The style as a kurbo stroke, for an engine and the editor's line samples: width, join,
|
||||
/// miter limit and the cap at both ends as they are; dash lengths and offset multiplied by the
|
||||
/// width under [`DashUnit::Widths`], taken as they are under [`DashUnit::Document`]. Alignment
|
||||
/// and opacity are not part of a kurbo stroke: an engine strokes an aligned closed path twice
|
||||
/// as wide and clips to its inside ([`StrokeAlign::Inside`]) or outside
|
||||
/// ([`StrokeAlign::Outside`]), and applies the opacity itself.
|
||||
pub fn to_kurbo(&self) -> kurbo::Stroke {
|
||||
// new: kurbo `Stroke::new(width).with_join(..).with_miter_limit(..).with_caps(..)
|
||||
// .with_dashes(offset, pattern)`. PhotoCraft strokes with its own engine
|
||||
// (crates/ui-egui/src/tools/shape_stroke_ui/editor.rs:329-343 renders through it).
|
||||
let scale = match self.dash_unit {
|
||||
DashUnit::Widths => f64::from(self.width),
|
||||
DashUnit::Document => 1.0,
|
||||
};
|
||||
let cap = match self.cap {
|
||||
LineCap::Butt => kurbo::Cap::Butt,
|
||||
LineCap::Round => kurbo::Cap::Round,
|
||||
LineCap::Square => kurbo::Cap::Square,
|
||||
};
|
||||
let join = match self.join {
|
||||
LineJoin::Miter => kurbo::Join::Miter,
|
||||
LineJoin::Round => kurbo::Join::Round,
|
||||
LineJoin::Bevel => kurbo::Join::Bevel,
|
||||
};
|
||||
kurbo::Stroke::new(f64::from(self.width))
|
||||
.with_join(join)
|
||||
.with_miter_limit(f64::from(self.miter_limit))
|
||||
.with_caps(cap)
|
||||
.with_dashes(f64::from(self.dash_offset) * scale, self.dashes.iter().map(|&d| f64::from(d) * scale))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
//! [`AddBesideHandles`]: the "+" buttons beside the four sides of a selected object, which add an artboard
|
||||
//! (Photoshop) or a connected object (FigJam) there. One canvas control for the Artboard tool and the connector
|
||||
//! tools: its buttons are parts in the canvas's arena, so a press on one reaches the control before the tool.
|
||||
|
||||
#[cfg(feature = "screen-testing")]
|
||||
pub(crate) mod stories;
|
||||
mod words;
|
||||
|
||||
use craft_behavior::kurbo::Rect as DocRect;
|
||||
use craft_behavior::{CanvasView, CursorIcon, HitLevel, HitPriority, HitShape, Metrics, NavShape, PartKey, PointerButton, PressPhase, Roving, Sense};
|
||||
use craft_ui::canvas::canvas_space;
|
||||
use craft_ui::contract::{
|
||||
Access, Common, Component, Cx, Focus as _, MeasureCx, Name, Outcome, PaintUi, PartsCx, Pointer as _, Props as _, Role, WordSetCx as _,
|
||||
};
|
||||
use craft_ui::primitives::{FocusKind, FocusRing, PaintShape, StrokeWidth};
|
||||
use craft_ui::runtime::commands::FireSource;
|
||||
use craft_ui::runtime::env::Label;
|
||||
use craft_ui::runtime::focus::{ActivateKeys, KeyUse};
|
||||
use craft_ui::style::{ComponentStyle, FocusLook, StyleColor, StyleCx};
|
||||
use egui::{Pos2, Rect, Response, Vec2};
|
||||
|
||||
pub use words::AddBesideWords;
|
||||
|
||||
/// The button on one side: `BUTTON.at(i)` with `i` the side's place in [`AddSide::ALL`].
|
||||
const BUTTON: PartKey = PartKey::new("button");
|
||||
|
||||
/// The least cosine between an arrow's direction and the way to a button for the arrow to reach it.
|
||||
const ARROW_ALIGNMENT: f32 = 0.5;
|
||||
|
||||
/// The plus's arm as a share of the button's radius.
|
||||
const PLUS_ARM_SHARE: f32 = 0.5;
|
||||
|
||||
/// A side of the object, in document space (never mirrored right to left).
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
#[non_exhaustive]
|
||||
pub enum AddSide {
|
||||
/// The top side.
|
||||
Top,
|
||||
/// The right side.
|
||||
Right,
|
||||
/// The bottom side.
|
||||
Bottom,
|
||||
/// The left side.
|
||||
Left,
|
||||
}
|
||||
|
||||
impl AddSide {
|
||||
/// Clockwise from the top: the buttons' keyboard order.
|
||||
pub const ALL: [AddSide; 4] = [AddSide::Top, AddSide::Right, AddSide::Bottom, AddSide::Left];
|
||||
|
||||
fn index(self) -> u64 {
|
||||
match self {
|
||||
AddSide::Top => 0,
|
||||
AddSide::Right => 1,
|
||||
AddSide::Bottom => 2,
|
||||
AddSide::Left => 3,
|
||||
}
|
||||
}
|
||||
|
||||
fn at(index: u64) -> Option<AddSide> {
|
||||
AddSide::ALL.get(usize::try_from(index).ok()?).copied()
|
||||
}
|
||||
}
|
||||
|
||||
/// The style of the "+" buttons: where they sit, and the disc and plus in rest and hot looks.
|
||||
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
|
||||
#[non_exhaustive]
|
||||
pub struct AddBesideStyle {
|
||||
#[style(metrics)]
|
||||
metrics: Metrics,
|
||||
#[style(focus)]
|
||||
focus: FocusLook,
|
||||
/// From the object's edge to a button's centre, screen points.
|
||||
offset: f32,
|
||||
/// A button's radius.
|
||||
radius: f32,
|
||||
/// The plus and the ring.
|
||||
accent: StyleColor,
|
||||
/// The disc.
|
||||
fill: StyleColor,
|
||||
/// A hovered or focused disc.
|
||||
hot_fill: StyleColor,
|
||||
/// The plus on a hovered or focused disc.
|
||||
hot_plus: StyleColor,
|
||||
}
|
||||
|
||||
/// The screen centres of the four buttons around `object` (document units) in [`AddSide::ALL`] order: each on the
|
||||
/// middle of its side, `offset` screen points outside the edge, through `view`, so a turned view turns the buttons
|
||||
/// with the object. A button of a degenerate object lies on the object's middle. Hiding is [`AddBesideHandles`]'.
|
||||
pub fn add_beside_places(view: &CanvasView, object: DocRect, offset: f32) -> [(AddSide, Pos2); 4] {
|
||||
let [top_left, top_right, bottom_right, bottom_left] = view.quad(object.abs());
|
||||
let centre = top_left.lerp(bottom_right, 0.5);
|
||||
let middles =
|
||||
[top_left.lerp(top_right, 0.5), top_right.lerp(bottom_right, 0.5), bottom_right.lerp(bottom_left, 0.5), bottom_left.lerp(top_left, 0.5)];
|
||||
let mut places = AddSide::ALL.map(|side| (side, centre));
|
||||
for (place, middle) in places.iter_mut().zip(middles) {
|
||||
let out = (middle - centre).normalized();
|
||||
place.1 = if out.is_finite() { middle + out * offset } else { middle };
|
||||
}
|
||||
places
|
||||
}
|
||||
|
||||
/// What [`AddBesideHandles`] reports.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
pub struct AddBesideOutput {
|
||||
/// The group's response.
|
||||
pub response: Response,
|
||||
/// A button was clicked, or Enter or Space pressed on a focused button.
|
||||
pub added: Option<AddSide>,
|
||||
/// Alt was held with the click: add with contents (an artboard's copy). A key press never asks for a copy.
|
||||
pub copy: bool,
|
||||
/// The button under the pointer or focused (the tool draws its ghost).
|
||||
pub hovered: Option<AddSide>,
|
||||
}
|
||||
|
||||
impl Outcome for AddBesideOutput {
|
||||
type Value = craft_ui::contract::NoValue;
|
||||
|
||||
fn response(&self) -> &Response {
|
||||
&self.response
|
||||
}
|
||||
|
||||
#[cfg(feature = "screen-testing")]
|
||||
fn story_facts(&self) -> craft_ui::testing::StoryOutput {
|
||||
let mut facts = craft_ui::testing::StoryOutput::default();
|
||||
facts.id = Some(self.response.id);
|
||||
facts.clicked = self.added.is_some();
|
||||
facts
|
||||
}
|
||||
}
|
||||
|
||||
/// The "+" buttons beside the four sides of `object` (document units).
|
||||
///
|
||||
/// - Place: each centred on its side, [`AddBesideStyle`]'s offset outside the edge, through the view (a turned view
|
||||
/// turns the sides with the object); see [`add_beside_places`].
|
||||
/// - Hidden: all of them when the object on screen is smaller than two radii on a side, or [`hidden`](Self::hidden)
|
||||
/// is set (a drag runs); one when its disc touches a [`clear_of`](Self::clear_of) rectangle (a size label, a
|
||||
/// toolbar) or leaves the canvas.
|
||||
/// - Pointer: the pointing hand; a click reports [`AddBesideOutput::added`], with Alt held also `copy`; the hot look
|
||||
/// (the accent disc) on hover and focus.
|
||||
/// - Keyboard: the group is one Tab stop named by the label (the "Add a connected shape" word after
|
||||
/// [`connecting`](Self::connecting)); the arrows move the focus to the button that lies in their screen
|
||||
/// direction, Enter or Space adds; each button is a `Button` node ("Add above", ...).
|
||||
#[must_use = "show the buttons with `show_at`"]
|
||||
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
|
||||
#[component(canvas_control, content_painter)]
|
||||
pub struct AddBesideHandles<'a> {
|
||||
#[common]
|
||||
common: Common,
|
||||
object: DocRect,
|
||||
/// Screen rectangles no button may cover.
|
||||
#[prop]
|
||||
clear_of: &'a [Rect],
|
||||
/// Hides every button (while a drag runs).
|
||||
#[prop(flag)]
|
||||
hidden: bool,
|
||||
/// Names the group for adding a connected shape, as the connector tools do.
|
||||
#[prop(flag)]
|
||||
connecting: bool,
|
||||
report: Report,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Report {
|
||||
added: Option<AddSide>,
|
||||
copy: bool,
|
||||
hovered: Option<AddSide>,
|
||||
}
|
||||
|
||||
impl<'a> AddBesideHandles<'a> {
|
||||
/// The buttons around `object`, in document units, the group named `label`.
|
||||
pub fn new(label: impl Into<Label>, object: DocRect) -> Self {
|
||||
AddBesideHandles { common: Common::new(), object, clear_of: &[], hidden: false, connecting: false, report: Report::default() }.label(label)
|
||||
}
|
||||
|
||||
/// The visible buttons' screen centres.
|
||||
fn visible(&self, view: &CanvasView, style: &AddBesideStyle, canvas: Rect) -> Vec<(AddSide, Pos2)> {
|
||||
let [top_left, top_right, _, bottom_left] = view.quad(self.object.abs());
|
||||
let finite = [top_left, top_right, bottom_left].iter().all(|p| p.x.is_finite() && p.y.is_finite());
|
||||
// Side lengths, not the bounds: a turned view keeps the test the same.
|
||||
let small = (top_right - top_left).length() < 2.0 * style.radius || (bottom_left - top_left).length() < 2.0 * style.radius;
|
||||
if self.hidden || small || !finite {
|
||||
return Vec::new();
|
||||
}
|
||||
let inside = canvas.shrink(style.radius);
|
||||
add_beside_places(view, self.object, style.offset)
|
||||
.into_iter()
|
||||
.filter(|&(_, at)| inside.contains(at) && !self.clear_of.iter().any(|rect| rect.expand(style.radius).contains(at)))
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl Component for AddBesideHandles<'_> {
|
||||
const ROLE: Role = Role::GROUP;
|
||||
const KEYS: KeyUse = KeyUse::CANVAS.with_activate(ActivateKeys::Both).with_moves().with_chrome_key(false);
|
||||
const OVERLAYS: bool = false;
|
||||
type Style = AddBesideStyle;
|
||||
type Output = AddBesideOutput;
|
||||
|
||||
fn style(cx: &StyleCx<'_>, _: AddBesideHandlesStyleKey) -> AddBesideStyle {
|
||||
let tokens = cx.tokens;
|
||||
AddBesideStyle {
|
||||
metrics: Metrics::new(),
|
||||
focus: cx.focus_look(),
|
||||
offset: tokens.space.gap.section,
|
||||
radius: tokens.shape.radius.surface,
|
||||
accent: cx.color(tokens.color.accent.solid),
|
||||
fill: cx.color(tokens.color.surface.raised),
|
||||
hot_fill: cx.color(tokens.color.accent.solid),
|
||||
hot_plus: cx.color(tokens.color.text.on_strong),
|
||||
}
|
||||
}
|
||||
|
||||
fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
Vec2::ZERO
|
||||
}
|
||||
|
||||
/// The visible buttons: click parts at handle priority in one roving group, in screen directions.
|
||||
fn parts(&mut self, rect: Rect, cx: &mut PartsCx<'_, Self>) {
|
||||
let Some(space) = canvas_space(&cx.env) else { return };
|
||||
let (view, radius) = (space.view, cx.style.radius);
|
||||
let buttons = self.visible(&view, cx.style, rect);
|
||||
for &(side, at) in &buttons {
|
||||
cx.part(BUTTON.at(side.index()), HitShape::circle(at, radius))
|
||||
.sense(Sense::CLICK | Sense::TAKE_FOCUS)
|
||||
.priority(HitPriority::new(HitLevel::Handle, 0))
|
||||
.cursor(CursorIcon::PointingHand)
|
||||
.focusable()
|
||||
.nudges();
|
||||
}
|
||||
if !buttons.is_empty() {
|
||||
cx.roving(Roving::new(NavShape::Spatial));
|
||||
}
|
||||
}
|
||||
|
||||
fn update(&mut self, cx: &mut Cx<'_, Self>) {
|
||||
let focused = cx.active_part().filter(|part| part.key == BUTTON).and_then(|part| part.index).and_then(AddSide::at);
|
||||
for side in AddSide::ALL {
|
||||
let Some(result) = cx.part_if_declared(BUTTON.at(side.index())) else { continue };
|
||||
if result.hovered {
|
||||
self.report.hovered = Some(side);
|
||||
}
|
||||
if let PressPhase::Release { start, click: true, .. } = result.press.phase
|
||||
&& start.button == PointerButton::Primary
|
||||
{
|
||||
self.report.added = Some(side);
|
||||
self.report.copy = result.press.mods.alt;
|
||||
} else if self.report.added.is_none() && matches!(cx.part_activated(BUTTON.at(side.index())), Some(FireSource::Key | FireSource::Access))
|
||||
{
|
||||
self.report.added = Some(side);
|
||||
}
|
||||
}
|
||||
if self.report.hovered.is_none() {
|
||||
self.report.hovered = focused;
|
||||
}
|
||||
// The arrows move the focus to the button that lies in their screen direction.
|
||||
if let Some(current) = focused
|
||||
&& let Some(space) = canvas_space(&cx.env)
|
||||
&& let Some((direction, _)) = cx.intents().take_nudge()
|
||||
{
|
||||
let places = self.visible(&space.view, cx.style, cx.rect);
|
||||
let ahead = direction.normalized();
|
||||
let from = places.iter().find(|(side, _)| *side == current).map(|&(_, at)| at);
|
||||
let next = from.and_then(|from| {
|
||||
places
|
||||
.iter()
|
||||
.filter(|(side, _)| *side != current)
|
||||
.map(|&(side, at)| (side, (at - from).normalized().dot(ahead)))
|
||||
.filter(|&(_, alignment)| alignment > ARROW_ALIGNMENT)
|
||||
.max_by(|a, b| a.1.total_cmp(&b.1))
|
||||
});
|
||||
if let Some((side, _)) = next {
|
||||
cx.focus_part(BUTTON.at(side.index()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
|
||||
let Some(space) = canvas_space(&cx.env) else { return };
|
||||
let style = &cx.style;
|
||||
let focused = cx.active_part().filter(|part| part.key == BUTTON).and_then(|part| part.index).and_then(AddSide::at);
|
||||
let ring = cx.focus_visible();
|
||||
let buttons = self.visible(&space.view, style, cx.rect);
|
||||
let draw = ui.draw();
|
||||
for &(side, at) in &buttons {
|
||||
let hot = self.report.hovered == Some(side) || focused == Some(side);
|
||||
let (fill, plus) = if hot { (style.hot_fill, style.hot_plus) } else { (style.fill, style.accent) };
|
||||
let disc = PaintShape::Circle(at, style.radius);
|
||||
draw.fill(&disc, fill);
|
||||
draw.stroke(&disc, StrokeWidth::Thin, style.accent);
|
||||
let arm = style.radius * PLUS_ARM_SHARE;
|
||||
draw.stroke(&PaintShape::Path(vec![at - Vec2::new(arm, 0.0), at + Vec2::new(arm, 0.0)]), StrokeWidth::Medium, plus);
|
||||
draw.stroke(&PaintShape::Path(vec![at - Vec2::new(0.0, arm), at + Vec2::new(0.0, arm)]), StrokeWidth::Medium, plus);
|
||||
}
|
||||
let Some(&(_, at)) = buttons.iter().find(|(side, _)| ring && focused == Some(*side)) else { return };
|
||||
let painter = ui.content_painter(cx);
|
||||
let ppp = painter.pixels_per_point();
|
||||
painter.painter.extend(FocusRing::shapes(&style.focus, FocusKind::Halo, &PaintShape::Circle(at, style.radius), ppp));
|
||||
}
|
||||
|
||||
fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) {
|
||||
let Some(space) = canvas_space(&cx.env) else { return };
|
||||
let words = cx.words::<AddBesideWords>();
|
||||
if self.connecting {
|
||||
access.name(Name::Text(words.add_connected.as_str().to_owned()));
|
||||
}
|
||||
for (side, _) in self.visible(&space.view, cx.style, cx.rect) {
|
||||
let name = match side {
|
||||
AddSide::Top => &words.above,
|
||||
AddSide::Right => &words.right,
|
||||
AddSide::Bottom => &words.below,
|
||||
AddSide::Left => &words.left,
|
||||
};
|
||||
access.node(BUTTON.at(side.index()), Role::BUTTON).name = Name::Text(name.as_str().to_owned());
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> AddBesideOutput {
|
||||
let Report { added, copy, hovered } = self.report;
|
||||
AddBesideOutput { response: cx.response.clone(), added, copy, hovered }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
//! Stories of the "+" buttons: an artboard on a pasteboard with the buttons around it, one side kept clear by a
|
||||
//! neighbour's rect, and the connected-shape form.
|
||||
|
||||
use super::AddBesideHandles;
|
||||
use craft_behavior::CanvasView;
|
||||
use craft_behavior::kurbo::{Point, Rect as DocRect};
|
||||
use craft_ui::canvas::{Canvas, PageFrame, Pasteboard};
|
||||
use craft_ui::contract::{Show as _, ShowContainer as _};
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use egui::{Rect, Ui};
|
||||
|
||||
/// The artboard the buttons surround, in document units: in the middle of the story document.
|
||||
fn artboard() -> DocRect {
|
||||
DocRect::new(220.0, 130.0, 420.0, 270.0)
|
||||
}
|
||||
|
||||
/// The view of the canvas the story shows: the story document at 100 %, centred.
|
||||
fn view(ui: &Ui, rect: Rect) -> CanvasView {
|
||||
craft_ui::testing::canvas_story::StoryDocument::STANDARD.view(rect, ui.pixels_per_point(), 100.0)
|
||||
}
|
||||
|
||||
/// Shows the artboard with `handles` over it on a canvas.
|
||||
fn on_canvas<'a>(ui: &mut Ui, rect: Rect, handles: impl Fn(Rect) -> AddBesideHandles<'a>) -> StoryOutput {
|
||||
let board = [PageFrame::new(artboard()).name("Artboard 1").active(true)];
|
||||
let view = view(ui, rect);
|
||||
let shown = Canvas::new("Document").view(view).show_at(ui, rect, |ui, body| {
|
||||
craft_ui::testing::canvas_story::show_document(ui, body.rect, &craft_ui::testing::canvas_story::StoryDocument::STANDARD);
|
||||
let name_clicked = Pasteboard::new("Pasteboard", &board).show_at(ui, body.rect).name_clicked.is_some();
|
||||
(handles(body.rect).show_at(ui, body.rect), name_clicked)
|
||||
});
|
||||
// The artboard's name is a button too: its click is a click of the story.
|
||||
shown.inner.map_or_else(StoryOutput::default, |(output, name_clicked)| {
|
||||
let mut facts = StoryOutput::from(output);
|
||||
facts.clicked |= name_clicked;
|
||||
facts
|
||||
})
|
||||
}
|
||||
|
||||
#[story(AddBesideHandles<'static>, covers = [Default], drive = Drive::Never)]
|
||||
fn add_beside(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
let rect = craft_ui::testing::stage(ui);
|
||||
let view = view(ui, rect);
|
||||
let neighbour = Rect::from_two_pos(
|
||||
view.to_screen(Point::new(artboard().x1 + 16.0, artboard().y0)),
|
||||
view.to_screen(Point::new(artboard().x1 + 80.0, artboard().y1)),
|
||||
);
|
||||
let clear = [neighbour];
|
||||
on_canvas(ui, rect, |_| AddBesideHandles::new("Add beside", artboard()).clear_of(&clear))
|
||||
}
|
||||
|
||||
#[story(AddBesideHandles<'static>, covers = [Default], drive = Drive::Never)]
|
||||
fn add_beside_connecting(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
let rect = craft_ui::testing::stage(ui);
|
||||
on_canvas(ui, rect, |_| AddBesideHandles::new("Add beside", artboard()).connecting())
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
//! The words of the "+" buttons, English by default.
|
||||
|
||||
craft_ui::words! {
|
||||
/// The "+" buttons' names. The host may name the group for what it adds ("Add artboard beside").
|
||||
pub struct AddBesideWords {
|
||||
group: "addBeside.group" = "Add beside";
|
||||
above: "addBeside.above" = "Add above";
|
||||
right: "addBeside.right" = "Add right";
|
||||
below: "addBeside.below" = "Add below";
|
||||
left: "addBeside.left" = "Add left";
|
||||
add_connected: "addBeside.addConnected" = "Add a connected shape";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
//! [`ArtboardBar`]: the members the Artboard tool adds to the app's options `Bar`.
|
||||
|
||||
use super::{ArtboardItem, ArtboardPreset, ArtboardWords};
|
||||
use craft_behavior::kurbo::Size;
|
||||
use craft_behavior::{EditEvent, EditEvents, Mixed};
|
||||
use craft_ui::bars::{BarItem, BarItems, ItemDisplay};
|
||||
use craft_ui::buttons::Button;
|
||||
use craft_ui::contract::{Bind, Entry, NoValue, Outcome, Props as _, Show as _, ShowContainer as _, clicked};
|
||||
use craft_ui::display::Divider;
|
||||
use craft_ui::form::Field;
|
||||
use craft_ui::pickers::Select;
|
||||
use craft_ui::runtime::env::{Env, UnitKind};
|
||||
use craft_ui::text::NumberField;
|
||||
use egui::{Response, Ui};
|
||||
use std::ops::RangeInclusive;
|
||||
|
||||
/// The smallest and largest side of a board, in pixels (PhotoCraft's field range).
|
||||
pub(super) const SIDE: RangeInclusive<f64> = 1.0..=300_000.0;
|
||||
|
||||
/// The commands of the Artboard bar. The app owns the boards and takes the command when it runs.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, craft_ui::contract::CommandSet)]
|
||||
#[command(prefix = "artboardCommand")]
|
||||
#[non_exhaustive]
|
||||
pub enum ArtboardCommand {
|
||||
/// A board of the selected board's size, else the canvas's.
|
||||
#[command(label = "Add New Artboard")]
|
||||
AddNew,
|
||||
}
|
||||
|
||||
/// What [`ArtboardBar`] reports.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
pub struct ArtboardBarOutput {
|
||||
/// The members' response.
|
||||
pub response: Response,
|
||||
/// The selected board's new size: a preset pick, Make Portrait or Make Landscape, or a typed W or H is a `Set`; a
|
||||
/// scrub of a caption is a gesture. The app resizes the board (contents stay).
|
||||
pub size: EditEvents<Size>,
|
||||
}
|
||||
|
||||
impl Outcome for ArtboardBarOutput {
|
||||
type Value = NoValue;
|
||||
|
||||
fn response(&self) -> &Response {
|
||||
&self.response
|
||||
}
|
||||
}
|
||||
|
||||
/// The members the Artboard tool adds to the options bar, in PhotoCraft's order: the Size preset (Custom, then the
|
||||
/// app's presets), W and H (1 to 300,000 px), Make Portrait (shown only while the board is wider than tall), Make
|
||||
/// Landscape (only while taller than wide), a rule and Add New Artboard ([`ArtboardCommand::AddNew`]). Without a
|
||||
/// selected board the size members are off. Each member is a Tab stop in the bar's order.
|
||||
#[must_use = "show the members with `show`"]
|
||||
#[derive(craft_ui::contract::Pattern)]
|
||||
pub struct ArtboardBar<'a> {
|
||||
selected: Option<&'a ArtboardItem>,
|
||||
presets: &'a [ArtboardPreset],
|
||||
}
|
||||
|
||||
impl<'a> ArtboardBar<'a> {
|
||||
/// The members for the `selected` board with the app's `presets`.
|
||||
pub fn new(selected: Option<&'a ArtboardItem>, presets: &'a [ArtboardPreset]) -> Self {
|
||||
ArtboardBar { selected, presets }
|
||||
}
|
||||
|
||||
/// Adds the members to the bar's row.
|
||||
pub fn show(self, ui: &mut Ui) -> ArtboardBarOutput {
|
||||
let words = Env::of(ui).words::<ArtboardWords>();
|
||||
let size = self.selected.map(|board| Size::new(board.rect.width().abs(), board.rect.height().abs()));
|
||||
let shown = size.unwrap_or(Size::ZERO);
|
||||
let on = size.is_some();
|
||||
let mut out = EditEvents::new();
|
||||
// The preset the board's size matches, else Custom.
|
||||
let mut entries = vec![Entry::new(None, words.custom.clone())];
|
||||
entries.extend(self.presets.iter().enumerate().map(|(i, preset)| Entry::new(Some(i), preset.name.clone())));
|
||||
let current = self.presets.iter().position(|preset| preset.size == shown);
|
||||
Field::new(words.size.clone()).enabled(on).show(ui, |ui, _| {
|
||||
let pick = Select::new(words.size.clone(), Bind::given(current), &entries).enabled(on).show(ui);
|
||||
if let Some(Some(i)) = pick.value().copied()
|
||||
&& let Some(preset) = self.presets.get(i)
|
||||
{
|
||||
out = pick.events.map(|_| preset.size);
|
||||
}
|
||||
});
|
||||
let side = |ui: &mut Ui, caption: &craft_ui::runtime::env::Label, name: &craft_ui::runtime::env::Label, value: f64, width: bool| {
|
||||
Field::new(caption.clone())
|
||||
.enabled(on)
|
||||
.show(ui, |ui, _| {
|
||||
let field = NumberField::new(name.clone(), Bind::given(Some(value))).range(SIDE).unit_kind(UnitKind::Pixels).enabled(on).show(ui);
|
||||
field.edit.events.map(|v| {
|
||||
if width { Size::new(v.unwrap_or(shown.width), shown.height) } else { Size::new(shown.width, v.unwrap_or(shown.height)) }
|
||||
})
|
||||
})
|
||||
.inner
|
||||
.unwrap_or_default()
|
||||
};
|
||||
let width = side(ui, &words.width, &words.width_name, shown.width, true);
|
||||
let height = side(ui, &words.height, &words.height_name, shown.height, false);
|
||||
let mut size_events = out;
|
||||
size_events.extend(width);
|
||||
size_events.extend(height);
|
||||
// Make Portrait is for a board wider than tall, Make Landscape for one taller than wide.
|
||||
let swapped = Size::new(shown.height, shown.width);
|
||||
let swap = |ui: &mut Ui, label: &craft_ui::runtime::env::Label| {
|
||||
clicked(&Button::new(label.clone()).show(ui)).then(|| EditEvent::set(Mixed::Same(shown), swapped, label.as_str().into(), None))
|
||||
};
|
||||
if shown.width > shown.height {
|
||||
size_events.extend(swap(ui, &words.make_portrait));
|
||||
}
|
||||
if shown.height > shown.width {
|
||||
size_events.extend(swap(ui, &words.make_landscape));
|
||||
}
|
||||
Divider::vertical().show(ui);
|
||||
let response = BarItems::new(vec![BarItem::new(ArtboardCommand::AddNew).display(ItemDisplay::Text)]).label(words.commands.clone()).show(ui);
|
||||
ArtboardBarOutput { response, size: size_events }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
//! The Artboard tool: [`ArtboardOverlay`] (the boards' bodies and the active board's handles, a canvas control),
|
||||
//! [`ArtboardTool`] (the canvas tool for the pasteboard), [`ArtboardBar`] (the options bar's members) and
|
||||
//! [`ArtboardProperties`] (the Properties section). Frames and names stay the `Pasteboard`'s; the "+" buttons are
|
||||
//! [`AddBesideHandles`](crate::ui::add_beside::AddBesideHandles), shown over the active board while
|
||||
//! [`ArtboardOverlayOutput::dragging`] is false and answered with [`ArtboardTool::add_beside`].
|
||||
//!
|
||||
//! The control and the tool report the same [`ArtboardEvent`], so the app has one handler.
|
||||
|
||||
use crate::geometry::artboard::{resized_keep_ratio, resized_rect};
|
||||
use crate::ui::add_beside::AddSide;
|
||||
use crate::ui::slice::Run;
|
||||
use craft_behavior::EditEvent;
|
||||
use craft_behavior::kurbo::{Point, Rect, Size, Vec2};
|
||||
use craft_keymap::Mods;
|
||||
use craft_theme::Srgba;
|
||||
use std::sync::Arc;
|
||||
|
||||
mod bar;
|
||||
mod overlay;
|
||||
mod properties;
|
||||
#[cfg(feature = "screen-testing")]
|
||||
mod stories;
|
||||
mod tool;
|
||||
mod words;
|
||||
|
||||
pub use bar::{ArtboardBar, ArtboardBarOutput, ArtboardCommand};
|
||||
pub use overlay::{ArtboardOverlay, ArtboardOverlayOutput};
|
||||
pub use properties::{ArtboardProperties, ArtboardPropertiesOutput};
|
||||
pub use tool::ArtboardTool;
|
||||
pub use words::{ArtboardToolWords, ArtboardWords};
|
||||
|
||||
/// An artboard's background.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub enum ArtboardBackground {
|
||||
/// An opaque white board.
|
||||
#[default]
|
||||
White,
|
||||
/// An opaque black board.
|
||||
Black,
|
||||
/// No fill; the checkerboard or what lies under shows through.
|
||||
Transparent,
|
||||
/// Other…: a colour asked for with a `ColorRequest`.
|
||||
Custom(Srgba),
|
||||
}
|
||||
|
||||
/// One artboard as the control and the tool see it this pass: a read-only snapshot.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct ArtboardItem {
|
||||
/// The board's name, as shown on its label.
|
||||
pub name: String,
|
||||
/// In document pixels.
|
||||
pub rect: Rect,
|
||||
/// A locked board selects but never moves or resizes (Illustrator).
|
||||
pub locked: bool,
|
||||
/// The board's fill.
|
||||
pub background: ArtboardBackground,
|
||||
}
|
||||
|
||||
impl ArtboardItem {
|
||||
/// An unlocked white board named `name` at `rect`.
|
||||
pub fn new(name: impl Into<String>, rect: Rect) -> Self {
|
||||
ArtboardItem { name: name.into(), rect, locked: false, background: ArtboardBackground::White }
|
||||
}
|
||||
}
|
||||
|
||||
/// A size preset of the options bar and the Properties section: the app's list; the library has no preset data.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct ArtboardPreset {
|
||||
/// The name the preset menu shows.
|
||||
pub name: String,
|
||||
/// In document pixels.
|
||||
pub size: Size,
|
||||
}
|
||||
|
||||
impl ArtboardPreset {
|
||||
/// A preset named `name` of `size`.
|
||||
pub fn new(name: impl Into<String>, size: Size) -> Self {
|
||||
ArtboardPreset { name: name.into(), size }
|
||||
}
|
||||
}
|
||||
|
||||
/// Which product's rules the control and the tool follow.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub struct ArtboardRules {
|
||||
/// The "+" buttons beside the selected board.
|
||||
pub plus_buttons: bool,
|
||||
/// Shift-click toggles a board in the selection; Shift-drag on the pasteboard is a marquee over boards; Shift-drag
|
||||
/// inside a board draws a new one.
|
||||
pub multi_select: bool,
|
||||
/// A double click inside a board reports `OpenOptions` (Illustrator's Artboard Options).
|
||||
pub open_on_double_click: bool,
|
||||
/// A click on an object outside the boards fits an artboard to it (`FitObject`).
|
||||
pub fit_object: bool,
|
||||
/// Alt-drag inside a board moves a copy.
|
||||
pub alt_copies: bool,
|
||||
/// Esc with no drag leaves the tool (`Leave`).
|
||||
pub escape_leaves: bool,
|
||||
/// The arrow step in document pixels (the app's keyboard increment); Shift ten times.
|
||||
pub arrow_step: f64,
|
||||
}
|
||||
|
||||
impl ArtboardRules {
|
||||
/// Photoshop's: "+" buttons, one board selected.
|
||||
pub const PHOTOSHOP: ArtboardRules = ArtboardRules {
|
||||
plus_buttons: true,
|
||||
multi_select: false,
|
||||
open_on_double_click: false,
|
||||
fit_object: false,
|
||||
alt_copies: false,
|
||||
escape_leaves: false,
|
||||
arrow_step: 1.0,
|
||||
};
|
||||
/// Illustrator's: no "+" buttons, multi-select and marquee, a double click opens Options, fit to an object, Alt
|
||||
/// copies, Esc leaves.
|
||||
pub const ILLUSTRATOR: ArtboardRules = ArtboardRules {
|
||||
plus_buttons: false,
|
||||
multi_select: true,
|
||||
open_on_double_click: true,
|
||||
fit_object: true,
|
||||
alt_copies: true,
|
||||
escape_leaves: true,
|
||||
arrow_step: 1.0,
|
||||
};
|
||||
|
||||
/// These rules with the app's keyboard increment.
|
||||
#[must_use]
|
||||
pub fn arrow_step(mut self, step: f64) -> Self {
|
||||
self.arrow_step = step;
|
||||
self
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for ArtboardRules {
|
||||
fn default() -> Self {
|
||||
ArtboardRules::PHOTOSHOP
|
||||
}
|
||||
}
|
||||
|
||||
/// What the control and the tool report.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
#[non_exhaustive]
|
||||
pub enum ArtboardEvent {
|
||||
/// A new board: `Begin` past the click slop, `Update`, `Commit` with its pixel rect, `Cancel`.
|
||||
Draw(EditEvent<Rect>),
|
||||
/// The selected boards moving by an offset in whole pixels (with their contents); `copy` for an Alt-drag.
|
||||
#[non_exhaustive]
|
||||
Move {
|
||||
/// Indices of the moved boards.
|
||||
indices: Vec<usize>,
|
||||
/// The gesture and the offset in whole pixels.
|
||||
event: EditEvent<Vec2>,
|
||||
/// Whether the boards are copied rather than moved.
|
||||
copy: bool,
|
||||
},
|
||||
/// Board `index` resized by a handle (contents stay): its new pixel rect.
|
||||
#[non_exhaustive]
|
||||
Resize {
|
||||
/// Index of the resized board.
|
||||
index: usize,
|
||||
/// The gesture and the new pixel rect.
|
||||
event: EditEvent<Rect>,
|
||||
},
|
||||
/// A "+" button: a board of the same size beside board `index`; `copy` (Alt) with
|
||||
/// its contents.
|
||||
#[non_exhaustive]
|
||||
AddBeside {
|
||||
/// Index of the board the new one goes beside.
|
||||
index: usize,
|
||||
/// Which side of that board.
|
||||
side: AddSide,
|
||||
/// Whether the contents are copied too.
|
||||
copy: bool,
|
||||
},
|
||||
/// The selection changed to `indices` (empty: none).
|
||||
#[non_exhaustive]
|
||||
Select {
|
||||
/// The newly selected boards.
|
||||
indices: Vec<usize>,
|
||||
/// The modifiers held at the click.
|
||||
mods: Mods,
|
||||
},
|
||||
/// Delete removed the selected boards.
|
||||
#[non_exhaustive]
|
||||
Delete {
|
||||
/// Indices of the removed boards.
|
||||
indices: Vec<usize>,
|
||||
},
|
||||
/// Enter, or a double click inside a board under [`ArtboardRules::open_on_double_click`]: Artboard Options.
|
||||
#[non_exhaustive]
|
||||
OpenOptions {
|
||||
/// Index of the board whose options open.
|
||||
index: usize,
|
||||
},
|
||||
/// Illustrator: a click on an object outside the boards: fit a board to the object at `at`.
|
||||
#[non_exhaustive]
|
||||
FitObject {
|
||||
/// The clicked point, in document space.
|
||||
at: Point,
|
||||
},
|
||||
/// Illustrator: Esc with no drag: the app returns to its selection tool.
|
||||
Leave,
|
||||
}
|
||||
|
||||
/// The board state the control and the tool act on for a key.
|
||||
pub(crate) struct Boards<'a> {
|
||||
pub(crate) items: &'a [ArtboardItem],
|
||||
pub(crate) selected: &'a [usize],
|
||||
}
|
||||
|
||||
impl Boards<'_> {
|
||||
/// The active board: the first selected one this pass's boards still have.
|
||||
pub(crate) fn active(&self) -> Option<usize> {
|
||||
self.selected.first().copied().filter(|&i| i < self.items.len())
|
||||
}
|
||||
|
||||
/// The selected boards that exist and are not locked.
|
||||
pub(crate) fn movable(&self) -> Vec<usize> {
|
||||
self.selected.iter().copied().filter(|&i| self.items.get(i).is_some_and(|b| !b.locked)).collect()
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn overlaps(a: Rect, b: Rect) -> bool {
|
||||
let (a, b) = (a.abs(), b.abs());
|
||||
a.x0 <= b.x1 && a.x1 >= b.x0 && a.y0 <= b.y1 && a.y1 >= b.y0
|
||||
}
|
||||
|
||||
/// What a key asks of the selected boards.
|
||||
pub(crate) enum KeyAct {
|
||||
/// An arrow key: the direction in document space (a unit step per axis) and the modifiers.
|
||||
Nudge {
|
||||
direction: Vec2,
|
||||
mods: Mods,
|
||||
},
|
||||
Delete,
|
||||
Submit,
|
||||
}
|
||||
|
||||
/// The events of a key on the selected boards: the one rule the control's focused board and the tool share. Arrows
|
||||
/// move the selected boards by the rules' step (Shift ten times), Alt and the arrows resize from the end edges, Delete
|
||||
/// removes the selection, Enter opens the options.
|
||||
pub(crate) fn key_events(boards: &Boards<'_>, rules: &ArtboardRules, act: KeyAct, words: &ArtboardToolWords) -> Vec<ArtboardEvent> {
|
||||
let Some(active) = boards.active() else { return Vec::new() };
|
||||
match act {
|
||||
KeyAct::Delete => {
|
||||
let indices = boards.selected.iter().copied().filter(|&i| i < boards.items.len()).collect();
|
||||
vec![ArtboardEvent::Delete { indices }]
|
||||
}
|
||||
KeyAct::Submit => vec![ArtboardEvent::OpenOptions { index: active }],
|
||||
KeyAct::Nudge { direction, mods } => {
|
||||
let step = rules.arrow_step * if mods.shift { 10.0 } else { 1.0 };
|
||||
let by = direction * step;
|
||||
if mods.alt {
|
||||
// The end edges (right, bottom) move; a locked board stays.
|
||||
let board = &boards.items[active];
|
||||
if board.locked {
|
||||
return Vec::new();
|
||||
}
|
||||
let handle = if by.x == 0.0 { [0, 1] } else { [1, 0] };
|
||||
let rect = resized_rect(board.rect, handle, by, false);
|
||||
let event = Run::set(words.resize_board.as_str().into(), board.rect, rect);
|
||||
vec![ArtboardEvent::Resize { index: active, event }]
|
||||
} else {
|
||||
let indices = boards.movable();
|
||||
if indices.is_empty() {
|
||||
return Vec::new();
|
||||
}
|
||||
let event = Run::set(words.move_board.as_str().into(), Vec2::ZERO, by);
|
||||
vec![ArtboardEvent::Move { indices, event, copy: false }]
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `rect` resized by `handle` dragged by `by`: Shift on a corner keeps the proportions, Alt resizes about the centre.
|
||||
pub(crate) fn resized(rect: Rect, handle: [i8; 2], by: Vec2, mods: Mods) -> Rect {
|
||||
if mods.shift { resized_keep_ratio(rect, handle, by, mods.alt) } else { resized_rect(rect, handle, by, mods.alt) }
|
||||
}
|
||||
|
||||
/// The label of an undo step.
|
||||
pub(crate) fn label(word: &craft_ui::runtime::env::Label) -> Arc<str> {
|
||||
word.as_str().into()
|
||||
}
|
||||
@@ -0,0 +1,430 @@
|
||||
//! [`ArtboardOverlay`]: the boards' bodies and the active board's handles, a canvas control (20.6). The boards' frames and
|
||||
//! names stay the `Pasteboard`'s.
|
||||
|
||||
use super::{ArtboardEvent, ArtboardItem, ArtboardRules, ArtboardToolWords, Boards, KeyAct, key_events, label, resized};
|
||||
use crate::geometry::artboard::drawn_rect;
|
||||
use crate::geometry::slice::HANDLES;
|
||||
use crate::ui::slice::{Run, cancel_reason, handle_point, snapped_move, whole};
|
||||
use craft_behavior::kurbo::{Point, Rect as DocRect, Vec2 as DocVec};
|
||||
use craft_behavior::{
|
||||
Axis, CursorIcon, GestureId, HitLevel, HitPriority, HitShape, Intent, Metrics, NavShape, PartKey, PointerButton, PressPhase, Roving, Sense,
|
||||
resize_cursor,
|
||||
};
|
||||
use craft_keymap::Mods;
|
||||
use craft_ui::canvas::{CanvasSpace, Snap, canvas_snap, canvas_space};
|
||||
use craft_ui::contract::{
|
||||
Access, Common, Component, Cx, Focus as _, MeasureCx, Name, NoValue, Outcome, PaintUi, PartsCx, Pointer as _, Props as _, Remember as _, Role,
|
||||
Styled as _, WordSetCx as _,
|
||||
};
|
||||
use craft_ui::primitives::{PaintShape, StrokeWidth};
|
||||
use craft_ui::runtime::env::Label;
|
||||
use craft_ui::runtime::focus::KeyUse;
|
||||
use craft_ui::style::{ComponentStyle, Flags, HandleLook, StyleCx};
|
||||
use egui::{CornerRadius, Pos2, Rect, Response, Vec2};
|
||||
|
||||
/// The part of one board: `BOARD.at(index)`.
|
||||
const BOARD: PartKey = PartKey::new("board");
|
||||
|
||||
/// The part of one handle of the active board: `HANDLE.at(i)` with `i` an index into [`HANDLES`].
|
||||
const HANDLE: PartKey = PartKey::new("handle");
|
||||
|
||||
/// The style of the artboard overlay.
|
||||
#[derive(Clone, Debug, PartialEq, ComponentStyle)]
|
||||
#[non_exhaustive]
|
||||
pub struct ArtboardOverlayStyle {
|
||||
#[style(metrics)]
|
||||
metrics: Metrics,
|
||||
handle: HandleLook,
|
||||
}
|
||||
|
||||
/// What the control reports.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
pub struct ArtboardOverlayOutput {
|
||||
/// The overlay's response.
|
||||
pub response: Response,
|
||||
/// What the pointer and the keys did, in order.
|
||||
pub events: Vec<ArtboardEvent>,
|
||||
/// A drag runs: the app hides the "+" buttons meanwhile.
|
||||
pub dragging: bool,
|
||||
}
|
||||
|
||||
impl Outcome for ArtboardOverlayOutput {
|
||||
type Value = NoValue;
|
||||
|
||||
fn response(&self) -> &Response {
|
||||
&self.response
|
||||
}
|
||||
}
|
||||
|
||||
/// What a press took, kept from its press to its release.
|
||||
#[derive(Clone, Debug, Default)]
|
||||
enum Held {
|
||||
/// A press on a board that does not move (a locked board, a double click).
|
||||
#[default]
|
||||
Hold,
|
||||
/// The boards `indices` move; a click that stays a click narrows a larger selection to `narrow`.
|
||||
Move { indices: Vec<usize>, copy: bool, narrow: Option<usize>, rect: DocRect, run: Run<DocVec>, start: Point },
|
||||
/// Board `index`, whose rect was `rect` at the press, resized by `handle`.
|
||||
Resize { index: usize, rect: DocRect, handle: [i8; 2], run: Run<DocRect> },
|
||||
/// Shift-press inside board `toggle`: a new board when it drags, else the board toggles in the selection.
|
||||
New { toggle: usize, run: Run<DocRect>, start: Point },
|
||||
}
|
||||
|
||||
impl Held {
|
||||
fn began(&self) -> bool {
|
||||
match self {
|
||||
Held::Move { run, .. } => run.began(),
|
||||
Held::Resize { run, .. } | Held::New { run, .. } => run.began(),
|
||||
Held::Hold => false,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The boards of a canvas, taken by the pointer and the keyboard.
|
||||
///
|
||||
/// - A press in a board selects it; a drag moves it with its contents in whole pixels (the canvas's snapping applies
|
||||
/// to the boards' edges); a locked board selects and never moves. The active board's eight handles resize it (Shift
|
||||
/// on a corner keeps proportions, also when Shift goes down mid-drag; Alt about the centre).
|
||||
/// - Under [`ArtboardRules`]: Shift-click toggles a board, Shift-drag inside a board draws a new one, Alt-drag moves a
|
||||
/// copy, a double click reports `OpenOptions`.
|
||||
/// - The boards, then the active board's handles, are one Tab stop. On a focused part the arrows move the selected
|
||||
/// boards by the rules' step (Shift ten times), Alt and the arrows resize from the end edges, Delete reports `Delete`,
|
||||
/// Enter `OpenOptions`.
|
||||
/// - Cursors: the move arrow over a board, [`resize_cursor`] over the handles.
|
||||
#[derive(craft_ui::contract::Component, craft_ui::contract::Props)]
|
||||
#[component(canvas_control)]
|
||||
pub struct ArtboardOverlay<'a> {
|
||||
#[common]
|
||||
common: Common,
|
||||
items: &'a [ArtboardItem],
|
||||
selected: &'a [usize],
|
||||
/// Which product's rules the control follows.
|
||||
#[prop]
|
||||
rules: ArtboardRules,
|
||||
events: Vec<ArtboardEvent>,
|
||||
dragging: bool,
|
||||
}
|
||||
|
||||
impl<'a> ArtboardOverlay<'a> {
|
||||
/// The overlay named `label` over `items`, with the boards `selected` (the active board first).
|
||||
pub fn new(label: impl Into<Label>, items: &'a [ArtboardItem], selected: &'a [usize]) -> Self {
|
||||
ArtboardOverlay { common: Common::new(), items, selected, rules: ArtboardRules::PHOTOSHOP, events: Vec::new(), dragging: false }.label(label)
|
||||
}
|
||||
|
||||
fn boards(&self) -> Boards<'a> {
|
||||
Boards { items: self.items, selected: self.selected }
|
||||
}
|
||||
|
||||
fn handles_shown(&self) -> Option<usize> {
|
||||
self.boards().active().filter(|&i| !self.items[i].locked)
|
||||
}
|
||||
|
||||
fn pointer(&mut self, cx: &mut Cx<'_, Self>, space: &CanvasSpace, snap: Option<&Snap>) {
|
||||
let words = cx.words::<ArtboardToolWords>();
|
||||
let boards = self.boards();
|
||||
let mut held: Held = cx.press_slot::<Held>().clone().unwrap_or_default();
|
||||
let mut live = cx.press_slot::<Held>().is_some();
|
||||
let snapping = |mods: Mods| move |along: Axis, position: f64| snap.map_or(position, |snap| snap.apply(along, position, mods));
|
||||
for index in 0..self.items.len() {
|
||||
let Some(result) = cx.part_if_declared(BOARD.at(index as u64)) else { continue };
|
||||
let press = result.press;
|
||||
let item = &self.items[index];
|
||||
match press.phase {
|
||||
PressPhase::Down { start, .. } if start.button == PointerButton::Primary => {
|
||||
let at = space.view.to_doc(start.origin);
|
||||
let mods = press.mods;
|
||||
live = true;
|
||||
held = Held::Hold;
|
||||
if self.rules.multi_select && mods.shift {
|
||||
let run = Run::new(mint(cx), label(&words.new_board), DocRect::from_origin_size(at, (0.0, 0.0)));
|
||||
held = Held::New { toggle: index, run, start: at };
|
||||
} else if self.rules.open_on_double_click && press.double_pressed() {
|
||||
self.events.push(ArtboardEvent::OpenOptions { index });
|
||||
} else if item.locked {
|
||||
if self.selected != [index] {
|
||||
self.events.push(ArtboardEvent::Select { indices: vec![index], mods });
|
||||
}
|
||||
} else {
|
||||
let mut indices = vec![index];
|
||||
let mut narrow = None;
|
||||
if self.selected.contains(&index) {
|
||||
if self.selected.len() > 1 {
|
||||
indices = boards.movable();
|
||||
narrow = Some(index);
|
||||
}
|
||||
} else {
|
||||
self.events.push(ArtboardEvent::Select { indices: vec![index], mods });
|
||||
}
|
||||
let rect = union(self.items, &indices);
|
||||
let run = Run::new(mint(cx), label(&words.move_board), DocVec::ZERO);
|
||||
held = Held::Move { indices, copy: self.rules.alt_copies && mods.alt, narrow, rect, run, start: at };
|
||||
}
|
||||
}
|
||||
PressPhase::DragStart { pos, .. } | PressPhase::Drag { pos, .. } => {
|
||||
let to = space.view.to_doc(pos);
|
||||
match &mut held {
|
||||
Held::Move { indices, copy, rect, run, start, .. } => {
|
||||
let by = whole(snapped_move(*rect, to - *start, &snapping(press.mods)));
|
||||
self.events.extend(run.follow(by).into_iter().map(|event| ArtboardEvent::Move {
|
||||
indices: indices.clone(),
|
||||
event,
|
||||
copy: *copy,
|
||||
}));
|
||||
}
|
||||
Held::New { run, start, .. } => {
|
||||
let rect = drawn_rect(*start, to);
|
||||
if rect.width() >= 1.0 && rect.height() >= 1.0 {
|
||||
self.events.extend(run.follow(rect).into_iter().map(ArtboardEvent::Draw));
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
PressPhase::Release { pos, .. } => {
|
||||
let to = space.view.to_doc(pos);
|
||||
let mods = press.mods;
|
||||
match std::mem::take(&mut held) {
|
||||
Held::Move { indices, copy, narrow, rect, run, start } => {
|
||||
if run.began() {
|
||||
let by = whole(snapped_move(rect, to - start, &snapping(mods)));
|
||||
self.events.extend(run.commit(by).into_iter().map(|event| ArtboardEvent::Move {
|
||||
indices: indices.clone(),
|
||||
event,
|
||||
copy,
|
||||
}));
|
||||
} else if let Some(only) = narrow {
|
||||
self.events.push(ArtboardEvent::Select { indices: vec![only], mods });
|
||||
}
|
||||
}
|
||||
Held::New { toggle, run, start } => {
|
||||
let rect = drawn_rect(start, to);
|
||||
if run.began() && rect.width() >= 1.0 && rect.height() >= 1.0 {
|
||||
self.events.extend(run.commit(rect).into_iter().map(ArtboardEvent::Draw));
|
||||
} else if let Some(event) = run.cancel(craft_behavior::CancelReason::Dismissed) {
|
||||
self.events.push(ArtboardEvent::Draw(event));
|
||||
} else {
|
||||
let mut indices = self.selected.to_vec();
|
||||
match indices.iter().position(|&k| k == toggle) {
|
||||
Some(at) => drop(indices.remove(at)),
|
||||
None => indices.insert(0, toggle),
|
||||
}
|
||||
self.events.push(ArtboardEvent::Select { indices, mods });
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
live = false;
|
||||
}
|
||||
PressPhase::Cancel { reason, .. } => {
|
||||
match std::mem::take(&mut held) {
|
||||
Held::Move { indices, copy, run, .. } => {
|
||||
if let Some(event) = run.cancel(cancel_reason(reason)) {
|
||||
self.events.push(ArtboardEvent::Move { indices, event, copy });
|
||||
}
|
||||
}
|
||||
Held::New { run, .. } => self.events.extend(run.cancel(cancel_reason(reason)).map(ArtboardEvent::Draw)),
|
||||
_ => {}
|
||||
}
|
||||
live = false;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
if let Some(active) = self.handles_shown() {
|
||||
let rect = self.items[active].rect;
|
||||
for (h, handle) in HANDLES.into_iter().enumerate() {
|
||||
let Some(result) = cx.part_if_declared(HANDLE.at(h as u64)) else { continue };
|
||||
let press = result.press;
|
||||
match press.phase {
|
||||
PressPhase::Down { start, .. } if start.button == PointerButton::Primary => {
|
||||
let run = Run::new(mint(cx), label(&words.resize_board), rect);
|
||||
held = Held::Resize { index: active, rect, handle, run };
|
||||
live = true;
|
||||
}
|
||||
PressPhase::DragStart { pos, .. } | PressPhase::Drag { pos, .. } => {
|
||||
if let Held::Resize { index, rect, handle, run } = &mut held {
|
||||
let now = resize_to(&space.view, *rect, *handle, pos, press.mods, &snapping(press.mods));
|
||||
self.events.extend(run.follow(now).into_iter().map(|event| ArtboardEvent::Resize { index: *index, event }));
|
||||
}
|
||||
}
|
||||
PressPhase::Release { pos, .. } => {
|
||||
if let Held::Resize { index, rect, handle, run } = std::mem::take(&mut held)
|
||||
&& run.began()
|
||||
{
|
||||
let now = resize_to(&space.view, rect, handle, pos, press.mods, &snapping(press.mods));
|
||||
self.events.extend(run.commit(now).into_iter().map(|event| ArtboardEvent::Resize { index, event }));
|
||||
}
|
||||
live = false;
|
||||
}
|
||||
PressPhase::Cancel { reason, .. } => {
|
||||
if let Held::Resize { index, run, .. } = std::mem::take(&mut held) {
|
||||
self.events.extend(run.cancel(cancel_reason(reason)).map(|event| ArtboardEvent::Resize { index, event }));
|
||||
}
|
||||
live = false;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
}
|
||||
self.dragging = live && held.began();
|
||||
*cx.press_slot::<Held>() = live.then_some(held);
|
||||
}
|
||||
|
||||
fn keys(&mut self, cx: &mut Cx<'_, Self>, space: &CanvasSpace) {
|
||||
let words = cx.words::<ArtboardToolWords>();
|
||||
let focused = cx.active_part().filter(|part| part.key == BOARD || part.key == HANDLE);
|
||||
// Focus arriving on a board by a key or a request selects it; a press selects by its own rule.
|
||||
let arrived = cx.focus_arrived_by_key().is_some_and(|part| part.key == BOARD);
|
||||
let Some(part) = focused else { return };
|
||||
if arrived
|
||||
&& part.key == BOARD
|
||||
&& let Some(index) = part.index.map(|i| i as usize).filter(|&i| i < self.items.len())
|
||||
&& self.selected != [index]
|
||||
&& self.events.is_empty()
|
||||
{
|
||||
self.events.push(ArtboardEvent::Select { indices: vec![index], mods: Mods::NONE });
|
||||
}
|
||||
let boards = self.boards();
|
||||
let mut acts = Vec::new();
|
||||
if let Some((direction, mods)) = cx.intents().take_nudge() {
|
||||
let doc = space.view.unmap_vec(direction);
|
||||
let unit = doc / doc.hypot().max(f64::EPSILON);
|
||||
acts.push(KeyAct::Nudge { direction: DocVec::new(unit.x.round(), unit.y.round()), mods });
|
||||
}
|
||||
if cx.intents().take_exact(&Intent::delete(true, craft_behavior::Granularity::Unit))
|
||||
|| cx.intents().take_exact(&Intent::delete(false, craft_behavior::Granularity::Unit))
|
||||
{
|
||||
acts.push(KeyAct::Delete);
|
||||
}
|
||||
if cx.intents().take(Intent::Submit) {
|
||||
acts.push(KeyAct::Submit);
|
||||
}
|
||||
for act in acts {
|
||||
self.events.extend(key_events(&boards, &self.rules, act, &words));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A gesture id no gesture of this context has had.
|
||||
fn mint<C: Component>(cx: &Cx<'_, C>) -> GestureId {
|
||||
craft_ui::runtime::edit::next_gesture_id(&cx.response.ctx)
|
||||
}
|
||||
|
||||
/// The bounding rect of the boards `indices`.
|
||||
fn union(items: &[ArtboardItem], indices: &[usize]) -> DocRect {
|
||||
indices.iter().filter_map(|&i| items.get(i)).map(|item| item.rect.abs()).reduce(|a, b| a.union(b)).unwrap_or(DocRect::ZERO)
|
||||
}
|
||||
|
||||
/// `rect` with `handle` dragged to the pointer at screen position `pos`, measured from the handle's own point.
|
||||
fn resize_to(view: &craft_behavior::CanvasView, rect: DocRect, handle: [i8; 2], pos: Pos2, mods: Mods, snap: &dyn Fn(Axis, f64) -> f64) -> DocRect {
|
||||
let doc = view.to_doc(pos);
|
||||
let to = Point::new(snap(Axis::Y, doc.x), snap(Axis::X, doc.y));
|
||||
resized(rect, handle, to - handle_point(rect, handle), mods)
|
||||
}
|
||||
|
||||
impl Component for ArtboardOverlay<'_> {
|
||||
const ROLE: Role = Role::GROUP;
|
||||
const OVERLAYS: bool = false;
|
||||
const KEYS: KeyUse = KeyUse::CANVAS.with_moves().with_deletes().with_chrome_key(false);
|
||||
type Style = ArtboardOverlayStyle;
|
||||
type Output = ArtboardOverlayOutput;
|
||||
|
||||
fn style(cx: &StyleCx<'_>, _: ArtboardOverlayStyleKey) -> ArtboardOverlayStyle {
|
||||
ArtboardOverlayStyle { metrics: Metrics::new(), handle: cx.handle() }
|
||||
}
|
||||
|
||||
fn measure(&mut self, _: &MeasureCx<'_, Self>) -> Vec2 {
|
||||
Vec2::ZERO
|
||||
}
|
||||
|
||||
/// The boards, then the active board's handles, in one roving group.
|
||||
fn parts(&mut self, _rect: Rect, cx: &mut PartsCx<'_, Self>) {
|
||||
let Some(space) = canvas_space(&cx.env) else { return };
|
||||
let view = space.view;
|
||||
for (index, item) in self.items.iter().enumerate() {
|
||||
let part = cx
|
||||
.part(BOARD.at(index as u64), HitShape::Polygon(view.quad(item.rect.abs()).to_vec()))
|
||||
.sense(Sense::DRAG | Sense::CLICK | Sense::TAKE_FOCUS)
|
||||
.priority(HitPriority::new(HitLevel::Body, 0))
|
||||
.cursor(if item.locked { CursorIcon::Default } else { CursorIcon::Move })
|
||||
.focusable();
|
||||
if self.selected.first() == Some(&index) {
|
||||
part.selected().flags(Flags::SELECTED);
|
||||
}
|
||||
}
|
||||
if let Some(active) = self.handles_shown() {
|
||||
let radius = cx.style.handle.side / 2.0;
|
||||
for (h, handle) in HANDLES.into_iter().enumerate() {
|
||||
let at = view.to_screen(handle_point(self.items[active].rect.abs(), handle));
|
||||
cx.part(HANDLE.at(h as u64), HitShape::circle(at, radius))
|
||||
.sense(Sense::DRAG | Sense::TAKE_FOCUS)
|
||||
.priority(HitPriority::new(HitLevel::Handle, 0))
|
||||
.cursor(resize_cursor(&view, DocVec::new(f64::from(handle[0]), f64::from(handle[1]))))
|
||||
.focusable();
|
||||
}
|
||||
}
|
||||
if !self.items.is_empty() {
|
||||
cx.roving(Roving::new(NavShape::Flat).page(Some(1)));
|
||||
}
|
||||
}
|
||||
|
||||
fn update(&mut self, cx: &mut Cx<'_, Self>) {
|
||||
let Some(space) = canvas_space(&cx.env) else { return };
|
||||
let snap = canvas_snap(&cx.env);
|
||||
self.pointer(cx, &space, snap.as_ref());
|
||||
self.keys(cx, &space);
|
||||
}
|
||||
|
||||
fn paint(&mut self, ui: &mut PaintUi<'_>, cx: &Cx<'_, Self>) {
|
||||
let (Some(space), Some(active)) = (canvas_space(&cx.env), self.handles_shown()) else { return };
|
||||
let draw = ui.draw();
|
||||
let look = &cx.style.handle;
|
||||
for (h, handle) in HANDLES.into_iter().enumerate() {
|
||||
let at = space.view.to_screen(handle_point(self.items[active].rect.abs(), handle));
|
||||
let square = PaintShape::Rect(Rect::from_center_size(at, Vec2::splat(look.side)), CornerRadius::ZERO);
|
||||
draw.fill(&square, cx.resolve_part(HANDLE.at(h as u64), &look.fill));
|
||||
draw.stroke(&square, StrokeWidth::Thin, look.stroke);
|
||||
}
|
||||
}
|
||||
|
||||
/// One node per board and per handle of the active board.
|
||||
fn access(&self, access: &mut Access, cx: &Cx<'_, Self>) {
|
||||
let words = cx.words::<ArtboardToolWords>();
|
||||
let format = cx.format();
|
||||
let count = |value: f64| format.number_ungrouped(value, 0);
|
||||
for (index, item) in self.items.iter().enumerate() {
|
||||
let r = item.rect.abs();
|
||||
let name = words.board.fill(&[
|
||||
("index", &count((index + 1) as f64)),
|
||||
("width", &count(r.width())),
|
||||
("height", &count(r.height())),
|
||||
("x", &count(r.x0)),
|
||||
("y", &count(r.y0)),
|
||||
]);
|
||||
access.node(BOARD.at(index as u64), Role::BUTTON).name = Name::Text(name);
|
||||
}
|
||||
if let Some(active) = self.handles_shown() {
|
||||
for (h, handle) in HANDLES.into_iter().enumerate() {
|
||||
let at = handle_point(self.items[active].rect.abs(), handle);
|
||||
let name = match handle {
|
||||
[-1, -1] => &words.handle_top_left,
|
||||
[1, -1] => &words.handle_top_right,
|
||||
[-1, 1] => &words.handle_bottom_left,
|
||||
[1, 1] => &words.handle_bottom_right,
|
||||
[0, -1] => &words.handle_top,
|
||||
[0, 1] => &words.handle_bottom,
|
||||
[-1, 0] => &words.handle_left,
|
||||
_ => &words.handle_right,
|
||||
};
|
||||
let node = access.node(HANDLE.at(h as u64), Role::BUTTON);
|
||||
node.name = Name::Text(name.as_str().to_owned());
|
||||
node.description = Some(words.handle_at.fill(&[("x", &count(at.x)), ("y", &count(at.y))]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn finish(self, cx: Cx<'_, Self>) -> ArtboardOverlayOutput {
|
||||
ArtboardOverlayOutput { response: cx.response.clone(), events: self.events, dragging: self.dragging }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,159 @@
|
||||
//! [`ArtboardProperties`]: an artboard's section in the Properties panel.
|
||||
|
||||
use super::bar::SIDE;
|
||||
use super::{ArtboardBackground, ArtboardItem, ArtboardPreset, ArtboardWords};
|
||||
use craft_behavior::EditEvents;
|
||||
use craft_behavior::kurbo::Rect;
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::choice::Swatch;
|
||||
use craft_ui::contract::{Bind, Entry, NoValue, Outcome, Show as _, ShowContainer as _};
|
||||
use craft_ui::form::{Field, FieldGroup};
|
||||
use craft_ui::layout_components::Row;
|
||||
use craft_ui::pickers::Select;
|
||||
use craft_ui::runtime::env::{Env, UnitKind};
|
||||
use craft_ui::runtime::requests::ColorRequest;
|
||||
use craft_ui::sections::Section;
|
||||
use craft_ui::text::NumberField;
|
||||
use egui::{Response, Ui};
|
||||
use std::ops::RangeInclusive;
|
||||
|
||||
/// The range of X and Y, in pixels.
|
||||
const OFFSET: RangeInclusive<f64> = -300_000.0..=300_000.0;
|
||||
|
||||
/// The key of the [`ColorRequest`] Other… files.
|
||||
const BACKGROUND_KEY: &str = "artboard.background";
|
||||
|
||||
/// The background select's rows.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
enum Choice {
|
||||
White,
|
||||
Black,
|
||||
Transparent,
|
||||
Other,
|
||||
}
|
||||
|
||||
/// What [`ArtboardProperties::show`] reports.
|
||||
#[derive(Debug)]
|
||||
#[non_exhaustive]
|
||||
pub struct ArtboardPropertiesOutput {
|
||||
/// The section's response.
|
||||
pub response: Response,
|
||||
/// The board's new rects, in order, from the preset, W, H, X or Y (a `Set`, or a caption scrub's gesture).
|
||||
pub rect: EditEvents<Rect>,
|
||||
/// A background picked from the select (White, Black or Transparent).
|
||||
pub background: Option<ArtboardBackground>,
|
||||
/// Other… was chosen, or the swatch of the custom colour was clicked: the app opens its colour picker with this
|
||||
/// request (titled "Artboard Background Color") and sets `Custom(color)` from the answer.
|
||||
pub pick_color: Option<ColorRequest>,
|
||||
}
|
||||
|
||||
impl Outcome for ArtboardPropertiesOutput {
|
||||
type Value = NoValue;
|
||||
|
||||
fn response(&self) -> &Response {
|
||||
&self.response
|
||||
}
|
||||
}
|
||||
|
||||
/// The Artboard section: Size preset, W and H (1 to 300,000 px), X and Y (±300,000 px, all four in pixels) and
|
||||
/// Background (White, Black, Transparent, Other… with a swatch of the custom colour). Every field is a Tab stop in
|
||||
/// reading order.
|
||||
#[must_use = "show the section with `show`"]
|
||||
#[derive(craft_ui::contract::Pattern)]
|
||||
pub struct ArtboardProperties<'a> {
|
||||
board: &'a ArtboardItem,
|
||||
presets: &'a [ArtboardPreset],
|
||||
}
|
||||
|
||||
impl<'a> ArtboardProperties<'a> {
|
||||
/// The section of `board`, with the app's `presets`.
|
||||
pub fn new(board: &'a ArtboardItem, presets: &'a [ArtboardPreset]) -> Self {
|
||||
ArtboardProperties { board, presets }
|
||||
}
|
||||
|
||||
/// Shows the section.
|
||||
pub fn show(self, ui: &mut Ui) -> ArtboardPropertiesOutput {
|
||||
let words = Env::of(ui).words::<ArtboardWords>();
|
||||
let rect = self.board.rect.abs();
|
||||
let (width, height) = (rect.width(), rect.height());
|
||||
let background = self.board.background;
|
||||
let custom = match background {
|
||||
ArtboardBackground::Custom(color) => Some(color),
|
||||
_ => None,
|
||||
};
|
||||
let mut rect_events = EditEvents::new();
|
||||
let mut picked = None;
|
||||
let mut pick_color = None;
|
||||
let request = |color: Option<Srgba>| {
|
||||
ColorRequest::new(BACKGROUND_KEY, color.unwrap_or(Srgba::rgb(1.0, 1.0, 1.0))).title(words.background_color.clone())
|
||||
};
|
||||
let mut presets = vec![Entry::new(None, words.custom.clone())];
|
||||
presets.extend(self.presets.iter().enumerate().map(|(i, preset)| Entry::new(Some(i), preset.name.clone())));
|
||||
let backgrounds = [
|
||||
Entry::new(Choice::White, words.white.clone()),
|
||||
Entry::new(Choice::Black, words.black.clone()),
|
||||
Entry::new(Choice::Transparent, words.transparent.clone()),
|
||||
Entry::new(Choice::Other, words.other.clone()),
|
||||
];
|
||||
let section = Section::new(words.artboard.clone()).show(ui, |ui, _| {
|
||||
FieldGroup::new(words.artboard.clone()).show(ui, |ui, _| {
|
||||
let current = self.presets.iter().position(|preset| preset.size.width == width && preset.size.height == height);
|
||||
Field::new(words.size.clone()).show(ui, |ui, _| {
|
||||
let pick = Select::new(words.size.clone(), Bind::given(current), &presets).show(ui);
|
||||
if let Some(Some(i)) = pick.value().copied()
|
||||
&& let Some(preset) = self.presets.get(i)
|
||||
{
|
||||
let moved = Rect::new(rect.x0, rect.y0, rect.x0 + preset.size.width, rect.y0 + preset.size.height);
|
||||
rect_events.extend(pick.events.map(|_| moved));
|
||||
}
|
||||
});
|
||||
let field = |ui: &mut Ui,
|
||||
caption: &craft_ui::runtime::env::Label,
|
||||
name: &craft_ui::runtime::env::Label,
|
||||
value: f64,
|
||||
range: &RangeInclusive<f64>| {
|
||||
Field::new(caption.clone())
|
||||
.show(ui, |ui, _| {
|
||||
NumberField::new(name.clone(), Bind::given(Some(value)))
|
||||
.range(range.clone())
|
||||
.unit_kind(UnitKind::Pixels)
|
||||
.show(ui)
|
||||
.edit
|
||||
.events
|
||||
})
|
||||
.inner
|
||||
.unwrap_or_default()
|
||||
};
|
||||
let resized = |size: (f64, f64)| Rect::new(rect.x0, rect.y0, rect.x0 + size.0, rect.y0 + size.1);
|
||||
let moved = |at: (f64, f64)| Rect::new(at.0, at.1, at.0 + width, at.1 + height);
|
||||
rect_events.extend(field(ui, &words.width, &words.width_name, width, &SIDE).map(|v| resized((v.unwrap_or(width), height))));
|
||||
rect_events.extend(field(ui, &words.height, &words.height_name, height, &SIDE).map(|v| resized((width, v.unwrap_or(height)))));
|
||||
rect_events.extend(field(ui, &words.x, &words.x, rect.x0, &OFFSET).map(|v| moved((v.unwrap_or(rect.x0), rect.y0))));
|
||||
rect_events.extend(field(ui, &words.y, &words.y, rect.y0, &OFFSET).map(|v| moved((rect.x0, v.unwrap_or(rect.y0)))));
|
||||
Field::new(words.background.clone()).show(ui, |ui, _| {
|
||||
Row::new().show(ui, |ui, _| {
|
||||
let now = match background {
|
||||
ArtboardBackground::White => Choice::White,
|
||||
ArtboardBackground::Black => Choice::Black,
|
||||
ArtboardBackground::Transparent => Choice::Transparent,
|
||||
_ => Choice::Other,
|
||||
};
|
||||
match Select::new(words.background.clone(), Bind::given(now), &backgrounds).show(ui).value().copied() {
|
||||
Some(Choice::White) => picked = Some(ArtboardBackground::White),
|
||||
Some(Choice::Black) => picked = Some(ArtboardBackground::Black),
|
||||
Some(Choice::Transparent) => picked = Some(ArtboardBackground::Transparent),
|
||||
Some(Choice::Other) => pick_color = Some(request(custom)),
|
||||
None => {}
|
||||
}
|
||||
if let Some(color) = custom
|
||||
&& let Some(asked) = Swatch::new(words.background_color.clone(), color).picker(BACKGROUND_KEY).show(ui).pick_color
|
||||
{
|
||||
pick_color = Some(asked);
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
ArtboardPropertiesOutput { response: section.response.clone(), rect: rect_events, background: picked, pick_color }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
//! Stories of the Artboard tool: the boards, the bar and the Properties section.
|
||||
|
||||
use super::{ArtboardBackground, ArtboardBar, ArtboardItem, ArtboardOverlay, ArtboardPreset, ArtboardProperties};
|
||||
use craft_behavior::kurbo::{Rect, Size};
|
||||
use craft_theme::Srgba;
|
||||
use craft_ui::bars::{Bar, BarKind};
|
||||
use craft_ui::canvas::Canvas;
|
||||
use craft_ui::contract::{Show as _, ShowContainer as _};
|
||||
use craft_ui::testing::{Drive, StoryData, StoryOutput, story};
|
||||
use egui::Ui;
|
||||
|
||||
fn presets() -> Vec<ArtboardPreset> {
|
||||
vec![ArtboardPreset::new("Letter", Size::new(612.0, 792.0)), ArtboardPreset::new("Phone", Size::new(390.0, 844.0))]
|
||||
}
|
||||
|
||||
fn boards() -> Vec<ArtboardItem> {
|
||||
vec![ArtboardItem::new("Artboard 1", Rect::new(0.0, 0.0, 180.0, 240.0)), ArtboardItem::new("Artboard 2", Rect::new(240.0, 0.0, 420.0, 240.0))]
|
||||
}
|
||||
|
||||
#[story(ArtboardOverlay<'static>, covers = [Default])]
|
||||
fn two_artboards(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
let (items, selected) = (boards(), [0_usize]);
|
||||
let stage = craft_ui::testing::stage(ui);
|
||||
let bounds = items.iter().fold(items[0].rect, |bounds, item| bounds.union(item.rect));
|
||||
let view = craft_ui::testing::canvas_story::story_view(stage, ui.pixels_per_point(), bounds.center(), 100.0);
|
||||
Canvas::new("Document").view(view).show_at(ui, stage, |ui, body| {
|
||||
craft_ui::testing::canvas_story::show_document(ui, body.rect, &craft_ui::testing::canvas_story::StoryDocument::STANDARD);
|
||||
ArtboardOverlay::new("Artboards", &items, &selected).show_at(ui, body.rect)
|
||||
});
|
||||
StoryOutput::default()
|
||||
}
|
||||
|
||||
#[story(ArtboardBar<'static>, covers = [Default], drive = Drive::Never)]
|
||||
fn bar_for_a_landscape_board(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
let board = ArtboardItem::new("Artboard 1", Rect::new(0.0, 0.0, 480.0, 270.0));
|
||||
let presets = presets();
|
||||
Bar::new("Options", BarKind::Options).show(ui, |ui, _| ArtboardBar::new(Some(&board), &presets).show(ui)).output.into()
|
||||
}
|
||||
|
||||
#[story(ArtboardProperties<'static>, covers = [Default], drive = Drive::Never)]
|
||||
fn properties_with_a_custom_background(ui: &mut Ui, _: &mut StoryData) -> StoryOutput {
|
||||
let mut board = ArtboardItem::new("Artboard 1", Rect::new(0.0, 0.0, 390.0, 844.0));
|
||||
board.background = ArtboardBackground::Custom(Srgba::rgb(0.9, 0.4, 0.2));
|
||||
let presets = presets();
|
||||
ArtboardProperties::new(&board, &presets).show(ui);
|
||||
StoryOutput::default()
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user