diff --git a/crates/ui-egui/src/eyedropper.rs b/crates/ui-egui/src/eyedropper.rs index 55119b01c..72362e395 100644 --- a/crates/ui-egui/src/eyedropper.rs +++ b/crates/ui-egui/src/eyedropper.rs @@ -1,225 +1,87 @@ -//! The Eyedropper in the colour menus (Shape Fill, Shape Outline, Font Color…): choose it, then -//! click the slide to take the colour drawn under the pointer; Esc or a click elsewhere cancels. -//! -//! The menus are drawn by many callers that each apply the colour a swatch gives. The Eyedropper -//! therefore hands its colour back through the same menu: the menu closes while the pointer picks, -//! then opens again for one frame and `color_grid` returns the colour as if its swatch had been -//! clicked, so every caller applies it its own way. -//! -//! Picture Format ▸ Color ▸ Set Transparent Color uses the same pointer, as PowerPoint does: the -//! click names the colour of the selected picture under it, which turns transparent. +//! The canvas Eyedropper samples the rendered slide with the framework's pick-mode dropper. +//! Colour menus receive a keyed host answer through `ThemeColorMenu::take_answer`; picture +//! transparency uses the picked document point with the engine's selected-picture command. -use egui::{Color32, Context, CursorIcon, Id, Pos2, Rect, Stroke, StrokeKind, Ui, pos2, vec2}; +use std::sync::Arc; + +use craft::color_ui::ui::{DropperMode, DropperTool}; +use craft::theme::Srgba; +use craft::ui::runtime::requests::HostAnswer; +use egui::{Context, Rect}; use crate::SlideApp; -use crate::canvas::Xf; -use crate::theme::{self, Tokens}; - -const REQUEST: &str = "deckcraft.eyedropper.request"; -const TRANSPARENT: &str = "deckcraft.eyedropper.transparent"; -const MENU: &str = "deckcraft.eyedropper.menu"; -const RESULT: &str = "deckcraft.eyedropper.result"; /// Pixels per slide unit of the picture the Eyedropper looks at. const SCALE: f64 = 2.0; -/// What a click with the pointer does. -#[derive(Clone, Copy)] -enum Pick { - /// Hands the colour to the colour menu on this button. - Menu(Id), - /// Makes the colour of the selected picture under the pointer transparent. +/// The target and the single dropper tool retained until picking or cancellation ends the arming. +pub struct Armed { + target: Target, + // PLAN: plan error: Armed.slide is unused; the sample carries its point and the engine uses current targets. + tool: Option>, +} + +/// The recipient of a picked colour. +pub enum Target { + /// The colour menu identified by its eyedropper request key. + Menu(String), + /// The selected picture under the picked document point. TransparentColor, } -/// An Eyedropper waiting for a click: the slide as it is drawn and what the click is for. -pub struct State { - pick: Pick, - slide: usize, - image: deckcraft_render::Image, -} - -/// Derive a unique egui id for an eyedropper menu target name. -fn key(name: &str) -> Id { - Id::unique(name) -} - -/// The colour menu button whose menu is open (noted by `color_popup` every frame it is). -pub fn note_open_menu(ctx: &Context, button: Id) { - ctx.data_mut(|d| d.insert_temp(key(MENU), button)); -} - -/// The menu button that is open now, if a menu noted itself. -pub fn open_menu(ctx: &Context) -> Option { - ctx.data(|d| d.get_temp::(key(MENU))) -} - -/// Keeps `hex` (`RRGGBB`) for the menu on `button`, which opens to hand it to its caller. -pub fn store_result(ctx: &Context, button: Id, hex: &str) { - ctx.data_mut(|d| d.insert_temp(key(RESULT), Some((button, hex.to_string())))); -} - -/// "Eyedropper" was chosen in the open menu. -pub fn request(ctx: &Context) { - ctx.data_mut(|d| d.insert_temp(key(REQUEST), true)); -} - -/// Picture Format ▸ Color ▸ "Set Transparent Color" was chosen. -pub fn request_transparent_color(ctx: &Context) { - ctx.data_mut(|d| d.insert_temp(key(TRANSPARENT), true)); -} - -/// Has the Eyedropper taken a colour for the menu on `button`? -pub fn result_waits_for(ctx: &Context, button: Id) -> bool { - ctx.data(|d| d.get_temp::>(key(RESULT))).flatten().is_some_and(|(b, _)| b == button) -} - -/// The colour the Eyedropper took (`RRGGBB`), once. -pub fn take_result(ctx: &Context) -> Option { - let r = ctx.data(|d| d.get_temp::>(key(RESULT))).flatten(); - if r.is_some() { - ctx.data_mut(|d| d.insert_temp(key(RESULT), None::<(Id, String)>)); - } - r.map(|(_, hex)| hex) -} - -/// Once a frame: start the Eyedropper when a menu asked for it, stop it when something else is -/// clicked. -pub fn tick(app: &mut SlideApp, ctx: &Context) { - if ctx.data_mut(|d| d.remove_temp::(key(REQUEST))).unwrap_or(false) - && let Some(menu) = open_menu(ctx) - { - begin(app, Pick::Menu(menu)); - } - if ctx.data_mut(|d| d.remove_temp::(key(TRANSPARENT))).unwrap_or(false) { - begin(app, Pick::TransparentColor); - } - // P3(canvas-w13): cv.A1 - if app.eyedropper_base.is_some() { - let outside = - ctx.input(|i| i.pointer.primary_pressed() && i.pointer.hover_pos().is_some_and(|p| app.canvas_rect.is_none_or(|c| !c.contains(p)))); - if outside { - // P3(canvas-w13): cv.A1 - app.eyedropper_base = None; - } - } -} - -fn begin(app: &mut SlideApp, pick: Pick) { +/// Arms one pick-mode tool over a snapshot of the active slide. +pub fn arm(app: &mut SlideApp, target: Target) { let Some(d) = app.session.active() else { return }; if d.selection.target != deckcraft_engine::Target::Slides { app.set_status("The Eyedropper takes colours from a slide"); return; } let slide = d.selection.slide; - let image = deckcraft_render::render_slide(&d.doc, slide, &deckcraft_render::RenderOpts { scale: SCALE, ..Default::default() }); - // P3(canvas-w13): cv.A1 - app.eyedropper_base = Some(State { pick, slide, image }); - app.set_status(match pick { - Pick::Menu(_) => "Eyedropper: click the slide (Esc cancels)", - Pick::TransparentColor => "Set Transparent Color: click the colour in the picture (Esc cancels)", - }); -} - -fn hex(c: [u8; 4]) -> String { - format!("{:02X}{:02X}{:02X}", c[0], c[1], c[2]) -} - -/// The slide canvas while the Eyedropper waits: the pointer is a crosshair with the colour under it -/// beside it, a click takes it. Returns true when it used the pointer (the tools get none). -pub fn canvas(app: &mut SlideApp, ui: &Ui, resp: &egui::Response, xf: Xf) -> bool { - // P3(canvas-w13): cv.A1 - let Some(state) = app.eyedropper_base.as_ref() else { return false }; - let escape = ui.input(|i| i.key_pressed(egui::Key::Escape)); - if escape || resp.secondary_clicked() { - // P3(canvas-w13): cv.A1 - app.eyedropper_base = None; - return true; - } - let Some(pos) = resp.hover_pos() else { return true }; - let on_slide = app.slide_rect.is_some_and(|r| r.contains(pos)); - if !on_slide { - ui.ctx().set_cursor_icon(CursorIcon::NotAllowed); - if resp.clicked() { - // P3(canvas-w13): cv.A1 - app.eyedropper_base = None; + let image = Arc::new(deckcraft_render::render_slide(&d.doc, slide, &deckcraft_render::RenderOpts { scale: SCALE, ..Default::default() })); + let tool = DropperTool::new(move |[x, y]| { + let (x, y) = (x * SCALE, y * SCALE); + if !(0.0..f64::from(image.width)).contains(&x) || !(0.0..f64::from(image.height)).contains(&y) { + return None; } - return true; + let [r, g, b, a] = image.straight_at(x as u32, y as u32)?.map(|channel| f32::from(channel) / 255.0); + Some(Srgba::new(r, g, b, a)) + }) + .mode(DropperMode::Pick); + let status = match &target { + Target::Menu(_) => "Eyedropper: click the slide (Esc cancels)", + Target::TransparentColor => "Set Transparent Color: click the colour in the picture (Esc cancels)", + }; + app.eyedropper = Some(Armed { target, tool: Some(tool) }); + app.set_status(status); +} + +/// Takes the arming's tool for the canvas pass without rebuilding its sampler or gesture state. +pub fn tool(app: &mut SlideApp) -> Option> { + app.eyedropper.as_mut()?.tool.take() +} + +/// Settles this pass's pick or cancellation and returns a continuing tool to its arming. +pub fn after_pass(app: &mut SlideApp, ctx: &Context, mut tool: DropperTool<'static>, canvas_rect: Rect) { + let Some(mut armed) = app.eyedropper.take() else { return }; + // A press outside the canvas disarms, as production did. + let outside = ctx.input(|i| i.pointer.primary_pressed() && i.pointer.hover_pos().is_some_and(|pos| !canvas_rect.contains(pos))); + if outside { + ctx.request_repaint(); + return; } - ui.ctx().set_cursor_icon(CursorIcon::Crosshair); - let p = xf.to_slide(pos); - let under = state.image.straight_at((p.x * SCALE).max(0.0) as u32, (p.y * SCALE).max(0.0) as u32); - if let Some(c) = under { - loupe(ui, pos, c); - } - if resp.clicked() { - let (pick, slide) = (state.pick, state.slide); - // P3(canvas-w13): cv.A1 - app.eyedropper_base = None; - match pick { - Pick::Menu(menu) => { - match app.session.execute("slide.colorAt", &serde_json::json!({"slide": slide, "x": p.x, "y": p.y, "scale": SCALE})) { - Ok(v) => { - if let Some(color) = v["color"].as_str() { - store_result(ui.ctx(), menu, color); - } - } - Err(e) => app.set_status(e.to_string()), - } - } - Pick::TransparentColor => { - if let Err(e) = app.session.execute("picture.transparentColor", &serde_json::json!({"at": [p.x, p.y]})) { - app.set_status(e.to_string()); + if let Some(([x, y], color)) = tool.take_at() { + match armed.target { + Target::Menu(key) => app.host_answers.push(HostAnswer::Eyedropper { key, color: color.with_alpha(1.0) }), + Target::TransparentColor => { + if let Err(error) = app.session.execute("picture.transparentColor", &serde_json::json!({"at": [x, y]})) { + app.set_status(error.to_string()); } } } - ui.ctx().request_repaint(); + } else if !tool.ended() { + armed.tool = Some(tool); + app.eyedropper = Some(armed); + return; } - true -} - -/// The colour under the pointer, drawn beside it with its hex. -fn loupe(ui: &Ui, pos: Pos2, c: [u8; 4]) { - let t = Tokens::get(ui.ctx()); - let painter = ui.ctx().layer_painter(egui::LayerId::new(egui::Order::Tooltip, key("deckcraft.eyedropper.loupe"))); - let at = pos + vec2(18.0, 18.0); - let swatch = Rect::from_min_size(at, vec2(64.0, 26.0)); - painter.rect(swatch, 3, Color32::from_rgb(c[0], c[1], c[2]), Stroke::new(2.0, Color32::WHITE), StrokeKind::Outside); - painter.rect_stroke(swatch.expand(2.0), 3, Stroke::new(1.0, t.border), StrokeKind::Outside); - let label = Rect::from_min_size(pos2(at.x, swatch.max.y + 5.0), vec2(64.0, 16.0)); - painter.rect_filled(label, 3, Color32::WHITE); - painter.text(label.center(), egui::Align2::CENTER_CENTER, format!("#{}", hex(c)), theme::bold(11.0), Color32::BLACK); -} - -/// The armed target and its single dropper tool. -#[allow(dead_code)] // P3(canvas-w13): cv.A7 -pub struct Armed { - target: Target, - tool: Option>, -} - -/// The target that receives a sampled colour. -pub enum Target { - /// A colour menu identified by its request key. - Menu(String), - /// The picture transparent colour. - TransparentColor, -} - -/// Arms the canvas eyedropper for a target. -pub fn arm(app: &mut crate::SlideApp, target: Target) { - let _ = (app, target); - todo!("cv.A7") -} - -/// Takes the arming dropper tool for this pass. -pub fn tool(app: &mut crate::SlideApp) -> Option> { - let _ = app; - todo!("cv.A7") -} - -/// Returns the dropper tool after the pass and settles its answer. -pub fn after_pass(app: &mut crate::SlideApp, ctx: &egui::Context, tool: craft::color_ui::ui::DropperTool<'static>, canvas_rect: Rect) { - let _ = (app, ctx, tool, canvas_rect); - todo!("cv.A7") + ctx.request_repaint(); } diff --git a/crates/ui-egui/src/eyedropper_tests.rs b/crates/ui-egui/src/eyedropper_tests.rs index 04e167726..2c1e39972 100644 --- a/crates/ui-egui/src/eyedropper_tests.rs +++ b/crates/ui-egui/src/eyedropper_tests.rs @@ -1,49 +1,59 @@ //! The Eyedropper on the slide canvas through real egui input. #![allow(clippy::unwrap_used, clippy::expect_used)] +use std::sync::Arc; + +use craft::color_ui::ui::{ColorPick, ThemeColorMenu}; +use craft::ui::runtime::requests::HostAnswer; use deckcraft_engine::Session; -use egui::{Event, Id, Key, Modifiers, PointerButton, Pos2}; +use egui::{Event, Key, Modifiers, PointerButton, Pos2}; use egui_kittest::Harness; use egui_kittest::kittest::Queryable; use serde_json::json; -use crate::eyedropper::{note_open_menu, request, result_waits_for, take_result}; +use crate::eyedropper::{self, Target}; use crate::{Services, SlideApp}; +const RED: deckcraft_color::Rgba = deckcraft_color::Rgba::rgb(255, 0, 0); + fn harness() -> Harness<'static, SlideApp> { let mut session = Session::with_new(); session.execute("slide.new", &json!({"layout": "blank"})).unwrap(); session.execute("shape.insert", &json!({"preset": "rect", "rect": [100, 100, 200, 100]})).unwrap(); - session.execute("shape.fill", &json!({"color": "#ff0000"})).unwrap(); - let mut h = Harness::builder().with_size(egui::vec2(1400.0, 900.0)).build_ui_state( - |ui, app: &mut SlideApp| { - app.logic(ui.ctx()); - app.ui(ui); - }, - // P3(canvas-w13): sh.A2 - SlideApp::new_base(session, Services::default()), - ); + session.execute("shape.fill", &json!({"color": RED.hex()})).unwrap(); + let mut h = crate::test_harness::harness_with(session, Services::default(), Harness::builder().with_size(egui::vec2(1400.0, 900.0)), |_| {}); + rerun_input_passes(&h); h.run_steps(4); h } -/// Test helper: stable unique id for the eyedropper test menu. -fn menu() -> Id { - Id::unique("test-menu") +// A second pass in each input frame must neither repeat an answer nor lose an arming. +fn rerun_input_passes(h: &Harness<'static, SlideApp>) { + h.ctx.on_end_pass( + "eyedropper-input-rerun", + Arc::new(|ui| { + if ui.ctx().current_pass_index() == 0 && ui.input(|i| !i.events.is_empty()) { + ui.ctx().request_discard("exercise eyedropper routing in a second pass"); + } + }), + ); +} + +fn menu() -> &'static str { + "test" } /// A colour menu asked for the Eyedropper. fn ask(h: &mut Harness<'static, SlideApp>) { - note_open_menu(&h.ctx, menu()); - request(&h.ctx); + eyedropper::arm(h.state_mut(), Target::Menu(menu().into())); h.run_steps(3); } /// Where a point of the slide is on screen. fn at(h: &Harness<'static, SlideApp>, x: f32, y: f32) -> Pos2 { let app = h.state(); - let r = app.slide_rect.expect("the slide is drawn"); - r.min + egui::vec2(x, y) * app.canvas_scale + let r = app.slide_rect().expect("the slide is drawn"); + r.min + egui::vec2(x, y) * app.canvas_scale() } fn click(h: &mut Harness<'static, SlideApp>, pos: Pos2) { @@ -71,21 +81,22 @@ fn a_click_on_the_slide_takes_the_colour_under_it_and_nothing_else_happens() { let on_shape = at(&h, 150.0, 150.0); h.input_mut().events.push(Event::PointerMoved(on_shape)); h.run_steps(3); - assert!(h.state().eyedropper.is_some() && !result_waits_for(&h.ctx, menu())); + assert!(h.state().eyedropper.is_some() && h.state().host_answers.is_empty()); click(&mut h, on_shape); assert!(h.state().eyedropper.is_none(), "one click ends it"); - assert!(result_waits_for(&h.ctx, menu()), "the colour waits for the menu that asked"); - assert_eq!(take_result(&h.ctx).as_deref(), Some("FF0000"), "the red of the shape under the pointer"); - assert_eq!(take_result(&h.ctx), None, "taken once"); + assert!(matches!(h.state().host_answers.as_slice(), [HostAnswer::Eyedropper { key, .. }] if key == menu())); + assert!(ThemeColorMenu::take_answer(&mut h.state_mut().host_answers, "other").is_none(), "another menu cannot take the answer"); + let red = ColorPick::Rgb(RED); + assert_eq!(ThemeColorMenu::take_answer(&mut h.state_mut().host_answers, menu()), Some(red.clone()), "the shape's fill reaches its asker"); + assert!(ThemeColorMenu::take_answer(&mut h.state_mut().host_answers, menu()).is_none(), "taken once"); assert_eq!(selection(&h), before, "the click did not select or move anything"); - // The slide itself is untouched, and the next click is an ordinary click again. assert_eq!(h.state().session.doc().unwrap().revision, revision, "the deck is untouched"); // Beside the shape the same click takes the slide's background instead. ask(&mut h); let empty = at(&h, 700.0, 450.0); click(&mut h, empty); - let bg = take_result(&h.ctx).expect("a colour"); - assert_ne!(bg, "FF0000"); + let bg = ThemeColorMenu::take_answer(&mut h.state_mut().host_answers, menu()).expect("a colour"); + assert_ne!(bg, red); } #[test] @@ -100,43 +111,42 @@ fn escape_and_a_click_off_the_slide_take_nothing() { h.run_steps(2); } assert!(h.state().eyedropper.is_none(), "Esc cancels"); - assert_eq!(take_result(&h.ctx), None); + assert!(h.state().host_answers.is_empty()); ask(&mut h); - let off = h.state().slide_rect.unwrap().min - egui::vec2(10.0, 10.0); + let off = h.state().slide_rect().unwrap().min - egui::vec2(10.0, 10.0); + assert!(h.state().canvas_rect().unwrap().contains(off), "the pasteboard case reaches the canvas tool"); click(&mut h, off); assert!(h.state().eyedropper.is_none(), "a click beside the slide cancels"); - assert_eq!(take_result(&h.ctx), None); + assert!(h.state().host_answers.is_empty()); - // Without an open colour menu there is nothing to hand a colour to. - let mut other = harness(); - request(&other.ctx); - other.run_steps(3); - assert!(other.state().eyedropper.is_none()); + ask(&mut h); + let outside = h.state().canvas_rect().unwrap().min - egui::vec2(1.0, 1.0); + h.input_mut().events.push(Event::PointerMoved(outside)); + h.run_steps(2); + h.input_mut().events.push(Event::PointerButton { pos: outside, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); + h.run_steps(2); + assert!(h.state().eyedropper.is_none(), "a press outside the canvas disarms before release"); + assert!(h.state().host_answers.is_empty()); + h.input_mut().events.push(Event::PointerButton { pos: outside, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); + h.run_steps(2); + assert!(h.state().host_answers.is_empty(), "the later release cannot hand back a colour"); } #[test] fn set_transparent_color_takes_the_colour_clicked_in_the_picture() { // Red on the left half, blue on the right. - let pixels = (0..8).flat_map(|i| if i % 4 < 2 { [255, 0, 0, 255] } else { [0, 0, 255, 255] }).collect(); + let blue = [0, 0, 255, 255]; + let pixels = (0..8).flat_map(|i| if i % 4 < 2 { [255, 0, 0, 255] } else { blue }).collect(); let png = deckcraft_render::Image { width: 4, height: 2, pixels }.to_png(); let mut session = Session::with_new(); session.execute("slide.new", &json!({"layout": "blank"})).unwrap(); let data = deckcraft_engine::cmd::base64_encode(&png); session.execute("insert.picture", &json!({"data": data, "name": "a.png", "rect": [100, 100, 400, 200]})).unwrap(); - // P3(canvas-w13): sh.A2 - let mut app = SlideApp::new_base(session, Services::default()); - app.ui.tab = "Picture Format".into(); - let mut h = Harness::builder().with_size(egui::vec2(1600.0, 1200.0)).build_ui_state( - |ui, app: &mut SlideApp| { - app.logic(ui.ctx()); - app.ui(ui); - }, - app, - ); + let mut h = crate::test_harness::harness_with(session, Services::default(), Harness::builder().with_size(egui::vec2(1600.0, 1200.0)), |_| {}); + h.state_mut().ui.tab = "Picture Format".into(); + rerun_input_passes(&h); h.run_steps(4); - // A colour menu opened earlier (Shape Fill, say) must not receive the colour. - note_open_menu(&h.ctx, menu()); h.get_by_label("Color").click(); h.run_steps(3); h.get_by_label("Set Transparent Color").click(); @@ -145,11 +155,12 @@ fn set_transparent_color_takes_the_colour_clicked_in_the_picture() { let blue_half = at(&h, 450.0, 200.0); click(&mut h, blue_half); assert!(h.state().eyedropper.is_none(), "one click ends it"); - assert!(!result_waits_for(&h.ctx, menu()), "the colour went to the picture, not to another menu"); + assert!(h.state().host_answers.is_empty(), "the colour went to the picture, not to a menu"); let doc = h.state().session.doc().unwrap(); let clear = doc.shapes().iter().find_map(|sh| match &sh.kind { - deckcraft_model::ShapeKind::Picture { fill } => Some(fill.adjust.clear_color), + deckcraft_model::ShapeKind::Picture { fill, .. } => Some(fill.adjust.clear_color), _ => None, }); - assert_eq!(clear, Some(Some(deckcraft_color::Rgba::rgb(0, 0, 255)))); + let [r, g, b, _] = blue; + assert_eq!(clear, Some(Some(deckcraft_color::Rgba::rgb(r, g, b)))); }