diff --git a/crates/engine/src/cmd/points.rs b/crates/engine/src/cmd/points.rs index 28eb0dd3b..7546e8c1b 100644 --- a/crates/engine/src/cmd/points.rs +++ b/crates/engine/src/cmd/points.rs @@ -1009,9 +1009,10 @@ pub fn segment_start_of(sh: &Shape, path: usize, index: usize) -> Option vs.iter().position(|v| Some(*v) == j.checked_sub(1)) } -/// Adding, deleting, opening or closing renumbers the points of `path`: a point type remembered -/// for one of them would follow the wrong point. +/// Renumbering invalidates menu picks and any point type remembered for `path`. fn forget_kinds(s: &mut Session, path: usize) { + s.tool.edit_segment = None; + s.tool.edit_vertex = None; if s.tool.vertex_kind.as_ref().is_some_and(|k| k.1 == path) { s.tool.vertex_kind = None; } diff --git a/crates/ui-egui/src/canvas/context_menu.rs b/crates/ui-egui/src/canvas/context_menu.rs index e180bcce4..e765174ef 100644 --- a/crates/ui-egui/src/canvas/context_menu.rs +++ b/crates/ui-egui/src/canvas/context_menu.rs @@ -1,311 +1,223 @@ -use super::{Hit, SlideApp, json}; +use craft::ui::contract::overlay::Anchor; +use craft::ui::contract::{Bind, Props as _, Show as _, ShowContainer as _}; +use craft::ui::display::Divider; +use craft::ui::menu::{Menu, MenuItem}; +use craft::ui::runtime::commands::{self, CommandRef, FireSource}; +use deckcraft_engine::tools::Hit; +use egui::{Pos2, Response, Ui}; +use serde_json::{Value, json}; -pub(super) fn context_menu(app: &mut SlideApp, resp: &egui::Response) { - // Right-clicking a vertex in Edit Points picks it for the point menu. - if resp.secondary_clicked() - && let Some(Hit::Vertex { path, index, .. }) = app.session.tool.hover.clone() - { - app.session.tool.edit_vertex = Some((path, index)); +use crate::SlideApp; +use crate::squiggles::{MenuWord, Tag}; + +/// The screen point at which the canvas menu was requested. +pub(crate) struct CanvasMenu { + at: Pos2, +} + +/// Shows the canvas menu, applying only the context request supplied for this pass. +pub(crate) fn show(app: &mut SlideApp, ui: &mut Ui, canvas: &Response, ask: Option) { + if let Some(at) = ask { + app.canvas_menu = Some(CanvasMenu { at }); + if let Some(Hit::Vertex { path, index, .. }) = app.session.tool.hover { + app.session.tool.edit_vertex = Some((path, index)); + } + let view = app.canvas_view; + app.squiggles.menu_word = app.session.active().and_then(|st| app.squiggles.word_at(st, view.to_doc(at), 4.0 / view.zoom)); } - resp.context_menu(|ui| { - let editing = app.session.active().and_then(|d| app.session.tool.editing_points(d).and_then(|id| d.shape(id).cloned())); - if let Some(sh) = editing { - edit_points_menu(app, ui, &sh); + let Some(menu) = &app.canvas_menu else { return }; + let at = menu.at; + let mut open = true; + Menu::context("Canvas", canvas).anchor(Anchor::Point(at)).open(Bind::bound(&mut open)).show(ui, |ui, _| { + let editing = app.session.active().and_then(|st| app.session.tool.editing_points(st).and_then(|id| st.shape(id).cloned())); + if let Some(shape) = editing { + edit_points_menu(app, ui, &shape); return; } - // A misspelt word under the pointer: its suggestions, then Ignore All and Add to Dictionary. - if let Some(w) = app.squiggles.menu_word.clone() { - spelling_menu(app, ui, &w); + if let Some(word) = app.squiggles.menu_word.clone() { + spelling_menu(app, ui, &word); } - let has_sel = app.session.active().is_some_and(|d| !d.selection.shapes.is_empty()); - for (l, id) in [("Cut", "edit.cut"), ("Copy", "edit.copy"), ("Paste", "edit.paste")] { - if ui.add_enabled(crate::ribbon::enabled(app, id), egui::Button::new(l)).clicked() { - let _ = app.run(id, json!({})); - ui.close(); - } + for (label, id) in [("Cut", "edit.cut"), ("Copy", "edit.copy"), ("Paste", "edit.paste")] { + MenuItem::command(id).label(label).show(ui); } - ui.separator(); - // Right-clicking the text being edited keeps it (`PointerKind::ContextClick`): text items. - let editing = app.session.active().is_some_and(|d| d.selection.text.as_ref().is_some_and(|t| !t.notes)); + Divider::horizontal().show(ui); + let editing = app.session.active().is_some_and(|st| st.selection.text.as_ref().is_some_and(|text| !text.notes)); if editing { text_items(app, ui); - } else if has_sel { + } else if app.session.active().is_some_and(|st| !st.selection.shapes.is_empty()) { shape_items(app, ui); } else { slide_items(app, ui); } }); + if !open { + app.canvas_menu = None; + app.squiggles.menu_word = None; + } } -fn edit_points_menu(app: &mut SlideApp, ui: &mut egui::Ui, sh: &deckcraft_model::Shape) { +fn edit_points_menu(app: &SlideApp, ui: &mut Ui, shape: &deckcraft_model::Shape) { if let Some((path, index)) = app.session.tool.edit_segment { - let cur = deckcraft_engine::cmd::points::segment_kind_of(sh, path, index); - for (l, k) in [("Straight Segment", "straight"), ("Curved Segment", "curved")] { - if ui.radio(cur == Some(k), l).clicked() { - let _ = app.run("shape.segmentType", json!({"path": path, "segment": index, "type": k})); - ui.close(); - } + let current = deckcraft_engine::cmd::points::segment_kind_of(shape, path, index); + for (label, kind) in [("Straight Segment", "straight"), ("Curved Segment", "curved")] { + MenuItem::command(CommandRef::with_params("shape.segmentType", json!({"path": path, "segment": index, "type": kind}))) + .label(label) + .radio_mark(current == Some(kind)) + .show(ui); } - // Each of these renumbers the points, so the picked segment is dropped. - if ui.button("Add Point").clicked() { - let t = app.session.tool.edit_segment_t.unwrap_or(0.5); - let _ = app.run("shape.addPoint", json!({"path": path, "segment": index, "t": t})); - app.session.tool.edit_segment = None; - ui.close(); - } - let closed = deckcraft_engine::cmd::points::closed_at(sh, path, index); - if ui.add_enabled(closed == Some(true), egui::Button::new("Delete Segment")).clicked() { - let _ = app.run("shape.deleteSegment", json!({"path": path, "segment": index})); - app.session.tool.edit_segment = None; - ui.close(); - } - // Open Path opens the outline at the segment's start point. + let t = app.session.tool.edit_segment_t.unwrap_or(0.5); + MenuItem::command(CommandRef::with_params("shape.addPoint", json!({"path": path, "segment": index, "t": t}))).label("Add Point").show(ui); + let closed = deckcraft_engine::cmd::points::closed_at(shape, path, index); + MenuItem::command(CommandRef::with_params("shape.deleteSegment", json!({"path": path, "segment": index}))) + .label("Delete Segment") + .enabled(closed == Some(true)) + .show(ui); + // Segments are indexed by their end vertex; opening cuts at the other end. let (label, id, at) = match closed { Some(false) => ("Close Path", "shape.closePath", index), - _ => ("Open Path", "shape.openPath", deckcraft_engine::cmd::points::segment_start_of(sh, path, index).unwrap_or(index)), + _ => ("Open Path", "shape.openPath", deckcraft_engine::cmd::points::segment_start_of(shape, path, index).unwrap_or(index)), }; - if ui.button(label).clicked() { - let _ = app.run(id, json!({"path": path, "index": at})); - app.session.tool.edit_segment = None; - ui.close(); - } - ui.separator(); + MenuItem::command(CommandRef::with_params(id, json!({"path": path, "index": at}))).label(label).show(ui); + Divider::horizontal().show(ui); } else if let Some((path, index)) = app.session.tool.edit_vertex { - let cur = deckcraft_engine::cmd::points::kind_of(sh, path, index); - for (l, k) in [("Smooth Point", "smooth"), ("Straight Point", "straight"), ("Corner Point", "corner")] { - if ui.radio(cur == Some(k), l).clicked() { - let _ = app.run("shape.pointType", json!({"path": path, "index": index, "type": k})); - ui.close(); - } + let current = deckcraft_engine::cmd::points::kind_of(shape, path, index); + for (label, kind) in [("Smooth Point", "smooth"), ("Straight Point", "straight"), ("Corner Point", "corner")] { + MenuItem::command(CommandRef::with_params("shape.pointType", json!({"path": path, "index": index, "type": kind}))) + .label(label) + .radio_mark(current == Some(kind)) + .show(ui); } - if ui.button("Delete Point").clicked() { - let _ = app.run("shape.deletePoint", json!({"path": path, "index": index})); - app.session.tool.edit_vertex = None; - ui.close(); - } - let (label, id) = match deckcraft_engine::cmd::points::closed_at(sh, path, index) { + MenuItem::command(CommandRef::with_params("shape.deletePoint", json!({"path": path, "index": index}))).label("Delete Point").show(ui); + let (label, id) = match deckcraft_engine::cmd::points::closed_at(shape, path, index) { Some(false) => ("Close Path", "shape.closePath"), _ => ("Open Path", "shape.openPath"), }; - if ui.button(label).clicked() { - let _ = app.run(id, json!({"path": path, "index": index})); - // The points are numbered from the new start now. - app.session.tool.edit_vertex = None; - ui.close(); - } - ui.separator(); + MenuItem::command(CommandRef::with_params(id, json!({"path": path, "index": index}))).label(label).show(ui); + Divider::horizontal().show(ui); } - if ui.button("Exit Edit Points").clicked() { - let _ = app.run("shape.editPoints", json!({"on": false})); - ui.close(); + MenuItem::command(CommandRef::with_params("shape.editPoints", json!({"on": false}))).label("Exit Edit Points").show(ui); +} + +fn spelling_menu(app: &mut SlideApp, ui: &mut Ui, word: &MenuWord) { + if let Some(from) = word.delete_from { + // Read the actual gap so tabs and nonbreaking spaces remain part of the checked range. + let cut = app + .session + .active() + .and_then(|st| match word.tag { + Tag::Shape { id, para } => st.shape(id)?.text.as_ref()?.paragraphs.get(para).map(|p| p.text()), + Tag::Cell { id, row, col, para } => match &st.shape(id)?.kind { + deckcraft_model::ShapeKind::Table(table) => table.cell(row, col)?.text.paragraphs.get(para).map(|p| p.text()), + _ => None, + }, + Tag::Notes { .. } => None, + }) + .map(|text| text.chars().skip(from).take(word.start + word.word.chars().count() - from).collect::()) + .unwrap_or_else(|| format!("{}{}", " ".repeat(word.start - from), word.word)); + MenuItem::command(CommandRef::with_params("review.spellingChange", spelling_params(word, from, &cut, ""))) + .label("Delete Repeated Word") + .show(ui); + } else if word.suggestions.is_empty() { + MenuItem::heading("(no spelling suggestions)").show(ui); + } + for suggestion in &word.suggestions { + MenuItem::command(CommandRef::with_params("review.spellingChange", spelling_params(word, word.start, &word.word, suggestion))) + .label(suggestion.clone()) + .show(ui); + } + Divider::horizontal().show(ui); + if MenuItem::new("Ignore All").show(ui).ran { + app.squiggles.ignore(&word.word); + } + MenuItem::command(CommandRef::with_params("review.addToDictionary", json!({"word": word.word}))).label("Add to Dictionary").show(ui); + Divider::horizontal().show(ui); +} + +fn spelling_params(word: &MenuWord, start: usize, cut: &str, to: &str) -> Value { + match word.tag { + Tag::Shape { id, para } => json!({"shape": id, "para": para, "start": start, "word": cut, "to": to}), + Tag::Cell { id, row, col, para } => json!({"shape": id, "row": row, "col": col, "para": para, "start": start, "word": cut, "to": to}), + Tag::Notes { .. } => json!({}), } } -fn spelling_menu(app: &mut SlideApp, ui: &mut egui::Ui, w: &crate::squiggles::MenuWord) { - if let Some(from) = w.delete_from { - if ui.button(egui::RichText::new("Delete Repeated Word").strong()).clicked() { - let cut: String = format!("{}{}", " ".repeat(w.start - from), w.word); - // The gap is spaces; take it from the text so tabs or no-break spaces match. - let gap = app - .session - .active() - .and_then(|st| match w.tag { - crate::squiggles::Tag::Shape { id, para } => st.shape(id)?.text.as_ref()?.paragraphs.get(para).map(|p| p.text()), - crate::squiggles::Tag::Cell { id, row, col, para } => match &st.shape(id)?.kind { - deckcraft_model::ShapeKind::Table(tb) => tb.cell(row, col)?.text.paragraphs.get(para).map(|p| p.text()), - _ => None, - }, - crate::squiggles::Tag::Notes { .. } => None, - }) - .map(|t| t.chars().skip(from).take(w.start + w.word.chars().count() - from).collect::()) - .unwrap_or(cut); - let mut p = json!({"para": 0, "start": from, "word": gap, "to": ""}); - if let Some(o) = p.as_object_mut() { - match w.tag { - crate::squiggles::Tag::Shape { id, para } => { - o.insert("shape".into(), json!(id)); - o.insert("para".into(), json!(para)); - } - crate::squiggles::Tag::Cell { id, row, col, para } => { - o.insert("shape".into(), json!(id)); - o.insert("row".into(), json!(row)); - o.insert("col".into(), json!(col)); - o.insert("para".into(), json!(para)); - } - crate::squiggles::Tag::Notes { .. } => {} - } +fn text_items(app: &mut SlideApp, ui: &mut Ui) { + for (label, id) in [("Paragraph…", "format.paragraphDialog"), ("Bullets", "format.bullets"), ("Numbering", "format.numbering")] { + MenuItem::command(id).label(label).show(ui); + } + if MenuItem::new("Link…").show(ui).ran { + app.open_dialog("hyperlink", json!({})); + } + Divider::horizontal().show(ui); + MenuItem::command(CommandRef::with_params("view.pane", json!({"pane": "format"}))).label("Format Shape…").show(ui); +} + +fn shape_items(app: &mut SlideApp, ui: &mut Ui) { + MenuItem::command("text.edit").label("Edit Text").show(ui); + if app.session.active().is_some_and(|st| st.selection.shapes.len() == 1 && st.selected_shapes().iter().all(|shape| !shape.is_line())) { + MenuItem::command(CommandRef::with_params("shape.editPoints", json!({"on": true}))).label("Edit Points").show(ui); + } + for (label, id) in [("Font…", "format.fontDialog"), ("Paragraph…", "format.paragraphDialog")] { + MenuItem::command(id).label(label).show(ui); + } + for (label, rows) in [ + ("Bring to Front", [("Bring to Front", "arrange.bringToFront"), ("Bring Forward", "arrange.bringForward")]), + ("Send to Back", [("Send to Back", "arrange.sendToBack"), ("Send Backward", "arrange.sendBackward")]), + ("Group", [("Group", "arrange.group"), ("Ungroup", "arrange.ungroup")]), + ] { + Menu::submenu_row(ui, label, |ui, _| { + for (label, id) in rows { + MenuItem::command(id).label(label).show(ui); } - let _ = app.run("review.spellingChange", p); - app.squiggles.menu_word = None; - ui.close(); - } - } else if w.suggestions.is_empty() { - ui.label(egui::RichText::new("(no spelling suggestions)").weak()); + }); } - for to in &w.suggestions { - if ui.button(egui::RichText::new(to).strong()).clicked() { - let p = match w.tag { - crate::squiggles::Tag::Shape { id, para } => json!({"shape": id, "para": para, "start": w.start, "word": w.word, "to": to}), - crate::squiggles::Tag::Cell { id, row, col, para } => { - json!({"shape": id, "row": row, "col": col, "para": para, "start": w.start, "word": w.word, "to": to}) - } - crate::squiggles::Tag::Notes { .. } => json!({}), - }; - let _ = app.run("review.spellingChange", p); - app.squiggles.menu_word = None; - ui.close(); + let locked = app.session.active().is_some_and(|st| st.selected_shapes().iter().all(|shape| shape.locked)); + MenuItem::command(CommandRef::with_params("shape.lock", json!({"locked": !locked}))).label(if locked { "Unlock" } else { "Lock" }).show(ui); + let picture = app + .session + .active() + .is_some_and(|st| st.selected_shapes().iter().any(|shape| matches!(shape.kind, deckcraft_model::ShapeKind::Picture { .. }))); + if picture { + MenuItem::command("app.changePictureDialog").label("Change Picture…").show(ui); + } + for (label, id) in [("Link…", "hyperlink"), ("Edit Alt Text…", "altText")] { + if MenuItem::new(label).show(ui).ran { + app.open_dialog(id, json!({})); } } - if ui.button("Ignore All").clicked() { - app.squiggles.ignore(&w.word); - app.squiggles.menu_word = None; - ui.close(); + for (label, id) in [("Set as Default Shape", "shape.setDefault"), ("Size and Position…", "shape.sizePosition")] { + MenuItem::command(id).label(label).show(ui); } - if ui.button("Add to Dictionary").clicked() { - if let Err(e) = app.session.execute("review.addToDictionary", &json!({"word": w.word})) { - app.set_status(e.to_string()); - } - app.squiggles.menu_word = None; - ui.close(); - } - ui.separator(); + MenuItem::command(CommandRef::with_params("view.pane", json!({"pane": "format"}))).label("Format Shape…").show(ui); } -fn text_items(app: &mut SlideApp, ui: &mut egui::Ui) { - if ui.button("Paragraph…").clicked() { - app.dialog = Some(crate::dialogs::Dialog::new("paragraph")); - ui.close(); - } - for (l, id) in [("Bullets", "format.bullets"), ("Numbering", "format.numbering")] { - if ui.add_enabled(crate::ribbon::enabled(app, id), egui::Button::new(l)).clicked() { - let _ = app.run(id, json!({})); - ui.close(); - } - } - if ui.button("Link…").clicked() { - app.dialog = Some(crate::dialogs::Dialog::new("hyperlink")); - ui.close(); - } - ui.separator(); - if ui.button("Format Shape…").clicked() { - let _ = app.run("view.pane", json!({"pane": "format"})); - ui.close(); - } -} - -fn shape_items(app: &mut SlideApp, ui: &mut egui::Ui) { - if ui.button("Edit Text").clicked() { - let _ = app.run("text.edit", json!({})); - ui.close(); - } - if crate::ribbon::enabled(app, "shape.editPoints") - && app.session.active().is_some_and(|d| d.selection.shapes.len() == 1 && d.selected_shapes().iter().all(|s| !s.is_line())) - && ui.button("Edit Points").clicked() - { - let _ = app.run("shape.editPoints", json!({"on": true})); - ui.close(); - } - if ui.button("Font…").clicked() { - let _ = app.run("format.fontDialog", json!({})); - ui.close(); - } - if ui.button("Paragraph…").clicked() { - let _ = app.run("format.paragraphDialog", json!({})); - ui.close(); - } - ui.menu_button("Bring to Front", |ui| { - crate::ribbon::menu_item(app, ui, crate::icons::Icon::BringToFront, "Bring to Front", "arrange.bringToFront", json!({})); - crate::ribbon::menu_item(app, ui, crate::icons::Icon::BringForward, "Bring Forward", "arrange.bringForward", json!({})); - }); - ui.menu_button("Send to Back", |ui| { - crate::ribbon::menu_item(app, ui, crate::icons::Icon::SendToBack, "Send to Back", "arrange.sendToBack", json!({})); - crate::ribbon::menu_item(app, ui, crate::icons::Icon::SendBackward, "Send Backward", "arrange.sendBackward", json!({})); - }); - ui.menu_button("Group", |ui| { - crate::ribbon::menu_item(app, ui, crate::icons::Icon::Group, "Group", "arrange.group", json!({})); - crate::ribbon::menu_item(app, ui, crate::icons::Icon::Ungroup, "Ungroup", "arrange.ungroup", json!({})); - }); - let locked = app.session.active().is_some_and(|d| d.selected_shapes().iter().all(|s| s.locked)); - if ui.button(if locked { "Unlock" } else { "Lock" }).clicked() { - let _ = app.run("shape.lock", json!({"locked": !locked})); - ui.close(); - } - let picture = - app.session.active().is_some_and(|d| d.selected_shapes().iter().any(|s| matches!(s.kind, deckcraft_model::ShapeKind::Picture { .. }))); - if picture && ui.button("Change Picture…").clicked() { - let _ = app.run("app.changePictureDialog", json!({})); - ui.close(); - } - if ui.button("Link…").clicked() { - app.dialog = Some(crate::dialogs::Dialog::new("hyperlink")); - ui.close(); - } - if ui.button("Edit Alt Text…").clicked() { - app.dialog = Some(crate::dialogs::Dialog::new("altText")); - ui.close(); - } - if ui.button("Set as Default Shape").clicked() { - let _ = app.run("shape.setDefault", json!({})); - ui.close(); - } - if ui.button("Size and Position…").clicked() { - let _ = app.run("shape.sizePosition", json!({})); - ui.close(); - } - if ui.button("Format Shape…").clicked() { - let _ = app.run("view.pane", json!({"pane": "format"})); - ui.close(); - } -} - -fn slide_items(app: &mut SlideApp, ui: &mut egui::Ui) { - ui.menu_button("Layout", |ui| { +fn slide_items(app: &mut SlideApp, ui: &mut Ui) { + Menu::submenu_row(ui, "Layout", |ui, _| { let layouts: Vec<(String, u32)> = app .session .active() - .and_then(|d| d.doc.masters.first().map(|m| m.layouts.iter().map(|l| (l.name.clone(), l.id.0)).collect())) + .and_then(|st| st.doc.masters.first().map(|master| master.layouts.iter().map(|layout| (layout.name.clone(), layout.id.0)).collect())) .unwrap_or_default(); - for (n, id) in layouts { - if ui.button(n).clicked() { - let _ = app.run("slide.layout", json!({"layout": id})); - ui.close(); - } + for (name, id) in layouts { + MenuItem::command(CommandRef::with_params("slide.layout", json!({"layout": id}))).label(name).show(ui); } }); - ui.menu_button("Grid and Guides", |ui| { - let mut on = app.ui.guides; - if ui.checkbox(&mut on, "Guides").clicked() { - let _ = app.run("view.guides", json!({"on": on})); - } + Menu::submenu_row(ui, "Grid and Guides", |ui, _| { + MenuItem::command(CommandRef::with_params("view.guides", json!({"on": !app.ui.guides}))) + .label("Guides") + .check(app.ui.guides) + .keep_open(true) + .show(ui); for (label, vertical) in [("Add Vertical Guide", true), ("Add Horizontal Guide", false)] { - if ui.button(label).clicked() { - let _ = app.run("guide.add", json!({"vertical": vertical})); - let _ = app.run("view.guides", json!({"on": true})); - ui.close(); + if MenuItem::command(CommandRef::with_params("guide.add", json!({"vertical": vertical}))).label(label).show(ui).ran { + // Queue visibility after addition, before Guides can seed defaults. + let _ = commands::fire(ui.ctx(), CommandRef::with_params("view.guides", json!({"on": true})), FireSource::Menu); } } }); - if ui.button("Reset Slide").clicked() { - let _ = app.run("slide.reset", json!({})); - ui.close(); - } - if ui.button("Format Background…").clicked() { - let _ = app.run("view.pane", json!({"pane": "background"})); - ui.close(); - } - if ui.button("New Comment").clicked() { - app.dialog = Some(crate::dialogs::Dialog::new("comment")); - ui.close(); + MenuItem::command("slide.reset").label("Reset Slide").show(ui); + MenuItem::command(CommandRef::with_params("view.pane", json!({"pane": "background"}))).label("Format Background…").show(ui); + if MenuItem::new("New Comment").show(ui).ran { + app.open_dialog("comment", json!({})); } } - -/// The canvas context menu state. -#[allow(dead_code)] // P3(canvas-w11): cv.A6 -pub struct CanvasMenu; - -/// Shows the canvas command menu with published command states. -#[allow(dead_code)] // P3(canvas-w11): cv.A6 -pub(crate) fn show(app: &mut crate::SlideApp, ui: &mut egui::Ui, canvas: &egui::Response, ask: Option) { - let _ = (app, ui, canvas, ask); - todo!("cv.A6") -} diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index dcafef7c0..3b2544f79 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -2,33 +2,30 @@ use std::sync::Arc; +use craft::behavior::CursorIcon; use deckcraft_engine::Session; -use egui::{Event, Modifiers, MouseWheelUnit, Pos2, TouchPhase, pos2, vec2}; +use deckcraft_geom::Point; +use egui::accesskit::Role; +use egui::{Event, Modifiers, Pos2, pos2, vec2}; use egui_kittest::Harness; use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::{Value, json}; -use super::*; +use super::tool::resize_cursor; use crate::{Services, SlideApp}; -/// #745: the resize cursor follows the handle's on-screen diagonal. A 45°-rotated shape's -/// NW corner sits at the top-right of the screen, where the drag axis is NE-SW — the old -/// fixed handle-to-cursor mapping showed NW-SE there. +/// #745: the resize cursor follows the handle's on-screen diagonal. #[test] fn resize_cursor_tracks_rotation() { let mut s = Session::with_new(); - // A square shape: the NW handle's diagonal is at 45° unrotated, so each 45° of shape - // rotation cleanly moves the cursor to the next of the four resize directions. - let id = s.execute("shape.insert", &serde_json::json!({"preset": "rect", "rect": [100.0, 100.0, 100.0, 100.0]})).unwrap()["id"].as_u64().unwrap() - as u32; + let id = s.execute("shape.insert", &json!({"preset": "rect", "rect": [100.0, 100.0, 100.0, 100.0]})).unwrap()["id"].as_u64().unwrap() as u32; let sid = deckcraft_model::ShapeId(id); - // Unrotated: the NW handle (0) drags the NW-SE diagonal. - assert_eq!(resize_cursor(&s, sid, 0), egui::CursorIcon::ResizeNwSe); - assert_eq!(resize_cursor(&s, sid, 4), egui::CursorIcon::ResizeNwSe); - assert_eq!(resize_cursor(&s, sid, 2), egui::CursorIcon::ResizeNeSw); - assert_eq!(resize_cursor(&s, sid, 6), egui::CursorIcon::ResizeNeSw); - assert_eq!(resize_cursor(&s, sid, 1), egui::CursorIcon::ResizeVertical); - assert_eq!(resize_cursor(&s, sid, 3), egui::CursorIcon::ResizeHorizontal); - // 45° rotation: the NW corner's drag axis rotates 45° with the shape — it is now vertical. + assert_eq!(resize_cursor(&s, sid, 0), CursorIcon::ResizeNwSe); + assert_eq!(resize_cursor(&s, sid, 4), CursorIcon::ResizeNwSe); + assert_eq!(resize_cursor(&s, sid, 2), CursorIcon::ResizeNeSw); + assert_eq!(resize_cursor(&s, sid, 6), CursorIcon::ResizeNeSw); + assert_eq!(resize_cursor(&s, sid, 1), CursorIcon::ResizeVertical); + assert_eq!(resize_cursor(&s, sid, 3), CursorIcon::ResizeHorizontal); { let doc = s.doc_mut().unwrap(); let pres = Arc::make_mut(&mut doc.doc); @@ -39,9 +36,8 @@ fn resize_cursor_tracks_rotation() { x.rot = 45.0; } } - assert_eq!(resize_cursor(&s, sid, 0), egui::CursorIcon::ResizeVertical, "45°: NW handle drags vertically"); - assert_eq!(resize_cursor(&s, sid, 2), egui::CursorIcon::ResizeHorizontal, "45°: NE handle drags horizontally"); - // 90° rotation: the NW corner is at the top-right; the drag axis is NE-SW. + assert_eq!(resize_cursor(&s, sid, 0), CursorIcon::ResizeVertical, "45°: NW handle drags vertically"); + assert_eq!(resize_cursor(&s, sid, 2), CursorIcon::ResizeHorizontal, "45°: NE handle drags horizontally"); { let doc = s.doc_mut().unwrap(); let pres = Arc::make_mut(&mut doc.doc); @@ -52,31 +48,26 @@ fn resize_cursor_tracks_rotation() { x.rot = 90.0; } } - assert_eq!(resize_cursor(&s, sid, 0), egui::CursorIcon::ResizeNeSw, "90°: the diagonal is NE-SW"); - assert_eq!(resize_cursor(&s, sid, 2), egui::CursorIcon::ResizeNwSe, "90°: NE diagonal is NW-SE"); - assert_eq!(resize_cursor(&s, sid, 1), egui::CursorIcon::ResizeHorizontal, "90°: the top edge is horizontal"); + assert_eq!(resize_cursor(&s, sid, 0), CursorIcon::ResizeNeSw, "90°: the diagonal is NE-SW"); + assert_eq!(resize_cursor(&s, sid, 2), CursorIcon::ResizeNwSe, "90°: NE diagonal is NW-SE"); + assert_eq!(resize_cursor(&s, sid, 1), CursorIcon::ResizeHorizontal, "90°: the top edge is horizontal"); } -/// #745: a corner handle shows a diagonal cursor whatever the shape's proportions. The -/// corner's direction is the diagonal, not the line to the box's centre, so a wide -/// rectangle's NW corner still drags along the NW-SE diagonal. +/// #745: a wide shape's corner follows the diagonal rather than the line to its centre. #[test] fn a_wide_shape_keeps_its_corner_cursors_diagonal() { let mut s = Session::with_new(); - let id = s.execute("shape.insert", &serde_json::json!({"preset": "rect", "rect": [100.0, 100.0, 400.0, 80.0]})).unwrap()["id"].as_u64().unwrap() - as u32; + let id = s.execute("shape.insert", &json!({"preset": "rect", "rect": [100.0, 100.0, 400.0, 80.0]})).unwrap()["id"].as_u64().unwrap() as u32; let sid = deckcraft_model::ShapeId(id); - assert_eq!(resize_cursor(&s, sid, 0), egui::CursorIcon::ResizeNwSe, "the NW corner drags NW-SE"); - assert_eq!(resize_cursor(&s, sid, 4), egui::CursorIcon::ResizeNwSe, "the SE corner drags NW-SE"); - assert_eq!(resize_cursor(&s, sid, 2), egui::CursorIcon::ResizeNeSw, "the NE corner drags NE-SW"); - assert_eq!(resize_cursor(&s, sid, 6), egui::CursorIcon::ResizeNeSw, "the SW corner drags NE-SW"); - // The edges keep their own cursors. - assert_eq!(resize_cursor(&s, sid, 1), egui::CursorIcon::ResizeVertical, "the top edge drags vertically"); - assert_eq!(resize_cursor(&s, sid, 3), egui::CursorIcon::ResizeHorizontal, "the right edge drags horizontally"); + assert_eq!(resize_cursor(&s, sid, 0), CursorIcon::ResizeNwSe, "the NW corner drags NW-SE"); + assert_eq!(resize_cursor(&s, sid, 4), CursorIcon::ResizeNwSe, "the SE corner drags NW-SE"); + assert_eq!(resize_cursor(&s, sid, 2), CursorIcon::ResizeNeSw, "the NE corner drags NE-SW"); + assert_eq!(resize_cursor(&s, sid, 6), CursorIcon::ResizeNeSw, "the SW corner drags NE-SW"); + assert_eq!(resize_cursor(&s, sid, 1), CursorIcon::ResizeVertical, "the top edge drags vertically"); + assert_eq!(resize_cursor(&s, sid, 3), CursorIcon::ResizeHorizontal, "the right edge drags horizontally"); } -/// #745: a placeholder that inherits its box from the layout still shows a resize cursor. -/// Its handles are drawn from the inherited box, so the cursor follows that one. +/// #745: a placeholder's handles follow the box inherited from its layout. #[test] fn a_placeholder_that_inherits_its_box_has_a_resize_cursor() { let s = Session::with_new(); @@ -89,257 +80,50 @@ fn a_placeholder_that_inherits_its_box_has_a_resize_cursor() { .find(|sh| sh.xfrm.is_none() && sh.ph.is_some()) .expect("the new slide has a placeholder without a box of its own") .id; - assert_eq!(resize_cursor(&s, ph, 0), egui::CursorIcon::ResizeNwSe, "the NW corner drags NW-SE"); - assert_eq!(resize_cursor(&s, ph, 2), egui::CursorIcon::ResizeNeSw, "the NE corner drags NE-SW"); - assert_eq!(resize_cursor(&s, ph, 1), egui::CursorIcon::ResizeVertical, "the top edge drags vertically"); + assert_eq!(resize_cursor(&s, ph, 0), CursorIcon::ResizeNwSe, "the NW corner drags NW-SE"); + assert_eq!(resize_cursor(&s, ph, 2), CursorIcon::ResizeNeSw, "the NE corner drags NE-SW"); + assert_eq!(resize_cursor(&s, ph, 1), CursorIcon::ResizeVertical, "the top edge drags vertically"); } fn harness() -> Harness<'static, SlideApp> { - let mut h = Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_ui_state( - |ui, app: &mut SlideApp| { - app.logic(ui.ctx()); - app.ui(ui); - }, - // P3(canvas-w11): sh.A2 - SlideApp::new_base(Session::with_new(), Services::default()), + let mut h = crate::test_harness::harness_with( + Session::with_new(), + Services::default(), + Harness::builder().with_size(vec2(1200.0, 800.0)), + |_| {}, ); h.run_steps(3); h } -/// The slide point (in slide points) under screen position `p`. +/// The slide point under screen position `p`. fn slide_point(h: &Harness<'_, SlideApp>, p: Pos2) -> Pos2 { - let (r, s) = (h.state().slide_rect.unwrap(), h.state().canvas_scale); - pos2((p.x - r.min.x) / s, (p.y - r.min.y) / s) + let (rect, scale) = (h.state().slide_rect().unwrap(), h.state().canvas_scale()); + pos2((p.x - rect.min.x) / scale, (p.y - rect.min.y) / scale) } -/// Test helper: inject a platform-command-modified line wheel event and run thirty harness -/// steps. -fn ctrl_wheel(h: &mut Harness<'_, SlideApp>, lines: f32) { - let wheel = Event::MouseWheel { - unit: MouseWheelUnit::Line, - delta: vec2(0.0, lines), - phase: TouchPhase::Move, - source: egui::MouseWheelSource::Wheel, - modifiers: Modifiers::COMMAND, - }; - h.event(wheel); - // egui spreads a wheel notch over several frames. - h.run_steps(30); -} - -/// Within half a slide point, plus the half device pixel the slide moves to sit on the pixel -/// grid (#184). -fn assert_near(a: Pos2, b: Pos2, what: &str) { - assert!((a - b).length() < 1.25, "{what}: {a:?} moved to {b:?}"); -} - -/// #106: wheel and pinch zoom zoomed toward the slide's corner instead of the pointer. -#[test] -fn wheel_and_pinch_zoom_keep_the_point_under_the_pointer() { - let mut h = harness(); - let fit = h.state().canvas_scale; - let r = h.state().slide_rect.unwrap(); - let p = r.min + vec2(r.width() * 0.8, r.height() * 0.7); - h.event(Event::PointerMoved(p)); - h.run_steps(1); - let under = slide_point(&h, p); - - h.event(Event::Zoom(2.0)); - h.run_steps(2); - assert!((h.state().canvas_scale - fit * 2.0).abs() < 1e-3); - assert_near(under, slide_point(&h, p), "pinch in"); - - ctrl_wheel(&mut h, 1.0); - assert!(h.state().canvas_scale > fit * 2.1, "Ctrl/Cmd + wheel up zooms in"); - assert_near(under, slide_point(&h, p), "wheel in"); - - ctrl_wheel(&mut h, -1.0); - ctrl_wheel(&mut h, -1.0); - assert!(h.state().canvas_scale < fit * 2.0, "Ctrl/Cmd + wheel down zooms out"); - assert_near(under, slide_point(&h, p), "wheel out"); - - h.event(Event::Zoom(0.8)); - h.run_steps(2); - assert_near(under, slide_point(&h, p), "pinch out"); - - // Zoomed out below the window size, the slide is centred again. - h.event(Event::Zoom(0.25)); - h.run_steps(2); - assert!(h.state().canvas_scale < fit); - let (canvas, slide) = (h.state().canvas_rect.unwrap(), h.state().slide_rect.unwrap()); - assert!((canvas.center() - slide.center()).length() < 1.0, "{canvas:?} {slide:?}"); -} - -/// Zoom In/Out (keys, buttons, slider) keeps the middle of the view where it is. -#[test] -fn zoom_commands_keep_the_middle_of_the_view() { - let mut h = harness(); - let c = h.state().canvas_rect.unwrap().center(); - let mid = slide_point(&h, c); - for _ in 0..4 { - h.state_mut().run("view.zoomIn", serde_json::json!({})).unwrap(); - h.run_steps(2); - assert_near(mid, slide_point(&h, c), "zoom in"); - } - h.state_mut().run("view.zoomOut", serde_json::json!({})).unwrap(); - h.run_steps(2); - assert_near(mid, slide_point(&h, c), "zoom out"); -} - -/// Drags with the primary button from `a` to `b`; `during` runs after every move. -fn drag_with(h: &mut Harness<'_, SlideApp>, a: Pos2, b: Pos2, mut during: impl FnMut(&SlideApp)) { - h.hover_at(a); - h.run_steps(1); - h.event(Event::PointerButton { pos: a, button: egui::PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); - h.run_steps(1); - for i in 1..=8 { - h.event(Event::PointerMoved(a + (b - a) * (i as f32 / 8.0))); - h.run_steps(1); - during(h.state()); - } - h.event(Event::PointerButton { pos: b, button: egui::PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); - h.run_steps(2); -} - -/// #1157: a slide zoomed past the window has a scroll bar on each axis that overflows, and -/// dragging its thumb pans the slide, not a marquee on the canvas. -#[test] -fn scroll_bars_pan_a_zoomed_slide() { - let mut h = harness(); - let fit = h.state().canvas_scale; - h.state_mut().ui.zoom = Some(fit * 3.0); - h.run_steps(3); - let canvas = h.state().canvas_rect.unwrap(); - let before = h.state().slide_rect.unwrap(); - let no_marquee = |app: &SlideApp| assert!(app.session.tool.marquee.is_none() && !app.session.tool.dragging(), "the bar drag reached the slide"); - - // Zoomed about the middle, so each thumb sits in the middle of its track. - let bottom = pos2(canvas.center().x, canvas.max.y - 4.0); - drag_with(&mut h, bottom, bottom + vec2(150.0, 0.0), no_marquee); - let after = h.state().slide_rect.unwrap(); - assert!(before.min.x - after.min.x > 150.0, "the horizontal thumb pans right: {before:?} -> {after:?}"); - assert!((before.min.y - after.min.y).abs() < 1.0, "only across: {before:?} -> {after:?}"); - - let right = pos2(canvas.max.x - 4.0, canvas.center().y); - drag_with(&mut h, right, right + vec2(0.0, 100.0), no_marquee); - let down = h.state().slide_rect.unwrap(); - assert!(after.min.y - down.min.y > 100.0, "the vertical thumb pans down: {after:?} -> {down:?}"); - assert!((after.min.x - down.min.x).abs() < 1.0, "only down: {after:?} -> {down:?}"); - - // A click on the track beside the thumb pages back toward it. - let left = pos2(canvas.min.x + 20.0, canvas.max.y - 4.0); - h.hover_at(left); - h.run_steps(1); - h.event(Event::PointerButton { pos: left, button: egui::PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); - h.event(Event::PointerButton { pos: left, button: egui::PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); - h.run_steps(2); - let paged = h.state().slide_rect.unwrap(); - assert!(paged.min.x - down.min.x > 100.0, "a track click pages left: {down:?} -> {paged:?}"); - assert!(h.state().session.tool.marquee.is_none()); - - // The ends of the tracks reach the slide's far edges. - drag_with(&mut h, right, right + vec2(0.0, 2000.0), |_| {}); - let end = h.state().slide_rect.unwrap(); - assert!((end.max.y - (canvas.max.y - 28.0)).abs() < 2.0, "the bottom of the slide comes into view: {end:?} in {canvas:?}"); -} - -/// A press on the thumb that ends just past its end is a nudge, not a page: the track click -/// is decided where the button went down, not where it came up. -#[test] -fn a_short_press_on_the_thumb_does_not_page() { - let mut h = harness(); - let fit = h.state().canvas_scale; - h.state_mut().ui.zoom = Some(fit * 3.0); - h.run_steps(3); - let (canvas, before) = (h.state().canvas_rect.unwrap(), h.state().slide_rect.unwrap()); - let overflow = vec2((before.width() + 56.0 - canvas.width()).max(0.0), (before.height() + 56.0 - canvas.height()).max(0.0)); - let offset = canvas.min + vec2(28.0, 28.0) - before.min; - let (_, thumb, _) = scroll_bar(canvas, 0.0, overflow, offset, 0).unwrap(); - let (a, b) = (pos2(thumb.max.x - 3.0, canvas.max.y - 4.0), pos2(thumb.max.x + 3.0, canvas.max.y - 4.0)); - h.hover_at(a); - h.run_steps(1); - h.event(Event::PointerButton { pos: a, button: egui::PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); - h.run_steps(1); - h.event(Event::PointerMoved(b)); - h.run_steps(1); - h.event(Event::PointerButton { pos: b, button: egui::PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); - h.run_steps(2); - let after = h.state().slide_rect.unwrap(); - let moved = before.min.x - after.min.x; - assert!((0.0..40.0).contains(&moved), "a 6 pt nudge of the thumb, not a page: {before:?} -> {after:?}"); -} - -/// Only the primary button drags a thumb: a right or middle drag after a left one leaves the -/// slide where it is. -#[test] -fn only_the_primary_button_drags_a_thumb() { - let mut h = harness(); - let fit = h.state().canvas_scale; - h.state_mut().ui.zoom = Some(fit * 3.0); - h.run_steps(3); - let canvas = h.state().canvas_rect.unwrap(); - let bottom = pos2(canvas.center().x, canvas.max.y - 4.0); - drag_with(&mut h, bottom, bottom + vec2(40.0, 0.0), |_| {}); - let before = h.state().slide_rect.unwrap(); - for button in [egui::PointerButton::Secondary, egui::PointerButton::Middle] { - let a = pos2(canvas.center().x + 40.0, canvas.max.y - 4.0); - h.hover_at(a); - h.run_steps(1); - h.event(Event::PointerButton { pos: a, button, pressed: true, modifiers: Modifiers::NONE }); - h.run_steps(1); - for i in 1..=4 { - h.event(Event::PointerMoved(a + vec2(30.0 * i as f32, 0.0))); - h.run_steps(1); - } - h.event(Event::PointerButton { pos: a + vec2(120.0, 0.0), button, pressed: false, modifiers: Modifiers::NONE }); - h.run_steps(2); - let after = h.state().slide_rect.unwrap(); - assert!((before.min - after.min).length() < 1.0, "{button:?} drag moved the slide: {before:?} -> {after:?}"); - } -} - -/// A slide that fits has no scroll bars: a drag along the canvas edge is a marquee. -#[test] -fn a_fitted_slide_has_no_scroll_bars() { - let mut h = harness(); - let canvas = h.state().canvas_rect.unwrap(); - let a = pos2(canvas.center().x, canvas.max.y - 4.0); - let mut marquee = false; - drag_with(&mut h, a, a + vec2(150.0, 0.0), |app| marquee |= app.session.tool.marquee.is_some()); - assert!(marquee, "the drag selects on the canvas"); -} - -fn app_with_table() -> (egui_kittest::Harness<'static, SlideApp>, deckcraft_model::ShapeId) { +fn app_with_table() -> (Harness<'static, SlideApp>, deckcraft_model::ShapeId) { let mut s = Session::with_new(); let data = json!([["Hello world", "b"], ["c", ""]]); let r = s.execute("insert.table", &json!({"rows": 2, "cols": 2, "rect": [100.0, 100.0, 400.0, 80.0], "data": data})).unwrap(); let id = deckcraft_model::ShapeId(r["id"].as_u64().unwrap() as u32); s.execute("edit.deselect", &json!({})).unwrap(); - let mut harness = egui_kittest::Harness::builder().with_size(egui::vec2(1200.0, 800.0)).build_ui_state( - |ui, app: &mut SlideApp| { - app.logic(ui.ctx()); - app.ui(ui); - }, - // P3(canvas-w11): sh.A2 - SlideApp::new_base(s, Services::default()), - ); - // The app keeps requesting repaints, so step frames instead of run(). - harness.run_steps(2); - (harness, id) + let mut h = crate::test_harness::harness_with(s, Services::default(), Harness::builder().with_size(vec2(1200.0, 800.0)), |_| {}); + h.run_steps(2); + (h, id) } /// Screen position of slide point (x, y). fn screen(app: &SlideApp, x: f64, y: f64) -> Pos2 { - Xf { origin: app.slide_rect.unwrap().min, scale: app.canvas_scale }.to_screen(Point::new(x, y)) + app.canvas_view.to_screen(Point::new(x, y)) } -/// Press and release at `p`, 50 ms apart in input time (two clicks make a double-click). -fn click(harness: &mut egui_kittest::Harness<'static, SlideApp>, p: Pos2) { +/// Press and release at `p`, 50 ms apart; two clicks at one point form a double click. +fn click(harness: &mut Harness<'static, SlideApp>, p: Pos2) { for pressed in [true, false] { let t = harness.ctx.input(|i| i.time) + 0.05; harness.input_mut().time = Some(t); - harness.event(egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: egui::Modifiers::NONE }); + harness.event(Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); harness.step(); } } @@ -365,7 +149,8 @@ fn empty_bullet_preview_follows_click_type_enter_and_toggle() { deckcraft_engine::cmd::text::caret_line(st, ts).unwrap().0 }; let first = caret(&h); - h.event(Event::Text("First point".into())); + let first_text = "First point"; + h.event(Event::Text(first_text.into())); h.run_steps(3); h.key_press(egui::Key::Enter); h.run_steps(3); @@ -373,20 +158,22 @@ fn empty_bullet_preview_follows_click_type_enter_and_toggle() { assert!((first.x - second.x).abs() < 0.01, "empty lines retain the bullet indent"); assert!(second.y > first.y); let st = h.state().session.active().unwrap(); - let l = deckcraft_engine::cmd::text::layout_for(st, st.selection.text.as_ref().unwrap()).unwrap(); - assert_eq!(l.empty_bullets.len(), 1); - assert_eq!(l.empty_bullets[0].para, 1); - let renders = h.state().textures.canvas_renders; + let ts = st.selection.text.as_ref().unwrap(); + let layout = deckcraft_engine::cmd::text::layout_for(st, ts).unwrap(); + assert_eq!(layout.empty_bullets.len(), 1); + assert_eq!(layout.empty_bullets[0].para, ts.caret.0); + let renders = h.state().picture.canvas_renders; h.state_mut().run("text.exit", json!({})).unwrap(); h.run_steps(3); - assert!(h.state().textures.canvas_renders > renders, "leaving text editing refreshes the marker texture"); + assert!(h.state().picture.canvas_renders > renders, "leaving text editing refreshes the marker texture"); h.state_mut().run("text.edit", json!({"id": id, "at": [1, 0]})).unwrap(); h.run_steps(3); - h.event(Event::Text("Second point".into())); + let second_text = "Second point"; + h.event(Event::Text(second_text.into())); h.run_steps(3); let st = h.state().session.active().unwrap(); let ts = st.selection.text.as_ref().unwrap(); - assert_eq!(deckcraft_engine::cmd::text::body_of(st, ts).unwrap().text(), "First point\nSecond point"); + assert_eq!(deckcraft_engine::cmd::text::body_of(st, ts).unwrap().text(), format!("{first_text}\n{second_text}")); assert!(deckcraft_engine::cmd::text::layout_for(st, ts).unwrap().empty_bullets.is_empty()); h.key_press(egui::Key::Enter); h.run_steps(3); @@ -400,7 +187,6 @@ fn empty_bullet_preview_follows_click_type_enter_and_toggle() { #[test] fn double_click_in_a_table_cell_shows_the_caret_there() { let (mut harness, id) = app_with_table(); - // The empty cell (1, 1) spans x 300..500, y 140..180. let p = screen(harness.state(), 400.0, 160.0); harness.hover_at(p); harness.step(); @@ -410,12 +196,11 @@ fn double_click_in_a_table_cell_shows_the_caret_there() { let st = harness.state().session.active().unwrap(); let ts = st.selection.text.clone().expect("editing the cell"); assert_eq!((ts.shape, ts.cell), (id, Some((1, 1)))); - assert!(text_marks(st, &ts).is_some_and(|m| m.selection.is_empty()), "no range"); + assert!(!ts.is_range(), "no range in the empty cell"); let (top, bottom) = deckcraft_engine::cmd::text::caret_line(st, &ts).expect("the cell's text has a caret"); for q in [top, bottom] { assert!(q.x > 300.0 && q.x < 500.0 && q.y >= 140.0 && q.y <= 180.0, "caret {q:?} outside cell (1, 1)"); } - // A click in another cell moves the caret there. let p = screen(harness.state(), 110.0, 120.0); click(&mut harness, p); harness.run_steps(1); @@ -459,113 +244,221 @@ fn right_click(h: &mut Harness<'_, SlideApp>, pos: Pos2) { h.run_steps(2); } -/// In Edit Points, right-clicking a segment offers Straight/Curved Segment and right-clicking -/// a point offers Open Path, then Close Path once the outline is open. -#[test] -fn edit_points_menu_sets_segment_types_and_opens_the_path() { - let mut h = harness(); - h.state_mut().run("slide.layout", json!({"layout": "blank"})).unwrap(); - h.state_mut().run("shape.insert", json!({"preset": "rect", "rect": [200, 150, 300, 200]})).unwrap(); - h.state_mut().run("shape.editPoints", json!({"on": true})).unwrap(); - h.run_steps(3); - let q = |h: &mut Harness<'_, SlideApp>| h.state_mut().session.execute("shape.points", &json!({})).unwrap(); - // The middle of the right edge: the segment ending at point 2. - let p = screen(h.state(), 500.0, 250.0); - right_click(&mut h, p); - h.get_by_label("Curved Segment").click(); - h.run_steps(3); - assert_eq!(q(&mut h)["segments"][0], json!(["straight", "straight", "curved", "straight"])); - // The bottom-right corner: Open Path breaks the outline there. - let p = screen(h.state(), 500.0, 350.0); - right_click(&mut h, p); - h.get_by_label("Open Path").click(); - h.run_steps(3); - assert_eq!(q(&mut h)["paths"][0].as_array().map(Vec::len), Some(5)); - right_click(&mut h, p); - h.get_by_label("Close Path").click(); - h.run_steps(3); - assert_eq!(q(&mut h)["paths"][0].as_array().map(Vec::len), Some(4)); -} - -/// In Edit Points, right-clicking a segment offers Add Point at the pointer, Delete Segment on -/// a closed outline, and Open Path at the segment's start point. +/// Segment menus use the pointer's parameter and the segment's start, and renumbering drops stale picks. #[test] fn edit_points_segment_menu_adds_points_and_deletes_segments() { - let mut h = harness(); - h.state_mut().run("slide.layout", json!({"layout": "blank"})).unwrap(); - h.state_mut().run("shape.insert", json!({"preset": "rect", "rect": [200, 150, 300, 200]})).unwrap(); - h.state_mut().run("shape.editPoints", json!({"on": true})).unwrap(); - h.run_steps(3); - let q = |h: &mut Harness<'_, SlideApp>| h.state_mut().session.execute("shape.points", &json!({})).unwrap(); - // A quarter of the way along the top edge: the new point goes there. - let p = screen(h.state(), 275.0, 150.0); - right_click(&mut h, p); - h.get_by_label("Add Point").click(); - h.run_steps(3); - assert_eq!(q(&mut h)["paths"][0], json!([[200.0, 150.0], [275.0, 150.0], [500.0, 150.0], [500.0, 350.0], [200.0, 350.0]])); - // The right edge: Open Path opens the outline at its top end. - let p = screen(h.state(), 500.0, 250.0); - right_click(&mut h, p); - h.get_by_label("Open Path").click(); - h.run_steps(3); - assert_eq!(q(&mut h)["paths"][0][0], json!([500.0, 150.0])); - assert_eq!(q(&mut h)["paths"][0].as_array().map(Vec::len), Some(6)); - h.state_mut().run("edit.undo", json!({})).unwrap(); - h.run_steps(3); - // Delete Segment removes the right edge: the outline now runs from its bottom end to its top end. - right_click(&mut h, p); - h.get_by_label("Delete Segment").click(); - h.run_steps(3); - assert_eq!(q(&mut h)["paths"][0], json!([[500.0, 350.0], [200.0, 350.0], [200.0, 150.0], [275.0, 150.0], [500.0, 150.0]])); - assert_eq!(q(&mut h)["segments"][0][0], json!(null)); - // On the open outline Delete Segment is grayed out; Close Path joins the ends again. - let p = screen(h.state(), 350.0, 350.0); - right_click(&mut h, p); - assert!(h.get_by_label("Delete Segment").accesskit_node().is_disabled()); - h.get_by_label("Close Path").click(); - h.run_steps(3); - assert_eq!(q(&mut h)["segments"][0][0], json!("straight")); + #[derive(Clone, Copy, Debug)] + enum Case { + Curve, + Add, + OpenSegment, + OpenVertex, + DeleteSegment, + DisabledDelete, + CloseVertex, + DeleteVertex, + } + for case in [ + Case::Curve, + Case::Add, + Case::OpenSegment, + Case::OpenVertex, + Case::DeleteSegment, + Case::DisabledDelete, + Case::CloseVertex, + Case::DeleteVertex, + ] { + let mut h = harness(); + h.ctx.on_end_pass( + "canvas menu second pass", + Arc::new(|ui| { + if ui.ctx().current_pass_index() == 0 { + ui.ctx().request_discard("canvas menu input belongs to one pass"); + } + }), + ); + h.state_mut().run("slide.layout", json!({"layout": "blank"})).unwrap(); + h.state_mut().run("shape.insert", json!({"preset": "rect", "rect": [200, 150, 300, 200]})).unwrap(); + h.state_mut().run("shape.editPoints", json!({"on": true})).unwrap(); + if matches!(case, Case::DisabledDelete | Case::CloseVertex) { + h.state_mut().run("shape.openPath", json!({"path": 0, "index": 0})).unwrap(); + } + h.run_steps(3); + let query = |h: &mut Harness<'_, SlideApp>| h.state_mut().session.execute("shape.points", &json!({})).unwrap(); + let vertices = |value: &Value| -> Vec { + value["paths"][0].as_array().unwrap().iter().map(|p| Point::new(p[0].as_f64().unwrap(), p[1].as_f64().unwrap())).collect() + }; + let before = query(&mut h); + let original = vertices(&before); + let (at, label, role) = match case { + Case::Curve => (Point::new(500.0, 250.0), "Curved Segment", Role::MenuItemRadio), + Case::Add => (Point::new(275.0, 150.0), "Add Point", Role::MenuItem), + Case::OpenSegment => (Point::new(500.0, 250.0), "Open Path", Role::MenuItem), + Case::OpenVertex => (original[2], "Open Path", Role::MenuItem), + Case::DeleteSegment | Case::DisabledDelete => (Point::new(500.0, 250.0), "Delete Segment", Role::MenuItem), + Case::CloseVertex => (original[0], "Close Path", Role::MenuItem), + Case::DeleteVertex => (original[1], "Delete Point", Role::MenuItem), + }; + let p = screen(h.state(), at.x, at.y); + let asked = slide_point(&h, p); + right_click(&mut h, p); + let picks = (h.state().session.tool.edit_segment, h.state().session.tool.edit_vertex); + assert!(picks.0.is_some() || picks.1.is_some(), "{case:?}: the right click picks geometry"); + if matches!(case, Case::DisabledDelete) { + assert!(h.get_by_role_and_label(role, label).accesskit_node().is_disabled(), "an open path cannot lose a segment"); + continue; + } + assert!(!h.get_by_role_and_label(role, label).accesskit_node().is_disabled(), "{case:?}: the command is available"); + h.get_by_role_and_label(role, label).click(); + h.run_steps(3); + let after = query(&mut h); + let result = vertices(&after); + match case { + Case::Curve => { + let (path, index) = picks.0.unwrap(); + assert_ne!(after["segments"][path][index], before["segments"][path][index], "the picked segment becomes curved"); + assert_eq!(result, original, "changing segment type preserves vertices"); + assert_eq!((h.state().session.tool.edit_segment, h.state().session.tool.edit_vertex), picks, "segment type preserves indices"); + } + Case::Add => { + assert!(result.len() > original.len()); + let added = result.iter().find(|p| !original.contains(p)).expect("a new vertex"); + assert!( + added.distance(Point::new(f64::from(asked.x), f64::from(asked.y))) < 1.0, + "the new point follows the pointer, not the midpoint" + ); + } + Case::OpenSegment | Case::OpenVertex => { + // Rectangle vertices run top-left, top-right, bottom-right, bottom-left. + // Its right edge ends at 2 but opens at 1; a vertex opens at itself. + let start = if matches!(case, Case::OpenSegment) { original[1] } else { at }; + assert_eq!(result.first(), Some(&start)); + assert_eq!(result.first(), result.last(), "opening duplicates the cut point as the two ends"); + assert!(result.len() > original.len()); + assert!(after["segments"][0][0].is_null(), "the first vertex ends no segment on an open path"); + } + Case::DeleteSegment | Case::DisabledDelete => { + assert_eq!(result.first(), Some(&original[2]), "the remaining outline starts at the removed edge's end"); + assert_eq!(result.last(), Some(&original[1]), "and ends at the removed edge's start"); + assert!(after["segments"][0][0].is_null()); + } + Case::CloseVertex => { + assert!(result.len() < original.len(), "closing merges coincident ends"); + assert!(!after["segments"][0][0].is_null(), "the closing edge ends at the first vertex"); + } + Case::DeleteVertex => { + assert!(result.len() < original.len()); + assert!(!result.contains(&at), "the picked vertex is removed"); + } + } + if !matches!(case, Case::Curve) { + assert!( + h.state().session.tool.edit_segment.is_none() && h.state().session.tool.edit_vertex.is_none(), + "{case:?}: renumbering clears both picks" + ); + } + assert!(h.state().canvas_menu.is_none(), "a picked command closes the menu across the second pass"); + } } +/// The menu follows live selection and text state, including a repeated word's actual character range. #[test] -fn grid_step_follows_spacing_and_rejects_unusable_values() { - let step = super::grid_line_step(72.0, 0.5).unwrap_or(0.0); - assert!((step - 36.0).abs() < 1e-3, "{step}"); - assert!(super::grid_line_step(6.0, 1.0).is_some()); - assert!(super::grid_line_step(0.0, 1.0).is_none()); - assert!(super::grid_line_step(f64::NAN, 1.0).is_none()); - assert!(super::grid_line_step(1_000.0, 1.0).is_none()); - assert!(super::grid_line_step(6.0, 0.0).is_none()); - assert!(super::grid_line_step(6.0, 0.1).is_none(), "a 6 pt grid at 10% zoom is finer than one screen point"); -} - -/// #830: when the Format or Animation Painter is armed, the cursor shows the copy icon so the -/// user can see the tool is waiting for a click. -#[test] -fn format_painter_sets_the_cursor() { - let mut h = harness(); - // Hover over the canvas so the pointer function runs and sets the cursor. - h.hover_at(egui::pos2(600.0, 400.0)); - h.run_steps(2); - let before = h.output().platform_output.cursor_icon; - assert_ne!(before, egui::CursorIcon::Copy, "no painter is armed yet"); - // Arming the format painter overrides the cursor to Copy (#830). - h.state_mut().session.painter = Some((Default::default(), false)); - h.run_steps(3); - let after = h.output().platform_output.cursor_icon; - assert_eq!(after, egui::CursorIcon::Copy, "the format painter arms the Copy cursor"); -} - -/// #830: the Animation Painter arms the same cursor. -#[test] -fn animation_painter_sets_the_cursor() { - let mut h = harness(); - h.hover_at(egui::pos2(600.0, 400.0)); - h.run_steps(2); - let before = h.output().platform_output.cursor_icon; - assert_ne!(before, egui::CursorIcon::Copy, "no painter is armed yet"); - h.state_mut().session.anim_painter = Some((vec![], false)); - h.run_steps(3); - let after = h.output().platform_output.cursor_icon; - assert_eq!(after, egui::CursorIcon::Copy, "the animation painter arms the Copy cursor"); +fn canvas_menu_rows_follow_the_selection() { + #[derive(Clone, Copy, Debug)] + enum Case { + Text, + Shape, + Line, + Picture, + Several, + Locked, + Empty, + Repeated, + } + for case in [Case::Text, Case::Shape, Case::Line, Case::Picture, Case::Several, Case::Locked, Case::Empty, Case::Repeated] { + let mut h = harness(); + h.state_mut().run("slide.layout", json!({"layout": "blank"})).unwrap(); + let word = "is"; + let text = format!("Heading\n{word}\u{a0}{word} good"); + let id = if matches!(case, Case::Empty) { + None + } else { + let inserted = if matches!(case, Case::Picture) { + // This fixture's pixels are generated here and belong to this test. + let png = deckcraft_render::Image { width: 1, height: 1, pixels: vec![80, 120, 160, 255] }.to_png(); + h.state_mut() + .run( + "insert.picture", + json!({"name": "menu.png", "data": deckcraft_engine::cmd::base64_encode(&png), "rect": [200, 150, 300, 200]}), + ) + .unwrap() + } else if matches!(case, Case::Line) { + h.state_mut().run("shape.insert", json!({"preset": "line", "rect": [200, 250, 300, 0]})).unwrap() + } else { + h.state_mut().run("shape.insert", json!({"preset": "rect", "rect": [200, 150, 300, 200]})).unwrap() + }; + Some(deckcraft_model::ShapeId(inserted["id"].as_u64().unwrap() as u32)) + }; + match case { + Case::Text => { + h.state_mut().run("text.set", json!({"id": id.unwrap(), "text": "Selected text"})).unwrap(); + h.state_mut().run("text.edit", json!({"id": id.unwrap()})).unwrap(); + } + Case::Several => { + let other = h.state_mut().run("shape.insert", json!({"preset": "ellipse", "rect": [550, 150, 100, 100]})).unwrap()["id"].clone(); + h.state_mut().run("edit.select", json!({"ids": [id.unwrap(), other]})).unwrap(); + } + Case::Locked => { + h.state_mut().run("shape.lock", json!({"locked": true})).unwrap(); + } + Case::Repeated => { + h.state_mut().run("text.set", json!({"id": id.unwrap(), "text": text})).unwrap(); + } + _ => {} + } + h.run_steps(3); + let p = if matches!(case, Case::Repeated) { + let st = h.state().session.active().unwrap().clone(); + h.state_mut().squiggles.disabled = false; + h.state_mut().squiggles.settle(&st); + let para = &st.shape(id.unwrap()).unwrap().text.as_ref().unwrap().paragraphs[1]; + let repeated = deckcraft_engine::spell::repeated(para, "en-US").into_iter().next().unwrap(); + let (a, b) = deckcraft_engine::cmd::text::range_underlines(&st, id.unwrap(), &[(1, repeated.start, repeated.end)])[0]; + screen(h.state(), (a.x + b.x) / 2.0, a.y - 2.0) + } else { + let at = if matches!(case, Case::Empty) { Point::new(700.0, 420.0) } else { Point::new(350.0, 250.0) }; + screen(h.state(), at.x, at.y) + }; + right_click(&mut h, p); + let shape_menu = !matches!(case, Case::Text | Case::Empty); + for (role, label, present) in [ + (Role::MenuItem, "Edit Text", shape_menu), + (Role::MenuItem, "Edit Points", shape_menu && !matches!(case, Case::Line | Case::Several)), + (Role::MenuItem, "Change Picture…", matches!(case, Case::Picture)), + (Role::MenuItem, "Lock", shape_menu && !matches!(case, Case::Locked)), + (Role::MenuItem, "Unlock", matches!(case, Case::Locked)), + (Role::MenuItemCheckBox, "Bullets", matches!(case, Case::Text)), + (Role::MenuItem, "Layout", matches!(case, Case::Empty)), + (Role::MenuItem, "Delete Repeated Word", matches!(case, Case::Repeated)), + ] { + assert_eq!(h.query_by_role_and_label(role, label).is_some(), present, "{case:?}: {label}"); + } + if matches!(case, Case::Repeated) { + let picked = h.state().squiggles.menu_word.as_ref().unwrap(); + let from = picked.delete_from.unwrap(); + let start = picked.start; + let end = start + picked.word.chars().count(); + let before = h.state().session.active().unwrap().shape(id.unwrap()).unwrap().text.as_ref().unwrap().clone(); + let paragraph = before.paragraphs[1].text(); + assert_eq!(picked.word, paragraph.chars().skip(start).take(end - start).collect::()); + let expected: String = paragraph.chars().take(from).chain(paragraph.chars().skip(end)).collect(); + h.get_by_role_and_label(Role::MenuItem, "Delete Repeated Word").click(); + h.run_steps(3); + let after = h.state().session.active().unwrap().shape(id.unwrap()).unwrap().text.as_ref().unwrap(); + assert_ne!(after.paragraphs[1].text(), paragraph, "the repeated word and its gap are removed"); + assert_eq!(after.paragraphs[1].text(), expected, "spellingChange uses the original nonbreaking gap"); + assert_eq!(after.paragraphs[0].text(), before.paragraphs[0].text(), "the command addresses the picked paragraph"); + assert!(h.state().squiggles.menu_word.is_none()); + } + } }