diff --git a/crates/ui-egui/src/dialogs/shape_fill_ui.rs b/crates/ui-egui/src/dialogs/shape_fill_ui.rs index e7dedf83d4..de451cea8a 100644 --- a/crates/ui-egui/src/dialogs/shape_fill_ui.rs +++ b/crates/ui-egui/src/dialogs/shape_fill_ui.rs @@ -10,11 +10,11 @@ use std::sync::Arc; use craft::color_ui::ui::{ColorPickerDialog, PickedColor}; use craft::theme::Srgba; use craft::ui::dialog::DialogId; -use photocraft_color::Color; +use photocraft_color::{Color, ColorMode}; use photocraft_doc::{DocId, Document, Fill, LayerContent, LayerId}; use serde_json::{Value, json}; -use crate::color_picker_ui::{PickTarget, hex, rgb_hex}; +use crate::color_picker_ui::{PickTarget, hex, inks_model, inks_of, rgb_hex, same_inks}; use crate::{PhotocraftApp, color_picker_ui}; const COMMAND: &str = "shape.edit"; @@ -97,7 +97,8 @@ pub(crate) fn open(app: &mut PhotocraftApp) -> Option { let target = ShapeTarget { which: Paint::Fill, layer: Some(layer), document: Some(st.doc.id), tool: false, thumbnail: true, alpha: color.alpha, solid: true }; let start = Srgba::from_rgb_array(color.to_rgb()); - Some(color_picker_ui::open_for(app, "Color Picker (Solid Color)", start, None, PickTarget::Shape(target))) + let kept = (color.mode == ColorMode::Cmyk).then(|| inks_model(color.c)); + Some(color_picker_ui::open_for(app, "Color Picker (Solid Color)", start, kept, PickTarget::Shape(target))) } /// Opens the picker from a Fill or Stroke popover on `which` paint of shape `layer` (the @@ -124,13 +125,26 @@ pub(crate) fn open_paint(app: &mut PhotocraftApp, which: Paint, layer: Option "Color Picker (Fill Color)", Paint::Stroke => "Color Picker (Stroke Color)", }; - Some(color_picker_ui::open_for(app, label, Srgba::from_rgb_array(start.to_rgb()), None, PickTarget::Shape(target))) + let kept = if start.mode == ColorMode::Cmyk { + Some(inks_model(start.c)) + } else if layer.is_none() { + app.session.tools.picked_role_cmyk(usize::from(which == Paint::Stroke)).map(inks_model) + } else { + None + }; + Some(color_picker_ui::open_for(app, label, Srgba::from_rgb_array(start.to_rgb()), kept, PickTarget::Shape(target))) } -/// The picker's colour as `shape.edit` stores it: RGB with the original paint's alpha. -fn picked(t: &ShapeTarget, p: &PickedColor) -> Color { +/// Keep explicit inks in CMYK documents and retain the original paint's alpha. +fn picked(t: &ShapeTarget, p: &PickedColor, mode: ColorMode) -> Color { + let alpha = clamp_alpha(t.alpha); + if mode == ColorMode::Cmyk + && let Some(c) = inks_of(p) + { + return Color { mode, c, alpha }; + } let [r, g, b] = p.color.to_rgb_array(); - Color::rgba(r, g, b, clamp_alpha(t.alpha)) + Color::rgba(r, g, b, alpha) } /// The target layer, unless the dialog has none or is stale (another document is active, or the @@ -156,8 +170,10 @@ fn target(app: &PhotocraftApp, t: &ShapeTarget, idx: Option) -> Result Result { let layer = target(app, t, app.session.active_index())?; - let color = picked(t, picker); - let rgba = [color.c[0], color.c[1], color.c[2], color.alpha]; + let mode = app.session.active().map_or(ColorMode::Rgb, |st| st.doc.mode); + let color = picked(t, picker, mode); + let [r, g, b] = picker.color.to_rgb_array(); + let rgba = [r, g, b, color.alpha]; // A locked shape refuses the edit: check first, so the next shape's colour isn't changed either. if let Some(layer) = layer && app.session.active().is_some_and(|st| { @@ -169,27 +185,32 @@ pub(crate) fn confirm(app: &mut PhotocraftApp, t: &ShapeTarget, picker: &PickedC } let result = match layer { None => json!({"color": rgba}), - Some(layer) => edit_paint(app, t, layer, rgba)?, + Some(layer) => edit_paint(app, t, layer, color)?, }; // Only once the shape took the colour (or there is none): a refused edit changes nothing. if t.tool { - crate::shape_options::set_tool_paint(app, t.which == Paint::Stroke, crate::shape_paint_ui::PaintChange::Color(rgba))?; + crate::shape_options::set_tool_paint_with_inks(app, t.which == Paint::Stroke, crate::shape_paint_ui::PaintChange::Color(rgba), inks_of(picker))?; } Ok(result) } -/// The `shape.edit` that gives `layer`'s paint the colour `rgba`; an unchanged solid colour keeps the -/// stored one as it is. -fn edit_paint(app: &mut PhotocraftApp, t: &ShapeTarget, layer: LayerId, rgba: [f32; 4]) -> Result { +/// Commit one paint edit, preserving an unchanged solid colour at its original precision. +fn edit_paint(app: &mut PhotocraftApp, t: &ShapeTarget, layer: LayerId, color: Color) -> Result { let which = t.which; - let rgb_now = hex([rgba[0], rgba[1], rgba[2]]); - let same = - app.session.active().and_then(|st| paint_of(&st.doc, layer, which)).is_some_and(|p| matches!(p, Some(Fill::Solid(c)) if hex(c.to_rgb()) == rgb_now)); + let same = app.session.active().and_then(|st| paint_of(&st.doc, layer, which)).is_some_and(|paint| { + let Some(Fill::Solid(original)) = paint else { return false }; + if color.mode == ColorMode::Cmyk { + original.mode == ColorMode::Cmyk && same_inks(original.c, color.c) + } else { + hex(original.to_rgb()) == hex(color.to_rgb()) + } + }); if t.solid && same { return Ok(json!({"layer": layer.0, "unchanged": true})); } + let color = if color.mode == ColorMode::Cmyk { json!(color) } else { json!([color.c[0], color.c[1], color.c[2], color.alpha]) }; let paint = match which { - Paint::Fill => json!(rgba), + Paint::Fill => color, Paint::Stroke => { let width = app .session @@ -200,7 +221,7 @@ fn edit_paint(app: &mut PhotocraftApp, t: &ShapeTarget, layer: LayerId, rgba: [f _ => None, }) .unwrap_or(0.0); - json!({"color": rgba, "width": crate::vector_ui::enabled_stroke_width(width)}) + json!({"color": color, "width": crate::vector_ui::enabled_stroke_width(width)}) } }; let mut p = json!({"layer": layer.0}); @@ -221,13 +242,13 @@ pub(crate) fn display_doc(app: &mut PhotocraftApp, idx: usize) -> Option<(Arc Option<(Arc(dialog).unwrap().set_color(cyan); + ok(&mut app, dialog).unwrap(); + let inks = [1.0, 0.0, 0.0, 0.0]; + assert_eq!(fill(&app, id), Some(Fill::Solid(Color { mode: ColorMode::Cmyk, c: inks, alpha: 1.0 }))); + + let dialog = open(&mut app).unwrap(); + assert_eq!(inks_of(&testing::current(&app, dialog).unwrap()), Some(inks)); + ok(&mut app, dialog).unwrap(); + assert_eq!(fill(&app, id), Some(Fill::Solid(Color { mode: ColorMode::Cmyk, c: inks, alpha: 1.0 }))); +} diff --git a/crates/ui-egui/src/tools/shape_options.rs b/crates/ui-egui/src/tools/shape_options.rs index cbab4d959b..54106450d2 100644 --- a/crates/ui-egui/src/tools/shape_options.rs +++ b/crates/ui-egui/src/tools/shape_options.rs @@ -453,6 +453,10 @@ pub(crate) fn pen_paint_swatches(app: &mut PhotocraftApp, ui: &mut egui::Ui) { /// Tool-bar paint changes affect the next shape; Properties edits the selected shape instead. pub(crate) fn set_tool_paint(app: &mut PhotocraftApp, stroke: bool, change: PaintChange) -> Result<(), String> { + set_tool_paint_with_inks(app, stroke, change, None) +} + +pub(crate) fn set_tool_paint_with_inks(app: &mut PhotocraftApp, stroke: bool, change: PaintChange, inks: Option<[f32; 4]>) -> Result<(), String> { // A colour takes the place of a gradient; No Color keeps it for when the paint comes back. let o = &mut app.ui.tool_options; let gradient = if stroke { &mut o.shape_stroke_gradient } else { &mut o.shape_fill_gradient }; @@ -462,7 +466,12 @@ pub(crate) fn set_tool_paint(app: &mut PhotocraftApp, stroke: bool, change: Pain PaintChange::None => {} } if let PaintChange::Color(color) = change { - app.run("tools.setColors", if stroke { json!({"background": color}) } else { json!({"foreground": color}) })?; + let role = if stroke { "background" } else { "foreground" }; + let mut params = json!({role: color}); + if let Some(inks) = inks { + params[format!("{role}Cmyk")] = json!(inks); + } + app.run("tools.setColors", params)?; } if stroke { app.ui.tool_options.stroke_width = if change == PaintChange::None { 0.0 } else { enabled_stroke_width(app.ui.tool_options.stroke_width) }; diff --git a/crates/ui-egui/src/tools/vector_ui/options.rs b/crates/ui-egui/src/tools/vector_ui/options.rs index ceb8ffaaee..6c91ebeff0 100644 --- a/crates/ui-egui/src/tools/vector_ui/options.rs +++ b/crates/ui-egui/src/tools/vector_ui/options.rs @@ -358,6 +358,7 @@ pub(super) fn selected_shape(session: &photocraft_engine::Session) -> Option photocraft_doc::Fill { photocraft_doc::Fill::Solid(photocraft_doc::Color::rgba(c[0], c[1], c[2], c[3])) } diff --git a/crates/ui-egui/src/tools/vector_ui/paint_tests.rs b/crates/ui-egui/src/tools/vector_ui/paint_tests.rs index 3c1b44863e..a7ebc4a4d3 100644 --- a/crates/ui-egui/src/tools/vector_ui/paint_tests.rs +++ b/crates/ui-egui/src/tools/vector_ui/paint_tests.rs @@ -11,7 +11,7 @@ use egui_kittest::{ Harness, kittest::{NodeT, Queryable}, }; -use photocraft_doc::ShapeLayer; +use photocraft_doc::{Fill, ShapeLayer}; use photocraft_engine::presets::PresetsExt; fn app(mode: &str, depth: u32) -> Box { @@ -325,6 +325,34 @@ fn float_paints_match_preview_creation_native_roundtrip_and_document_depth() { } } +#[test] +fn cmyk_shape_keeps_native_fill_and_stroke_inks() { + use photocraft_color::{Color, ColorMode}; + use photocraft_engine::sample_cmds::{SampleLayers, sample_cmyk_at}; + + let mut app = app("cmyk", 8); + let cyan = [1.0, 0.0, 0.0, 0.0]; + let magenta = [0.0, 1.0, 0.0, 0.0]; + app.run( + "tools.setColors", + json!({ + "foreground": [0.0, 0.6, 0.9, 1.0], "foregroundCmyk": cyan, + "background": [0.9, 0.0, 0.5, 1.0], "backgroundCmyk": magenta, + }), + ) + .unwrap(); + app.ui.tool_options.shape_fill = true; + app.ui.tool_options.stroke_width = 8.0; + draw(&mut app, Tool::Rectangle, [20.0, 20.0], [100.0, 80.0]); + + let solid = |c| Fill::Solid(Color { mode: ColorMode::Cmyk, c, alpha: 1.0 }); + let shape = shape(&app); + assert_eq!(shape.fill, Some(solid(cyan))); + assert_eq!(shape.stroke.as_ref().unwrap().paint, solid(magenta)); + let state = app.session.active().unwrap(); + assert_eq!(sample_cmyk_at(&state.doc, state.active_layer, 60.0, 50.0, 1, None, SampleLayers::Current), Some(cyan)); +} + #[test] fn open_pen_uses_selected_stroke_color_and_width() { let mut app = app("rgb", 32); diff --git a/crates/ui-egui/src/tools/vector_ui/shapes.rs b/crates/ui-egui/src/tools/vector_ui/shapes.rs index a716dbc973..5825133283 100644 --- a/crates/ui-egui/src/tools/vector_ui/shapes.rs +++ b/crates/ui-egui/src/tools/vector_ui/shapes.rs @@ -4,7 +4,7 @@ use craft::draw::geometry::shape::ShapeGeometry; use craft::draw::ui::shape_drag::{BoxConstraints, ShapeKind}; use craft::keymap::Mods; -use super::options::{draws_path, solid_paint}; +use super::options::draws_path; use super::{Color32, PhotocraftApp, Tool, Value, json, paint_param}; use crate::state::ToolOptions; @@ -56,26 +56,39 @@ pub(super) fn open_pen_stroke_param(app: &PhotocraftApp) -> Value { } let mut fallback = app.ui.tool_options.shape_stroke.params(); fallback["width"] = json!(1.0); - fallback["color"] = json!(app.session.tools.foreground); + fallback["color"] = solid_paint_param(tool_solid_color(app, false)); fallback } /// The paint the next shape's fill (`stroke` false) or stroke takes: the options bar's gradient, /// else the foreground / background colour. pub(super) fn tool_paint(app: &PhotocraftApp, stroke: bool) -> photocraft_doc::Fill { - let (gradient, color) = tool_paint_source(app, stroke); - gradient.clone().unwrap_or_else(|| solid_paint(color)) + tool_gradient(app, stroke).clone().unwrap_or_else(|| photocraft_doc::Fill::Solid(tool_solid_color(app, stroke))) } /// [`tool_paint`] as `shape.create` takes it. fn tool_paint_param(app: &PhotocraftApp, stroke: bool) -> Value { - let (gradient, color) = tool_paint_source(app, stroke); - gradient.as_ref().map_or_else(|| json!(color), paint_param) + tool_gradient(app, stroke).as_ref().map_or_else(|| solid_paint_param(tool_solid_color(app, stroke)), paint_param) } -fn tool_paint_source(app: &PhotocraftApp, stroke: bool) -> (&Option, [f32; 4]) { - let o = &app.ui.tool_options; - if stroke { (&o.shape_stroke_gradient, app.session.tools.background) } else { (&o.shape_fill_gradient, app.session.tools.foreground) } +fn tool_gradient(app: &PhotocraftApp, stroke: bool) -> &Option { + let options = &app.ui.tool_options; + if stroke { &options.shape_stroke_gradient } else { &options.shape_fill_gradient } +} + +fn solid_paint_param(color: photocraft_color::Color) -> Value { + if color.mode == photocraft_color::ColorMode::Cmyk { json!(color) } else { json!([color.c[0], color.c[1], color.c[2], color.alpha]) } +} + +fn tool_solid_color(app: &PhotocraftApp, stroke: bool) -> photocraft_color::Color { + use photocraft_color::{Color, ColorMode}; + let [r, g, b, alpha] = if stroke { app.session.tools.background } else { app.session.tools.foreground }; + if app.session.active().is_some_and(|st| st.doc.mode == ColorMode::Cmyk) + && let Some(c) = app.session.tools.picked_role_cmyk(usize::from(stroke)) + { + return Color { mode: ColorMode::Cmyk, c, alpha }; + } + Color::rgba(r, g, b, alpha) } /// A Line-tool drag snapped as Photoshop's Align Edges (on by default) does: the ends on whole diff --git a/crates/vector/src/lib.rs b/crates/vector/src/lib.rs index b3d0da0916..069f6eb290 100644 --- a/crates/vector/src/lib.rs +++ b/crates/vector/src/lib.rs @@ -258,6 +258,8 @@ pub enum Paint { None, /// Straight RGBA. Solid([f32; 4]), + /// Straight CMYK and a separate alpha. + Cmyk([f32; 4], f32), Gradient { /// Colour stops sorted by location (straight RGBA). stops: Vec<(f32, [f32; 4])>, @@ -290,6 +292,7 @@ impl Paint { [v[0], v[1], v[2], c.alpha] }; match f { + Fill::Solid(c) if c.mode == ColorMode::Cmyk => Paint::Cmyk(c.c, c.alpha), Fill::Solid(c) => Paint::Solid(rgba(c)), // No `..` here on purpose: a new gradient field must fail to compile until the // shape renderer honours it (the same sentinel the document/compositor pair uses). @@ -319,6 +322,10 @@ impl Paint { match self { Paint::None => [0.0; 4], Paint::Solid(c) => *c, + Paint::Cmyk(inks, alpha) => { + let [r, g, b] = photocraft_color::convert::cmyk_to_rgb(*inks); + [r, g, b, *alpha] + } Paint::Gradient { stops, midpoints, opacity_stops, style, layout, reverse, dither: dith, frame } => { let t = gradient_t(*style, layout.0, layout.1, *reverse, layout.2, *frame, x, y); let mut c = sample_stops(stops, midpoints, opacity_stops, t); @@ -329,6 +336,14 @@ impl Paint { } } } + fn cmyka_at(&self, x: f64, y: f64) -> [f32; 5] { + if let Self::Cmyk([c, m, y, k], alpha) = *self { + return [c, m, y, k, alpha]; + } + let [r, g, b, alpha] = self.at(x, y); + let [c, m, y, k] = photocraft_color::convert::rgb_to_cmyk([r, g, b]); + [c, m, y, k, alpha] + } } /// `(chord, diagonal)` gradient lengths over a `w × h` frame at `angle` (radians): Linear and @@ -635,16 +650,21 @@ impl CompiledShape { /// Straight RGBA for every pixel of `rect`. pub fn render_rgba(&self, rect: Rect) -> Vec<[f32; 4]> { + self.render_components(rect, Paint::at) + } + + fn render_components(&self, rect: Rect, at: impl Fn(&Paint, f64, f64) -> [f32; N]) -> Vec<[f32; N]> { let n = rect.width() as usize * rect.height() as usize; - let mut out = vec![[0.0f32; 4]; n]; + let mut out = vec![[0.0; N]; n]; + let alpha = N - 1; let w = rect.width() as usize; if let Some((r, paint)) = &self.fill { let cov = r.render(rect); for (i, (o, c)) in out.iter_mut().zip(&cov).enumerate() { if *c > 0.0 { let (x, y) = ((rect.x0 + (i % w) as i32) as f64 + 0.5, (rect.y0 + (i / w) as i32) as f64 + 0.5); - let mut p = paint.at(x, y); - p[3] *= c; + let mut p = at(paint, x, y); + p[alpha] *= c; *o = p; } } @@ -662,16 +682,16 @@ impl CompiledShape { continue; } let (x, y) = ((rect.x0 + (i % w) as i32) as f64 + 0.5, (rect.y0 + (i / w) as i32) as f64 + 0.5); - let s = paint.at(x, y); - let sa = s[3] * c * opacity; - let da = o[3]; + let s = at(paint, x, y); + let sa = s[alpha] * c * opacity; + let da = o[alpha]; let a = sa + da * (1.0 - sa); if a > 0.0 { - for k in 0..3 { + for k in 0..alpha { o[k] = (s[k] * sa + o[k] * da * (1.0 - sa)) / a; } } - o[3] = a; + o[alpha] = a; } } out @@ -684,7 +704,20 @@ impl CompiledShape { let Some(b) = self.bounds else { return s }; let area = b.intersect(&clip); let ch = format.channels(); + let native_cmyk = format.mode == ColorMode::Cmyk + && (self.fill.as_ref().is_some_and(|(_, paint)| matches!(paint, Paint::Cmyk(..))) + || self.stroke.as_ref().is_some_and(|(_, paint, _)| matches!(paint, Paint::Cmyk(..)))); render_bands(&mut s, area, &|band| { + if native_cmyk { + let mut cmyka = self.render_components(band, Paint::cmyka_at); + for pixel in &mut cmyka { + if pixel[4] <= 0.0 { + *pixel = [0.0; 5]; + } + } + let vals: Vec<_> = cmyka.iter().flat_map(|p| p[..ch].iter().copied()).collect(); + return band_tiles(band, &vals, ch, |px| if format.alpha { px[4] > 0.0 } else { px.iter().any(|v| *v != 0.0) }); + } let rgba = self.render_rgba(band); let mut vals = vec![0.0f32; rgba.len() * ch]; for (p, o) in rgba.iter().zip(vals.chunks_exact_mut(ch)) { diff --git a/crates/vector/src/tests.rs b/crates/vector/src/tests.rs index 481deff10d..1b7acaadc3 100644 --- a/crates/vector/src/tests.rs +++ b/crates/vector/src/tests.rs @@ -237,6 +237,26 @@ fn render_shape_formats_and_paint() { assert_eq!(s.content_bounds(), Rect::new(1, 1, 5, 5)); } +#[test] +fn native_cmyk_shape_drops_invisible_ink_in_alpha_free_output() { + let ink = [1.0, 0.0, 0.0, 0.0]; + let canvas = Rect::new(0, 0, 20, 20); + let format = PixelFormat::new(ColorMode::Cmyk, SampleType::U8, false); + let mut shape = ShapeLayer { + path: shapes::rect(2.0, 2.0, 10.0, 10.0), + fill: Some(Fill::Solid(Color { mode: ColorMode::Cmyk, c: ink, alpha: 0.0 })), + ..Default::default() + }; + + let transparent = render_shape(&shape, format, canvas); + assert_eq!(transparent.pixel(7, 7), vec![0.0; 4]); + assert!(transparent.content_bounds().is_empty()); + + shape.fill = Some(Fill::Solid(Color { mode: ColorMode::Cmyk, c: ink, alpha: 1.0 })); + let opaque = render_shape(&shape, format, canvas); + assert_eq!(opaque.pixel(7, 7), ink); +} + #[test] fn gradient_fill_spans_bounds() { let sh = ShapeLayer {