From c9fe3946ec08de669dd2131f680a438be4472f95 Mon Sep 17 00:00:00 2001 From: "Dylan M. Taylor" Date: Thu, 19 Nov 2026 18:25:02 -0500 Subject: [PATCH] Framework batch 4 d: port follow-ups (see runs/fwb4-d.md) --- crates/automation/src/synthetic.rs | 20 ++- crates/automation/tests/it/synthetic.rs | 23 ++- crates/dialogs/src/service.rs | 21 +++ crates/host/src/files.rs | 20 +++ crates/host/src/lib.rs | 34 ++++ crates/review/src/annotate.rs | 29 ++-- crates/review/src/ui/annotate/tool.rs | 34 +++- crates/review/src/ui/comments/row.rs | 5 + crates/review/tests/it/annotate.rs | 222 +++++++++++++++++++++++- crates/review/tests/it/comments.rs | 42 ++++- 10 files changed, 420 insertions(+), 30 deletions(-) diff --git a/crates/automation/src/synthetic.rs b/crates/automation/src/synthetic.rs index d74048815..50732ec5e 100644 --- a/crates/automation/src/synthetic.rs +++ b/crates/automation/src/synthetic.rs @@ -79,9 +79,21 @@ impl At { let range = Some((-MAX_SCREEN_POINT, MAX_SCREEN_POINT)); let x = p.number_in("x", "x", range)?.unwrap_or(0.0) as f32; let y = p.number_in("y", "y", range)?.unwrap_or(0.0) as f32; + Self::in_space(p, pos2(x, y)) + } + + /// `x` and `y`, both required, in the space `coordinates` names (`screen`, the default, or `document`). + fn required(p: &Params<'_>) -> Result { + let range = Some((-MAX_SCREEN_POINT, MAX_SCREEN_POINT)); + let x = p.number_in("x", "x", range)?.ok_or_else(|| "missing `x`".to_owned())? as f32; + let y = p.number_in("y", "y", range)?.ok_or_else(|| "missing `y`".to_owned())? as f32; + Self::in_space(p, pos2(x, y)) + } + + fn in_space(p: &Params<'_>, pos: Pos2) -> Result { Ok(match p.choice("coordinates", "coordinates", &["screen", "document"])?.unwrap_or("screen") { - "document" => Self::Document(pos2(x, y)), - _ => Self::Screen(pos2(x, y)), + "document" => Self::Document(pos), + _ => Self::Screen(pos), }) } @@ -252,12 +264,12 @@ pub struct Move { } impl Move { - /// `{x?, y?, coordinates?, rest?, modifiers…}`, no other fields. `rest` is seconds between 0 and [`MAX_REST`]. + /// `{x, y, coordinates?, rest?, modifiers…}`, no other fields. `rest` is seconds between 0 and [`MAX_REST`]. pub fn from_params(params: &Value) -> Result { let p = only(params, &["rest"])?; let p = Params(&p); Ok(Self { - at: At::from_params(&p)?, + at: At::required(&p)?, mods: p.modifiers(&KEY_MODIFIERS)?, rest: p.number_in("rest", "rest", Some((0.0, MAX_REST)))?.unwrap_or(0.0), }) diff --git a/crates/automation/tests/it/synthetic.rs b/crates/automation/tests/it/synthetic.rs index 76e492a2a..d90b535c8 100644 --- a/crates/automation/tests/it/synthetic.rs +++ b/crates/automation/tests/it/synthetic.rs @@ -278,10 +278,10 @@ fn bad_input_params_are_refused_before_anything_is_queued() { ("ui.click", json!({"x": 10, "button": "thumb"})), ("ui.click", json!({"x": 10, "hold": true, "count": MAX_CLICKS + 1})), ("ui.click", json!({"x": far, "hold": true})), - ("ui.move", json!({"x": 10, "nudge": 1})), - ("ui.move", json!({"x": 10, "rest": "long"})), - ("ui.move", json!({"x": 10, "coordinates": "page"})), - ("ui.move", json!({"y": -far})), + ("ui.move", json!({"x": 10, "y": 10, "nudge": 1})), + ("ui.move", json!({"x": 10, "y": 10, "rest": "long"})), + ("ui.move", json!({"x": 10, "y": 10, "coordinates": "page"})), + ("ui.move", json!({"x": 10, "y": -far})), ("ui.key", json!({"key": "A", "hold": true, "nudge": 1})), ("ui.key", json!({"key": 5})), ("ui.key", json!({"key": "NoSuchKey", "hold": true})), @@ -417,3 +417,18 @@ fn a_point_that_is_not_finite_is_refused() { } assert_eq!(At::Screen(pos2(3.0, 4.0)).resolve(&|_| None), Ok(pos2(3.0, 4.0))); } + +/// `ui.move` requires both `x` and `y`: omitting either coordinate refuses the request before anything is queued +/// instead of silently moving to 0 on the missing axis. +#[trial] +fn ui_move_refuses_a_missing_coordinate() { + let mut rig = Rig::new(); + rig.fx.settle(); + let (host, ctx) = (rig.host(), rig.fx.ctx().clone()); + for params in [json!({"x": 1}), json!({"y": 1}), json!({})] { + let answer = input_method("ui.move", ¶ms, &host, ViewportId::ROOT, &map); + assert!(matches!(answer, Some(Err(_))), "ui.move {params} is refused: {answer:?}"); + assert!(host.injected_idle(), "ui.move {params} left nothing waiting"); + assert!(hook_without_pass(&ctx, ViewportId::ROOT).is_empty(), "ui.move {params} queued nothing"); + } +} diff --git a/crates/dialogs/src/service.rs b/crates/dialogs/src/service.rs index 8e08c1e41..bdf8ef17a 100644 --- a/crates/dialogs/src/service.rs +++ b/crates/dialogs/src/service.rs @@ -609,6 +609,10 @@ impl Files for FileService { Ok(false) } + fn exists(&self, path: &Path) -> bool { + path.exists() + } + fn last_folder(&self, purpose: &str) -> Option { self.inner.lock().unwrap_or_else(|e| e.into_inner()).last_folder.get(purpose).cloned() } @@ -771,4 +775,21 @@ mod service_tests { assert_eq!(log.borrow().len(), 3, "no question for a path the panel asked about"); let _ = std::fs::remove_dir_all(&dir); } + + // `FileService::exists` checks the real file system, so batch writers on desktop see files already on disk. + #[trial] + fn exists_checks_the_file_system() { + let dir = std::env::temp_dir().join(format!("craft-dialogs-exists-{}", std::process::id())); + std::fs::create_dir_all(&dir).expect("scratch dir"); + let present = dir.join("present.pdf"); + let missing = dir.join("missing.pdf"); + let _ = std::fs::remove_file(&present); + let _ = std::fs::remove_file(&missing); + let (service, _panels) = FileService::new(Wake::none()); + assert!(!service.exists(&present)); + assert_eq!(service.write(&present, b"data", WriteIntent::SaveAs), Ok(false)); + assert!(service.exists(&present)); + assert!(!service.exists(&missing)); + let _ = std::fs::remove_dir_all(&dir); + } } diff --git a/crates/host/src/files.rs b/crates/host/src/files.rs index 3347578fb..f933d2763 100644 --- a/crates/host/src/files.rs +++ b/crates/host/src/files.rs @@ -260,6 +260,12 @@ pub trait Files: Send + Sync { /// Writes atomically where the platform allows (temp file and rename). `Ok(true)` when a host page took the bytes /// (a browser embedded in a page), `Ok(false)` when they were written here. fn write(&self, path: &Path, bytes: &[u8], intent: WriteIntent) -> Result; + /// Whether something already exists at `path`. `false` when the service has no file system to + /// check (a browser). + fn exists(&self, path: &Path) -> bool { + let _ = path; + false + } /// The folder the last answered pick of `purpose` chose. fn last_folder(&self, purpose: &str) -> Option; /// Answers the next pick, or the oldest pick still open, with `picked` instead of showing a @@ -325,6 +331,16 @@ impl Files for NoPickFiles { Err(FileError::Unsupported) } + #[cfg(not(target_arch = "wasm32"))] + fn exists(&self, path: &Path) -> bool { + path.exists() + } + + #[cfg(target_arch = "wasm32")] + fn exists(&self, _path: &Path) -> bool { + false + } + fn last_folder(&self, _purpose: &str) -> Option { None } @@ -508,6 +524,10 @@ impl Files for ScriptedFiles { Ok(false) } + fn exists(&self, path: &Path) -> bool { + self.state().files.contains_key(path) + } + /// Answers the oldest open pick of a [`held`](ScriptedFiles::held) service; otherwise the /// answer is queued for the next pick. [`answer`](ScriptedFiles::answer) answers the newest /// instead, so this does not go through it. diff --git a/crates/host/src/lib.rs b/crates/host/src/lib.rs index 755ad3c45..78cb4fcfe 100644 --- a/crates/host/src/lib.rs +++ b/crates/host/src/lib.rs @@ -288,6 +288,40 @@ mod tests { assert_eq!(files.written(), written); } + /// `Files::exists` reports files already present or written through the service and ignores refused writes: + /// batch writers rely on it to pick a fresh name instead of replacing an existing file. + #[test] + fn exists_reports_present_and_written_files() { + let existing = std::path::Path::new("/batch/notes.pdf"); + let missing = std::path::Path::new("/batch/new.pdf"); + let refused = std::path::Path::new("/batch/refused.pdf"); + let files = ScriptedFiles::new().with_file(existing, b"keep".to_vec()).failing_writes(refused); + assert!(files.exists(existing), "a pre-existing scripted file exists"); + assert!(!files.exists(missing), "a path not in the service does not exist"); + assert!(files.write(refused, b"no", WriteIntent::SaveAs).is_err()); + assert!(!files.exists(refused), "a refused write does not create an entry"); + assert_eq!(files.write(missing, b"ok", WriteIntent::SaveAs), Ok(false)); + assert!(files.exists(missing), "an accepted write exists afterwards"); + + #[cfg(not(target_arch = "wasm32"))] + { + let dir = std::env::temp_dir().join(format!("craft-host-exists-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let on_disk = dir.join("present.pdf"); + let absent = dir.join("absent.pdf"); + let _ = std::fs::remove_file(&on_disk); + let _ = std::fs::remove_file(&absent); + let disk = NoPickFiles::default(); + assert!(!disk.exists(&on_disk)); + assert!(!disk.exists(&absent)); + assert_eq!(disk.write(&on_disk, b"data", WriteIntent::SaveAs), Ok(false)); + assert!(disk.exists(&on_disk), "NoPickFiles reports a written file on disk"); + assert!(!disk.exists(&absent), "NoPickFiles reports a missing path as absent"); + let _ = std::fs::remove_file(&on_disk); + let _ = std::fs::remove_dir(&dir); + } + } + #[cfg(feature = "ui")] #[test] fn installed_host_survives_a_memory_reset() { diff --git a/crates/review/src/annotate.rs b/crates/review/src/annotate.rs index 2f43e36a5..efb1e72e0 100644 --- a/crates/review/src/annotate.rs +++ b/crates/review/src/annotate.rs @@ -192,7 +192,7 @@ pub const SLIP_RESIZE: f64 = 4.0; /// The smallest side of a shape the tool keeps, in page units. pub const MIN_SHAPE: f64 = 2.0; -/// The Shift rule of a point drag, held from the neighbouring point. +/// The Shift rule of a point drag or drawn line, held from its anchor point. #[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] #[non_exhaustive] pub enum ShiftLock { @@ -203,6 +203,23 @@ pub enum ShiftLock { LevelOrPlumb, } +impl ShiftLock { + /// `to` held to this rule from `anchor`. + pub(crate) fn apply(self, anchor: Point, to: Point) -> Point { + match self { + ShiftLock::Angle45 => turn_to_45(anchor, to), + // The nearer axis from the anchor: the segment goes level or plumb. + ShiftLock::LevelOrPlumb => { + if (to.x - anchor.x).abs() >= (to.y - anchor.y).abs() { + Point::new(to.x, anchor.y) + } else { + Point::new(anchor.x, to.y) + } + } + } + } +} + /// `points` with the callout's point `i` moved to `to`: the knee (`i == 1`) moves along its knee line only (level /// beside the box, upright above or below it) and never nearer the box than [`CALLOUT_KNEE_GAP`]; every other point /// moves through [`reshaped`], held to `lock` from its neighbour. @@ -493,15 +510,7 @@ pub fn reshaped(points: &[Point], i: usize, to: Point, lock: Option) let mut out = points.to_vec(); let anchor = if i == 0 { points.get(1) } else { points.get(i - 1) }; let to = match (anchor, lock) { - (Some(&a), Some(ShiftLock::Angle45)) => turn_to_45(a, to), - // The nearer axis from the neighbour: the segment goes level or plumb. - (Some(&a), Some(ShiftLock::LevelOrPlumb)) => { - if (to.x - a.x).abs() >= (to.y - a.y).abs() { - Point::new(to.x, a.y) - } else { - Point::new(a.x, to.y) - } - } + (Some(&a), Some(lock)) => lock.apply(a, to), _ => to, }; if let Some(p) = out.get_mut(i) { diff --git a/crates/review/src/ui/annotate/tool.rs b/crates/review/src/ui/annotate/tool.rs index 86599ce2d..34c084b7f 100644 --- a/crates/review/src/ui/annotate/tool.rs +++ b/crates/review/src/ui/annotate/tool.rs @@ -1,6 +1,5 @@ //! The canvas tool: presses, drags, the "New Annotation..." form and the [`CanvasTool`] implementation. -use craft_behavior::geometry::turn_to_45; use craft_behavior::{CancelReason, CanvasView, Cursor, CursorIcon, EditEvent, GestureId, Mixed, PointerButton, SelectionChange}; use craft_keymap::Mods; use craft_theme::Srgba; @@ -185,7 +184,8 @@ fn segments_cross(a: Point, b: Point, c: Point, d: Point, reach: f64) -> bool { /// [`SelectOptions::shift_lock`]); a press on empty page starts a marquee. Moves, resizes and reshapes are /// `EditEvent` gestures; a move within [`SLIP_MOVE`] or a resize within [`SLIP_RESIZE`] ends /// as a cancel, Esc cancels and the release after it is ignored. [`SelectOptions`] names the variations. -/// - A drawing tool: a drag draws the kind (Shift: squares, circles, 45 degree lines), and a shape smaller +/// - A drawing tool: a drag draws the kind (Shift: squares, circles, and lines held by +/// [`SelectOptions::shift_lock`]), and a shape smaller /// than [`MIN_SHAPE`] makes none; PolyLine, Polygon and Cloud add a point per click, close on a click at /// their first point (not PolyLine), take back their last point with Backspace and end with a double click /// or Enter; Ink and freehand highlight record strokes until the tool changes, or make one annotation per @@ -410,7 +410,7 @@ pub struct SelectOptions { pub toggle: ToggleMods, /// What opens a note or text box. pub open: OpenOn, - /// The Shift rule of a point drag. + /// The Shift rule of a point drag and of drawn lines and polygon sides. pub shift_lock: ShiftLock, /// The modifiers that nudge by the far step. pub far_nudge: FarNudge, @@ -847,9 +847,14 @@ impl AnnotateTool { // shape without adding one. self.finish_poly(kind, &reading.words); } else { + let next = if pointer.mods.shift { + self.poly.last().map_or(at, |&last| self.select_options.shift_lock.apply(last, at)) + } else { + at + }; let repeat = reading.view.doc_len(REPEAT_POINT); - if !self.poly.last().is_some_and(|&last| (last - at).hypot() < repeat) { - self.poly.push(at); + if !self.poly.last().is_some_and(|&last| (last - next).hypot() < repeat) { + self.poly.push(next); } } ToolAction::Done @@ -873,7 +878,7 @@ impl AnnotateTool { use AnnotationKind as K; match kind { K::Line | K::Arrow => { - let end = if shift { turn_to_45(origin, current) } else { current }; + let end = if shift { self.select_options.shift_lock.apply(origin, current) } else { current }; if (end - origin).hypot() < MIN_SHAPE { return None; } @@ -1208,7 +1213,7 @@ impl CanvasTool for AnnotateTool { let color = drawn(*kind); match kind { AnnotationKind::Line | AnnotationKind::Arrow => { - let end = if shift { turn_to_45(*origin, *current) } else { *current }; + let end = if shift { self.select_options.shift_lock.apply(*origin, *current) } else { *current }; outline(screen(&[*origin, end]), false, color); } AnnotationKind::Oval => { @@ -1248,7 +1253,20 @@ impl CanvasTool for AnnotateTool { && !self.poly.is_empty() { let mut path = self.poly.clone(); - path.extend(self.hover); + if let Some(hover) = self.hover { + let next = if let Some(&first) = self.poly.first() + && kind != AnnotationKind::PolyLine + && self.poly.len() >= 3 + && (first - hover).hypot() <= view.doc_len(cx.slop) + { + first + } else if shift { + self.poly.last().map_or(hover, |&last| self.select_options.shift_lock.apply(last, hover)) + } else { + hover + }; + path.push(next); + } outline(screen(&path), false, drawn(kind)); } } diff --git a/crates/review/src/ui/comments/row.rs b/crates/review/src/ui/comments/row.rs index 483703a60..0f6a3d444 100644 --- a/crates/review/src/ui/comments/row.rs +++ b/crates/review/src/ui/comments/row.rs @@ -651,6 +651,11 @@ impl Component for CommentRow<'_> { access.node(MORE.at(index as u64), Role::BUTTON).name = craft_ui::contract::Name::Text(words.more.as_str().to_owned()); } } + if let Some(heading) = &self.heading { + let parts = if heading.count.is_empty() { vec![heading.title.clone()] } else { vec![heading.title.clone(), heading.count.clone()] }; + access.name(craft_ui::contract::Name::Joined(parts)); + return; + } let Some(thread) = self.thread else { return }; let Some(first) = thread.messages.first() else { return }; let named = |name: String, message: &CommentMessage| { diff --git a/crates/review/tests/it/annotate.rs b/crates/review/tests/it/annotate.rs index c025ecf94..02d6f6f52 100644 --- a/crates/review/tests/it/annotate.rs +++ b/crates/review/tests/it/annotate.rs @@ -2,13 +2,14 @@ use craft_behavior::{CancelReason, CanvasView, EditEvent}; use craft_keymap::Mods; -use craft_review::annotate::{Annotation, AnnotationEdit, AnnotationId, AnnotationKind, AnnotationTool, HandleRule, SLIP_MOVE}; +use craft_review::annotate::{Annotation, AnnotationEdit, AnnotationId, AnnotationKind, AnnotationTool, HandleRule, SLIP_MOVE, ShiftLock}; use craft_review::ui::annotate::{ DrawOptions, EmptyPress, EraseMode, HandlesWhileDrawing, InkStrokes, MarkupPress, OpenOn, SelectOptions, ToggleMods, }; use craft_review::ui::{AnnotateTool, AnnotateWords}; use craft_ui::testing::{ToolFixture, pointer, trial}; -use egui::{Event, Key, Modifiers, PointerButton, Pos2, Rect as ScreenRect, vec2}; +use egui::epaint::ColorMode; +use egui::{Color32, Event, Key, Modifiers, PointerButton, Pos2, Rect as ScreenRect, Shape, vec2}; use kurbo::{Point, Rect, Vec2}; /// Frames past the double-click time (0.3 s at 1/60 s a frame), so the next press is a click of its own. @@ -521,3 +522,220 @@ fn a_click_on_a_hosts_part_selects_toggles_and_opens_by_the_tools_rules() { let edits = values(&rig); assert!(edits.contains(&AnnotationEdit::Open(AnnotationId(2))), "a double press on the note opens it by the same rule: {edits:?}"); } + +/// Presses at `from`, drags to `to` with `modifiers` held and leaves the button down, so the next frame paints the +/// live preview. +fn hold_drag(rig: &mut ToolFixture, from: Point, to: Point, modifiers: Modifiers) { + let (start, end) = (on_screen(rig, from), on_screen(rig, to)); + let fixture = rig.fixture(); + fixture.hold(modifiers); + fixture.frame(vec![pointer::moved(start)]); + fixture.frame(vec![button(start, true, modifiers)]); + for step in 1..=3 { + fixture.frame(vec![pointer::moved(start + (end - start) * (step as f32 / 3.0))]); + } +} + +/// Releases the drag held by [`hold_drag`] at `to`. +fn release_drag(rig: &mut ToolFixture, to: Point, modifiers: Modifiers) { + let end = on_screen(rig, to); + let fixture = rig.fixture(); + fixture.frame(vec![button(end, false, modifiers)]); + fixture.hold(Modifiers::NONE); + fixture.idle(PAST_DOUBLE_CLICK); +} + +/// Clicks at `at` with `modifiers` held, then waits past the double-click time. +fn click_holding(rig: &mut ToolFixture, at: Point, modifiers: Modifiers) { + let pos = on_screen(rig, at); + let fixture = rig.fixture(); + fixture.hold(modifiers); + fixture.frame(vec![pointer::moved(pos)]); + fixture.frame(vec![button(pos, true, modifiers)]); + fixture.frame(vec![button(pos, false, modifiers)]); + fixture.hold(Modifiers::NONE); + fixture.idle(PAST_DOUBLE_CLICK); +} + +/// The painted path shapes in `shapes` stroked in `color`. +fn colored_paths(shapes: &[Shape], color: Color32) -> Vec<&egui::epaint::PathShape> { + shapes + .iter() + .filter_map(|shape| match shape { + Shape::Path(path) if path.stroke.color == ColorMode::Solid(color) => Some(path), + _ => None, + }) + .collect() +} + +/// New Line, Arrow and PolyLine/Polygon drawings honour `SelectOptions::shift_lock`: under `LevelOrPlumb`, Shift holds +/// a line, an arrow, a polygon side and their live previews level or plumb (while hovering a polygon's first corner +/// still previews the closing side); under the default `Angle45`, Shift snaps to 45-degree steps. +#[trial] +fn new_lines_arrows_and_poly_sides_honour_shift_lock() { + let mut ortho = SelectOptions::default(); + ortho.shift_lock = ShiftLock::LevelOrPlumb; + let color = [0x10, 0x80, 0xE0]; + let stroke_color = Color32::from_rgb(color[0], color[1], color[2]); + + // Line: mostly across -> level, mostly down -> plumb; preview while held is level too. + let mut tool = AnnotateTool::new(AnnotationTool::Draw(AnnotationKind::Line), 0).select_options(ortho); + tool.color = color; + let mut line_rig = rig(tool); + let origin = Point::new(40.0, 100.0); + let tilted = Point::new(140.0, 145.0); + hold_drag(&mut line_rig, origin, tilted, Modifiers::SHIFT); + let shapes = line_rig.fixture().frame_shapes(); + let paths = colored_paths(&shapes, stroke_color); + let expected_end = on_screen(&line_rig, Point::new(140.0, 100.0)); + assert!( + paths.iter().any(|p| p.points.len() == 2 && (p.points[1] - expected_end).length() < 0.5), + "line preview with LevelOrPlumb stays level: {paths:?}" + ); + release_drag(&mut line_rig, tilted, Modifiers::SHIFT); + drag_holding(&mut line_rig, Point::new(200.0, 40.0), Point::new(215.0, 150.0), Modifiers::SHIFT); + drag_holding(&mut line_rig, Point::new(40.0, 160.0), Point::new(140.0, 190.0), Modifiers::NONE); + let made = created(&line_rig); + assert_eq!(made.len(), 3, "{made:?}"); + assert!(near(made[0].points[1], Point::new(140.0, 100.0)), "mostly across stays level: {:?}", made[0].points); + assert!(near(made[1].points[1], Point::new(200.0, 150.0)), "mostly down stays plumb: {:?}", made[1].points); + assert!(near(made[2].points[1], Point::new(140.0, 190.0)), "without Shift stays free: {:?}", made[2].points); + + // Arrow honours LevelOrPlumb too. + let mut arrow_rig = rig(AnnotateTool::new(AnnotationTool::Draw(AnnotationKind::Arrow), 0).select_options(ortho)); + drag_holding(&mut arrow_rig, Point::new(260.0, 180.0), Point::new(150.0, 170.0), Modifiers::SHIFT); + let made = created(&arrow_rig); + assert_eq!(made.len(), 1); + assert!(near(made[0].points[1], Point::new(150.0, 180.0)), "arrow stays level: {:?}", made[0].points); + + // PolyLine: each Shift click is held level or plumb with the corner before; plain click is free. + let mut poly_rig = rig(AnnotateTool::new(AnnotationTool::Draw(AnnotationKind::PolyLine), 0).select_options(ortho)); + click_holding(&mut poly_rig, Point::new(20.0, 20.0), Modifiers::NONE); + click_holding(&mut poly_rig, Point::new(90.0, 30.0), Modifiers::SHIFT); + click_holding(&mut poly_rig, Point::new(95.0, 80.0), Modifiers::SHIFT); + click_holding(&mut poly_rig, Point::new(130.0, 60.0), Modifiers::NONE); + poly_rig.fixture().key(Key::Enter, Modifiers::NONE); + let made = created(&poly_rig); + assert_eq!(made.len(), 1); + let pts = &made[0].points; + assert_eq!(pts.len(), 4, "{pts:?}"); + assert!( + near(pts[1], Point::new(90.0, 20.0)) && near(pts[2], Point::new(90.0, 80.0)) && near(pts[3], Point::new(130.0, 60.0)), + "polyline Shift clicks hold level/plumb: {pts:?}" + ); + + // Polygon rubber band: held level/plumb away from the start, but closes directly to the first corner when near it. + let mut polygon = AnnotateTool::new(AnnotationTool::Draw(AnnotationKind::Polygon), 0).select_options(ortho); + polygon.color = color; + let mut polygon_rig = rig(polygon); + for p in [Point::new(40.0, 40.0), Point::new(140.0, 40.0), Point::new(140.0, 140.0)] { + click(&mut polygon_rig, p); + } + let away = on_screen(&polygon_rig, Point::new(80.0, 155.0)); + polygon_rig.fixture().hold(Modifiers::SHIFT).frame(vec![pointer::moved(away)]); + let shapes = polygon_rig.fixture().frame_shapes(); + let paths = colored_paths(&shapes, stroke_color); + let expected_ortho = on_screen(&polygon_rig, Point::new(80.0, 140.0)); + assert!( + paths.iter().any(|p| p.points.len() == 4 && (p.points[3] - expected_ortho).length() < 0.5), + "polygon rubber band holds level with Shift: {paths:?}" + ); + let near_first = on_screen(&polygon_rig, Point::new(41.0, 41.0)); + polygon_rig.fixture().frame(vec![pointer::moved(near_first)]); + let shapes = polygon_rig.fixture().frame_shapes(); + let paths = colored_paths(&shapes, stroke_color); + let first_screen = on_screen(&polygon_rig, Point::new(40.0, 40.0)); + assert!( + paths.iter().any(|p| p.points.len() == 4 && (p.points[3] - first_screen).length() < 0.5), + "over the first corner, the rubber band closes to it even with Shift: {paths:?}" + ); + polygon_rig.fixture().hold(Modifiers::NONE); + + // Default Angle45 still snaps a diagonal line to 45 degrees. + let mut angle45_rig = rig_for(AnnotationKind::Line); + drag_holding(&mut angle45_rig, Point::new(40.0, 40.0), Point::new(140.0, 120.0), Modifiers::SHIFT); + let made = created(&angle45_rig); + assert_eq!(made.len(), 1); + let d = made[0].points[1] - made[0].points[0]; + assert!((d.x - d.y).abs() < 0.5 && d.x > 50.0, "default Angle45 snaps near-diagonal to 45 degrees: {:?}", made[0].points); +} + +/// Place drags (TextBox and Callout) and Eraser drags (both Path swath and Strokes marching ants) paint their live +/// preview while the button is held and clear it once released. +#[trial] +fn place_and_erase_drags_paint_their_preview_while_held() { + let color = [0x10, 0x80, 0xE0]; + let stroke_color = Color32::from_rgb(color[0], color[1], color[2]); + + // TextBox place drag: closed 4-corner outline in the tool's colour while held, gone on release. + let mut tb = AnnotateTool::new(AnnotationTool::Draw(AnnotationKind::TextBox), 0); + tb.color = color; + let mut tb_rig = rig(tb); + let (from, to) = (Point::new(50.0, 50.0), Point::new(160.0, 120.0)); + hold_drag(&mut tb_rig, from, to, Modifiers::NONE); + let held_shapes = tb_rig.fixture().frame_shapes(); + let held_paths = colored_paths(&held_shapes, stroke_color); + assert!( + held_paths.iter().any(|p| p.points.len() == 5 && (p.points[0] - on_screen(&tb_rig, from)).length() < 0.5), + "TextBox drag paints its box preview while held: {held_paths:?}" + ); + release_drag(&mut tb_rig, to, Modifiers::NONE); + let after_shapes = tb_rig.fixture().frame_shapes(); + assert!(colored_paths(&after_shapes, stroke_color).is_empty(), "TextBox preview clears after release"); + + // Callout place drag: leader line in the tool's colour from tip to box while held, gone on release. + let mut callout = AnnotateTool::new(AnnotationTool::Draw(AnnotationKind::Callout), 0); + callout.color = color; + let mut callout_rig = rig(callout); + hold_drag(&mut callout_rig, from, to, Modifiers::NONE); + let held_shapes = callout_rig.fixture().frame_shapes(); + let held_paths = colored_paths(&held_shapes, stroke_color); + assert!( + held_paths + .iter() + .any(|p| p.points.len() == 2 && (p.points[0] - on_screen(&callout_rig, from)).length() < 0.5 && (p.points[1] - on_screen(&callout_rig, to)).length() < 0.5), + "Callout drag paints its leader preview while held: {held_paths:?}" + ); + release_drag(&mut callout_rig, to, Modifiers::NONE); + let after_shapes = callout_rig.fixture().frame_shapes(); + assert!(colored_paths(&after_shapes, stroke_color).is_empty(), "Callout preview clears after release"); + + // Path eraser: swath stroke width matches 2 * eraser_radius while held, gone on release. + for radius in [6.0_f32, 36.0_f32] { + let mut options = DrawOptions::default(); + options.erase = EraseMode::Path; + options.eraser_radius = radius; + let mut eraser_rig = rig(AnnotateTool::new(AnnotationTool::Eraser, 0).draw_options(options)); + let swath_widths = |shapes: &[Shape]| -> Vec { + shapes + .iter() + .filter_map(|shape| match shape { + Shape::Path(path) if path.points.len() >= 2 && (path.stroke.width - 2.0 * radius).abs() < 0.1 => Some(path.stroke.width), + _ => None, + }) + .collect() + }; + hold_drag(&mut eraser_rig, Point::new(60.0, 100.0), Point::new(220.0, 100.0), Modifiers::NONE); + let held_shapes = eraser_rig.fixture().frame_shapes(); + assert_eq!(swath_widths(&held_shapes).len(), 1, "radius {radius}: swath painted at twice the radius while held"); + let cap_circles = held_shapes + .iter() + .filter(|shape| matches!(shape, Shape::Circle(c) if (c.radius - radius).abs() < 0.1)) + .count(); + assert!(cap_circles >= 2, "radius {radius}: swath paints round dots along its path: {cap_circles}"); + release_drag(&mut eraser_rig, Point::new(220.0, 100.0), Modifiers::NONE); + let after_shapes = eraser_rig.fixture().frame_shapes(); + assert!(swath_widths(&after_shapes).is_empty(), "radius {radius}: swath clears after release"); + } + + // Strokes eraser: marching ants while held, gone on release. + let mut strokes_eraser = rig(AnnotateTool::new(AnnotationTool::Eraser, 0)); + let ant_shapes = |shapes: &[Shape]| shapes.iter().filter(|shape| matches!(shape, Shape::Mesh(_) | Shape::LineSegment { .. })).count(); + let baseline_ants = ant_shapes(&strokes_eraser.fixture().frame_shapes()); + hold_drag(&mut strokes_eraser, Point::new(60.0, 100.0), Point::new(220.0, 100.0), Modifiers::NONE); + let held_ants = ant_shapes(&strokes_eraser.fixture().frame_shapes()); + assert!(held_ants > baseline_ants, "strokes eraser paints marching ants while held: {held_ants} vs {baseline_ants}"); + release_drag(&mut strokes_eraser, Point::new(220.0, 100.0), Modifiers::NONE); + let after_ants = ant_shapes(&strokes_eraser.fixture().frame_shapes()); + assert_eq!(after_ants, baseline_ants, "strokes eraser preview clears after release"); +} diff --git a/crates/review/tests/it/comments.rs b/crates/review/tests/it/comments.rs index d599f135b..00976bd8a 100644 --- a/crates/review/tests/it/comments.rs +++ b/crates/review/tests/it/comments.rs @@ -213,7 +213,7 @@ fn a_heading_folds_its_page_and_a_double_click_edits_a_card() { let _ = CommentsPanel::new("Comments", &threads, &mut state).show(ui); }); fixture.settle(); - let page_one = heading(&fixture, "Page 1").expect("page 1's heading"); + let page_one = heading(&fixture, "Page 1, 1").expect("page 1's heading"); fixture.click_at(page_one.center()).settle(); assert_eq!(state.borrow().collapsed_pages, vec![1], "the click folds page 1"); assert!(card(&fixture, "Note 1.").is_none(), "a folded page hides its cards"); @@ -224,7 +224,7 @@ fn a_heading_folds_its_page_and_a_double_click_edits_a_card() { assert_eq!(state.borrow().selected.items, vec![ThreadId(1)], "the reveal selects only its thread"); assert!(card(&fixture, "Note 1.").is_some(), "the revealed card is drawn"); - let page_one = heading(&fixture, "Page 1").expect("page 1's heading"); + let page_one = heading(&fixture, "Page 1, 1").expect("page 1's heading"); fixture.click_at(page_one.center()).settle(); assert_eq!(state.borrow().collapsed_pages, vec![1], "the reveal was taken once: later passes do not unfold the page again"); @@ -392,6 +392,44 @@ fn a_card_out_of_view_that_grows_is_rebuilt_at_its_size_when_scrolled_back() { assert!(second.top() >= first.bottom(), "the card below starts under the grown card: {first:?} then {second:?}"); } +/// Each group heading puts its count in its access name: under Page sort, the unfiltered count of that page's threads +/// even when search hides some of them; under another sort, the shown count of that group. +#[trial] +fn a_heading_puts_its_count_in_its_access_name() { + let threads = vec![ + thread(1, 1, "Needle on page one."), + thread(2, 1, "Other on page one."), + thread(3, 1, "Third on page one."), + thread(4, 2, "Needle on page two."), + ]; + let mut initial = CommentsPanelState::default(); + initial.search = "needle".into(); + let state = Rc::new(RefCell::new(initial)); + let shown_state = state.clone(); + let mut fixture = Fixture::new(move |ui| { + let mut state = shown_state.borrow_mut(); + let _ = CommentsPanel::new("Comments", &threads, &mut state).show(ui); + }); + fixture.in_room(Room::Panel).settle(); + let names = row_names(&fixture); + assert!( + names.iter().any(|name| name.contains("Page 1") && name.contains('3')), + "Page 1's heading carries its unfiltered count 3: {names:?}" + ); + assert!( + names.iter().any(|name| name.contains("Page 2") && name.contains('1')), + "Page 2's heading carries its unfiltered count 1: {names:?}" + ); + + state.borrow_mut().sort = CommentSort::Type; + fixture.settle(); + let names = row_names(&fixture); + assert!( + names.iter().any(|name| !name.contains("Needle") && name.contains('2')), + "under Type sort, the group heading carries its shown count 2: {names:?}" + ); +} + /// An editor opened on card 1, far above the cards in view: the cards in view do not jump, and scrolled back to the /// top the card is rebuilt with its editor and the card below it starts under it. #[trial]