PhotoCraft: An open-source, photo editor written by scratch in pure Rust
Color: a picked colour recolours the selected type and shapes, as in Photoshop
bazmarth2fc221e66ba3
diff --git a/crates/ui-egui/src/apply_color.rs b/crates/ui-egui/src/apply_color.rsnew file mode 100644index 000000000..ce51b23fe--- /dev/null+++ b/crates/ui-egui/src/apply_color.rs@@ -0,0 +1,94 @@+//! A new foreground colour recolours the selected objects, as in Photoshop: the Color panel, the+//! Swatches panel and the Color Picker set the foreground, and depending on the tool in hand it+//! also goes to what is selected:+//!+//! * characters selected while editing type: those characters (`type_tool::foreground_changed`);+//! * a Type tool, not editing: the colour of every selected type layer (`type.setStyle`);+//! * a shape tool, a Pen or a path selection tool: the fill of every selected shape layer+//! (`shape.edit` with `fill`);+//! * any other tool (Move, the brushes…): nothing, only the foreground changes.+//!+//! One pick is one history step for all the layers it recolours; a drag in the Color panel's field+//! or sliders is one step too.++use egui::Context;+use photocraft_doc::LayerContent;+use serde_json::json;++use crate::PhotocraftApp;+use crate::state::Tool;++fn hex(c: [f32; 4]) -> String {+ let b = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8;+ format!("#{:02x}{:02x}{:02x}", b(c[0]), b(c[1]), b(c[2]))+}++/// Does a new foreground recolour selected shape layers with `tool`?+fn recolours_shapes(tool: Tool) -> bool {+ crate::vector_ui::is_shape_tool(tool)+ || matches!(+ tool,+ Tool::PathSelection+ | Tool::DirectSelection+ | Tool::Pen+ | Tool::FreeformPen+ | Tool::CurvaturePen+ | Tool::AddAnchorPoint+ | Tool::DeleteAnchorPoint+ | Tool::ConvertPoint+ )+}++/// Is the pointer still held from an earlier frame (a drag in the Color panel), so this pick+/// joins the previous one's history step?+pub fn continuing(ctx: &Context) -> bool {+ ctx.input(|i| i.pointer.any_down() && !i.pointer.any_pressed())+}++/// The foreground colour just changed through the Color panel, the Swatches panel or the Color+/// Picker: recolour what is selected, as the tool in hand says (see the module docs).+/// `continuing` (a drag still in progress) joins the previous pick's history step.+pub fn foreground_changed(app: &mut PhotocraftApp, continuing: bool) {+ // Editing type: the selected characters, in the editing session's step; nothing else.+ if app.ui.text_edit.is_some() {+ crate::type_tool::foreground_changed(app);+ return;+ }+ let tool = app.ui.tool;+ let type_tool = tool.is_type() && !tool.is_type_mask();+ if !type_tool && !recolours_shapes(tool) {+ return;+ }+ let Some(st) = app.session.active() else { return };+ let (texts, shapes): (Vec<u64>, Vec<u64>) = {+ let selected: Vec<_> = st.selected_layers().into_iter().filter_map(|id| st.doc.layer(id)).collect();+ let pick = |want: fn(&LayerContent) -> bool| selected.iter().filter(|l| want(&l.content)).map(|l| l.id.0).collect::<Vec<_>>();+ (pick(|c| matches!(c, LayerContent::Text(_))), pick(|c| matches!(c, LayerContent::Shape(_))))+ };+ let targets = if type_tool { &texts } else { &shapes };+ if targets.is_empty() {+ return;+ }+ let key = match app.ui.apply_color_key.clone().filter(|_| continuing) {+ Some(k) => k,+ None => {+ let k = format!("apply-color-{}", app.ui.alloc_id());+ app.ui.apply_color_key = Some(k.clone());+ k+ }+ };+ let color = hex(app.session.tools.foreground);+ let result = if type_tool {+ app.run("type.setStyle", json!({"layers": texts, "color": color, "coalesce": key})).map(|_| ())+ } else {+ shapes.iter().try_for_each(|id| app.run("shape.edit", json!({"layer": id, "fill": color, "coalesce": key})).map(|_| ()))+ };+ if let Err(e) = result {+ app.ui.status = e;+ app.ui.status_error = true;+ }+}++#[cfg(test)]+#[path = "apply_color_tests.rs"]+mod tests;diff --git a/crates/ui-egui/src/apply_color_tests.rs b/crates/ui-egui/src/apply_color_tests.rsnew file mode 100644index 000000000..0a0accb6b--- /dev/null+++ b/crates/ui-egui/src/apply_color_tests.rs@@ -0,0 +1,144 @@+//! A new foreground colour recolours the selected type or shape layers, as the tool in hand says.++use photocraft_doc::{Fill, LayerContent, LayerId};+use serde_json::json;++use crate::PhotocraftApp;+use crate::state::Tool;++const RED: [f32; 4] = [1.0, 0.0, 0.0, 1.0];++/// Two type layers and two shape layers (black, the default colours), all selected.+fn app(tool: Tool) -> (PhotocraftApp, Vec<LayerId>, Vec<LayerId>) {+ let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", json!({"width": 300, "height": 200})).unwrap();+ app.sync_views();+ app.run("tools.setColors", json!({"foreground": "#000000"})).unwrap();+ let mut texts = Vec::new();+ for y in [40, 90] {+ texts.push(LayerId(app.run("type.create", json!({"x": 20, "y": y, "text": "Hello", "size": 20})).unwrap()["layer"].as_u64().unwrap()));+ }+ let mut shapes = Vec::new();+ for x in [150, 220] {+ app.run("shape.create", json!({"kind": "rect", "rect": [x, 20, 50, 50], "fill": "#000000"})).unwrap();+ shapes.push(app.session.active().unwrap().active_layer.unwrap());+ }+ for id in texts.iter().chain(&shapes) {+ app.run("layer.select", json!({"layer": id.0, "mode": "add"})).unwrap();+ }+ app.ui.tool = tool;+ (app, texts, shapes)+}++fn text_rgb(app: &PhotocraftApp, id: LayerId) -> [f32; 3] {+ match &app.session.active().unwrap().doc.layer(id).unwrap().content {+ LayerContent::Text(t) => {+ let c = t.char_runs().into_iter().next().map_or(t.color, |r| r.style.color);+ [c.c[0], c.c[1], c.c[2]]+ }+ _ => panic!("type layer"),+ }+}++fn fill_rgb(app: &PhotocraftApp, id: LayerId) -> Option<[f32; 3]> {+ match &app.session.active().unwrap().doc.layer(id).unwrap().content {+ LayerContent::Shape(sh) => match &sh.fill {+ Some(Fill::Solid(c)) => Some([c.c[0], c.c[1], c.c[2]]),+ _ => None,+ },+ _ => panic!("shape layer"),+ }+}++fn red(c: [f32; 3]) -> bool {+ (c[0] - 1.0).abs() < 1e-3 && c[1].abs() < 1e-3 && c[2].abs() < 1e-3+}++fn steps(app: &PhotocraftApp) -> usize {+ app.session.active().unwrap().history.entries().len()+}++fn pick(app: &mut PhotocraftApp, c: [f32; 4], continuing: bool) {+ app.session.tools.foreground = c;+ super::foreground_changed(app, continuing);+}++#[test]+fn a_type_tool_recolours_every_selected_type_layer_in_one_step() {+ for tool in [Tool::Type, Tool::VerticalType] {+ let (mut app, texts, shapes) = app(tool);+ let n = steps(&app);+ pick(&mut app, RED, false);+ assert!(texts.iter().all(|id| red(text_rgb(&app, *id))), "{tool:?}");+ assert!(shapes.iter().all(|id| !red(fill_rgb(&app, *id).unwrap())), "{tool:?}: shapes keep their fill");+ assert_eq!(steps(&app), n + 1, "one history step");+ assert!(app.session.undo());+ assert!(texts.iter().all(|id| !red(text_rgb(&app, *id))));+ }+}++#[test]+fn shape_and_path_tools_recolour_every_selected_shape_fill_in_one_step() {+ for tool in [Tool::Rectangle, Tool::Polygon, Tool::PathSelection, Tool::DirectSelection, Tool::Pen, Tool::CurvaturePen] {+ let (mut app, texts, shapes) = app(tool);+ let n = steps(&app);+ pick(&mut app, RED, false);+ assert!(shapes.iter().all(|id| fill_rgb(&app, *id).is_some_and(red)), "{tool:?}");+ assert!(texts.iter().all(|id| !red(text_rgb(&app, *id))), "{tool:?}: type keeps its colour");+ assert_eq!(steps(&app), n + 1, "{tool:?}: one history step for both layers");+ }+}++#[test]+fn other_tools_only_change_the_foreground() {+ for tool in [Tool::Move, Tool::Brush, Tool::RectMarquee, Tool::Eyedropper, Tool::HorizontalTypeMask] {+ let (mut app, texts, shapes) = app(tool);+ let n = steps(&app);+ pick(&mut app, RED, false);+ assert_eq!(app.session.tools.foreground, RED);+ assert!(texts.iter().all(|id| !red(text_rgb(&app, *id))) && shapes.iter().all(|id| !red(fill_rgb(&app, *id).unwrap())), "{tool:?}");+ assert_eq!(steps(&app), n, "{tool:?}: nothing recorded");+ }+}++#[test]+fn a_color_panel_drag_is_one_history_step_and_a_new_pick_another() {+ let (mut app, _, shapes) = app(Tool::Rectangle);+ let n = steps(&app);+ pick(&mut app, [0.2, 0.0, 0.0, 1.0], false);+ pick(&mut app, [0.6, 0.0, 0.0, 1.0], true);+ pick(&mut app, RED, true);+ assert!(fill_rgb(&app, shapes[0]).is_some_and(red));+ assert_eq!(steps(&app), n + 1, "the drag is one step");+ pick(&mut app, [0.0, 0.0, 1.0, 1.0], false);+ assert_eq!(steps(&app), n + 2, "a new pick is another");+}++#[test]+fn a_swatch_and_the_color_picker_go_through_it() {+ let (mut app, _, shapes) = app(Tool::Rectangle);+ let same = |app: &PhotocraftApp, id: LayerId| {+ let f = app.session.tools.foreground;+ fill_rgb(app, id).is_some_and(|c| (0..3).all(|i| (c[i] - f[i]).abs() < 1e-3))+ };+ // A swatch from the default library (the first one that isn't black).+ let names = app.run("swatches.list", json!({})).unwrap();+ let name = names["groups"]+ .as_array()+ .into_iter()+ .flatten()+ .flat_map(|g| g["swatches"].as_array().cloned().unwrap_or_default())+ .find(|w| w["hex"].as_str().is_some_and(|h| h != "#000000"))+ .and_then(|w| w["name"].as_str().map(str::to_string))+ .expect("a default swatch");+ crate::swatches_ui::use_swatch(&mut app, &name, false);+ assert_ne!(app.session.tools.foreground, [0.0, 0.0, 0.0, 1.0]);+ assert!(shapes.iter().all(|id| same(&app, *id)), "the swatch recoloured the shapes");+ // The Color Picker's OK for the foreground.+ let mut f = serde_json::Map::new();+ f.insert("__colorPicker".into(), json!("foreground"));+ f.insert("color".into(), json!("#0000ff"));+ crate::color_picker_ui::confirm(&mut app, &f).unwrap();+ assert_eq!(app.session.tools.foreground, [0.0, 0.0, 1.0, 1.0]);+ assert!(shapes.iter().all(|id| same(&app, *id)), "the picker recoloured the shapes");+}diff --git a/crates/ui-egui/src/color_picker_ui.rs b/crates/ui-egui/src/color_picker_ui.rsindex 09a3ce8d4..f275fcf4d 100644--- a/crates/ui-egui/src/color_picker_ui.rs+++ b/crates/ui-egui/src/color_picker_ui.rs@@ -824,7 +824,7 @@ pub fn confirm(app: &mut PhotocraftApp, f: &Map<String, Value>) -> Result<Value,}let r = app.run("tools.setColors", params)?;if target == "foreground" {- crate::type_tool::foreground_changed(app);+ crate::apply_color::foreground_changed(app, false);}Ok(r)}diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex d8d091314..4f469ee41 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -22,6 +22,7 @@ pub mod adjust_ui;mod alt_grab;pub mod analysis_ui;pub mod anchor_tools;+pub mod apply_color;pub mod artboard_tool;pub mod artboard_ui;pub(crate) mod background_redraw;diff --git a/crates/ui-egui/src/panels.rs b/crates/ui-egui/src/panels.rsindex 82c2b667a..bdebea956 100644--- a/crates/ui-egui/src/panels.rs+++ b/crates/ui-egui/src/panels.rs@@ -2132,7 +2132,7 @@ fn hsb_sliders(app: &mut PhotocraftApp, ui: &mut egui::Ui) {if changed {app.session.tools.foreground = hsva_srgb(hsva);ui.data_mut(|d| d.insert_temp(key, hsva));- crate::type_tool::foreground_changed(app);+ crate::apply_color::foreground_changed(app, crate::apply_color::continuing(ui.ctx()));}}@@ -3690,7 +3690,7 @@ fn color_field(app: &mut PhotocraftApp, ui: &mut egui::Ui) {app.session.tools.background = hsva_srgb(hsva);} else {app.session.tools.foreground = hsva_srgb(hsva);- crate::type_tool::foreground_changed(app);+ crate::apply_color::foreground_changed(app, crate::apply_color::continuing(ui.ctx()));}ui.data_mut(|d| d.insert_temp(key, (hsva.h, hsva.s)));}@@ -3703,7 +3703,7 @@ fn color_field(app: &mut PhotocraftApp, ui: &mut egui::Ui) {app.session.tools.background = c;} else {app.session.tools.foreground = c;- crate::type_tool::foreground_changed(app);+ crate::apply_color::foreground_changed(app, crate::apply_color::continuing(ui.ctx()));}// Keep the hue for greys, so the field marker doesn't jump to red; the saturation with// it, so a later black lands on the corner it was last dragged to (#3228).diff --git a/crates/ui-egui/src/state.rs b/crates/ui-egui/src/state.rsindex aeefb3ecb..b2c0ee575 100644--- a/crates/ui-egui/src/state.rs+++ b/crates/ui-egui/src/state.rs@@ -1152,6 +1152,9 @@ pub struct UiState {/// Direct Selection tool: selected anchors and the drag in progress (#790).#[serde(default)]pub direct_selection: crate::direct_select::DirectSelection,+ /// The history step a Color panel drag recolouring the selection joins (`apply_color`).+ #[serde(skip)]+ pub apply_color_key: Option<String>,/// A live rectangle's corner radius widget being dragged (TOOL-214-12).#[serde(skip)]pub corner_radius: Option<crate::corner_radius::Drag>,@@ -1344,6 +1347,7 @@ impl Default for UiState {pen: None,stroke_editor: None,direct_selection: Default::default(),+ apply_color_key: None,corner_radius: None,selected_path: None,panels: Panels::default(),diff --git a/crates/ui-egui/src/swatches_ui.rs b/crates/ui-egui/src/swatches_ui.rsindex a18ddee64..6013ec779 100644--- a/crates/ui-egui/src/swatches_ui.rs+++ b/crates/ui-egui/src/swatches_ui.rs@@ -51,8 +51,9 @@ fn colors(app: &PhotocraftApp, ctx: &egui::Context) -> Arc<Vec<Vec<Color32>>> {pub fn use_swatch(app: &mut PhotocraftApp, name: &str, background: bool) {let target = if background { "background" } else { "foreground" };if run(app, "swatches.use", json!({"swatch": name, "target": target})).is_some() && !background {- // Clicking a swatch while characters are selected recolours them (#364).- crate::type_tool::foreground_changed(app);+ // Clicking a swatch recolours the selected characters (#364), or the selected type or+ // shape layers with a Type, shape or Pen tool, as in Photoshop.+ crate::apply_color::foreground_changed(app, false);}}diff --git a/docs/ui-parity.md b/docs/ui-parity.mdindex 7fbe8932c..e22aee348 100644--- a/docs/ui-parity.md+++ b/docs/ui-parity.md@@ -1,6 +1,6 @@# UI parity: tools, handles, modifiers and feel-> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-14 · **Change:** minor (guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed) · **Target:** Adobe Photoshop 2026+> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-14 · **Change:** minor (a picked colour recolours the selected type and shapes; guide keys and clicks; menu bar from the keyboard, #4988; Crop tool Content-Aware Fill; on-canvas corner radius widgets, TOOL-214-12; Curvature Pen edits the active path; Clip Thumbnails to Layer Bounds; Pen ⇧ 45°; last selected tool restored at launch; Layers panel filter-type dropdown with Kind, Name and Mode, #5048; Free Transform box and marching ants follow the selection, #5297; History: the trash deletes the selected snapshot, rows drag onto the trash, #5324; smart filter reordering by drag; smart object perspective row corrected to done, #426; Free Transform H/V skew fields; toolbar tool shortcuts can be reassigned; ⇧-dragged guides land on ruler ticks; layer and selection keys; tool keys; spring-loaded tool letters; type formatting keys; Pen Auto Add/Delete, #4144; smart filter rows; stale missing-tool rows corrected: Color Replacement, Red Eye and the Add/Delete Anchor Point pair are live toolbar tools, Frame landed; no percentage changed) · **Target:** Adobe Photoshop 2026How PhotoCraft's direct manipulation compares with Photoshop 2026 (27.11.0): the toolbox, thehandles and modifier keys of each gesture, nudging, snapping, numeric precision, navigation,@@ -207,6 +207,7 @@ Paragraph; the rest open as in-app floating windows.| Drag panels to reorder and regroup | partial | #2272, #2305 || Docked resize pushes the neighbour | partial | #2573 || Color panel wheel and RGB/HSB/CMYK/Lab sliders | missing | UI-217-17, #2569 |+| A colour picked in the Color or Swatches panel or the Color Picker recolours the selection: selected characters while editing; every selected type layer with a Type tool; every selected shape's fill with a shape, Pen or path selection tool; only the foreground with other tools; one history step (a Color panel drag too) | done: `apply_color.rs`, `apply_color_tests.rs` | || Window size and dock width remembered | done | UI-217-2 || Command palette with recents | done | UI-217-7 || Menu bar from the keyboard: Alt / F10 focus the bar, ← → ↓ ↩ drive it, Alt+letter opens a menu, underlined mnemonics run items | done | `menu_keys.rs`, #4988; macOS uses the native bar |@@ -253,3 +254,4 @@ Paragraph; the rest open as in-app floating windows.| 2026-10-11 | minor | Pen ⇧ 45° done: ⇧-click puts the next anchor on the nearest 45° ray, ⇧-drag turns its handles in 45° steps (TOOL-214-10 done, #3751) || 2026-10-14 | minor | Last selected tool restored across launches; temporary overrides excluded, explicit Eraser choices retained, and final selection flushed on normal exit || 2026-10-13 | minor | Free Transform with a selection: the box is the selection's rectangle, and the marching ants follow it while it is transformed (#5297) |+| 2026-10-14 | minor | A colour picked in the Color or Swatches panel or the Color Picker recolours the selected type layers (Type tool) or shape fills (shape, Pen and path selection tools) |