diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 06e775c28e6..672e8a96e8b 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -4936,7 +4936,7 @@ pub(crate) fn layer_edges_rect(app: &PhotocraftApp, idx: usize) -> Option(key)).is_none() { - ui.data_mut(|d| d.insert_temp(key, Marker::Color(0))); + let key = strip_key(app, sink); + let selection_key = key.with("selection"); + if ui.data(|d| d.get_temp::(selection_key)).is_none() { + ui.data_mut(|d| d.insert_temp(selection_key, Marker::Color(0))); + } + let pending = match sink { + Sink::Layer(id) => app.gradient.panel.clone().filter(|(l, ..)| *l == id).map(|(_, _, p)| p), + Sink::Preset => app.gradient.preset_stop.clone(), + }; + let colors = (app.session.tools.foreground, app.session.tools.background); + match stop_strip(ui, key, &f, sink.midpoints(), pending.as_ref(), colors) { + Some(StopAction::Preview(p)) => match sink { + Sink::Layer(id) => app.gradient.panel = Some((id, cmds::STOP, sink.params(p))), + Sink::Preset => app.gradient.preset_stop = Some(p), + }, + Some(StopAction::Commit(p)) => { + match sink { + Sink::Layer(_) => app.gradient.panel = None, + Sink::Preset => app.gradient.preset_stop = None, + } + let selected = ui.data(|d| d.get_temp::(selection_key)); + let selection = selection_after_edit(&f, &p, selected); + if app.run(sink.cmd(), sink.params(p)).is_ok() + && let Some(marker) = selection + { + ui.data_mut(|d| d.insert_temp(selection_key, marker)); + } + } + Some(StopAction::Color(i)) => match sink { + Sink::Layer(id) => edit_stop_color(app, id, i), + Sink::Preset => preset_stop_color(app, i), + }, + None => {} } - stop_strip(app, ui, sink, f); properties_panel::stop_fields(app, ui, sink); } +/// A shared stop strip keeps previews local; its caller chooses the command or paint target. +pub(crate) enum StopAction { + Preview(Value), + Commit(Value), + Color(usize), +} + /// Keep selection on a stop after the engine sorts its new position. fn selection_after_edit(f: &Fill, p: &Value, previous: Option) -> Option { let Fill::Gradient { stops, opacity_stops, .. } = f else { return previous }; @@ -845,8 +881,8 @@ fn selection_after_edit(f: &Fill, p: &Value, previous: Option) -> Option Some(if opacity { Marker::Opacity(at) } else { Marker::Color(at) }) } -fn stop_strip(app: &mut PhotocraftApp, ui: &mut egui::Ui, sink: Sink, f: Fill) { - let Fill::Gradient { stops, .. } = &f else { return }; +fn stop_strip(ui: &mut egui::Ui, key: egui::Id, f: &Fill, midpoints: bool, pending: Option<&Value>, colors: ([f32; 4], [f32; 4])) -> Option { + let Fill::Gradient { stops, .. } = f else { return None }; let t = Tokens::get(ui.ctx()); let w = ui.available_width().max(120.0); let (outer, resp) = ui.allocate_exact_size(vec2(w, 58.0), Sense::click_and_drag()); @@ -857,12 +893,8 @@ fn stop_strip(app: &mut PhotocraftApp, ui: &mut egui::Ui, sink: Sink, f: Fill) { let x_of = |loc: f32| bar.left() + loc.clamp(0.0, 1.0) * bar.width(); let loc_of = |x: f32| ((x - bar.left()) / bar.width().max(1.0)).clamp(0.0, 1.0); // The ramp being shown (with a pending drag's edit applied). - let pending: Option = match sink { - Sink::Layer(id) => app.gradient.panel.clone().filter(|(l, ..)| *l == id).map(|(_, _, p)| p), - Sink::Preset => app.gradient.preset_stop.clone(), - }; - let (fg, bg) = (app.session.tools.foreground, app.session.tools.background); - let shown = pending.as_ref().and_then(|p| cmds::apply_stop(&f, p, fg, bg).ok()).unwrap_or_else(|| f.clone()); + let (fg, bg) = colors; + let shown = pending.and_then(|p| cmds::apply_stop(f, p, fg, bg).ok()).unwrap_or_else(|| f.clone()); let mut track_fill = shown.clone(); if let Fill::Gradient { reverse, .. } = &mut track_fill { // All markers address un-reversed positions; Reverse applies to the canvas output. @@ -880,7 +912,6 @@ fn stop_strip(app: &mut PhotocraftApp, ui: &mut egui::Ui, sink: Sink, f: Fill) { sorted.sort_by(|a, b| a.0.total_cmp(&b.0)); let mut ops: Vec<(f32, f32)> = if os.is_empty() { vec![(0.0, 1.0), (1.0, 1.0)] } else { os.clone() }; ops.sort_by(|a, b| a.0.total_cmp(&b.0)); - let key = strip_key(app, sink); let selection_key = key.with("selection"); let selected: Option = ui.data(|d| d.get_temp(selection_key)); let dragging: Option = ui.data(|d| d.get_temp(key)); @@ -901,7 +932,7 @@ fn stop_strip(app: &mut PhotocraftApp, ui: &mut egui::Ui, sink: Sink, f: Fill) { p.rect_filled(body, 1.0, color); p.rect_stroke(body, 1.0, Stroke::new(1.0, if sel { t.accent } else { t.text_dim }), StrokeKind::Outside); } - if sink.midpoints() { + if midpoints { for i in 0..sorted.len().saturating_sub(1) { let (a, b) = (sorted[i].0, sorted[i + 1].0); if b - a > 1e-3 { @@ -931,7 +962,7 @@ fn stop_strip(app: &mut PhotocraftApp, ui: &mut egui::Ui, sink: Sink, f: Fill) { if let Some(i) = sorted.iter().position(|(l, _)| (x_of(*l) - pos.x).abs() <= 6.0 && pos.y >= bar.bottom() + 3.0) { return Some(Marker::Color(i)); } - if !sink.midpoints() { + if !midpoints { return None; } return (0..sorted.len().saturating_sub(1)) @@ -954,6 +985,7 @@ fn stop_strip(app: &mut PhotocraftApp, ui: &mut egui::Ui, sink: Sink, f: Fill) { ui.data_mut(|d| d.insert_temp(selection_key, m)); } let dragging: Option = ui.data(|d| d.get_temp(key)); + let mut preview = None; if let (Some(m), Some(pos)) = (dragging, resp.interact_pointer_pos()) { let off = if pos.y > bar.bottom() + 28.0 || pos.y < bar.top() - 26.0 { 1.0 } else { 0.0 }; let loc = loc_of(pos.x); @@ -968,70 +1000,32 @@ fn stop_strip(app: &mut PhotocraftApp, ui: &mut egui::Ui, sink: Sink, f: Fill) { } }; if resp.dragged() { - match sink { - Sink::Layer(id) => app.gradient.panel = Some((id, cmds::STOP, sink.params(edit))), - Sink::Preset => app.gradient.preset_stop = Some(edit), - } + preview = Some(edit); } } if resp.drag_stopped() { ui.data_mut(|d| d.remove::(key)); - match sink { - Sink::Layer(_) => { - if let Some((_, cmd, p)) = app.gradient.panel.take() { - let selection = selection_after_edit(&f, &p, selected); - if app.run(cmd, p).is_ok() - && let Some(marker) = selection - { - ui.data_mut(|d| d.insert_temp(selection_key, marker)); - } - } - } - Sink::Preset => { - if let Some(p) = app.gradient.preset_stop.take() { - let selection = selection_after_edit(&f, &p, selected); - if app.run(sink.cmd(), p).is_ok() - && let Some(marker) = selection - { - ui.data_mut(|d| d.insert_temp(selection_key, marker)); - } - } - } - } - return; + return preview.or_else(|| pending.cloned()).map(StopAction::Commit); } if resp.double_clicked() && let Some(pos) = resp.interact_pointer_pos() && let Some(Marker::Color(i)) = hit(pos) { ui.data_mut(|d| d.insert_temp(selection_key, Marker::Color(i))); - match sink { - Sink::Layer(id) => edit_stop_color(app, id, i), - Sink::Preset => preset_stop_color(app, i), - } - return; + return Some(StopAction::Color(i)); } if resp.clicked() && let Some(pos) = resp.interact_pointer_pos() { if let Some(marker) = hit(pos) { ui.data_mut(|d| d.insert_temp(selection_key, marker)); - return; + return None; } let loc = loc_of(pos.x); - let opacity = pos.y < bar.center().y; - let p = if opacity { - sink.params(json!({"action": "add", "kind": "opacity", "location": loc})) - } else { - sink.params(json!({"action": "add", "location": loc})) - }; - let selection = selection_after_edit(&f, &p, selected); - if app.run(sink.cmd(), p).is_ok() - && let Some(marker) = selection - { - ui.data_mut(|d| d.insert_temp(selection_key, marker)); - } + let p = if pos.y < bar.center().y { json!({"action": "add", "kind": "opacity", "location": loc}) } else { json!({"action": "add", "location": loc}) }; + return Some(StopAction::Commit(p)); } + preview.map(StopAction::Preview) } #[cfg(test)] diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 5ca970ca573..dee51de9bc2 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -190,6 +190,8 @@ pub mod select_mask_view; pub mod served_fonts; pub mod shape_dialog; pub(crate) mod shape_fill_ui; +mod shape_options; +mod shape_paint_ui; pub mod shape_stroke_ui; pub mod shortcut_dispatch; pub mod shortcuts; diff --git a/crates/ui-egui/src/move_ui.rs b/crates/ui-egui/src/move_ui.rs index f9e5dd75825..2cbac2fb5ed 100644 --- a/crates/ui-egui/src/move_ui.rs +++ b/crates/ui-egui/src/move_ui.rs @@ -174,7 +174,7 @@ fn with_descendants(doc: &Document, ids: &[LayerId]) -> Vec { /// offset of the latest Move drag frame drawn ([`display_doc`]) when the layer moves with the drag, /// so its Layer Edges outline moves in lockstep with its pixels (#2413). `None` when it shows /// where it is. -pub(crate) fn shown_offset(app: &PhotocraftApp, doc: DocId, revision: u64, id: LayerId) -> Option<(i32, i32)> { +pub(crate) fn shown_layer_offset(app: &PhotocraftApp, doc: DocId, revision: u64, id: LayerId) -> Option<(i32, i32)> { let p = app.move_preview.as_ref().filter(|p| p.doc == doc && p.revision == revision && !p.floating && p.shown.is_some())?; if !p.moving.contains(&id) { return None; diff --git a/crates/ui-egui/src/preset_panels.rs b/crates/ui-egui/src/preset_panels.rs index b52f1400d77..bac0591b744 100644 --- a/crates/ui-egui/src/preset_panels.rs +++ b/crates/ui-egui/src/preset_panels.rs @@ -261,22 +261,34 @@ pub(crate) fn pattern_picker(app: &PhotocraftApp, ui: &mut egui::Ui, selected: & resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, tl!("Patterns"))); let mut picked = None; egui::Popup::menu(&resp).show(|ui| { - ui.set_max_width(6.0 * (SWATCH + 4.0)); - ui.horizontal_wrapped(|ui| { - ui.spacing_mut().item_spacing = vec2(4.0, 4.0); - for p in pats { - let (r, cell) = ui.allocate_exact_size(vec2(SWATCH, SWATCH), Sense::click()); - ui.painter().image(pattern_texture(&ctx, p).id(), r, uv, Color32::WHITE); - let (w, c) = if p.id == selected { (2.0, t.accent) } else { (1.0, t.field_border) }; - ui.painter().rect_stroke(r, 0.0, Stroke::new(w, c), egui::StrokeKind::Outside); - let cell = cell.on_hover_text(p.display_name()); - cell.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, p.display_name())); - if cell.clicked() { - picked = Some(p.id.clone()); - ui.close(); - } + picked = pattern_grid(app, ui, selected); + }); + picked +} + +/// Library grid shared by the standalone picker and paint popups. Drawing it inline avoids +/// replacing an already-open paint popup with a second memory-backed popup. +pub(crate) fn pattern_grid(app: &PhotocraftApp, ui: &mut egui::Ui, selected: &str) -> Option { + const SWATCH: f32 = 40.0; + let t = Tokens::get(ui.ctx()); + let ctx = ui.ctx().clone(); + let uv = Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0)); + let mut picked = None; + ui.set_max_width(6.0 * (SWATCH + 4.0)); + ui.horizontal_wrapped(|ui| { + ui.spacing_mut().item_spacing = vec2(4.0, 4.0); + for p in &app.session.patterns.items { + let (r, cell) = ui.allocate_exact_size(vec2(SWATCH, SWATCH), Sense::click()); + ui.painter().image(pattern_texture(&ctx, p).id(), r, uv, Color32::WHITE); + let (w, c) = if p.id == selected { (2.0, t.accent) } else { (1.0, t.field_border) }; + ui.painter().rect_stroke(r, 0.0, Stroke::new(w, c), egui::StrokeKind::Outside); + let cell = cell.on_hover_text(p.display_name()); + cell.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), p.display_name())); + if cell.clicked() { + picked = Some(p.id.clone()); + ui.close(); } - }); + } }); picked.filter(|id| id != selected) } diff --git a/crates/ui-egui/src/shape_options.rs b/crates/ui-egui/src/shape_options.rs new file mode 100644 index 00000000000..ea93972567c --- /dev/null +++ b/crates/ui-egui/src/shape_options.rs @@ -0,0 +1,172 @@ +//! Shape toolbar edits share the engine commands used by the Properties panel. + +use photocraft_doc::LayerContent; +use serde_json::{Value, json}; + +use crate::PhotocraftApp; +use crate::shape_paint_ui::{PaintChange, swatch}; +use crate::state::Tool; +use crate::theme::Tokens; +use crate::vector_ui::{enabled_stroke_width, paint_gesture}; + +fn solid(color: [f32; 4]) -> photocraft_doc::Fill { + photocraft_doc::Fill::Solid(photocraft_doc::Color::rgba(color[0], color[1], color[2], color[3])) +} + +/// The shape layer the options bar edits. +struct SelectedShape { + doc: photocraft_doc::DocId, + layer: photocraft_doc::LayerId, + fill: Option, + stroke: Option, + live: Option, +} + +fn selected_shape(session: &photocraft_engine::Session) -> Option { + let st = session.active()?; + let layer = st.active_layer?; + match &st.doc.layer(layer)?.content { + LayerContent::Shape(sh) => Some(SelectedShape { doc: st.doc.id, layer, fill: sh.fill.clone(), stroke: sh.stroke.clone(), live: sh.live.clone() }), + _ => None, + } +} + +pub(crate) fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) { + let t = Tokens::get(ui.ctx()); + let lbl = |ui: &mut egui::Ui, s: &str| { + ui.label(egui::RichText::new(s).color(t.text_dim).size(12.0)); + }; + let o = &mut app.ui.tool_options; + let target = selected_shape(&app.session); + // Fill and Stroke edit the selected shape layer too (#3347), and still set the next shape's. + let (fg, bg) = (app.session.tools.foreground, app.session.tools.background); + let (mut has_fill, fill, stroke) = match &target { + Some(s) => (s.fill.is_some(), s.fill.clone(), s.stroke.clone()), + None => (o.shape_fill, o.shape_fill.then(|| solid(fg)), (o.stroke_width > 0.0).then(|| o.shape_stroke.stroke(o.stroke_width, solid(bg)))), + }; + let mut width = stroke.as_ref().map_or(0.0, |s| s.width); + let stroke_enabled = stroke.as_ref().is_some_and(|s| s.width > 0.0); + let style = stroke.as_ref().map_or_else(|| o.shape_stroke.clone(), crate::shape_stroke_ui::StrokeOptions::from); + let gesture_key = ui.id().with("shape-options-paint-gesture"); + let gesture = paint_gesture(ui, gesture_key); + let key = |k: &str| target.as_ref().map(|s| format!("shape-options-{:?}-{}-{k}:{}:{gesture}", s.doc, s.layer.0, gesture_key.value())); + let mut edit: Option = None; + lbl(ui, tl!("Fill:")); + if crate::widgets::checkbox(ui, &mut has_fill, "").changed() { + o.shape_fill = has_fill; + edit = Some(json!({"fill": if has_fill { json!(fg) } else { Value::Null }})); + } + let fill_color = swatch(ui, fill.as_ref(), fg, tl!("Fill color")); + lbl(ui, tl!("Stroke:")); + let stroke_color = swatch(ui, stroke.as_ref().map(|s| &s.paint), bg, tl!("Stroke color")); + if crate::widgets::value_field(ui, &mut width, 0.0..=288.0, "px", 58.0).changed() { + o.stroke_width = width; + // A 0 px "change" (an arrow step clamped at the minimum) must not add a stroke. + if stroke.is_some() || width > 0.0 { + let mut p = json!({"width": width}); + if stroke.is_none() { + p["color"] = json!(bg); + } + edit = Some(json!({"stroke": p, "coalesce": key("stroke-w")})); + } + } + let preview = target.as_ref().filter(|s| s.stroke.is_some()).map(|s| (s.doc, s.layer)); + if let Some(change) = + crate::shape_stroke_ui::button(ui, "tool-stroke", &style, &mut app.ui.stroke_editor, true, tool != Tool::EllipseShape, preview, stroke_enabled) + { + let mut p = change.options.params(); + if !stroke_enabled { + p["width"] = json!(3.0); + } + if stroke.is_none() { + p["color"] = json!(bg); + } + edit = Some(json!({"stroke": p, "coalesce": change.coalesce})); + o.shape_stroke = change.options; + o.stroke_width = enabled_stroke_width(o.stroke_width); + } + match tool { + Tool::Rectangle => { + crate::widgets::vline(ui, 22.0); + lbl(ui, tl!("Radius:")); + let mut r = match target.as_ref().and_then(|s| s.live.as_ref()) { + Some(photocraft_doc::LiveShape::Rect { radii, .. }) => radii[0] as f32, + _ => o.corner_radius, + }; + if crate::widgets::value_field(ui, &mut r, 0.0..=10000.0, "px", 62.0).changed() { + o.corner_radius = r; + let rf = r as f64; + edit = Some(json!({"radii": [rf, rf, rf, rf], "coalesce": key("radius")})); + } + } + Tool::Polygon => { + crate::widgets::vline(ui, 22.0); + lbl(ui, tl!("Sides:")); + let mut s = o.polygon_sides as f32; + if crate::widgets::value_field(ui, &mut s, 3.0..=100.0, "", 48.0).changed() { + o.polygon_sides = s.round().clamp(3.0, 100.0) as u32; + } + } + Tool::Line => { + crate::widgets::vline(ui, 22.0); + lbl(ui, tl!("Weight:")); + crate::widgets::value_field(ui, &mut o.line_weight, 1.0..=1000.0, "px", 58.0); + } + Tool::CustomShape => { + crate::widgets::vline(ui, 22.0); + crate::preset_panels::shape_picker(app, ui); + } + _ if matches!(tool, Tool::PathSelection | Tool::DirectSelection) => { + if let Some(photocraft_doc::LiveShape::Rect { radii, .. }) = target.as_ref().and_then(|s| s.live.as_ref()) { + crate::widgets::vline(ui, 22.0); + lbl(ui, tl!("Radius:")); + let mut r = radii[0] as f32; + if crate::widgets::value_field(ui, &mut r, 0.0..=10000.0, "px", 62.0).changed() { + o.corner_radius = r; + let rf = r as f64; + edit = Some(json!({"radii": [rf, rf, rf, rf], "coalesce": key("radius")})); + } + } + } + _ => {} + } + for (is_stroke, change) in [(false, fill_color), (true, stroke_color)] { + let Some(change) = change else { continue }; + if let Err(e) = set_tool_paint(app, is_stroke, change) { + app.ui.status = e; + app.ui.status_error = true; + } + edit = Some(match (is_stroke, change) { + (false, PaintChange::None) => json!({"fill": null}), + (false, PaintChange::Color(color)) => json!({"fill": color, "coalesce": key("fill")}), + (true, PaintChange::None) => json!({"stroke": null}), + (true, PaintChange::Color(color)) => json!({"stroke": {"color": color, "width": enabled_stroke_width(width)}, "coalesce": key("stroke")}), + }); + } + if let (Some(mut p), Some(s)) = (edit, &target) { + p["layer"] = json!(s.layer.0); + if let Err(e) = app.run("shape.edit", p) { + app.ui.status = e; + app.ui.status_error = true; + } + if !ui.input(|i| i.pointer.any_down()) { + ui.data_mut(|d| { + let gesture = d.get_temp_mut_or_default::<(u64, u64)>(gesture_key); + gesture.0 = gesture.0.wrapping_add(1); + }); + } + } +} + +/// 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> { + if let PaintChange::Color(color) = change { + app.run("tools.setColors", if stroke { json!({"background": color}) } else { json!({"foreground": color}) })?; + } + if stroke { + app.ui.tool_options.stroke_width = if change == PaintChange::None { 0.0 } else { enabled_stroke_width(app.ui.tool_options.stroke_width) }; + } else { + app.ui.tool_options.shape_fill = change != PaintChange::None; + } + Ok(()) +} diff --git a/crates/ui-egui/src/shape_paint_ui.rs b/crates/ui-egui/src/shape_paint_ui.rs new file mode 100644 index 00000000000..28bb1c90580 --- /dev/null +++ b/crates/ui-egui/src/shape_paint_ui.rs @@ -0,0 +1,130 @@ +//! Shape fill and stroke swatches shared by the options bar and the Properties panel. + +use egui::{Color32, Sense, Stroke, vec2}; + +use crate::theme::Tokens; + +pub(crate) fn color_of(f: &photocraft_doc::Fill) -> Option<[f32; 4]> { + match f { + photocraft_doc::Fill::Solid(c) => { + let [r, g, b] = c.to_rgb(); + Some([r, g, b, c.alpha]) + } + _ => None, + } +} + +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) enum PaintChange { + Color([f32; 4]), + None, +} + +fn rgba32(c: [f32; 4]) -> Color32 { + let b = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; + Color32::from_rgba_unmultiplied(b(c[0]), b(c[1]), b(c[2]), b(c[3])) +} + +fn picker_color(c: [f32; 4]) -> egui::ecolor::Hsva { + let linear = egui::ecolor::linear_from_gamma; + let display = c.map(|v| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }); + egui::ecolor::Hsva::from_rgba_unmultiplied(linear(display[0]), linear(display[1]), linear(display[2]), display[3]) +} + +fn picker_rgba(hsva: egui::ecolor::Hsva) -> [f32; 4] { + let [r, g, b, a] = hsva.to_rgba_unmultiplied(); + let gamma = egui::ecolor::gamma_from_linear; + [gamma(r), gamma(g), gamma(b), a] +} + +/// The shared compact picker keeps the float RGB paint and its alpha. Color32 is only display +/// data: opening the picker must never quantize an existing high-depth colour or enable paint. +pub(crate) fn swatch(ui: &mut egui::Ui, fill: Option<&photocraft_doc::Fill>, fallback: [f32; 4], tip: &str) -> Option { + let t = Tokens::get(ui.ctx()); + let (r, resp) = ui.allocate_exact_size(vec2(30.0, 22.0), Sense::click()); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::ColorButton, ui.is_enabled(), tip)); + let current = fill.and_then(color_of); + crate::widgets::checker(ui.painter(), r.shrink(1.0), 4.0); + match (current, fill) { + (Some(c), _) => { + ui.painter().rect_filled(r.shrink(1.0), t.radius_sm, rgba32(c)); + } + (None, Some(photocraft_doc::Fill::Gradient { stops, .. })) if !stops.is_empty() => { + // Gradient fills preview as a left-to-right ramp through their stops. + let rgb = |c: &photocraft_doc::Color| { + let v = c.to_rgba8(); + Color32::from_rgba_unmultiplied(v[0], v[1], v[2], v[3]) + }; + let mut mesh = egui::Mesh::default(); + let mut ramp: Vec<(f32, Color32)> = stops.iter().map(|(p, c)| (p.clamp(0.0, 1.0), rgb(c))).collect(); + ramp.insert(0, (0.0, ramp[0].1)); + ramp.push((1.0, ramp[ramp.len() - 1].1)); + for (i, (p, c)) in ramp.iter().enumerate() { + let x = r.left() + r.width() * p; + mesh.colored_vertex(egui::pos2(x, r.top()), *c); + mesh.colored_vertex(egui::pos2(x, r.bottom()), *c); + if i > 0 { + let k = (i as u32) * 2; + mesh.add_triangle(k - 2, k - 1, k); + mesh.add_triangle(k - 1, k, k + 1); + } + } + ui.painter().add(mesh); + } + (None, Some(_)) => {} + (None, None) => { + ui.painter().rect_filled(r.shrink(1.0), t.radius_sm, t.field); + ui.painter().line_segment([r.shrink(3.0).left_bottom(), r.shrink(3.0).right_top()], Stroke::new(1.5, t.danger)); + } + }; + let border = if resp.has_focus() { + t.accent + } else if resp.hovered() { + t.text_dim + } else { + t.field_border + }; + ui.painter().rect_stroke(r, t.radius_sm, Stroke::new(1.0, border), egui::StrokeKind::Inside); + let resp = resp.on_hover_text(tip); + let screen_id = resp.id.with("screen-color"); + let original = current.unwrap_or(fallback); + let sampled = |rgb: [f32; 3]| PaintChange::Color([rgb[0], rgb[1], rgb[2], original[3]]); + let mut out = crate::screen_picker::take(ui.ctx(), screen_id).map(sampled); + let cache = resp.id.with("shape-paint-hsva"); + let mut hsva = ui + .data(|d| d.get_temp::<([f32; 4], egui::ecolor::Hsva)>(cache)) + .filter(|(previous, _)| *previous == original) + .map_or_else(|| picker_color(original), |(_, hsva)| hsva); + if let Some(PaintChange::Color(color)) = out { + hsva = picker_color(color); + } + crate::widgets::swatch_popup(&resp).show(|ui| { + ui.horizontal(|ui| { + if ui.selectable_label(fill.is_none(), tl!("No Color")).clicked() && fill.is_some() { + out = Some(PaintChange::None); + } + if ui.selectable_label(current.is_some(), tl!("Solid")).clicked() && current.is_none() { + out = Some(PaintChange::Color(original)); + } + }); + ui.separator(); + let before = picker_rgba(hsva); + if egui::color_picker::color_picker_hsva_2d(ui, &mut hsva, egui::color_picker::Alpha::OnlyBlend) { + let color = picker_rgba(hsva); + // egui's HSV gamma/linear round trip can move a float by an ulp without input. + if color.iter().zip(before).any(|(a, b)| (a - b).abs() > 0.000001) { + out = Some(PaintChange::Color(color)); + } + } + if let Some(rgb) = crate::screen_picker::button(ui, screen_id) { + out = Some(sampled(rgb)); + hsva = picker_color([rgb[0], rgb[1], rgb[2], original[3]]); + } + }); + let cached_color = match out { + Some(PaintChange::Color(color)) => color, + _ => original, + }; + ui.data_mut(|d| d.insert_temp(cache, (cached_color, hsva))); + out +} diff --git a/crates/ui-egui/src/vector_paint_tests.rs b/crates/ui-egui/src/vector_paint_tests.rs index f050b9fac31..27c09768a91 100644 --- a/crates/ui-egui/src/vector_paint_tests.rs +++ b/crates/ui-egui/src/vector_paint_tests.rs @@ -1,5 +1,7 @@ //! Pointer, keyboard, colour precision and history regressions for shape appearance controls. use super::*; +use crate::shape_options::set_tool_paint; +use crate::shape_paint_ui::color_of; use egui::{Event, Key, Modifiers, PointerButton}; use egui_kittest::{Harness, kittest::Queryable}; use photocraft_doc::ShapeLayer; diff --git a/crates/ui-egui/src/vector_ui.rs b/crates/ui-egui/src/vector_ui.rs index 838df100784..030ddfeac35 100644 --- a/crates/ui-egui/src/vector_ui.rs +++ b/crates/ui-egui/src/vector_ui.rs @@ -11,6 +11,7 @@ use serde_json::{Value, json}; use crate::PhotocraftApp; use crate::canvas::ViewXform; +use crate::shape_paint_ui::{PaintChange, swatch}; use crate::state::{Tool, ToolOptions}; use crate::theme::Tokens; @@ -1201,143 +1202,15 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo let mut mode = "shape".to_string(); crate::widgets::dropdown(ui, "shape-mode", &mut mode, &[("shape".to_string(), tl!("Shape"))], 80.0); crate::widgets::vline(ui, 22.0); - // Fill and Stroke edit the selected shape layer too (#3347), and still set the next shape's. - let (fg, bg) = (app.session.tools.foreground, app.session.tools.background); - let (mut has_fill, fill, stroke) = match &target { - Some(s) => (s.fill.is_some(), s.fill.clone(), s.stroke.clone()), - None => (o.shape_fill, o.shape_fill.then(|| solid_paint(fg)), (o.stroke_width > 0.0).then(|| o.shape_stroke.stroke(o.stroke_width, solid_paint(bg)))), - }; - let mut width = stroke.as_ref().map_or(0.0, |s| s.width); - let stroke_enabled = stroke.as_ref().is_some_and(|s| s.width > 0.0); - let style = stroke.as_ref().map_or_else(|| o.shape_stroke.clone(), crate::shape_stroke_ui::StrokeOptions::from); - let gesture_key = ui.id().with("shape-options-paint-gesture"); - let gesture = paint_gesture(ui, gesture_key); - let key = |k: &str| target.as_ref().map(|s| format!("shape-options-{:?}-{}-{k}:{}:{gesture}", s.doc, s.layer.0, gesture_key.value())); - let mut edit: Option = None; - lbl(ui, tl!("Fill:")); - if crate::widgets::checkbox(ui, &mut has_fill, "").changed() { - o.shape_fill = has_fill; - edit = Some(json!({"fill": if has_fill { json!(fg) } else { Value::Null }})); - } - let fill_color = swatch(ui, fill.as_ref(), fg, tl!("Fill color")); - lbl(ui, tl!("Stroke:")); - let stroke_color = swatch(ui, stroke.as_ref().map(|s| &s.paint), bg, tl!("Stroke color")); - if crate::widgets::value_field(ui, &mut width, 0.0..=288.0, "px", 58.0).changed() { - o.stroke_width = width; - // A 0 px "change" (an arrow step clamped at the minimum) must not add a stroke. - if stroke.is_some() || width > 0.0 { - let mut p = json!({"width": width}); - if stroke.is_none() { - p["color"] = json!(bg); - } - edit = Some(json!({"stroke": p, "coalesce": key("stroke-w")})); - } - } - let preview = target.as_ref().filter(|s| s.stroke.is_some()).map(|s| (s.doc, s.layer)); - if let Some(change) = - crate::shape_stroke_ui::button(ui, "tool-stroke", &style, &mut app.ui.stroke_editor, true, tool != Tool::EllipseShape, preview, stroke_enabled) - { - let mut p = change.options.params(); - if !stroke_enabled { - p["width"] = json!(3.0); - } - if stroke.is_none() { - p["color"] = json!(bg); - } - edit = Some(json!({"stroke": p, "coalesce": change.coalesce})); - o.shape_stroke = change.options; - o.stroke_width = enabled_stroke_width(o.stroke_width); - } - match tool { - Tool::Rectangle => { - crate::widgets::vline(ui, 22.0); - lbl(ui, tl!("Radius:")); - let mut r = match target.as_ref().and_then(|s| s.live.as_ref()) { - Some(photocraft_doc::LiveShape::Rect { radii, .. }) => radii[0] as f32, - _ => o.corner_radius, - }; - if crate::widgets::value_field(ui, &mut r, 0.0..=10000.0, "px", 62.0).changed() { - o.corner_radius = r; - let rf = r as f64; - edit = Some(json!({"radii": [rf, rf, rf, rf], "coalesce": key("radius")})); - } - } - Tool::Polygon => { - crate::widgets::vline(ui, 22.0); - lbl(ui, tl!("Sides:")); - let mut s = o.polygon_sides as f32; - if crate::widgets::value_field(ui, &mut s, 3.0..=100.0, "", 48.0).changed() { - o.polygon_sides = s.round().clamp(3.0, 100.0) as u32; - } - } - Tool::Line => { - crate::widgets::vline(ui, 22.0); - lbl(ui, tl!("Weight:")); - crate::widgets::value_field(ui, &mut o.line_weight, 1.0..=1000.0, "px", 58.0); - } - Tool::CustomShape => { - crate::widgets::vline(ui, 22.0); - crate::preset_panels::shape_picker(app, ui); - } - _ if matches!(tool, Tool::PathSelection | Tool::DirectSelection) => { - if let Some(photocraft_doc::LiveShape::Rect { radii, .. }) = target.as_ref().and_then(|s| s.live.as_ref()) { - crate::widgets::vline(ui, 22.0); - lbl(ui, tl!("Radius:")); - let mut r = radii[0] as f32; - if crate::widgets::value_field(ui, &mut r, 0.0..=10000.0, "px", 62.0).changed() { - o.corner_radius = r; - let rf = r as f64; - edit = Some(json!({"radii": [rf, rf, rf, rf], "coalesce": key("radius")})); - } - } - } - _ => {} - } - for (is_stroke, change) in [(false, fill_color), (true, stroke_color)] { - let Some(change) = change else { continue }; - if let Err(e) = set_tool_paint(app, is_stroke, change) { - app.ui.status = e; - app.ui.status_error = true; - } - edit = Some(match (is_stroke, change) { - (false, PaintChange::None) => json!({"fill": null}), - (false, PaintChange::Color(color)) => json!({"fill": color, "coalesce": key("fill")}), - (true, PaintChange::None) => json!({"stroke": null}), - (true, PaintChange::Color(color)) => json!({"stroke": {"color": color, "width": enabled_stroke_width(width)}, "coalesce": key("stroke")}), - }); - } - if let (Some(mut p), Some(s)) = (edit, &target) { - p["layer"] = json!(s.layer.0); - if let Err(e) = app.run("shape.edit", p) { - app.ui.status = e; - app.ui.status_error = true; - } - if !ui.input(|i| i.pointer.any_down()) { - ui.data_mut(|d| { - let gesture = d.get_temp_mut_or_default::<(u64, u64)>(gesture_key); - gesture.0 = gesture.0.wrapping_add(1); - }); - } - } + crate::shape_options::options_bar(app, ui, tool); true } -/// The shape layer the options bar edits. -struct SelectedShape { - doc: photocraft_doc::DocId, - layer: photocraft_doc::LayerId, - fill: Option, - stroke: Option, - live: Option, -} - -fn selected_shape(session: &photocraft_engine::Session) -> Option { +/// Whether the active layer supplies the selected-shape options. +fn selected_shape(session: &photocraft_engine::Session) -> Option { let st = session.active()?; let layer = st.active_layer?; - match &st.doc.layer(layer)?.content { - LayerContent::Shape(sh) => Some(SelectedShape { doc: st.doc.id, layer, fill: sh.fill.clone(), stroke: sh.stroke.clone(), live: sh.live.clone() }), - _ => None, - } + matches!(st.doc.layer(layer)?.content, LayerContent::Shape(_)).then_some(layer) } // --------------------------------------------------------------------------------------------- @@ -1347,148 +1220,10 @@ fn solid_paint(c: [f32; 4]) -> photocraft_doc::Fill { photocraft_doc::Fill::Solid(photocraft_doc::Color::rgba(c[0], c[1], c[2], c[3])) } -fn color_of(f: &photocraft_doc::Fill) -> Option<[f32; 4]> { - match f { - photocraft_doc::Fill::Solid(c) => { - let [r, g, b] = c.to_rgb(); - Some([r, g, b, c.alpha]) - } - _ => None, - } -} - -#[derive(Clone, Copy, Debug, PartialEq)] -enum PaintChange { - Color([f32; 4]), - None, -} - -fn enabled_stroke_width(width: f32) -> f32 { +pub(crate) fn enabled_stroke_width(width: f32) -> f32 { if width.is_finite() && width > 0.0 { width } else { 3.0 } } -/// Tool-bar paint changes affect the next shape; Properties edits the selected shape instead. -fn set_tool_paint(app: &mut PhotocraftApp, stroke: bool, change: PaintChange) -> Result<(), String> { - if let PaintChange::Color(color) = change { - app.run("tools.setColors", if stroke { json!({"background": color}) } else { json!({"foreground": color}) })?; - } - if stroke { - app.ui.tool_options.stroke_width = if change == PaintChange::None { 0.0 } else { enabled_stroke_width(app.ui.tool_options.stroke_width) }; - } else { - app.ui.tool_options.shape_fill = change != PaintChange::None; - } - Ok(()) -} - -fn rgba32(c: [f32; 4]) -> Color32 { - let b = |v: f32| (v.clamp(0.0, 1.0) * 255.0).round() as u8; - Color32::from_rgba_unmultiplied(b(c[0]), b(c[1]), b(c[2]), b(c[3])) -} - -fn picker_color(c: [f32; 4]) -> egui::ecolor::Hsva { - let linear = egui::ecolor::linear_from_gamma; - let display = c.map(|v| if v.is_finite() { v.clamp(0.0, 1.0) } else { 0.0 }); - egui::ecolor::Hsva::from_rgba_unmultiplied(linear(display[0]), linear(display[1]), linear(display[2]), display[3]) -} - -fn picker_rgba(hsva: egui::ecolor::Hsva) -> [f32; 4] { - let [r, g, b, a] = hsva.to_rgba_unmultiplied(); - let gamma = egui::ecolor::gamma_from_linear; - [gamma(r), gamma(g), gamma(b), a] -} - -/// The shared compact picker keeps the float RGB paint and its alpha. Color32 is only display -/// data: opening the picker must never quantize an existing high-depth colour or enable paint. -fn swatch(ui: &mut egui::Ui, fill: Option<&photocraft_doc::Fill>, fallback: [f32; 4], tip: &str) -> Option { - let t = Tokens::get(ui.ctx()); - let (r, resp) = ui.allocate_exact_size(vec2(30.0, 22.0), Sense::click()); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::ColorButton, ui.is_enabled(), tip)); - let current = fill.and_then(color_of); - crate::widgets::checker(ui.painter(), r.shrink(1.0), 4.0); - match (current, fill) { - (Some(c), _) => { - ui.painter().rect_filled(r.shrink(1.0), t.radius_sm, rgba32(c)); - } - (None, Some(photocraft_doc::Fill::Gradient { stops, .. })) if !stops.is_empty() => { - // Gradient fills preview as a left-to-right ramp through their stops. - let rgb = |c: &photocraft_doc::Color| { - let v = c.to_rgba8(); - Color32::from_rgba_unmultiplied(v[0], v[1], v[2], v[3]) - }; - let mut mesh = egui::Mesh::default(); - let mut ramp: Vec<(f32, Color32)> = stops.iter().map(|(p, c)| (p.clamp(0.0, 1.0), rgb(c))).collect(); - ramp.insert(0, (0.0, ramp[0].1)); - ramp.push((1.0, ramp[ramp.len() - 1].1)); - for (i, (p, c)) in ramp.iter().enumerate() { - let x = r.left() + r.width() * p; - mesh.colored_vertex(egui::pos2(x, r.top()), *c); - mesh.colored_vertex(egui::pos2(x, r.bottom()), *c); - if i > 0 { - let k = (i as u32) * 2; - mesh.add_triangle(k - 2, k - 1, k); - mesh.add_triangle(k - 1, k, k + 1); - } - } - ui.painter().add(mesh); - } - (None, Some(_)) => {} - (None, None) => { - ui.painter().rect_filled(r.shrink(1.0), t.radius_sm, t.field); - ui.painter().line_segment([r.shrink(3.0).left_bottom(), r.shrink(3.0).right_top()], Stroke::new(1.5, t.danger)); - } - }; - let border = if resp.has_focus() { - t.accent - } else if resp.hovered() { - t.text_dim - } else { - t.field_border - }; - ui.painter().rect_stroke(r, t.radius_sm, Stroke::new(1.0, border), egui::StrokeKind::Inside); - let resp = resp.on_hover_text(tip); - let screen_id = resp.id.with("screen-color"); - let original = current.unwrap_or(fallback); - let sampled = |rgb: [f32; 3]| PaintChange::Color([rgb[0], rgb[1], rgb[2], original[3]]); - let mut out = crate::screen_picker::take(ui.ctx(), screen_id).map(sampled); - let cache = resp.id.with("shape-paint-hsva"); - let mut hsva = ui - .data(|d| d.get_temp::<([f32; 4], egui::ecolor::Hsva)>(cache)) - .filter(|(previous, _)| *previous == original) - .map_or_else(|| picker_color(original), |(_, hsva)| hsva); - if let Some(PaintChange::Color(color)) = out { - hsva = picker_color(color); - } - crate::widgets::swatch_popup(&resp).show(|ui| { - ui.horizontal(|ui| { - if ui.selectable_label(fill.is_none(), tl!("No Color")).clicked() && fill.is_some() { - out = Some(PaintChange::None); - } - if ui.selectable_label(current.is_some(), tl!("Solid")).clicked() && current.is_none() { - out = Some(PaintChange::Color(original)); - } - }); - ui.separator(); - let before = picker_rgba(hsva); - if egui::color_picker::color_picker_hsva_2d(ui, &mut hsva, egui::color_picker::Alpha::OnlyBlend) { - let color = picker_rgba(hsva); - // egui's HSV gamma/linear round trip can move a float by an ulp without input. - if color.iter().zip(before).any(|(a, b)| (a - b).abs() > 0.000001) { - out = Some(PaintChange::Color(color)); - } - } - if let Some(rgb) = crate::screen_picker::button(ui, screen_id) { - out = Some(sampled(rgb)); - hsva = picker_color([rgb[0], rgb[1], rgb[2], original[3]]); - } - }); - let cached_color = match out { - Some(PaintChange::Color(color)) => color, - _ => original, - }; - ui.data_mut(|d| d.insert_temp(cache, (cached_color, hsva))); - out -} - /// One corner of the live rectangle, preserving the other three radii. /// The engine takes the full [top-left, top-right, bottom-right, bottom-left] array. fn corner_radii_patch(radii: [f64; 4], corner: usize, radius: f32) -> Value { @@ -1501,7 +1236,7 @@ fn corner_radii_patch(radii: [f64; 4], corner: usize, radius: f32) -> Value { /// Follow the existing brush/mask continuous-edit convention: one history state per press or /// keyboard edit, with every value tick of a held-pointer gesture sharing its key. -fn paint_gesture(ui: &egui::Ui, key: egui::Id) -> u64 { +pub(crate) fn paint_gesture(ui: &egui::Ui, key: egui::Id) -> u64 { let pass = ui.ctx().cumulative_pass_nr(); let pressed = ui.input(|i| i.pointer.any_pressed()); ui.data_mut(|d| {