From 05b194b42c677a93283fc2927d291af24ca6cb4e Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Fri, 27 Nov 2026 14:51:31 +0000 Subject: [PATCH] panels-w10: net change of 1 commits - panels-w10: written by an agent --- crates/ui-egui/src/panels/background.rs | 306 ++++---- crates/ui-egui/src/panels/background_tests.rs | 72 +- crates/ui-egui/src/panels/fillui.rs | 712 +++++++++--------- .../ui-egui/src/panels/pattern_fill_tests.rs | 187 ++--- 4 files changed, 575 insertions(+), 702 deletions(-) diff --git a/crates/ui-egui/src/panels/background.rs b/crates/ui-egui/src/panels/background.rs index 2010afaac..b8957c013 100644 --- a/crates/ui-egui/src/panels/background.rs +++ b/crates/ui-egui/src/panels/background.rs @@ -1,7 +1,22 @@ -use super::{Fill, SlideApp, Ui, Value, cref_param, json, run, scheme, theme, vec2, widgets}; +//! Background fills and picture placement, edited through engine commands. +use craft::i18n::Word; +use craft::ui::buttons::Button; +use craft::ui::choice::{Checkbox, Radio, RadioGroup}; +use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; +use craft::ui::form::{Field, SliderField}; +use craft::ui::layout_components::{Row, Stack}; +use craft::ui::pickers::Select; +use craft::ui::runtime::env::UnitKind; +use craft::ui::sections::Section; +use craft::ui::text::{NumberField, StepArrows}; +use deckcraft_model::style::{PictureFill, PictureMode}; + +use super::color_row::color_row; +use super::{Fill, SlideApp, Ui, Value, cref_param, json, run}; + +/// Edits the current slide's background and its master-graphics visibility. pub(super) fn background(app: &mut SlideApp, ui: &mut Ui) { - let sc = scheme(app); let bg = app.session.active().and_then(|d| d.current_slide().and_then(|s| s.background.clone())); let fill = match &bg { Some(deckcraft_model::Background::Fill { fill }) => Some(fill.clone()), @@ -14,153 +29,146 @@ pub(super) fn background(app: &mut SlideApp, ui: &mut Ui) { Some(Fill::Pattern(_)) => "pattern", _ => "auto", }; - // What "Apply to All" re-applies: the current slide's background as command params. - let mut current: Option = None; - ui.label(egui::RichText::new("Fill").font(theme::bold(13.0))); - for (l, k) in [ - ("Solid fill", "solid"), - ("Gradient fill", "gradient"), - ("Picture or texture fill", "picture"), - ("Pattern fill", "pattern"), - ("Follow the layout", "auto"), - ] { - if ui.radio(kind == k, l).clicked() && kind != k { - match k { - "solid" => run(app, "design.background", json!({"color": "bg1"})), + let mut section = Section::fixed(Word::plain("Fill")).show(ui, |ui, _| { + let mut commands = Vec::new(); + let mut pick_picture = false; + let group = RadioGroup::new(Word::plain("Background fill"), Bind::given(kind)).show(ui, |ui, _| { + Stack::new().show(ui, |ui, _| { + for (label, value) in [ + ("Solid fill", "solid"), + ("Gradient fill", "gradient"), + ("Picture or texture fill", "picture"), + ("Pattern fill", "pattern"), + ("Follow the layout", "auto"), + ] { + Radio::new(value).label(Word::plain(label)).show(ui); + } + }); + }); + if let Some(picked) = group.output.events.committed().filter(|picked| **picked != kind) { + match *picked { + "solid" => commands.push(json!({"color": "bg1"})), "gradient" => { let mut g = crate::fillui::default_gradient(deckcraft_model::ColorRef::scheme(deckcraft_color::SchemeSlot::Bg2), 90.0); g.rotate_with_shape = false; - run(app, "design.background", json!({"gradient": crate::fillui::gradient_json(&g)})); + commands.push(json!({"gradient": crate::fillui::gradient_json(&g)})); } - "picture" => { - if let Some(pick) = app.services.pick_open.as_mut() - && let Some(path) = pick("picture") - && let Some(Ok(bytes)) = app.services.read.as_ref().map(|r| r(&path)) - { - let _ = app.run("design.background", json!({"picture": deckcraft_engine::cmd::base64_encode(&bytes)})); - } - } - "pattern" => run(app, "design.background", json!({"pattern": {"preset": "pct20", "fg": "accent1", "bg": "bg1"}})), - _ => run(app, "design.background", json!({"reset": true})), + "picture" => pick_picture = true, + "pattern" => commands.push(json!({"pattern": {"preset": "pct20", "fg": "accent1", "bg": "bg1"}})), + _ => commands.push(json!({"reset": true})), } } - } - ui.add_space(4.0); - match &fill { - Some(Fill::Solid { color }) => { - current = Some(json!({"color": cref_param(color)})); - ui.horizontal(|ui| { - ui.label("Color"); - let r = widgets::drop_button(ui, "Color", vec2(70.0, 20.0), true); - widgets::color_popup(&r).show(|ui| { - if let Some(Some(c)) = widgets::color_grid(ui, &sc, None) { - run(app, "design.background", json!({"color": cref_param(&c)})); - } + match &fill { + Some(Fill::Solid { color }) => { + let mut picked = None; + color_row(app, ui, "Color", None, |_, color| { + picked = color; }); - }); - let mut tr = ((1.0 - color.alpha()) * 100.0) as f32; - if ui.add(egui::Slider::new(&mut tr, 0.0..=100.0).text("Transparency").suffix("%")).drag_stopped() { - run(app, "design.background", json!({"transparency": (f64::from(tr) / 100.0).clamp(0.0, 1.0)})); + if let Some(color) = picked { + commands.push(json!({"color": cref_param(&color)})); + } + commands.extend(transparency(ui, color.alpha())); } - } - Some(Fill::Gradient(g)) => { - current = Some(json!({"gradient": crate::fillui::gradient_json(g)})); - // P3(panels-w10): pn.A10 - if let Some(ng) = crate::fillui::gradient_editor(app, ui, "bg-grad", g) { - run(app, "design.background", json!({"gradient": crate::fillui::gradient_json(&ng)})); + Some(Fill::Gradient(g)) => { + if let Some(edited) = crate::fillui::gradient_editor(app, ui, "Gradient", g) { + commands.push(json!({"gradient": crate::fillui::gradient_json(&edited)})); + } } - } - Some(Fill::Pattern(pt)) => { - current = Some(json!({"pattern": crate::fillui::pattern_json(pt)})); - // P3(panels-w10): pn.A10 - if let Some(np) = crate::fillui::pattern_editor(app, ui, pt) { - run(app, "design.background", json!({"pattern": crate::fillui::pattern_json(&np)})); + Some(Fill::Pattern(p)) => { + if let Some(edited) = crate::fillui::pattern_editor(app, ui, p) { + commands.push(json!({"pattern": crate::fillui::pattern_json(&edited)})); + } } - } - Some(Fill::Picture(pf)) => { - if ui.button("Insert picture from file…").clicked() - && let Some(pick) = app.services.pick_open.as_mut() - && let Some(path) = pick("picture") - && let Some(Ok(bytes)) = app.services.read.as_ref().map(|r| r(&path)) - { - let _ = app.run("design.background", json!({"picture": deckcraft_engine::cmd::base64_encode(&bytes)})); + Some(Fill::Picture(p)) => { + if Button::new(Word::plain("Insert picture from file…")).show(ui).clicked() { + pick_picture = true; + } + commands.extend(picture_background_options(ui, p)); } - picture_background_options(app, ui, pf); - } - _ => {} - } - ui.add_space(4.0); - let hide = app.session.active().and_then(|d| d.current_slide().map(|s| !s.show_master_shapes)).unwrap_or(false); - let mut h = hide; - if ui.checkbox(&mut h, "Hide background graphics").changed() { - run(app, "design.hideBackgroundGraphics", json!({"hide": h})); - } - ui.add_space(8.0); - let picture = matches!(fill, Some(Fill::Picture(_))); - ui.horizontal(|ui| { - if ui.add_enabled(current.is_some() || picture, egui::Button::new("Apply to All")).clicked() { - if let Some(Value::Object(mut o)) = current.clone() { - o.insert("all".into(), json!(true)); - run(app, "design.background", Value::Object(o)); - } else if picture { - run(app, "design.background", json!({"copy": true})); - } - } - if ui.button("Reset Background").clicked() { - run(app, "design.background", json!({"reset": true})); + _ => {} } + (commands, pick_picture) }); + // A measuring body cannot submit commands; a second pass submits only its own control events. + if let Some((commands, pick_picture)) = section.settle(|_, result| std::mem::take(result)) { + for params in commands { + run(app, "design.background", params); + } + if pick_picture { + app.pick_and_run("picture", "design.background", json!({})); + } + } + let hide = app.session.active().and_then(|d| d.current_slide().map(|s| !s.show_master_shapes)).unwrap_or(false); + if let Some(hide) = Checkbox::new(Bind::given(hide)).label(Word::plain("Hide background graphics")).show(ui).events.committed() { + run(app, "design.hideBackgroundGraphics", json!({"hide": hide})); + } + let current = match &fill { + Some(Fill::Solid { color }) => Some(json!({"color": cref_param(color)})), + Some(Fill::Gradient(g)) => Some(json!({"gradient": crate::fillui::gradient_json(g)})), + Some(Fill::Pattern(p)) => Some(json!({"pattern": crate::fillui::pattern_json(p)})), + _ => None, + }; + let picture = matches!(fill, Some(Fill::Picture(_))); + let mut buttons = Row::new().show(ui, |ui, _| { + let apply = Button::new(Word::plain("Apply to All")).enabled(current.is_some() || picture).show(ui).clicked(); + let reset = Button::new(Word::plain("Reset Background")).show(ui).clicked(); + (apply, reset) + }); + let (apply, reset) = buttons.settle(|_, value| *value).unwrap_or_default(); + if apply { + if let Some(Value::Object(mut params)) = current { + params.insert("all".into(), json!(true)); + run(app, "design.background", Value::Object(params)); + } else if picture { + run(app, "design.background", json!({"copy": true})); + } + } + if reset { + run(app, "design.background", json!({"reset": true})); + } } -/// Render picture-fill background controls and route transparency, tiling, and tile geometry -/// changes through the engine. -fn picture_background_options(app: &mut SlideApp, ui: &mut Ui, pf: &deckcraft_model::style::PictureFill) { - use deckcraft_model::style::PictureMode; - let alpha = pf.alpha.unwrap_or(1.0); - let mut tr = ((1.0 - alpha) * 100.0) as f32; - if ui.add(egui::Slider::new(&mut tr, 0.0..=100.0).text("Transparency").suffix("%")).drag_stopped() { - run(app, "design.background", json!({"transparency": (f64::from(tr) / 100.0).clamp(0.0, 1.0)})); +fn transparency(ui: &mut Ui, alpha: f64) -> Option { + let result = SliderField::new(Word::plain("Transparency"), Bind::given((1.0 - alpha) * 100.0), 0.0..=100.0) + .unit_kind(UnitKind::Percent) + .show(ui); + result.events.committed().map(|value| json!({"transparency": value / 100.0})) +} + +fn picture_background_options(ui: &mut Ui, picture: &PictureFill) -> Vec { + let mut commands: Vec<_> = transparency(ui, picture.alpha.unwrap_or(1.0)).into_iter().collect(); + let tiled = matches!(picture.mode, PictureMode::Tile { .. }); + if let Some(tile) = Checkbox::new(Bind::given(tiled)).label(Word::plain("Tile picture as texture")).show(ui).events.committed() { + commands.push(json!({"pictureProps": {"tile": tile}})); } - let mut tile = matches!(pf.mode, PictureMode::Tile { .. }); - if ui.checkbox(&mut tile, "Tile picture as texture").changed() { - run(app, "design.background", json!({"pictureProps": {"tile": tile}})); - } - let PictureMode::Tile { tx, ty, sx, sy, flip, align } = &pf.mode else { return }; - for (label, id, value, suffix, scale) in [ - ("Offset X", "bg-ox", *tx, " pt", 1.0), - ("Offset Y", "bg-oy", *ty, " pt", 1.0), - ("Scale X", "bg-sx", *sx * 100.0, "%", 0.01), - ("Scale Y", "bg-sy", *sy * 100.0, "%", 0.01), + let PictureMode::Tile { tx, ty, sx, sy, flip, align } = &picture.mode else { return commands }; + for (label, key, value, unit, scale) in [ + ("Offset X", "offsetX", *tx, UnitKind::Points, 1.0), + ("Offset Y", "offsetY", *ty, UnitKind::Points, 1.0), + ("Scale X", "scaleX", *sx * 100.0, UnitKind::Percent, 0.01), + ("Scale Y", "scaleY", *sy * 100.0, UnitKind::Percent, 0.01), ] { - ui.horizontal(|ui| { - ui.add_sized(vec2(72.0, 20.0), egui::Label::new(label)); - if let Some(v) = widgets::spinner(ui, id, label, value, if scale < 1.0 { 5.0 } else { 1.0 }, suffix, 64.0) { - let key = match id { - "bg-ox" => "offsetX", - "bg-oy" => "offsetY", - "bg-sx" => "scaleX", - _ => "scaleY", - }; - run(app, "design.background", json!({"pictureProps": {key: v * scale}})); - } + let mut field = Field::new(Word::plain(label)).show(ui, |ui, _| { + NumberField::new(Word::plain(label), Bind::given(Some(value))) + .unit_kind(unit) + .step(if scale < 1.0 { 5.0 } else { 1.0 }) + .step_arrows(StepArrows::Trailing) + .show(ui) + .events + .committed() + .copied() + .flatten() }); + if let Some(value) = field.settle(|_, value| value.take()).flatten() { + commands.push(json!({"pictureProps": {key: value * scale}})); + } } - let align_name = match align.as_str() { - "t" => "Top", - "tr" => "Top Right", - "l" => "Left", - "ctr" => "Center", - "r" => "Right", - "bl" => "Bottom Left", - "b" => "Bottom", - "br" => "Bottom Right", - _ => "Top Left", - }; - ui.horizontal(|ui| { - let field = ui.add_sized(vec2(72.0, 20.0), egui::Label::new("Alignment")); - // P3(panels-w10): earlier framework ComboBox removal (no contract id) - let combo = egui::ComboBox::from_id_salt("bg-align").selected_text(align_name).width(140.0).show_ui(ui, |ui| { - for (k, l) in [ + for (label, key, current, choices) in [ + ( + "Alignment", + "align", + align.as_str(), + &[ ("tl", "Top Left"), ("t", "Top"), ("tr", "Top Right"), @@ -170,30 +178,18 @@ fn picture_background_options(app: &mut SlideApp, ui: &mut Ui, pf: &deckcraft_mo ("bl", "Bottom Left"), ("b", "Bottom"), ("br", "Bottom Right"), - ] { - if ui.selectable_label(align == k, l).clicked() { - run(app, "design.background", json!({"pictureProps": {"align": k}})); - } - } + ][..], + ), + ("Mirror", "mirror", flip.as_str(), &[("none", "None"), ("x", "Horizontal"), ("y", "Vertical"), ("xy", "Both")][..]), + ] { + let entries: Vec<_> = choices.iter().map(|(value, label)| Entry::new(*value, Word::plain(label))).collect(); + let current = choices.iter().find(|(value, _)| *value == current).unwrap_or(&choices[0]).0; + let mut field = Field::new(Word::plain(label)).show(ui, |ui, _| { + Select::new(Word::plain(label), Bind::given(current), &entries).show(ui).events.committed().copied() }); - let _ = combo.response.labelled_by(field.id); - }); - let mirror_name = match flip.as_str() { - "x" => "Horizontal", - "y" => "Vertical", - "xy" => "Both", - _ => "None", - }; - ui.horizontal(|ui| { - let field = ui.add_sized(vec2(72.0, 20.0), egui::Label::new("Mirror")); - // P3(panels-w10): earlier framework ComboBox removal (no contract id) - let combo = egui::ComboBox::from_id_salt("bg-mirror").selected_text(mirror_name).width(140.0).show_ui(ui, |ui| { - for (k, l) in [("none", "None"), ("x", "Horizontal"), ("y", "Vertical"), ("xy", "Both")] { - if ui.selectable_label(flip == k, l).clicked() { - run(app, "design.background", json!({"pictureProps": {"mirror": k}})); - } - } - }); - let _ = combo.response.labelled_by(field.id); - }); + if let Some(value) = field.settle(|_, value| value.take()).flatten() { + commands.push(json!({"pictureProps": {key: value}})); + } + } + commands } diff --git a/crates/ui-egui/src/panels/background_tests.rs b/crates/ui-egui/src/panels/background_tests.rs index 2b0b3d7e3..f6d335115 100644 --- a/crates/ui-egui/src/panels/background_tests.rs +++ b/crates/ui-egui/src/panels/background_tests.rs @@ -3,6 +3,7 @@ use deckcraft_engine::Session; use deckcraft_model::style::PictureMode; use deckcraft_model::{Background, Fill}; +use egui::accesskit::Role; use egui_kittest::Harness; use egui_kittest::kittest::Queryable; use serde_json::json; @@ -12,16 +13,11 @@ use crate::{Services, SlideApp}; /// 1×1 PNG. const PNG: &str = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="; -fn harness(mut app: SlideApp) -> Harness<'static, SlideApp> { - app.ui.tab = "Design".into(); - app.ui.pane = Some("background".into()); - let mut h = Harness::builder().with_size(egui::vec2(1800.0, 1100.0)).build_ui_state( - |ui, app: &mut SlideApp| { - app.logic(ui.ctx()); - app.ui(ui); - }, - app, - ); +fn harness(session: Session) -> Harness<'static, SlideApp> { + let mut h = + crate::test_harness::harness_with(session, Services::default(), Harness::builder().with_size(egui::vec2(1800.0, 1100.0)), |_| {}); + h.state_mut().ui.tab = "Design".into(); + h.state_mut().ui.pane = Some("background".into()); h.run_steps(3); h } @@ -35,31 +31,34 @@ fn picture_mode(h: &Harness<'_, SlideApp>) -> PictureMode { #[test] fn picture_fill_shows_transparency_and_tiling() { - let mut s = Session::with_new(); - s.execute("design.background", &json!({"picture": PNG, "name": "dot.png"})).unwrap(); - // P3(panels-w10): sh.A2 - let mut h = harness(SlideApp::new_base(s, Services::default())); - assert!(h.query_all_by_label("Format Background").next().is_some(), "the pane is open"); - let _ = h.get_by_label("Picture or texture fill"); - assert!(h.query_all_by_label("Transparency").next().is_some()); - h.get_by_label("Tile picture as texture").click(); - h.run_steps(2); - let _ = h.get_by_label("Offset X"); - let _ = h.get_by_label("Scale X"); - let _ = h.get_by_label("Alignment"); - let _ = h.get_by_label("Mirror"); - assert!(matches!(picture_mode(&h), PictureMode::Tile { .. })); -} - -#[test] -fn solid_fill_shows_transparency_without_tile_options() { - let mut s = Session::with_new(); - s.execute("design.background", &json!({"color": "accent1"})).unwrap(); - // P3(panels-w10): sh.A2 - let h = harness(SlideApp::new_base(s, Services::default())); - assert!(h.query_all_by_label("Transparency").next().is_some()); - let _ = h.get_by_label("Solid fill"); - assert!(h.query_by_label("Tile picture as texture").is_none()); + for (params, picture) in [(json!({"color": "accent1"}), false), (json!({"picture": PNG, "name": "dot.png"}), true)] { + let mut s = Session::with_new(); + s.execute("design.background", ¶ms).unwrap(); + let mut h = harness(s); + let _ = h.get_by_role_and_label(Role::Slider, "Transparency"); + let _ = h.get_by_role_and_label(Role::RadioButton, if picture { "Picture or texture fill" } else { "Solid fill" }); + assert_eq!(h.query_by_role_and_label(Role::Button, "Color color").is_some(), !picture); + assert_eq!(h.query_by_role_and_label(Role::CheckBox, "Tile picture as texture").is_some(), picture); + let tile_rows = [ + (Role::SpinButton, "Offset X"), + (Role::SpinButton, "Offset Y"), + (Role::SpinButton, "Scale X"), + (Role::SpinButton, "Scale Y"), + (Role::ComboBox, "Alignment"), + (Role::ComboBox, "Mirror"), + ]; + for (role, name) in tile_rows { + assert!(h.query_by_role_and_label(role, name).is_none()); + } + if picture { + h.get_by_role_and_label(Role::CheckBox, "Tile picture as texture").click(); + h.run_steps(2); + for (role, name) in tile_rows { + let _ = h.get_by_role_and_label(role, name); + } + assert!(matches!(picture_mode(&h), PictureMode::Tile { .. })); + } + } } #[test] @@ -68,8 +67,7 @@ fn apply_to_all_copies_the_picture() { s.execute("design.background", &json!({"picture": PNG, "name": "dot.png"})).unwrap(); s.execute("slide.new", &json!({})).unwrap(); s.execute("slide.go", &json!({"index": 0})).unwrap(); - // P3(panels-w10): sh.A2 - let mut h = harness(SlideApp::new_base(s, Services::default())); + let mut h = harness(s); h.get_by_label("Apply to All").click(); h.run_steps(2); let doc = &h.state().session.active().unwrap().doc; diff --git a/crates/ui-egui/src/panels/fillui.rs b/crates/ui-egui/src/panels/fillui.rs index 4e2708132..7a8dc8011 100644 --- a/crates/ui-egui/src/panels/fillui.rs +++ b/crates/ui-egui/src/panels/fillui.rs @@ -2,15 +2,30 @@ //! type, direction, angle and a stop bar (add, drag, recolour, set transparency, remove stops); and //! the pattern editor: a gallery of the preset patterns with foreground and background colors. +use craft::color_ui::gradient::{ColorStop, GradientStops, StopRows, StopRules}; +use craft::color_ui::ui::gradient::GradientEditor; +use craft::i18n::Word; +use craft::theme::Srgba; +use craft::ui::choice::Segmented; +use craft::ui::contract::{Bind, Entry, Props as _, Show as _, ShowContainer as _}; +use craft::ui::form::Field; +use craft::ui::list::ThumbAspect; +use craft::ui::pickers::Select; +use craft::ui::popover::Popover; +use craft::ui::primitives::{Glyph, IconSpec}; +use craft::ui::runtime::env::UnitKind; +use craft::ui::runtime::requests::HostAnswer; +use craft::ui::text::{NumberField, StepArrows}; use deckcraft_color::{ColorScheme, ColorTransform, SchemeSlot}; use deckcraft_model::ColorRef; use deckcraft_model::style::{Gradient, GradientFlip, GradientShape, GradientStop, PatternFill}; -use egui::{Color32, CornerRadius, Rect, Sense, Stroke, Ui, pos2, vec2}; +use egui::{Color32, CornerRadius, Rect, Ui, vec2}; use serde_json::{Value, json}; +use super::color_row::{color_menu, color_row, take_color_answer}; +use super::preset_grid::preset_grid; use crate::ribbon::cref_param; -use crate::theme::{self, Tokens}; -use crate::widgets; +use crate::theme; /// A default two-stop gradient on `base`: the colour and a darker shade. pub fn default_gradient(base: ColorRef, angle: f64) -> Gradient { @@ -60,43 +75,6 @@ fn c32(c: &ColorRef, sc: &ColorScheme) -> Color32 { theme::to_color32(c.resolve(sc, None)) } -/// Paint `g` left→right into `r` (the stop bar and preset swatches). -fn paint_bar(ui: &Ui, r: Rect, g: &Gradient, sc: &ColorScheme) { - // Checkerboard under transparent stops. - let p = ui.painter(); - let n = (r.width() / 6.0).ceil() as i32; - for i in 0..n { - for j in 0..((r.height() / 6.0).ceil() as i32) { - if (i + j) % 2 == 0 { - let cell = Rect::from_min_size(pos2(r.min.x + i as f32 * 6.0, r.min.y + j as f32 * 6.0), vec2(6.0, 6.0)).intersect(r); - p.rect_filled(cell, CornerRadius::ZERO, Color32::from_gray(220)); - } - } - } - let mut mesh = egui::Mesh::default(); - let stops: Vec<(f32, Color32)> = g.stops.iter().map(|s| (s.pos as f32, c32(&s.color, sc))).collect(); - let mut pts: Vec<(f32, Color32)> = vec![]; - if let Some(first) = stops.first() { - pts.push((0.0, first.1)); - } - pts.extend(stops.iter().copied()); - if let Some(last) = stops.last() { - pts.push((1.0, last.1)); - } - for (k, (t, c)) in pts.iter().enumerate() { - let x = r.min.x + t.clamp(0.0, 1.0) * r.width(); - mesh.colored_vertex(pos2(x, r.min.y), *c); - mesh.colored_vertex(pos2(x, r.max.y), *c); - if k > 0 { - let i = (k as u32) * 2; - mesh.add_triangle(i - 2, i - 1, i); - mesh.add_triangle(i - 1, i, i + 1); - } - } - p.add(egui::Shape::mesh(mesh)); - p.rect_stroke(r, CornerRadius::ZERO, Stroke::new(1.0, Tokens::get(ui.ctx()).border), egui::StrokeKind::Inside); -} - const DIRECTIONS_LINEAR: [(&str, f64); 8] = [("→", 0.0), ("↘", 45.0), ("↓", 90.0), ("↙", 135.0), ("←", 180.0), ("↖", 225.0), ("↑", 270.0), ("↗", 315.0)]; const DIRECTIONS_PATH: [(&str, [f64; 4]); 5] = [ @@ -107,243 +85,214 @@ const DIRECTIONS_PATH: [(&str, [f64; 4]); 5] = [ ("From bottom right", [1.0, 1.0, 0.0, 0.0]), ]; -/// The editor for `g`; returns the new gradient when the user changed something. -pub(crate) fn gradient_editor(app: &mut crate::SlideApp, ui: &mut Ui, label: &str, g: &Gradient) -> Option { - // P3(panels-w10): pn.A10 - let (id, scheme) = (label, app.color_scheme()); - let sc = &scheme; - let t = Tokens::get(ui.ctx()); - let mut out: Option = None; - let sel_id = ui.scope_id().with((id, "stop")); - let mut sel: usize = ui.data_mut(|d| d.get_temp(sel_id).unwrap_or(0)).min(g.stops.len().saturating_sub(1)); +enum DirectionGlyph { + Linear(usize), + Focus(usize), +} - // Preset variations of the first stop's colour. - ui.label("Preset gradients"); - ui.horizontal_wrapped(|ui| { - let base = g.stops.first().map(|s| s.color.clone()).unwrap_or(ColorRef::scheme(SchemeSlot::Accent1)); - let mut light = base.clone(); - light.mods.push(ColorTransform::LumMod(40_000)); - light.mods.push(ColorTransform::LumOff(60_000)); - let mut dark = base.clone(); - dark.mods.push(ColorTransform::LumMod(50_000)); - let variants: Vec = vec![ - default_gradient(base.clone(), 90.0), - Gradient { - stops: vec![GradientStop { pos: 0.0, color: light.clone() }, GradientStop { pos: 1.0, color: base.clone() }], - ..default_gradient(base.clone(), 90.0) - }, - Gradient { - stops: vec![GradientStop { pos: 0.0, color: base.clone() }, GradientStop { pos: 1.0, color: dark.clone() }], - ..default_gradient(base.clone(), 0.0) - }, - Gradient { - stops: vec![ - GradientStop { pos: 0.0, color: light.clone() }, - GradientStop { pos: 0.5, color: base.clone() }, - GradientStop { pos: 1.0, color: dark.clone() }, - ], - ..default_gradient(base.clone(), 45.0) - }, - Gradient { - tile: [0.0; 4], - stops: vec![GradientStop { pos: 0.0, color: light }, GradientStop { pos: 1.0, color: dark }], - shape: GradientShape::Path { path: "circle".into(), focus: [0.5, 0.5, 0.5, 0.5] }, - rotate_with_shape: true, - flip: None, - }, - Gradient { - stops: vec![GradientStop { pos: 0.0, color: base.clone() }, GradientStop { pos: 1.0, color: with_alpha(base, 0.0) }], - ..default_gradient(ColorRef::scheme(SchemeSlot::Accent1), 90.0) - }, - ]; - for v in variants { - let (r, resp) = ui.allocate_exact_size(vec2(34.0, 22.0), Sense::click()); - paint_bar(ui, r.shrink(2.0), &v, sc); - if resp.hovered() { - ui.painter().rect_stroke(r, CornerRadius::same(2), Stroke::new(1.5, t.accent), egui::StrokeKind::Inside); +const LINEAR_ICONS: [DirectionGlyph; 8] = [ + DirectionGlyph::Linear(0), + DirectionGlyph::Linear(1), + DirectionGlyph::Linear(2), + DirectionGlyph::Linear(3), + DirectionGlyph::Linear(4), + DirectionGlyph::Linear(5), + DirectionGlyph::Linear(6), + DirectionGlyph::Linear(7), +]; +const PATH_ICONS: [DirectionGlyph; 5] = + [DirectionGlyph::Focus(0), DirectionGlyph::Focus(1), DirectionGlyph::Focus(2), DirectionGlyph::Focus(3), DirectionGlyph::Focus(4)]; + +impl craft::ui::contract::MemoProps for DirectionGlyph { + fn key(&self, key: &mut craft::ui::contract::MemoKey) { + match self { + Self::Linear(i) => { + key.write_u32(0); + key.feed_hash(i); } - if resp.clicked() { - out = Some(v); + Self::Focus(i) => { + key.write_u32(1); + key.feed_hash(i); } } - }); + } +} + +impl Glyph for DirectionGlyph { + fn paint(&self, painter: &egui::Painter, tokens: &craft::ui::style::UiTokens, rect: Rect, color: Color32, _: bool) { + let stroke = egui::Stroke::new(tokens.stroke.thin, color); + match self { + Self::Linear(i) => { + let angle = DIRECTIONS_LINEAR[*i].1.to_radians() as f32; + let direction = vec2(angle.cos(), angle.sin()); + let side = vec2(-direction.y, direction.x); + let length = rect.width().min(rect.height()) * 0.35; + let tip = rect.center() + direction * length; + painter.line_segment([rect.center() - direction * length, tip], stroke); + for sign in [-1.0, 1.0] { + painter.line_segment([tip, tip - direction * length * 0.5 + side * length * 0.5 * sign], stroke); + } + } + Self::Focus(i) => { + let focus = DIRECTIONS_PATH[*i].1; + let inset = rect.shrink(rect.width().min(rect.height()) * 0.2); + painter.rect_stroke(inset, CornerRadius::ZERO, stroke, egui::StrokeKind::Inside); + let point = inset.min + vec2(inset.width() * focus[0] as f32, inset.height() * focus[1] as f32); + painter.circle_filled(point, rect.width().min(rect.height()) * 0.12, color); + } + } + } +} + +/// The editor for `g`; returns the new gradient when the user changed something. +pub(crate) fn gradient_editor(app: &mut crate::SlideApp, ui: &mut Ui, label: &str, g: &Gradient) -> Option { + let scheme = app.color_scheme(); + let sc = &scheme; + let mut out: Option = None; + + // Preset variations of the first stop's colour. + let base = g.stops.first().map(|s| s.color.clone()).unwrap_or(ColorRef::scheme(SchemeSlot::Accent1)); + let mut light = base.clone(); + light.mods.push(ColorTransform::LumMod(40_000)); + light.mods.push(ColorTransform::LumOff(60_000)); + let mut dark = base.clone(); + dark.mods.push(ColorTransform::LumMod(50_000)); + let variants: Vec = vec![ + default_gradient(base.clone(), 90.0), + Gradient { + stops: vec![GradientStop { pos: 0.0, color: light.clone() }, GradientStop { pos: 1.0, color: base.clone() }], + ..default_gradient(base.clone(), 90.0) + }, + Gradient { + stops: vec![GradientStop { pos: 0.0, color: base.clone() }, GradientStop { pos: 1.0, color: dark.clone() }], + ..default_gradient(base.clone(), 0.0) + }, + Gradient { + stops: vec![ + GradientStop { pos: 0.0, color: light.clone() }, + GradientStop { pos: 0.5, color: base.clone() }, + GradientStop { pos: 1.0, color: dark.clone() }, + ], + ..default_gradient(base.clone(), 45.0) + }, + Gradient { + tile: [0.0; 4], + stops: vec![GradientStop { pos: 0.0, color: light }, GradientStop { pos: 1.0, color: dark }], + shape: GradientShape::Path { path: "circle".into(), focus: [0.5, 0.5, 0.5, 0.5] }, + rotate_with_shape: true, + flip: None, + }, + Gradient { + stops: vec![GradientStop { pos: 0.0, color: base.clone() }, GradientStop { pos: 1.0, color: with_alpha(base, 0.0) }], + ..default_gradient(ColorRef::scheme(SchemeSlot::Accent1), 90.0) + }, + ]; + let preset_names = + ["Color to dark", "Light to color", "Color to shade", "Light through color to shade", "Radial light to shade", "Color to transparent"]; + let presets: Vec<_> = preset_names.into_iter().enumerate().map(|(i, name)| (i, Word::plain(name).into())).collect(); + if let Some(i) = preset_grid(ui, "Preset gradients", &presets, None, ThumbAspect::new(17, 11), |cx, rect, i| { + let stops: Vec<_> = variants[*i].stops.iter().map(|s| (s.pos as f32, c32(&s.color, sc).into())).collect(); + cx.checker(rect); + cx.ramp(rect, CornerRadius::ZERO, &stops, craft::behavior::Axis::X); + }) { + let mut preset = variants[i].clone(); + preset.rotate_with_shape = g.rotate_with_shape; + out = Some(preset); + } - // Type and direction. let kind = match &g.shape { GradientShape::Linear { .. } => "Linear", GradientShape::Path { path, .. } if path == "rect" => "Rectangular", GradientShape::Path { path, .. } if path == "shape" => "Path", GradientShape::Path { .. } => "Radial", }; - ui.horizontal(|ui| { - let field = ui.add_sized(vec2(70.0, 20.0), egui::Label::new("Type")); - // P3(panels-w10): earlier framework ComboBox removal (no contract id) - let combo = egui::ComboBox::from_id_salt((id, "kind")).selected_text(kind).width(120.0).show_ui(ui, |ui| { - for k in ["Linear", "Radial", "Rectangular", "Path"] { - if ui.selectable_label(kind == k, k).clicked() && kind != k { - let focus = match &g.shape { - GradientShape::Path { focus, .. } => *focus, - _ => [0.5, 0.5, 0.5, 0.5], - }; - let shape = match k { - "Linear" => GradientShape::Linear { angle: 90.0, scaled: false }, - "Rectangular" => GradientShape::Path { path: "rect".into(), focus }, - "Path" => GradientShape::Path { path: "shape".into(), focus }, - _ => GradientShape::Path { path: "circle".into(), focus }, - }; - out = Some(Gradient { shape, ..g.clone() }); - } - } - }); - let _ = combo.response.labelled_by(field.id); + let types: Vec<_> = ["Linear", "Radial", "Rectangular", "Path"].into_iter().map(|k| Entry::new(k, Word::plain(k))).collect(); + let mut type_field = Field::new(Word::plain("Type")).show(ui, |ui, _| { + Select::new(Word::plain("Type"), Bind::given(kind), &types).show(ui).events.committed().copied() }); - ui.horizontal_wrapped(|ui| { - ui.add_sized(vec2(70.0, 20.0), egui::Label::new("Direction")); - match &g.shape { - GradientShape::Linear { angle, .. } => { - for (l, a) in DIRECTIONS_LINEAR { - let on = (angle - a).abs() < 0.5; - if ui.selectable_label(on, l).on_hover_text(format!("{a}°")).clicked() { - out = Some(Gradient { shape: GradientShape::Linear { angle: a, scaled: false }, ..g.clone() }); - } - } - } - GradientShape::Path { path, focus } => { - for (l, f) in DIRECTIONS_PATH { - let on = focus.iter().zip(f).all(|(a, b)| (a - b).abs() < 1e-3); - if ui.selectable_label(on, l.trim_start_matches("From ")).on_hover_text(l).clicked() { - out = Some(Gradient { shape: GradientShape::Path { path: path.clone(), focus: f }, ..g.clone() }); - } - } - } - } - }); - if let GradientShape::Linear { angle, .. } = &g.shape { - ui.horizontal(|ui| { - ui.add_sized(vec2(70.0, 20.0), egui::Label::new("Angle")); - if let Some(a) = widgets::spinner(ui, &format!("{id}-angle"), "Angle", *angle, 15.0, "°", 70.0) { - out = Some(Gradient { shape: GradientShape::Linear { angle: a.rem_euclid(360.0), scaled: false }, ..g.clone() }); - } - }); + if let Some(k) = type_field.settle(|_, value| value.take()).flatten().filter(|k| *k != kind) { + let focus = match &g.shape { + GradientShape::Path { focus, .. } => *focus, + _ => [0.5; 4], + }; + let shape = match k { + "Linear" => GradientShape::Linear { angle: 90.0, scaled: false }, + "Rectangular" => GradientShape::Path { path: "rect".into(), focus }, + "Path" => GradientShape::Path { path: "shape".into(), focus }, + _ => GradientShape::Path { path: "circle".into(), focus }, + }; + out = Some(Gradient { shape, ..g.clone() }); } - - // Stop bar: click to add, drag a stop to move it. - ui.add_space(4.0); - ui.label("Gradient stops"); - let (bar, bar_resp) = ui.allocate_exact_size(vec2(ui.available_width().min(260.0), 18.0), Sense::click()); - bar_resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Unknown, true, "Gradient bar")); - paint_bar(ui, bar, g, sc); - let (marks, _) = ui.allocate_exact_size(vec2(bar.width(), 14.0), Sense::hover()); - let drag_id = ui.scope_id().with((id, "drag")); - let mut dragging: Option<(usize, f64)> = ui.data_mut(|d| d.get_temp(drag_id)); - // A double-clicked stop opens its colour menu, as in PowerPoint (#2175). - let mut open_color = false; - for (i, s) in g.stops.iter().enumerate() { - let pos = dragging.filter(|d| d.0 == i).map_or(s.pos, |d| d.1); - let x = bar.min.x + pos as f32 * bar.width(); - let r = Rect::from_center_size(pos2(x, marks.center().y), vec2(10.0, 12.0)); - let resp = ui.interact(r, ui.scope_id().with((id, "mark", i)), Sense::click_and_drag()); - resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, format!("Gradient stop {}", i + 1))); - let fill = c32(&s.color, sc); - let stroke = if i == sel { Stroke::new(2.0, t.accent) } else { Stroke::new(1.0, t.handle_stroke) }; - let tri = vec![pos2(x, r.min.y), pos2(r.max.x, r.min.y + 4.0), pos2(r.max.x, r.max.y), pos2(r.min.x, r.max.y), pos2(r.min.x, r.min.y + 4.0)]; - ui.painter().add(egui::Shape::convex_polygon(tri, fill, stroke)); - if resp.clicked() || resp.drag_started() { - sel = i; - } - if resp.double_clicked() { - sel = i; - open_color = true; - } - if resp.dragged() - && let Some(p) = resp.interact_pointer_pos() - { - dragging = Some((i, ((p.x - bar.min.x) / bar.width()).clamp(0.0, 1.0) as f64)); - } - if resp.drag_stopped() - && let Some((di, dp)) = dragging.take() - { - let mut ng = g.clone(); - if let Some(st) = ng.stops.get_mut(di) { - st.pos = (dp * 1000.0).round() / 1000.0; - } - out = Some(ng); - } - } - ui.data_mut(|d| match dragging { - Some(v) => { - d.insert_temp(drag_id, v); - } - None => d.remove::<(usize, f64)>(drag_id), - }); - if bar_resp.clicked() - && let Some(p) = bar_resp.interact_pointer_pos() - && g.stops.len() < 10 - { - // A new stop takes the colour of the nearest stop. - let pos = (((p.x - bar.min.x) / bar.width()).clamp(0.0, 1.0) as f64 * 1000.0).round() / 1000.0; - let near = g.stops.iter().min_by(|a, b| (a.pos - pos).abs().total_cmp(&(b.pos - pos).abs())).map(|s| s.color.clone()); - let mut ng = g.clone(); - ng.stops.push(GradientStop { pos, color: near.unwrap_or(ColorRef::scheme(SchemeSlot::Accent1)) }); - ng.stops.sort_by(|a, b| a.pos.total_cmp(&b.pos)); - sel = ng.stops.iter().position(|s| s.pos == pos).unwrap_or(0); - out = Some(ng); - } - - // The selected stop. - if let Some(s) = g.stops.get(sel) { - ui.horizontal(|ui| { - ui.add_sized(vec2(70.0, 20.0), egui::Label::new("Color")); - let (sw, _) = ui.allocate_exact_size(vec2(18.0, 18.0), Sense::hover()); - ui.painter().rect(sw, CornerRadius::same(3), c32(&s.color, sc), Stroke::new(1.0, t.border), egui::StrokeKind::Inside); - let r = widgets::drop_button(ui, "", vec2(24.0, 20.0), true); - r.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, "Stop color")); - let mut popup = widgets::color_popup(&r); - if open_color { - popup = popup.open_memory(egui::SetOpenCommand::Bool(true)); - } - popup.show(|ui| { - if let Some(Some(c)) = widgets::color_grid(ui, sc, None) { - let mut ng = g.clone(); - ng.stops[sel].color = with_alpha(c, alpha_of(&s.color)); - out = Some(ng); - } + match &g.shape { + GradientShape::Linear { angle, scaled } => { + let entries: Vec<_> = DIRECTIONS_LINEAR + .iter() + .enumerate() + .map(|(i, (_, a))| Entry::new(i, format!("{a}°")).icon(IconSpec::glyph(&LINEAR_ICONS[i]))) + .collect(); + let selected = DIRECTIONS_LINEAR.iter().position(|(_, a)| (angle - a).abs() < 0.5); + let mut direction = Field::new(Word::plain("Direction")).show(ui, |ui, _| { + Segmented::new(Word::plain("Direction"), Bind::given(selected.unwrap_or(usize::MAX)), &entries) + .show(ui) + .events + .committed() + .copied() }); - let can_remove = g.stops.len() > 2; - if ui.add_enabled(can_remove, egui::Button::new("Remove stop")).clicked() { - let mut ng = g.clone(); - ng.stops.remove(sel); - sel = sel.saturating_sub(1); - out = Some(ng); + if let Some(i) = direction.settle(|_, value| value.take()).flatten() { + out = Some(Gradient { shape: GradientShape::Linear { angle: DIRECTIONS_LINEAR[i].1, scaled: *scaled }, ..g.clone() }); } - }); - ui.horizontal(|ui| { - ui.add_sized(vec2(70.0, 20.0), egui::Label::new("Position")); - if let Some(v) = widgets::spinner(ui, &format!("{id}-pos-{sel}"), "Position", (s.pos * 100.0).round(), 5.0, "%", 70.0) { - let mut ng = g.clone(); - ng.stops[sel].pos = (v / 100.0).clamp(0.0, 1.0); - ng.stops.sort_by(|a, b| a.pos.total_cmp(&b.pos)); - out = Some(ng); + let mut field = Field::new(Word::plain("Angle")).show(ui, |ui, _| { + NumberField::new(Word::plain("Angle"), Bind::given(Some(*angle))) + .unit_kind(UnitKind::Degrees) + .step(15.0) + .step_arrows(StepArrows::Trailing) + .show(ui) + .events + .committed() + .copied() + .flatten() + }); + if let Some(a) = field.settle(|_, value| value.take()).flatten() { + out = Some(Gradient { shape: GradientShape::Linear { angle: a.rem_euclid(360.0), scaled: *scaled }, ..g.clone() }); } - }); - ui.horizontal(|ui| { - let label = ui.add_sized(vec2(70.0, 20.0), egui::Label::new("Transparency")); - let key = ui.scope_id().with((id, "tr", sel)); - let mut tr: f32 = ui.data_mut(|d| d.get_temp(key).unwrap_or(((1.0 - alpha_of(&s.color)) * 100.0) as f32)); - let r = ui.add(egui::Slider::new(&mut tr, 0.0..=100.0).suffix("%")).labelled_by(label.id); - if r.changed() { - ui.data_mut(|d| d.insert_temp(key, tr)); + } + GradientShape::Path { path, focus } => { + let entries: Vec<_> = DIRECTIONS_PATH + .iter() + .enumerate() + .map(|(i, (name, _))| Entry::new(i, Word::plain(name)).icon(IconSpec::glyph(&PATH_ICONS[i]))) + .collect(); + let selected = DIRECTIONS_PATH.iter().position(|(_, f)| focus.iter().zip(f).all(|(a, b)| (a - b).abs() < 1e-3)); + let mut direction = Field::new(Word::plain("Direction")).show(ui, |ui, _| { + Segmented::new(Word::plain("Direction"), Bind::given(selected.unwrap_or(usize::MAX)), &entries) + .show(ui) + .events + .committed() + .copied() + }); + if let Some(i) = direction.settle(|_, value| value.take()).flatten() { + out = Some(Gradient { shape: GradientShape::Path { path: path.clone(), focus: DIRECTIONS_PATH[i].1 }, ..g.clone() }); } - if r.drag_stopped() || (r.changed() && !r.dragged()) { - let mut ng = g.clone(); - ng.stops[sel].color = with_alpha(s.color.clone(), 1.0 - tr as f64 / 100.0); - ui.data_mut(|d| d.remove::(key)); - out = Some(ng); - } - }); + } } - ui.data_mut(|d| d.insert_temp(sel_id, sel)); - out + + let mut stops = to_stops(g, sc); + let editor = GradientEditor::<()>::new(label.to_owned(), Bind::bound(&mut stops)) + .rules(StopRules::new(StopRows::Combined).stops(2, 10)) + .midpoints(false) + .fields(true) + .show(ui); + if let Some(edited) = editor.edit.events.committed() { + out = Some(from_stops(edited, g)); + } + // The bar emits requests only in the receiving pass (gradient/editor.rs); a rerun reuses no input. + if let Some(request) = editor.color_requested + && let Some(rect) = request.rect + { + app.fill_editor.stop = Some((request.index, rect.left_bottom())); + } + stop_menu(app, ui, label, g, &mut out); + out.filter(|edited| edited != g) } /// The gallery names of the DrawingML preset patterns. @@ -491,106 +440,127 @@ fn paint_pattern(p: &egui::Painter, r: Rect, name: &str, fg: Color32, bg: Color3 /// The editor for `pt`: a gallery of the presets drawn in the current colors, then Foreground and /// Background color menus. Returns the new pattern when the user changed something. pub(crate) fn pattern_editor(app: &mut crate::SlideApp, ui: &mut Ui, p: &PatternFill) -> Option { - // P3(panels-w10): pn.A10 let (pt, scheme) = (p, app.color_scheme()); let sc = &scheme; - let t = Tokens::get(ui.ctx()); let mut out: Option = None; let (fg, bg) = (c32(&pt.fg, sc), c32(&pt.bg, sc)); - ui.label("Pattern"); - ui.horizontal_wrapped(|ui| { - ui.spacing_mut().item_spacing = vec2(2.0, 2.0); - for name in pattern_gallery() { - let on = pt.preset == name; - let (r, resp) = ui.allocate_exact_size(vec2(22.0, 22.0), Sense::click()); - paint_pattern(ui.painter(), r.shrink(2.0), name, fg, bg); - let stroke = if on || resp.hovered() || resp.has_focus() { Stroke::new(2.0, t.accent) } else { Stroke::new(1.0, t.border) }; - ui.painter().rect_stroke(r.shrink(1.0), CornerRadius::same(2), stroke, egui::StrokeKind::Inside); - let label = pattern_label(name); - resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, on, label)); - if resp.on_hover_text(label).clicked() && !on { - out = Some(PatternFill { preset: name.to_string(), ..pt.clone() }); - } - } - }); + let presets: Vec<_> = pattern_gallery().map(|name| (name.to_owned(), Word::plain(pattern_label(name)).into())).collect(); + if let Some(preset) = preset_grid(ui, "Pattern", &presets, Some(pt.preset.clone()), ThumbAspect::SQUARE, |cx, rect, name| { + paint_pattern(&cx.painter, rect, name, fg, bg); + }) + .filter(|preset| preset != &pt.preset) + { + out = Some(PatternFill { preset, ..pt.clone() }); + } for (label, foreground) in [("Foreground", true), ("Background", false)] { - ui.horizontal(|ui| { - ui.add_sized(vec2(80.0, 20.0), egui::Label::new(label)); - let cur = if foreground { &pt.fg } else { &pt.bg }; - let (sw, _) = ui.allocate_exact_size(vec2(18.0, 18.0), Sense::hover()); - ui.painter().rect(sw, CornerRadius::same(3), c32(cur, sc), Stroke::new(1.0, t.border), egui::StrokeKind::Inside); - let r = widgets::drop_button(ui, "", vec2(24.0, 20.0), true); - let name = format!("{label} color"); - r.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &name)); - widgets::color_popup(&r).show(|ui| { - if let Some(Some(c)) = widgets::color_grid(ui, sc, None) { - out = Some(if foreground { PatternFill { fg: c, ..pt.clone() } } else { PatternFill { bg: c, ..pt.clone() } }); + color_row(app, ui, label, None, |_, picked| { + if let Some(color) = picked { + let pattern = out.get_or_insert_with(|| pt.clone()); + if foreground { + pattern.fg = color; + } else { + pattern.bg = color; } - }); + } }); } - out + out.filter(|pattern| pattern != pt) +} + +/// The open stop-colour popover; delayed samples carry their target in their answer key. +#[derive(Default)] +pub struct FillEditorState { + stop: Option<(usize, egui::Pos2)>, +} + +/// Converts a gradient to framework stops. +pub(crate) fn to_stops(g: &Gradient, sc: &ColorScheme) -> GradientStops { + GradientStops::new( + g.stops + .iter() + .enumerate() + .map(|(i, stop)| { + let color = stop.color.resolve(sc, None); + let color = Srgba { + r: f32::from(color.r) / 255.0, + g: f32::from(color.g) / 255.0, + b: f32::from(color.b) / 255.0, + a: alpha_of(&stop.color) as f32, + }; + ColorStop::new(stop.pos as f32, color).with_tag(i as u64 + 1) + }) + .collect(), + ) +} + +/// Applies framework stops while preserving other gradient settings. +pub(crate) fn from_stops(stops: &GradientStops, g: &Gradient) -> Gradient { + let stops = stops + .color + .iter() + .map(|stop| { + let source = source_stop(stop.tag, g).or_else(|| { + g.stops.iter().min_by(|a, b| (a.pos - f64::from(stop.location)).abs().total_cmp(&(b.pos - f64::from(stop.location)).abs())) + }); + let color = source.map_or_else(|| ColorRef::scheme(SchemeSlot::Accent1), |s| s.color.clone()); + GradientStop { pos: f64::from(stop.location), color: with_alpha(color, f64::from(stop.color.a)) } + }) + .collect(); + Gradient { stops, ..g.clone() } +} + +fn source_stop(tag: u64, g: &Gradient) -> Option<&GradientStop> { + tag.checked_sub(1).and_then(|i| usize::try_from(i).ok()).and_then(|i| g.stops.get(i)) +} + +fn stop_menu(app: &mut crate::SlideApp, ui: &mut Ui, label: &str, g: &Gradient, out: &mut Option) { + if craft::ui::runtime::measure::active(ui.ctx()) { + return; + } + // The UI scope names the fill property; document, subject and value prevent delayed samples crossing targets. + let prefix = format!("fill.gradient.{:?}.{label}:", ui.scope_id()); + let subject = + app.session.active().map(|doc| (doc.uid, doc.current_slide().map(|s| s.id), doc.selection.target, doc.selection.shapes.clone())); + let identity = format!("{prefix}{subject:?}:{g:?}:"); + let keys: Vec<_> = (0..g.stops.len()).map(|i| format!("{identity}{i}")).collect(); + // Answers are consumed in their receiving pass. A second pass has no drained answer to replay. + app.host_answers.retain(|answer| !matches!(answer, HostAnswer::Eyedropper { key, .. } if key.starts_with(&prefix) && !keys.contains(key))); + for (i, key) in keys.iter().enumerate() { + if let Some(Some(color)) = take_color_answer(app, key) { + recolor_stop(out, g, i, color); + app.fill_editor.stop = None; + } + } + let open = app.fill_editor.stop; + if let Some((i, point)) = open { + let Some(key) = keys.get(i) else { + app.fill_editor.stop = None; + return; + }; + let mut menu = Popover::new(Word::plain("Stop color"), Bind::given(open.is_some())) + .id_salt(label) + .at_point(point) + .show(ui, |ui, cx| color_menu(app, ui, cx, key, None)); + let picked = menu.settle(|_, value| value.take()).flatten(); + if let Some(Some(color)) = picked { + recolor_stop(out, g, i, color); + app.fill_editor.stop = None; + } + if menu.output.closed.is_some() { + app.fill_editor.stop = None; + } + } +} + +fn recolor_stop(out: &mut Option, g: &Gradient, i: usize, color: ColorRef) { + if let Some(stop) = out.get_or_insert_with(|| g.clone()).stops.get_mut(i) { + stop.color = with_alpha(color, alpha_of(&stop.color)); + } } #[cfg(test)] mod tests { - #![allow(clippy::unwrap_used, clippy::expect_used)] - use super::*; - use egui_kittest::Harness; - use egui_kittest::kittest::Queryable; - - /// #2175: double-clicking a gradient stop selects it and opens its colour menu; a colour - /// picked there colours that stop. - #[test] - fn double_clicking_a_stop_opens_its_color_menu() { - let sc = deckcraft_model::Theme::default().colors; - // P3(panels-w10): pn.A10 - let _ = ≻ - // P3(panels-w10): sh.A2 - let mut app = crate::SlideApp::new_base(deckcraft_engine::Session::new(), crate::Services::default()); - let start = Gradient { - stops: vec![ - GradientStop { pos: 0.0, color: ColorRef::scheme(SchemeSlot::Accent1) }, - GradientStop { pos: 1.0, color: ColorRef::scheme(SchemeSlot::Accent2) }, - ], - ..default_gradient(ColorRef::scheme(SchemeSlot::Accent1), 90.0) - }; - // The gradient, and whether the interface fonts are in (they apply from the next frame). - let mut h = Harness::builder().with_size(vec2(400.0, 700.0)).with_step_dt(1.0 / 60.0).build_ui_state( - move |ui, (g, fonts): &mut (Gradient, bool)| { - if !*fonts { - theme::install_fonts(ui.ctx()); - *fonts = true; - return; - } - // P3(panels-w10): pn.A10 - if let Some(ng) = gradient_editor(&mut app, ui, "test-grad", &g.clone()) { - *g = ng; - } - }, - (start, false), - ); - h.run_steps(3); - assert!(h.query_by_label("Theme Colors").is_none(), "the menu starts closed"); - let stop = h.get_by_label("Gradient stop 2").rect().center(); - h.hover_at(stop); - h.run_steps(1); - for _ in 0..2 { - for pressed in [true, false] { - h.event(egui::Event::PointerButton { pos: stop, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); - h.run_steps(1); - } - } - h.run_steps(2); - assert!(h.query_by_label("Theme Colors").is_some(), "the colour menu opened"); - h.get_by_label(SchemeSlot::Accent6.label()).click(); - h.run_steps(2); - let g = &h.state().0; - assert_eq!(g.stops.len(), 2, "no stop was added"); - assert_eq!(g.stops[1].color, ColorRef::scheme(SchemeSlot::Accent6), "the double-clicked stop took the colour"); - assert_eq!(g.stops[0].color, ColorRef::scheme(SchemeSlot::Accent1)); - } #[test] fn gradient_json_retains_flip_mode() { @@ -603,25 +573,35 @@ mod tests { }; assert_eq!(gradient_json(&gradient).get("flip"), Some(&json!("xy"))); } -} -/// The selected gradient stop and its position. -#[allow(dead_code)] // P3(panels-w10): pn.A10 -#[derive(Default)] -pub struct FillEditorState { - stop: Option<(usize, egui::Pos2)>, -} - -/// Converts a gradient to framework stops. -#[allow(dead_code)] // P3(panels-w10): pn.A10 -pub(crate) fn to_stops(g: &Gradient, sc: &ColorScheme) -> craft::color_ui::gradient::GradientStops { - let _ = (g, sc); - todo!("pn.A10") -} - -/// Applies framework stops while preserving other gradient settings. -#[allow(dead_code)] // P3(panels-w10): pn.A10 -pub(crate) fn from_stops(stops: &craft::color_ui::gradient::GradientStops, g: &Gradient) -> Gradient { - let _ = (stops, g); - todo!("pn.A10") + #[test] + fn gradient_stops_round_trip_keeps_scheme_colours_and_alpha() { + let mut scheme_color = ColorRef::scheme(SchemeSlot::Accent2); + scheme_color.mods.push(ColorTransform::LumMod(60_000)); + let g = Gradient { + stops: vec![ + GradientStop { pos: 0.0, color: with_alpha(scheme_color.clone(), 0.4) }, + GradientStop { pos: 1.0, color: with_alpha(ColorRef::rgb(deckcraft_color::Rgba::rgb(10, 40, 80)), 0.7) }, + ], + shape: GradientShape::Path { path: "rect".into(), focus: [0.0, 0.0, 1.0, 1.0] }, + flip: Some(GradientFlip::Xy), + tile: [0.1, 0.2, 0.3, 0.4], + rotate_with_shape: false, + }; + let mut stops = to_stops(&g, &deckcraft_model::Theme::default().colors); + assert_eq!(from_stops(&stops, &g), g); + stops.color.swap(0, 1); + stops.color[0].location = 0.0; + stops.color[0].color.a = 1.0; + stops.color[1].location = 1.0; + stops.color[1].color.a = 0.25; + let added = ColorStop::new(0.8, stops.color[1].color); + stops.color.insert(1, added); + let result = from_stops(&stops, &g); + assert_eq!(result.stops[0].color, with_alpha(g.stops[1].color.clone(), 1.0)); + assert!(!result.stops[0].color.mods.iter().any(|m| matches!(m, ColorTransform::Alpha(_)))); + assert_eq!(result.stops[2].color, with_alpha(scheme_color, 0.25)); + assert_eq!(result.stops[1].color, with_alpha(g.stops[1].color.clone(), f64::from(added.color.a))); + assert_eq!(Gradient { stops: g.stops.clone(), ..result }, g); + } } diff --git a/crates/ui-egui/src/panels/pattern_fill_tests.rs b/crates/ui-egui/src/panels/pattern_fill_tests.rs index 2da0c2a79..08e583bfa 100644 --- a/crates/ui-egui/src/panels/pattern_fill_tests.rs +++ b/crates/ui-egui/src/panels/pattern_fill_tests.rs @@ -1,27 +1,21 @@ -//! Format Shape and Format Background ▸ Pattern fill: the preset gallery and the Foreground and -//! Background color menus. +//! Pattern edits preserve colour references in both fill hosts. use deckcraft_color::Rgba; use deckcraft_engine::Session; use deckcraft_model::style::PatternFill; use deckcraft_model::{Background, ColorBase, ColorRef, Fill, ShapeId}; use egui::accesskit::Role; -use egui::{Event, Key, Modifiers, PointerButton}; +use egui::{Event, Key, Modifiers}; use egui_kittest::Harness; use egui_kittest::kittest::Queryable; use serde_json::json; use crate::{Services, SlideApp}; -fn harness(mut app: SlideApp, pane: &str) -> Harness<'static, SlideApp> { - app.ui.pane = Some(pane.into()); - let mut h = Harness::builder().with_size(egui::vec2(1800.0, 1100.0)).build_ui_state( - |ui, app: &mut SlideApp| { - app.logic(ui.ctx()); - app.ui(ui); - }, - app, - ); +fn harness(session: Session, pane: &str) -> Harness<'static, SlideApp> { + let mut h = + crate::test_harness::harness_with(session, Services::default(), Harness::builder().with_size(egui::vec2(1800.0, 1100.0)), |_| {}); + h.state_mut().ui.pane = Some(pane.into()); h.run_steps(3); h } @@ -50,149 +44,54 @@ fn background_pattern(h: &Harness<'_, SlideApp>) -> PatternFill { } } -/// Open the color menu named `button` and pick `hex` from its More Colors field. +/// Enter a colour through the menu's named hex field and submit it with Enter. fn pick_hex(h: &mut Harness<'_, SlideApp>, button: &str, hex: &str) { - h.get_by_label(button).click(); + h.get_by_role_and_label(Role::Button, button).click(); h.run_steps(2); - // The hex field is the text input on the "More Colors… #" label's row, to its right. - let label = h.get_by_label("More Colors… #").rect(); - let field = h - .get_all_by_role(Role::TextInput) - .find(|n| n.rect().min.x >= label.max.x - 1.0 && (n.rect().center().y - label.center().y).abs() < 6.0) - .map(|n| n.rect().center()) - .expect("the More Colors hex field"); + h.get_by_role_and_label(Role::TextInput, "More Colors…").click(); + h.run_steps(1); for pressed in [true, false] { - h.input_mut().events.push(Event::PointerButton { pos: field, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); - h.run_steps(2); + h.input_mut().events.push(Event::Key { + key: Key::A, + physical_key: None, + pressed, + repeat: false, + modifiers: Modifiers { ctrl: true, command: true, ..Modifiers::NONE }, + }); + h.run_steps(1); } - h.input_mut().events.push(Event::Text(hex.into())); - h.run_steps(2); + h.get_by_role_and_label(Role::TextInput, "More Colors…").type_text(hex); + h.run_steps(1); for pressed in [true, false] { h.input_mut().events.push(Event::Key { key: Key::Enter, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE }); - h.run_steps(2); + h.run_steps(1); } h.run_steps(2); } -#[test] -fn shape_pattern_fill_picks_a_preset_from_the_gallery() { - let (s, id) = patterned_shape(); - // P3(panels-w10): sh.A2 - let mut h = harness(SlideApp::new_base(s, Services::default()), "format"); - let _ = h.get_by_label("Pattern fill"); - assert!(h.query_by_label("Transparency").is_none(), "a pattern has no solid-fill transparency"); - assert_eq!(crate::fillui::pattern_gallery().count(), 48); - for name in crate::fillui::pattern_gallery() { - assert!(deckcraft_render::pattern_presets().any(|p| p == name), "{name}"); - let _ = h.get_by_label(crate::fillui::pattern_label(name)); - } - for label in ["Horizontal", "Vertical", "Cross", "Downward diagonal", "Upward diagonal", "Diagonal cross"] { - assert!(h.query_by_label(label).is_none(), "{label} is not in the gallery"); - } - let undo = h.state().session.active().unwrap().history.undo.len(); - h.get_by_label("Dark downward diagonal").click(); - h.run_steps(2); - let pt = shape_pattern(&h, id); - assert_eq!(pt.preset, "dkDnDiag"); - assert_eq!((pt.fg, pt.bg), (ColorRef::scheme(deckcraft_color::SchemeSlot::Accent1), ColorRef::scheme(deckcraft_color::SchemeSlot::Bg1))); - assert_eq!(h.state().session.active().unwrap().history.undo.len(), undo + 1, "one undo step"); -} +// PLAN: plan error: panels-w8 owns the solid-fill move target fill_color_and_transparency_show_only_where_they_change_the_fill in format_shape_tests.rs outside this set's Files table. #[test] fn shape_pattern_fill_keeps_preset_and_system_colors() { - let (mut s, id) = patterned_shape(); - let fg = json!({"preset": "red", "lumMod": 50000}); - let bg = json!({"system": "window", "last": "#F0F0F0"}); - s.execute("shape.fill", &json!({"pattern": {"preset": "pct25", "fg": fg, "bg": bg}})).unwrap(); - // P3(panels-w10): sh.A2 - let mut h = harness(SlideApp::new_base(s, Services::default()), "format"); - let before = shape_pattern(&h, id); - assert!(matches!(before.fg.base, ColorBase::Preset { .. }) && matches!(before.bg.base, ColorBase::System { .. })); - h.get_by_label("Zig zag").click(); - h.run_steps(2); - let pt = shape_pattern(&h, id); - assert_eq!(pt.preset, "zigZag"); - assert_eq!((&pt.fg, &pt.bg), (&before.fg, &before.bg), "a preset change keeps both colors"); - pick_hex(&mut h, "Foreground color", "00FF00"); - assert_eq!(shape_pattern(&h, id).bg, before.bg, "a foreground change keeps the background"); -} - -#[test] -fn pattern_gallery_shows_which_swatch_has_keyboard_focus() { - let (s, _) = patterned_shape(); - // P3(panels-w10): sh.A2 - let mut h = harness(SlideApp::new_base(s, Services::default()), "format"); - let r = h.get_by_label("Zig zag").rect(); - let accent = crate::theme::Tokens::get(&h.ctx).accent; - let outlined = |h: &Harness<'_, SlideApp>| { - h.output().shapes.iter().any(|c| match &c.shape { - egui::Shape::Rect(rs) => { - rs.stroke.width == 2.0 && rs.stroke.color == accent && (rs.rect.center() - r.center()).length() < 0.5 && rs.rect.width() < r.width() - } - _ => false, - }) - }; - assert!(!outlined(&h), "an unselected swatch has a plain border"); - h.get_by_label("Zig zag").focus(); - h.run_steps(2); - assert!(h.get_by_label("Zig zag").is_focused()); - assert!(outlined(&h), "the focused swatch is outlined"); -} - -/// A solid fill shows its transparency slider and does not expose a pattern gallery. -#[test] -fn shape_solid_fill_keeps_its_transparency_without_a_pattern_gallery() { - let (mut s, _) = patterned_shape(); - s.execute("shape.fill", &json!({"color": "accent2"})).unwrap(); - // P3(panels-w10): sh.A2 - let h = harness(SlideApp::new_base(s, Services::default()), "format"); - // 0.37 exposes the slider's numeric entry as a SpinButton with the same name; the slider is - // the control the user drags. - let _ = h.get_by_role_and_label(Role::Slider, "Transparency"); - assert!(h.query_by_label("Foreground color").is_none()); - assert!(h.query_by_label("Zig zag").is_none()); -} - -#[test] -fn shape_pattern_fill_sets_its_foreground_and_background_colors() { - let (s, id) = patterned_shape(); - // P3(panels-w10): sh.A2 - let mut h = harness(SlideApp::new_base(s, Services::default()), "format"); - pick_hex(&mut h, "Foreground color", "00FF00"); - let pt = shape_pattern(&h, id); - assert_eq!(pt.fg, ColorRef::rgb(Rgba::from_hex("00FF00").unwrap())); - assert_eq!(pt.preset, "pct25", "the pattern stays"); - pick_hex(&mut h, "Background color", "112233"); - let pt = shape_pattern(&h, id); - assert_eq!(pt.bg, ColorRef::rgb(Rgba::from_hex("112233").unwrap())); - assert_eq!(pt.fg, ColorRef::rgb(Rgba::from_hex("00FF00").unwrap()), "the foreground stays"); -} - -#[test] -fn background_pattern_fill_offers_every_preset_and_both_colors() { - let mut s = Session::with_new(); - s.execute("design.background", &json!({"pattern": {"preset": "pct20", "fg": "accent1", "bg": "bg1"}})).unwrap(); - // P3(panels-w10): sh.A2 - let mut h = harness(SlideApp::new_base(s, Services::default()), "background"); - h.get_by_label("Zig zag").click(); - h.run_steps(2); - assert_eq!(background_pattern(&h).preset, "zigZag"); - pick_hex(&mut h, "Background color", "FFEE00"); - let pt = background_pattern(&h); - assert_eq!((pt.preset.as_str(), pt.bg), ("zigZag", ColorRef::rgb(Rgba::from_hex("FFEE00").unwrap()))); -} - -#[test] -fn background_pattern_fill_keeps_a_system_color() { - let mut s = Session::with_new(); - let bg = json!({"system": "window", "last": "#F0F0F0"}); - s.execute("design.background", &json!({"pattern": {"preset": "pct20", "fg": "accent1", "bg": bg}})).unwrap(); - // P3(panels-w10): sh.A2 - let mut h = harness(SlideApp::new_base(s, Services::default()), "background"); - let before = background_pattern(&h).bg; - assert!(matches!(before.base, ColorBase::System { .. })); - h.get_by_label("Zig zag").click(); - h.run_steps(2); - let pt = background_pattern(&h); - assert_eq!((pt.preset.as_str(), pt.bg), ("zigZag", before)); + for pane in ["format", "background"] { + let (mut s, id) = patterned_shape(); + let fg = json!({"preset": "red", "lumMod": 50000}); + let bg = json!({"system": "window", "last": "#F0F0F0"}); + let command = if pane == "format" { "shape.fill" } else { "design.background" }; + s.execute(command, &json!({"pattern": {"preset": "pct25", "fg": fg, "bg": bg}})).unwrap(); + let mut h = harness(s, pane); + let pattern = |h: &Harness<'_, SlideApp>| if pane == "format" { shape_pattern(h, id) } else { background_pattern(h) }; + let before = pattern(&h); + assert!(matches!(before.fg.base, ColorBase::Preset { .. }) && matches!(before.bg.base, ColorBase::System { .. })); + h.get_by_label("Zig zag").click(); + h.run_steps(2); + let picked = pattern(&h); + assert_ne!(picked.preset, before.preset, "the tile pick reached the document"); + assert_eq!((&picked.fg, &picked.bg), (&before.fg, &before.bg), "a preset change keeps both colour references"); + pick_hex(&mut h, "Foreground color", "00FF00"); + let recolored = pattern(&h); + assert_eq!(recolored.fg, ColorRef::rgb(Rgba::from_hex("00FF00").unwrap()), "the hex submission reached the foreground"); + assert_eq!(recolored.bg, before.bg, "a foreground edit keeps the system background"); + assert_eq!(recolored.preset, picked.preset, "a foreground edit keeps the chosen pattern"); + } }