From 1d23ec031c39e3224077e4f040d54669ed0d05a3 Mon Sep 17 00:00:00 2001 From: bflatastic Date: Sat, 21 Nov 2026 21:27:05 +0700 Subject: [PATCH] color-w5: net change of 1 commits - color-w5: written from its sheet --- crates/color-ui/src/palette.rs | 62 ++++-- crates/color-ui/src/palette/reader.rs | 8 +- crates/color-ui/src/palette/tests.rs | 43 +++- crates/color-ui/src/ui/swatches.rs | 1 + crates/color-ui/src/ui/swatches/library.rs | 31 +-- crates/color-ui/src/ui/swatches/menu.rs | 34 +-- crates/color-ui/src/ui/swatches/panel.rs | 229 +++++++++++++++------ crates/color-ui/src/ui/swatches/stories.rs | 48 ++++- 8 files changed, 341 insertions(+), 115 deletions(-) diff --git a/crates/color-ui/src/palette.rs b/crates/color-ui/src/palette.rs index 33c5dc5be..00f66b3ab 100644 --- a/crates/color-ui/src/palette.rs +++ b/crates/color-ui/src/palette.rs @@ -193,16 +193,42 @@ impl From for SwatchPaint { /// One named swatch. #[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)] +#[serde(from = "SwatchEntryWire", into = "SwatchEntryWire")] pub struct SwatchEntry { /// The swatch's label. pub name: String, /// What the swatch holds. pub paint: SwatchPaint, - #[serde(default)] /// How the file marks the colour; `Process` unless the file says otherwise. pub kind: SwatchKind, } +/// The stored form of a [`SwatchEntry`]. It still reads an entry stored as `{name, color, kind}`, which holds a +/// colour, and writes `paint` only. +#[derive(serde::Serialize, serde::Deserialize)] +struct SwatchEntryWire { + name: String, + #[serde(default, skip_serializing_if = "Option::is_none")] + color: Option, + #[serde(default, skip_serializing_if = "Option::is_none")] + paint: Option, + #[serde(default)] + kind: SwatchKind, +} + +impl From for SwatchEntry { + fn from(wire: SwatchEntryWire) -> Self { + let paint = wire.paint.or(wire.color.map(SwatchPaint::Color)).unwrap_or(SwatchPaint::None); + SwatchEntry { name: wire.name, paint, kind: wire.kind } + } +} + +impl From for SwatchEntryWire { + fn from(entry: SwatchEntry) -> Self { + SwatchEntryWire { name: entry.name, color: None, paint: Some(entry.paint), kind: entry.kind } + } +} + impl SwatchEntry { /// A process swatch. pub fn new(name: impl Into, color: SwatchColor) -> SwatchEntry { @@ -211,18 +237,20 @@ impl SwatchEntry { /// A process swatch holding `paint`. pub fn with_paint(name: impl Into, paint: SwatchPaint) -> SwatchEntry { - let _ = (name, paint); - todo!("co.K28") + SwatchEntry { name: name.into(), paint, kind: SwatchKind::Process } } /// The swatch's colour: the colour of a `Color` or `Tint` paint, else `None`. pub fn color(&self) -> Option<&SwatchColor> { - todo!("co.K28") + match &self.paint { + SwatchPaint::Color(color) | SwatchPaint::Tint { color, .. } => Some(color), + _ => None, + } } /// Whether the swatch is reserved: a `None` paint or the Registration kind. pub fn is_reserved(&self) -> bool { - todo!("co.K28") + self.kind == SwatchKind::Registration || matches!(self.paint, SwatchPaint::None) } } @@ -378,20 +406,21 @@ pub fn write_swatches(groups: &[SwatchGroup], format: SwatchFormat) -> Result<(V } let mut report = SwatchReport::default(); let all = || groups.iter().flat_map(|g| g.entries.iter()); - let kinds = all().filter(|e| e.kind != SwatchKind::Process).count(); + let kinds = all().filter(|e| e.color().is_some() && e.kind != SwatchKind::Process).count(); + let skipped = all().filter(|e| e.color().is_none()).count(); let flattened = groups.len() > 1; - match format { + let bytes = match format { SwatchFormat::Aco => { if count_swatches(groups) > ACO_MAX_SWATCHES { return Err(malformed(format, "an .aco file holds at most 65535 swatches")); } - let entries: Vec<(String, AcoColor)> = all().filter_map(|e| e.color().map(|c| (e.name.clone(), to_aco(c)))).collect(); // P3(color-w5): co.K28 + let entries: Vec<(String, AcoColor)> = all().filter_map(|e| e.color().map(|c| (e.name.clone(), to_aco(c)))).collect(); if flattened { report.notes.push(SwatchNote::GroupsFlattened); } push_note(&mut report, kinds, SwatchNote::KindsDropped); push_note(&mut report, names_cut(groups, false), SwatchNote::NamesCut); - Ok((write_aco(&entries), report)) + write_aco(&entries) } SwatchFormat::Act => { let (colors, books, converted) = rgb_colors(groups); @@ -412,7 +441,7 @@ pub fn write_swatches(groups: &[SwatchGroup], format: SwatchFormat) -> Result<(V out.resize(ACT_PALETTE_LEN, 0); out.extend((triplets.len() as u16).to_be_bytes()); out.extend(0xFFFFu16.to_be_bytes()); - Ok((out, report)) + out } SwatchFormat::Ase => { if count_swatches(groups) > ASE_MAX_SWATCHES || groups.len() > ASE_MAX_GROUPS { @@ -425,9 +454,8 @@ pub fn write_swatches(groups: &[SwatchGroup], format: SwatchFormat) -> Result<(V put_ase_name(&mut name, &g.name); put_ase_block(&mut body, ASE_GROUP_START, &name); blocks += 2; - for e in &g.entries { - match e.color().and_then(to_ase) { - // P3(color-w5): co.K28 + for (e, color) in g.entries.iter().filter_map(|e| e.color().map(|c| (e, c))) { + match to_ase(color) { Some(color) => { put_ase_color(&mut body, &e.name, &color, e.kind); blocks += 1; @@ -445,7 +473,7 @@ pub fn write_swatches(groups: &[SwatchGroup], format: SwatchFormat) -> Result<(V out.extend(0u16.to_be_bytes()); out.extend(blocks.to_be_bytes()); out.extend(body); - Ok((out, report)) + out } SwatchFormat::Gpl | SwatchFormat::Css => { let (colors, books, converted) = rgb_colors(groups); @@ -458,9 +486,11 @@ pub fn write_swatches(groups: &[SwatchGroup], format: SwatchFormat) -> Result<(V } else { write_css(groups, &colors) }; - Ok((text.into_bytes(), report)) + text.into_bytes() } - } + }; + push_note(&mut report, skipped, SwatchNote::PaintsSkipped); + Ok((bytes, report)) } /// PhotoCraft's default swatches (46 RGB colours in five groups: Grays, the exact RGB primaries diff --git a/crates/color-ui/src/palette/reader.rs b/crates/color-ui/src/palette/reader.rs index 52811c465..538075bc8 100644 --- a/crates/color-ui/src/palette/reader.rs +++ b/crates/color-ui/src/palette/reader.rs @@ -75,8 +75,10 @@ pub(super) fn stem_of(file_name: &str) -> String { if stem.is_empty() { "Imported Swatches".into() } else { stem } } +/// The swatches a file can carry: those with a colour. Gradient, pattern and None swatches are not counted, so a +/// library of them alone is empty to every writer. pub(super) fn count_swatches(groups: &[SwatchGroup]) -> usize { - groups.iter().map(|g| g.entries.len()).sum() + groups.iter().map(|g| g.entries.iter().filter(|e| e.color().is_some()).count()).sum() } /// Whole UTF-16 scalar values of `name` that fit in `max` units. @@ -94,7 +96,7 @@ pub(super) fn utf16_units(name: &str, max: usize) -> Vec { pub(super) fn names_cut(groups: &[SwatchGroup], include_groups: bool) -> usize { let cut = |name: &str| name.encode_utf16().count() > MAX_NAME_UNITS; - let swatches = groups.iter().flat_map(|g| g.entries.iter()).filter(|e| cut(&e.name)).count(); + let swatches = groups.iter().flat_map(|g| g.entries.iter()).filter(|e| e.color().is_some() && cut(&e.name)).count(); swatches + if include_groups { groups.iter().filter(|g| cut(&g.name)).count() } else { 0 } } @@ -167,7 +169,7 @@ pub(super) fn rgb_colors(groups: &[SwatchGroup]) -> (Vec>, usize, g.entries .iter() .filter_map(|e| { - let color = e.color()?; // P3(color-w5): co.K28 + let color = e.color()?; match color { SwatchColor::Book { .. } => { books += 1; diff --git a/crates/color-ui/src/palette/tests.rs b/crates/color-ui/src/palette/tests.rs index 406de951a..498366b4e 100644 --- a/crates/color-ui/src/palette/tests.rs +++ b/crates/color-ui/src/palette/tests.rs @@ -47,7 +47,7 @@ fn aco_round_trips_colours_in_their_own_model() { assert_eq!(groups[0].name, "Brand"); for ((name, color), entry) in colors.iter().zip(&groups[0].entries) { assert_eq!(entry.name, *name); - assert_same(color, entry.color().unwrap()); // P3(color-w5): co.K28 + assert_same(color, entry.color().unwrap()); } // A version 1 section comes first, then version 2 with the names. assert_eq!(&bytes[..4], &[0, 1, 0, 6]); @@ -68,7 +68,6 @@ fn ase_keeps_groups_and_aco_reports_flattening() { let (back, _) = read_swatches(&ase, "x.ase").unwrap(); assert_eq!(back.iter().map(|g| g.name.as_str()).collect::>(), ["Brand", "Greys"]); assert_eq!(back[0].entries[1].kind, SwatchKind::Spot); - // P3(color-w5): co.K28 assert_same(back[0].entries[1].color().unwrap(), groups[0].entries[1].color().unwrap()); assert_same(back[1].entries[0].color().unwrap(), &SwatchColor::Gray(0.5)); @@ -91,3 +90,43 @@ fn ase_keeps_groups_and_aco_reports_flattening() { assert_eq!(flat.len(), 1); assert_eq!(flat[0].entries.len(), 3); } + +/// Every writer leaves out the swatches that have no colour and counts them once, after its other notes; colours, +/// tints and the Registration swatch are written. A library of paints alone is empty. An entry stored without a +/// paint reads as a colour. +#[trial] +fn writers_skip_paint_swatches_and_report_them() { + let mut registration = SwatchEntry::new("Registration", SwatchColor::Cmyk([1.0; 4])); + registration.kind = SwatchKind::Registration; + let paints = vec![ + SwatchEntry::with_paint("Sky", SwatchPaint::Gradient), + SwatchEntry::with_paint("Dots", SwatchPaint::Pattern), + SwatchEntry::with_paint("None", SwatchPaint::None), + ]; + let mut entries = vec![ + SwatchEntry::new("Red", SwatchColor::Rgb([1.0, 0.0, 0.0])), + SwatchEntry::with_paint("Pink", SwatchPaint::Tint { base: "Red".into(), tint: 0.5, color: SwatchColor::Rgb([1.0, 0.5, 0.5]) }), + registration, + ]; + entries.extend(paints.clone()); + let groups = vec![group("All", entries)]; + for format in SwatchFormat::ALL { + let (bytes, report) = write_swatches(&groups, format).unwrap(); + let counted = report.notes.iter().filter(|n| matches!(n, SwatchNote::PaintsSkipped(_))).count(); + assert_eq!(counted, 1, "{format:?}: {report:?}"); + assert_eq!(report.notes.last(), Some(&SwatchNote::PaintsSkipped(3)), "{format:?}: {report:?}"); + if format.can_read() { + let (back, _) = read_swatches(&bytes, &format!("x.{}", format.extension())).unwrap(); + assert_eq!(count_swatches(&back), 3, "{format:?}"); + } + assert_eq!(write_swatches(&[group("Paints", paints.clone())], format).unwrap_err(), SwatchError::Empty, "{format:?}"); + } + + let legacy: SwatchEntry = serde_json::from_str(r#"{"name":"Old","color":{"model":"rgb","values":[1.0,0.0,0.0]},"kind":"spot"}"#).unwrap(); + assert_eq!(legacy.paint, SwatchPaint::Color(SwatchColor::Rgb([1.0, 0.0, 0.0]))); + assert_eq!(legacy.kind, SwatchKind::Spot); + for entry in &groups[0].entries { + let json = serde_json::to_string(entry).unwrap(); + assert_eq!(serde_json::from_str::(&json).unwrap(), *entry, "{json}"); + } +} diff --git a/crates/color-ui/src/ui/swatches.rs b/crates/color-ui/src/ui/swatches.rs index 6293e937f..204c0b0e0 100644 --- a/crates/color-ui/src/ui/swatches.rs +++ b/crates/color-ui/src/ui/swatches.rs @@ -44,6 +44,7 @@ craft_ui::words! { skipped: count "swatches.skipped" = "{n} color in a model that cannot be read was skipped." | "{n} colors in a model that cannot be read were skipped."; converted: count "swatches.converted" = "{n} color was converted to RGB." | "{n} colors were converted to RGB."; kinds_dropped: count "swatches.kindsDropped" = "{n} spot or global color was written as a process color." | "{n} spot or global colors were written as process colors."; + paints_skipped: count "swatches.paintsSkipped" = "{n} gradient, pattern or None swatch was not written." | "{n} gradient, pattern or None swatches were not written."; truncated: count "swatches.truncated" = "{n} color past the 256 the format holds was left out." | "{n} colors past the 256 the format holds were left out."; transparent_kept: count "swatches.transparentKept" = "{n} color was kept transparent." | "{n} colors were kept transparent."; names_cut: count "swatches.namesCut" = "{n} name was cut to the length the format holds." | "{n} names were cut to the length the format holds."; diff --git a/crates/color-ui/src/ui/swatches/library.rs b/crates/color-ui/src/ui/swatches/library.rs index 824a1eba5..d27aa9fbc 100644 --- a/crates/color-ui/src/ui/swatches/library.rs +++ b/crates/color-ui/src/ui/swatches/library.rs @@ -21,15 +21,13 @@ pub enum SwatchKey { Swatch(String), } -/// What the Swatches panel keeps between passes, owned by the host: the browser's view, the selected row, the row to +/// What the Swatches panel keeps between passes, owned by the host: the browser's view, the selected rows, 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, - /// The selected row. - pub selected: Option, /// The selected rows, with the lead. pub selection: Selection, /// A row to open the rename on in the next pass. @@ -40,7 +38,7 @@ pub struct SwatchesState { impl Default for SwatchesState { fn default() -> Self { - SwatchesState { browser: PresetState::new(), selected: None, selection: Selection::default(), rename: None, export_notes: None } + SwatchesState { browser: PresetState::new(), selection: Selection::default(), rename: None, export_notes: None } } } @@ -246,6 +244,11 @@ impl SwatchLibrary { /// 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) -> Option { + self.add_entry(color.into(), name, group) + } + + /// [`add`](Self::add) for any paint. + fn add_entry(&mut self, paint: SwatchPaint, name: Option<&str>, group: Option) -> Option { if swatches_full(&self.groups) { return None; } @@ -258,7 +261,7 @@ impl SwatchLibrary { } let group = group.unwrap_or(0).min(self.groups.len() - 1); let entries = &mut self.groups[group].entries; - entries.push(SwatchEntry::new(name, color)); + entries.push(SwatchEntry::with_paint(name, paint)); Some(SwatchAt { group, index: entries.len() - 1 }) } @@ -405,7 +408,7 @@ pub(super) fn value_text(color: &SwatchColor, book: &str) -> String { #[derive(Clone, Debug, PartialEq)] #[non_exhaustive] pub enum SwatchEdit { - /// Adds `color` named `name` to `group`, or the first group. + /// Adds `paint` named `name` to `group`, or the first group. #[non_exhaustive] Add { /// The group's name, `None` for the first group. @@ -480,7 +483,7 @@ pub enum SwatchEdit { } impl SwatchEdit { - /// Adds `color` named `name` to `group`, or the first group. + /// Adds `paint` named `name` to `group`, or the first group. pub fn add(group: Option, name: String, paint: impl Into) -> Self { SwatchEdit::Add { group, name, paint: paint.into() } } @@ -502,8 +505,6 @@ impl SwatchLibrary { pub fn apply(&mut self, edit: &SwatchEdit) -> bool { match edit { SwatchEdit::Add { group, name, paint } => { - // P3(color-w5): co.K29 - let SwatchPaint::Color(color) = paint else { return false }; let group = match group { Some(g) => match self.groups.iter().position(|x| x.name == *g) { Some(index) => Some(index), @@ -511,7 +512,7 @@ impl SwatchLibrary { }, None => None, }; - self.add(*color, Some(name), group).is_some() + self.add_entry(paint.clone(), Some(name), group).is_some() } SwatchEdit::NewGroup { name } => self.new_group(name).is_some(), SwatchEdit::Rename { swatch, name } => self.find(swatch).is_some_and(|at| self.rename(at, name)), @@ -560,15 +561,17 @@ impl SwatchLibrary { } /// The rows of the swatch list: each group at depth 0 with its count, each swatch at depth 1 with "name, value" as its -/// tooltip and accessible name. `SwatchesPanel` and `PaintChip`'s swatches list build their rows with it. +/// tooltip and accessible name (the name alone for a swatch without a colour). `SwatchesPanel` and `PaintChip`'s +/// swatches list build their rows with it. pub fn swatch_rows(groups: &[SwatchGroup], words: &SwatchesWords) -> Vec> { let mut rows = Vec::with_capacity(groups.len() + groups.iter().map(|g| g.entries.len()).sum::()); for group in groups { rows.push(PresetRow::group(SwatchKey::Group(group.name.clone()), group.name.as_str(), 0).count(group.entries.len())); for entry in &group.entries { - // P3(color-w5): co.K28 - let Some(color) = entry.color() else { continue }; - let named = format!("{}, {}", entry.name, value_text(color, words.book_color.as_str())); + let named = match entry.color() { + Some(color) => format!("{}, {}", entry.name, value_text(color, words.book_color.as_str())), + None => entry.name.clone(), + }; rows.push(PresetRow::item(SwatchKey::Swatch(entry.name.clone()), entry.name.as_str(), 1).tooltip(named.clone()).accessible_name(named)); } } diff --git a/crates/color-ui/src/ui/swatches/menu.rs b/crates/color-ui/src/ui/swatches/menu.rs index 5fd623d22..1b2a9f414 100644 --- a/crates/color-ui/src/ui/swatches/menu.rs +++ b/crates/color-ui/src/ui/swatches/menu.rs @@ -165,13 +165,13 @@ fn new_swatch_edit(groups: &[SwatchGroup], st: &mut SwatchesState, foreground: S if swatches_full(groups) { return None; } - let group = st.selected.as_ref().and_then(|key| group_of(groups, key)).and_then(|index| groups.get(index)).map(|g| g.name.clone()); + let group = st.selection.lead.as_ref().and_then(|key| group_of(groups, key)).and_then(|index| groups.get(index)).map(|g| g.name.clone()); let color = SwatchColor::Rgb(foreground.to_rgb_array().map(|v| v.clamp(0.0, 1.0))); let name = free_name(groups, words.swatch_n.as_str()); let key = SwatchKey::Swatch(name.clone()); - st.selected = Some(key.clone()); + st.selection = craft_behavior::Selection::single(key.clone()); st.rename = Some(key); - Some(SwatchEdit::Add { group, name, paint: color.into() }) // P3(color-w5): co.K29 + Some(SwatchEdit::add(group, name, color)) } /// An empty group under a unique name, opened for renaming. `None` when the library holds the most groups. @@ -201,21 +201,18 @@ pub(super) fn event_edits( words: &SwatchesWords, ) -> Vec { match event { - PresetEvent::Select { key: SwatchKey::Swatch(name), .. } => { - st.selected = Some(SwatchKey::Swatch(name)); - Vec::new() - } - PresetEvent::Select { key, .. } | PresetEvent::Activate { key, .. } => { - st.selected = Some(key).filter(|k| matches!(k, SwatchKey::Swatch(_))); - Vec::new() - } PresetEvent::Rename { key: SwatchKey::Swatch(old), text, .. } => { let Some(name) = find_swatch(groups, &old).and_then(|at| swatch_rename(groups, at, &text)).filter(|name| *name != old) else { return Vec::new(); }; - if st.selected == Some(SwatchKey::Swatch(old.clone())) { - st.selected = Some(SwatchKey::Swatch(name.clone())); - } + let (old_key, new_key) = (SwatchKey::Swatch(old.clone()), SwatchKey::Swatch(name.clone())); + let swap = |key: &mut SwatchKey| { + if *key == old_key { + *key = new_key.clone(); + } + }; + let selection = &mut st.selection; + selection.items.iter_mut().chain(selection.lead.iter_mut()).chain(selection.anchor.iter_mut()).for_each(swap); vec![SwatchEdit::Rename { swatch: old, name }] } PresetEvent::Rename { key: SwatchKey::Group(old), text, .. } => { @@ -249,7 +246,14 @@ fn footer_edits( match event { PresetFooterEvent::New => new_swatch_edit(groups, st, foreground, words).into_iter().collect(), PresetFooterEvent::NewGroup => new_group_edit(groups, st, words).into_iter().collect(), - PresetFooterEvent::Delete => st.selected.clone().and_then(|key| delete_edit(groups, &key)).into_iter().collect(), + PresetFooterEvent::Delete => { + // A swatch of a selected group goes with the group: deleting it after the group would find nothing. + let with_group = |key: &SwatchKey| { + matches!(key, SwatchKey::Swatch(_)) + && group_of(groups, key).and_then(|i| groups.get(i)).is_some_and(|g| st.selection.contains(&SwatchKey::Group(g.name.clone()))) + }; + st.selection.items.iter().filter(|key| !with_group(key)).filter_map(|key| delete_edit(groups, key)).collect() + } _ => Vec::new(), } } diff --git a/crates/color-ui/src/ui/swatches/panel.rs b/crates/color-ui/src/ui/swatches/panel.rs index a2aa141ee..232f7d14d 100644 --- a/crates/color-ui/src/ui/swatches/panel.rs +++ b/crates/color-ui/src/ui/swatches/panel.rs @@ -1,6 +1,7 @@ //! `SwatchesPanel`: the panel body, its state and what it reports. use std::collections::HashMap; +use std::rc::Rc; use craft_cms::convert::CmykConverter; use craft_i18n::Format; @@ -8,9 +9,11 @@ use craft_theme::Srgba; use craft_theme::variant::Tone; use craft_ui::bars::StatusMessage; use craft_ui::choice::SwatchFace; -use craft_ui::contract::{Bind, DropAt, DropPlace, DropZone, Entry, Held, NoValue, Outcome, Pattern, SelectMode, ShowContainer as _, request_rename}; +use craft_ui::contract::{Bind, DropAt, DropPlace, DropZone, Entry, Held, NoValue, Outcome, Pattern, SelectMode, ShowContainer as _}; use craft_ui::layout_components::Stack; -use craft_ui::patterns::presets::{PresetBrowser, PresetEvent, PresetFileEvent, PresetFooterOptions, PresetReorder, PresetWords, ThumbInfo}; +use craft_ui::patterns::presets::{ + PresetBrowser, PresetDrop, PresetEvent, PresetFileEvent, PresetFooterOptions, PresetReorder, PresetRowMenu, PresetWords, ThumbInfo, +}; use craft_ui::primitives::{ContentPainterCx, IconSpec}; use craft_ui::runtime::env::{Count, Env}; use egui::{Rect, Response, Ui}; @@ -32,8 +35,8 @@ pub struct SwatchesPanelOutput { pub used: Option<(SwatchAt, Srgba, bool)>, /// The edits the user made this pass, in pass order, for the host to run; the panel never writes the library. pub edits: Vec, - /// The browser events the panel does not turn into `used` or `edits`: `Activate`, `Menu`, `DropAt`, `Reorder` and - /// `Dropped`. + /// The browser events the panel does not turn into `used` or `edits`, in the order they happened: `Activate`, + /// `Menu`, `DropAt`, `Dropped` and `Reorder`. `Reorder` is also in `edits`; a host runs one of the two. pub events: Vec>, } @@ -45,18 +48,30 @@ impl Outcome for SwatchesPanelOutput { } } +type ThumbFn<'a> = Box, Rect, ThumbInfo<'_, SwatchKey>) + 'a>; +type ToolsFn<'a> = Box; +type RowIconsFn<'a> = Box Vec<(IconSpec<'static>, String)> + 'a>; +type RowItemsFn<'a> = Box Vec> + 'a>; +type DropMaker<'a> = Box PresetDrop<'a, SwatchKey> + 'a>; + /// The Swatches panel on the library's groups, 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. +/// - Click uses the swatch for the foreground; Alt-click (or Ctrl or Cmd) for the background. The swatch is selected, +/// in `SwatchesState::selection`; [`select`](SwatchesPanel::select) chooses one swatch or several. /// 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. +/// renamed in place. Its Delete removes every selected swatch and group. /// - Every change of the library comes back as a [`SwatchEdit`] with resolved names and positions; the host runs it. /// - 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`]. +/// - The browser's options [`thumb`](SwatchesPanel::thumb), [`tools`](SwatchesPanel::tools), +/// [`drop_zone`](SwatchesPanel::drop_zone), [`footer`](SwatchesPanel::footer), [`reveal`](SwatchesPanel::reveal), +/// [`search`](SwatchesPanel::search), [`row_icons`](SwatchesPanel::row_icons), [`takes_drop`](SwatchesPanel::takes_drop) +/// and [`row_items`](SwatchesPanel::row_items) pass through; the events they cause come out in +/// [`SwatchesPanelOutput::events`]. /// - It fills the room it is given, and its browser scrolls the swatches: show it outside a body that scrolls. #[must_use = "show the panel with `show`"] #[derive(Pattern)] @@ -65,6 +80,16 @@ pub struct SwatchesPanel<'a> { state: Bind<'a, SwatchesState>, cmyk: Option<&'a CmykConverter>, foreground: Srgba, + thumb: Option>, + tools: Option>, + drop_zone: Option, + footer: Option>>, + reveal: Option, + search: bool, + row_icons: Option>, + select: SelectMode, + takes_drop: Option>, + row_items: Option>, } /// What the body decided; `show` stores the state and reports the rest after the real run. @@ -73,12 +98,28 @@ struct Settled { st: SwatchesState, used: Option<(SwatchAt, Srgba, bool)>, edits: Vec, + events: Vec>, } impl<'a> SwatchesPanel<'a> { /// The panel over the library's `groups` and the host-owned `state`; `foreground` is what New Swatch adds. pub fn new(groups: &'a [SwatchGroup], state: Bind<'a, SwatchesState>, foreground: Srgba) -> Self { - SwatchesPanel { groups, state, cmyk: None, foreground } + SwatchesPanel { + groups, + state, + cmyk: None, + foreground, + thumb: None, + tools: None, + drop_zone: None, + footer: None, + reveal: None, + search: true, + row_icons: None, + select: SelectMode::Single, + takes_drop: None, + row_items: None, + } } /// The document's CMYK converter, which draws CMYK swatches and gives their colours when used; without it they @@ -89,143 +130,205 @@ impl<'a> SwatchesPanel<'a> { } /// Paints each swatch's thumbnail with `painter` in place of the panel's own swatch face (the host's gradient and - /// pattern previews). + /// pattern previews). The painter draws the selected state from `ThumbInfo::selected`. #[must_use] - pub fn thumb(self, painter: impl Fn(&ContentPainterCx<'_>, Rect, ThumbInfo<'_, SwatchKey>) + 'a) -> Self { - let _ = painter; - todo!("co.K31") + pub fn thumb(mut self, painter: impl Fn(&ContentPainterCx<'_>, Rect, ThumbInfo<'_, SwatchKey>) + 'a) -> Self { + self.thumb = Some(Box::new(painter)); + self } /// The host's tools, shown beside the browser's toolbar. #[must_use] - pub fn tools(self, tools: impl FnMut(&mut Ui) + 'a) -> Self { - let _ = tools; - todo!("co.K31") + pub fn tools(mut self, tools: impl FnMut(&mut Ui) + 'a) -> Self { + self.tools = Some(Box::new(tools)); + self } /// Where a drop onto the panel lands. #[must_use] - pub fn drop_zone(self, zone: DropZone) -> Self { - let _ = zone; - todo!("co.K31") + pub fn drop_zone(mut self, zone: DropZone) -> Self { + self.drop_zone = Some(zone); + self } /// The footer's options; `None` leaves the footer out. Without it the footer keeps Delete enabled while a swatch /// is selected. #[must_use] - pub fn footer(self, footer: Option>) -> Self { - let _ = footer; - todo!("co.K31") + pub fn footer(mut self, footer: Option>) -> Self { + self.footer = Some(footer); + self } /// The swatch to scroll into view. #[must_use] - pub fn reveal(self, key: Option) -> Self { - let _ = key; - todo!("co.K31") + pub fn reveal(mut self, key: Option) -> Self { + self.reveal = key; + self } /// Whether the browser shows its search field. #[must_use] - pub fn search(self, on: bool) -> Self { - let _ = on; - todo!("co.K31") + pub fn search(mut self, on: bool) -> Self { + self.search = on; + self } /// The icons trailing each swatch row, through `PresetRow::trailing`. #[must_use] - pub fn row_icons(self, icons: impl Fn(&SwatchKey) -> Vec<(IconSpec<'static>, String)> + 'a) -> Self { - let _ = icons; - todo!("co.K31") + pub fn row_icons(mut self, icons: impl Fn(&SwatchKey) -> Vec<(IconSpec<'static>, String)> + 'a) -> Self { + self.row_icons = Some(Box::new(icons)); + self } /// How picks select: one swatch, or several with Shift and Cmd. #[must_use] - pub fn select(self, mode: SelectMode) -> Self { - let _ = mode; - todo!("co.K31") + pub fn select(mut self, mode: SelectMode) -> Self { + self.select = mode; + self } /// A host payload of type `P` can be dropped onto a swatch or between swatches at `place` where `accepts` agrees; /// the drop comes back as `PresetEvent::Dropped`. #[must_use] - pub fn takes_drop(self, place: DropPlace, accepts: impl Fn(&P, &DropAt) -> bool + 'a) -> Self { - let _ = (place, accepts); - todo!("co.K31") + pub fn takes_drop(mut self, place: DropPlace, accepts: impl Fn(&P, &DropAt) -> bool + 'a) -> Self { + // The body can run more than once a pass, and a `PresetDrop` is used up by the browser: it is built per run. + let accepts = Rc::new(accepts); + self.takes_drop = Some(Box::new(move || { + let accepts = Rc::clone(&accepts); + PresetDrop::new::

(place, move |payload: &P, at: &DropAt| accepts(payload, at)) + })); + self } - /// The host's rows of the row menu for a swatch. + /// The host's rows of the row menu for a swatch; the standard rows give way to them. #[must_use] - pub fn row_items(self, items: impl Fn(&SwatchKey) -> Vec> + 'a) -> Self { - let _ = items; - todo!("co.K31") + pub fn row_items(mut self, items: impl Fn(&SwatchKey) -> Vec> + 'a) -> Self { + self.row_items = Some(Box::new(items)); + self } /// Draws the panel and returns the user's actions this pass. pub fn show(self, ui: &mut Ui) -> SwatchesPanelOutput { - let SwatchesPanel { groups, state, cmyk, foreground } = self; + let SwatchesPanel { + groups, + state, + cmyk, + foreground, + thumb, + mut tools, + drop_zone, + footer, + reveal, + search, + row_icons, + select, + takes_drop, + row_items, + } = self; let cmyk = cmyk.unwrap_or_else(|| CmykConverter::coated()); let words = Env::of(ui).words::(); let mut held_state = Held::new(state); let ctx = ui.ctx().clone(); - let rename_scope = ui.scope_id().with("browser-rows"); + let browser_id = ui.scope_id(); let mut shown = Stack::new().fill().show(ui, |ui, cx| { let before_state = held_state.read(cx)?; let mut st = before_state.clone(); - if st.selected.as_ref().is_some_and(|k| !has(groups, k)) { - st.selected = None; + let live = |key: &SwatchKey| has(groups, key); + st.selection.items.retain(live); + st.selection.lead = st.selection.lead.take().filter(live); + st.selection.anchor = st.selection.anchor.take().filter(live); + let mut rows = swatch_rows(groups, &words); + if let Some(icons) = &row_icons { + for row in rows.iter_mut().filter(|row| matches!(row.key, SwatchKey::Swatch(_))) { + row.trailing = icons(&row.key); + } } - let rows = swatch_rows(groups, &words); + let footer_options = match &footer { + Some(host) => host.clone(), + None => Some(PresetFooterOptions::new().can_delete(!st.selection.items.is_empty())), + }; let out = { - // P3(color-w5): co.K28 - let colors: HashMap<&str, &SwatchColor> = - groups.iter().flat_map(|g| g.entries.iter().filter_map(|e| e.color().map(|c| (e.name.as_str(), c)))).collect(); + let colors: HashMap<&str, &SwatchColor> = if thumb.is_some() { + HashMap::new() + } else { + groups.iter().flat_map(|g| g.entries.iter().filter_map(|e| e.color().map(|c| (e.name.as_str(), c)))).collect() + }; let mut browser = PresetBrowser::new(words.title.clone(), Bind::bound(&mut st.browser), &rows) .toolbar(true) + .search(search) + .select(select) .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); + .selection(Bind::bound(&mut st.selection)) + .thumb(|cx: &ContentPainterCx<'_>, rect: Rect, info: ThumbInfo<'_, SwatchKey>| match thumb.as_ref() { + Some(host) => host(cx, rect, info), + None => { + 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()); + if let Some(options) = footer_options { + browser = browser.footer(options); + } + if let Some(zone) = drop_zone { + browser = browser.drop_zone(zone); + } + if let Some(key) = &reveal { + browser = browser.reveal(key.clone()); + } + if let Some(tools) = tools.as_mut() { + browser = browser.tools(|ui: &mut Ui| tools(ui)); + } + if let Some(items) = &row_items { + browser = browser.row_menu(PresetRowMenu::Host).row_items(|key: &SwatchKey| items(key)); + } + if let Some(make) = &takes_drop { + browser = browser.takes_drop(make()); } browser.show(ui) }; let mut used = None; let mut edits = Vec::new(); + let mut events = Vec::new(); for event in out.events { if let PresetEvent::Select { key: SwatchKey::Swatch(name), mods, .. } = &event && let Some(at) = find_swatch(groups, name) && let Some(entry) = groups.get(at.group).and_then(|g| g.entries.get(at.index)) && let Some(color) = entry.color() - // P3(color-w5): co.K28 { used = Some((at, color.to_srgb(cmyk), mods.alt || mods.cmd || mods.ctrl)); } + let forwarded = matches!( + event, + PresetEvent::Activate { .. } + | PresetEvent::Menu { .. } + | PresetEvent::DropAt { .. } + | PresetEvent::Dropped { .. } + | PresetEvent::Reorder { .. } + ) + .then(|| event.clone()); edits.extend(event_edits(groups, &mut st, event, foreground, &words)); + events.extend(forwarded); } - Some(Settled { before_state, st, used, edits }) + Some(Settled { before_state, st, used, edits, events }) }); // Once per pass, after the real run: the rename request and the edited state are stored, the edits reported. - let (used, edits) = shown + let (used, edits, events) = shown .settle(|cx, settled| { - let Settled { before_state, mut st, used, edits } = settled.take()?; + let Settled { before_state, mut st, used, edits, events } = settled.take()?; if let Some(key) = st.rename.take() { - request_rename(&ctx, rename_scope, &key); + PresetBrowser::request_rename(&ctx, browser_id, &key); } if st != before_state { held_state.write(cx, &before_state, st, words.title.as_str()); } - Some((used, edits)) + Some((used, edits, events)) }) .flatten() .unwrap_or_default(); - SwatchesPanelOutput { response: shown.output, used, edits, events: Vec::new() } + SwatchesPanelOutput { response: shown.output, used, edits, events } } /// Carries out the host's answer to a file request of the panel menu: Import and Replace read the file into an @@ -282,7 +385,7 @@ impl<'a> SwatchesPanel<'a> { SwatchNote::Truncated(n) => count(&words.truncated, n), SwatchNote::NamesCut(n) => count(&words.names_cut, n), SwatchNote::TransparentKept(n) => count(&words.transparent_kept, n), - SwatchNote::PaintsSkipped(_) => todo!("co.K30"), + SwatchNote::PaintsSkipped(n) => count(&words.paints_skipped, n), }) .collect() } diff --git a/crates/color-ui/src/ui/swatches/stories.rs b/crates/color-ui/src/ui/swatches/stories.rs index 49beddde7..be2ba5b3b 100644 --- a/crates/color-ui/src/ui/swatches/stories.rs +++ b/crates/color-ui/src/ui/swatches/stories.rs @@ -1,9 +1,14 @@ //! Stories of `SwatchesPanel`. -use super::{SwatchLibrary, SwatchesPanel, SwatchesState}; +use super::{SwatchKey, SwatchLibrary, SwatchesPanel, SwatchesState}; +use crate::palette::{SwatchColor, SwatchEntry, SwatchGroup, SwatchPaint}; +use craft_theme::Srgba; +use craft_ui::choice::SwatchFace; use craft_ui::contract::Bind; +use craft_ui::patterns::presets::ThumbInfo; +use craft_ui::primitives::{ContentPainterCx, IconSpec}; use craft_ui::testing::{Drive, StoryData, StoryOutput, story}; -use egui::Ui; +use egui::{Rect, Ui}; /// The panel over a library and state kept in the story's data; the reported edits run on the library, so the story stays /// interactive. @@ -25,3 +30,42 @@ fn swatches_panel(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { fn swatches_panel_empty(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { interactive(ui, data, "empty", SwatchLibrary { groups: Vec::new() }) } + +/// The host's own rows: its thumbnail painter on a gradient and a pattern entry, an icon trailing each of them, its tools, +/// and no footer. +#[story(SwatchesPanel<'static>, covers = [], drive = Drive::Never)] +fn swatches_panel_host_rows(ui: &mut Ui, data: &mut StoryData) -> StoryOutput { + let entries = vec![ + SwatchEntry::new("Red", SwatchColor::Rgb([1.0, 0.0, 0.0])), + SwatchEntry::with_paint("Sunset", SwatchPaint::Gradient), + SwatchEntry::with_paint("Dots", SwatchPaint::Pattern), + ]; + let start = SwatchLibrary::new(vec![SwatchGroup { name: "Host".to_owned(), entries }]); + let (library, state) = data.value("host-rows", (start, SwatchesState::default())); + let thumb = |cx: &ContentPainterCx<'_>, rect: Rect, info: ThumbInfo<'_, SwatchKey>| { + if let SwatchKey::Swatch(name) = info.key { + let color = match name.as_str() { + "Sunset" => Srgba::rgb(0.95, 0.5, 0.2), + "Dots" => Srgba::rgb(0.4, 0.4, 0.45), + _ => Srgba::rgb(1.0, 0.0, 0.0), + }; + SwatchFace::new(color).selected(info.selected).paint(cx, rect); + } + }; + let out = SwatchesPanel::new(&library.groups, Bind::bound(state), Srgba::rgb(0.2, 0.4, 0.6)) + .thumb(thumb) + .row_icons(|key| match key { + SwatchKey::Swatch(name) if name == "Sunset" => vec![(IconSpec::initial("G"), "Gradient".to_owned())], + SwatchKey::Swatch(name) if name == "Dots" => vec![(IconSpec::initial("P"), "Pattern".to_owned())], + _ => Vec::new(), + }) + .tools(|ui| { + ui.label("Host tools"); + }) + .footer(None) + .show(ui); + for edit in &out.edits { + library.apply(edit); + } + out.into() +}