DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge origin/main into codex/pencil-live-preview
moppeeer16e3469f7a42
diff --cc crates/ui-egui/src/canvas.rsindex df473465c,40b146f56..2b0f2cb48--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@@ -1237,39 -1415,37 +1415,69 @@@ fn draw_tool_overlays(app: &mut DesignApainter.rect_filled(r, 3.0, tok.measure_bg);painter.galley(r.min + vec2(5.0, 3.0), g, tok.measure_text);}+ Overlay::PageHandles(r) => {+ // The Page tool's selected page: outline and eight handles, as InDesign draws them.+ let r = xf.rect(r);+ let col = Color32::from_rgb(79, 153, 255);+ painter.rect_stroke(r, 0.0, Stroke::new(1.0, col), StrokeKind::Middle);+ for i in (0..9).filter(|i| *i != 4) {+ let c = pos2(r.min.x + r.width() * (i % 3) as f32 / 2.0, r.min.y + r.height() * (i / 3) as f32 / 2.0);+ let h = Rect::from_center_size(c, vec2(7.0, 7.0));+ painter.rect_filled(h, 0.0, Color32::WHITE);+ painter.rect_stroke(h, 0.0, Stroke::new(1.0, col), StrokeKind::Inside);+ }+ }+ Overlay::Tag { p, text } => {+ let text = crate::i18n::tr(&app.ui.language, &text).to_owned();+ let s = xf.to_screen(p);+ let g = painter.layout_no_wrap(text, egui::FontId::proportional(10.0), tok.measure_text);+ let r = Rect::from_min_size(s - vec2(0.0, g.size().y + 4.0), g.size() + vec2(8.0, 4.0));+ painter.rect_filled(r, 2.0, tok.measure_bg);+ painter.rect_stroke(r, 2.0, Stroke::new(1.0, Color32::from_rgb(79, 153, 255)), StrokeKind::Inside);+ painter.galley(r.min + vec2(4.0, 2.0), g, tok.measure_text);+ }+ Overlay::Tip { p, text } => {+ let text = crate::i18n::tr(&app.ui.language, &text).to_owned();+ let s = xf.to_screen(p) + vec2(14.0, 14.0);+ let g = painter.layout(text, egui::FontId::proportional(11.0), tok.measure_text, 260.0);+ let r = Rect::from_min_size(s, g.size() + vec2(10.0, 6.0));+ painter.rect_filled(r, 3.0, tok.measure_bg);+ painter.galley(r.min + vec2(5.0, 3.0), g, tok.measure_text);+ }+ Overlay::LiquidPins { object, page, pins, resize } => draw_liquid_pins(painter, xf.rect(object), xf.rect(page), pins, resize),- Overlay::Path { .. } => {}+ Overlay::Path { path, color, dashed: d } => draw_path_overlay(painter, xf, &path, c32(color), d),+ }+ }+}++/// A path overlay (canvas coordinates; the Pencil's stroke while drawing, the Smooth and Erase+/// drags) as screen polylines, its curves flattened to about a quarter of a screen pixel.+fn draw_path_overlay(painter: &egui::Painter, xf: &Xf, path: &designcraft_geom::BezPath, color: Color32, dashed_line: bool) {+ use designcraft_geom::PathEl;+ let stroke = Stroke::new(1.0, color);+ let mut runs: Vec<Vec<Pos2>> = Vec::new();+ designcraft_geom::kurbo::flatten(path, 0.25 / xf.zoom.max(1e-9), |el| match el {+ PathEl::MoveTo(p) => runs.push(vec![xf.to_screen(p)]),+ PathEl::LineTo(p) => {+ if let Some(run) = runs.last_mut() {+ run.push(xf.to_screen(p));+ }+ }+ PathEl::ClosePath => {+ if let Some(run) = runs.last_mut()+ && let Some(&first) = run.first()+ {+ run.push(first);+ }+ }+ // Flattening yields only moves, lines and closes.+ PathEl::QuadTo(..) | PathEl::CurveTo(..) => {}+ });+ for run in runs.into_iter().filter(|r| r.len() >= 2) {+ if dashed_line {+ painter.extend(egui::Shape::dashed_line(&run, stroke, 3.0, 3.0));+ } else {+ painter.add(egui::Shape::line(run, stroke));}}}@@@ -1950,59 -2652,157 +2684,212 @@@ mod testsright_click(&mut h, pos2(rect.center().x, rect.min.y - RULER / 2.0));assert!(h.query_by_label(" Points").is_none());}++ #[test]+ fn baseline_grid_lines_are_the_ones_on_the_page() {+ // A start far above the page used to be walked line by line, without end.+ for start in [-1e9, -1e17] {+ let mut far = baseline_grid_lines(start, 12.0, 792.0);+ assert_eq!((far.next(), far.count()), (Some(8.0), 65));+ }+ let lines = |start, increment, height| baseline_grid_lines(start, increment, height).collect::<Vec<_>>();+ assert_eq!(lines(36.0, 12.0, 72.0), [36.0, 48.0, 60.0], "the bottom edge is not a line");+ assert_eq!(lines(-30.0, 12.0, 30.0), [6.0, 18.0], "a start above the page keeps its rhythm");+ assert_eq!(lines(f64::NAN, 12.0, 792.0), [0.0; 0]);+ assert_eq!(baseline_grid_lines(0.0, 12.0, f64::INFINITY).count(), MAX_BASELINES);+ }+ }++ #[cfg(test)]+ mod scrollbar_tests {+ use egui::{Event, Modifiers, PointerButton};+ use egui_kittest::Harness;++ use super::*;+ use crate::test_window::{Window, open, wheel};++ fn window() -> Harness<'static, Window> {+ let mut h = open(DesignApp::new(designcraft_engine::Session::new(), crate::Services::default()), vec2(1440.0, 900.0));+ // Zoomed in so both axes scroll.+ set_zoom(&mut h.state_mut().app, 2.0);+ h.run_steps(3);+ h+ }++ fn origin(h: &Harness<'static, Window>) -> Point {+ h.state().app.view().map(|v| v.origin).unwrap_or_default()+ }++ /// The scrollbar's track and thumb as the canvas lays them out for the current view, and+ /// the content pixels per thumb pixel.+ fn bar(h: &Harness<'static, Window>, vertical: bool) -> (Rect, Rect, f32) {+ let app = &h.state().app;+ let rect = app.canvas_rect.unwrap();+ let st = app.session.active().unwrap();+ let xf = Xf::new(rect, app.view().unwrap());+ let cb = xf.rect(CanvasLayout::new(&st.doc, st.editing_parents).pasteboard);+ let outer = Rect::from_min_max(rect.min, rect.max + vec2(SCROLLBAR, SCROLLBAR));+ scrollbar_rects(outer, rect, cb, vertical)+ }++ /// A primary-button drag from `a` to `b` in a few moves, with `mods` held throughout.+ fn drag(h: &mut Harness<'static, Window>, a: Pos2, b: Pos2, mods: Modifiers) {+ h.event(Event::ModifiersChanged(mods));+ h.hover_at(a);+ h.step();+ h.event(Event::PointerButton { pos: a, button: PointerButton::Primary, pressed: true, modifiers: mods });+ h.step();+ for n in 1..=4 {+ h.hover_at(a + (b - a) * n as f32 / 4.0);+ h.step();+ }+ h.event(Event::PointerButton { pos: b, button: PointerButton::Primary, pressed: false, modifiers: mods });+ h.event(Event::ModifiersChanged(Modifiers::NONE));+ h.run_steps(3);+ }++ #[test]+ fn document_views_have_scrollbars_beside_the_view() {+ let h = window();+ let rect = h.state().app.canvas_rect.unwrap();+ for vertical in [true, false] {+ let r = h.ctx.read_response(egui::Id::new(("canvas_scrollbar", 0u8, vertical))).expect("scrollbar").rect;+ let (track, thumb, k) = bar(&h, vertical);+ assert_eq!(r, track);+ assert!(k > 0.0, "the zoomed-in view scrolls");+ if vertical {+ assert_eq!((r.min.x, r.width(), r.min.y, r.max.y), (rect.max.x, SCROLLBAR, rect.min.y, rect.max.y));+ assert!(thumb.height() < track.height());+ } else {+ assert_eq!((r.min.y, r.height(), r.min.x, r.max.x), (rect.max.y, SCROLLBAR, rect.min.x, rect.max.x));+ assert!(thumb.width() < track.width());+ }+ }+ }++ #[test]+ fn dragging_a_thumb_pans_and_clicking_the_track_pages() {+ let mut h = window();+ let zoom = h.state().app.view().unwrap().zoom;+ // Vertical thumb: down 40 px moves the view down by 40 thumb pixels' worth of content.+ let (_, thumb, k) = bar(&h, true);+ let before = origin(&h);+ drag(&mut h, thumb.center(), thumb.center() + vec2(0.0, 40.0), Modifiers::NONE);+ let after = origin(&h);+ let want = 40.0 * k as f64 / zoom;+ assert!((after.y - before.y - want).abs() < want * 0.2, "{before:?} → {after:?}, want +{want}");+ assert_eq!(after.x, before.x);+ // Horizontal thumb: left 30 px.+ let (_, thumb, k) = bar(&h, false);+ drag(&mut h, thumb.center(), thumb.center() - vec2(30.0, 0.0), Modifiers::NONE);+ let next = origin(&h);+ let want = 30.0 * k as f64 / zoom;+ assert!((after.x - next.x - want).abs() < want * 0.2, "{after:?} → {next:?}, want -{want}");+ assert_eq!(next.y, after.y);+ // A click on the vertical track above the thumb pages up by one view.+ let (track, thumb, _) = bar(&h, true);+ assert!(thumb.min.y - track.min.y > 4.0);+ crate::test_window::click_at(&mut h, pos2(track.center().x, track.min.y + 2.0));+ let paged = origin(&h);+ let view = h.state().app.canvas_rect.unwrap().height() as f64 / zoom;+ assert!((next.y - paged.y - view).abs() < 0.01, "{next:?} → {paged:?}, want -{view}");+ }++ #[test]+ fn scrolling_the_view_moves_the_thumbs() {+ let mut h = window();+ let (_, v0, _) = bar(&h, true);+ let (_, h0, _) = bar(&h, false);+ let c = h.state().app.canvas_rect.unwrap().center();+ wheel(&mut h, c, vec2(-50.0, -80.0));+ let (_, v1, _) = bar(&h, true);+ let (_, h1, _) = bar(&h, false);+ assert!(v1.min.y > v0.min.y && h1.min.x > h0.min.x, "{v0:?} → {v1:?}, {h0:?} → {h1:?}");+ let r = h.ctx.read_response(egui::Id::new(("canvas_scrollbar", 0u8, true))).expect("scrollbar");+ assert_eq!(r.rect, bar(&h, true).0);+ }++ #[test]+ fn alt_drag_while_editing_text_pans_and_keeps_the_caret() {+ let mut h = window();+ let app = &mut h.state_mut().app;+ let rect = app.canvas_rect.unwrap();+ let xf = Xf::new(rect, app.view().unwrap());+ // A text frame filling the visible part of the page, with the caret in it.+ let (a, b) = (xf.to_canvas(rect.min + vec2(20.0, 20.0)), xf.to_canvas(rect.max - vec2(20.0, 20.0)));+ let r = app.run("frame.create", json!({"rect": [a.x, a.y, b.x, b.y], "content": "text", "text": "Hello brave world"})).unwrap();+ let sid = r["story"].as_u64().unwrap();+ app.run("tool.select", json!({"tool": "type"})).unwrap();+ app.run("text.select", json!({"story": sid, "anchor": 3, "focus": 3})).unwrap();+ assert!(app.session.wants_text());+ h.run_steps(2);+ let caret = h.state().app.session.doc().unwrap().selection.text;+ let before = origin(&h);+ let zoom = h.state().app.view().unwrap().zoom;+ let from = rect.center();+ drag(&mut h, from, from + vec2(60.0, 40.0), Modifiers::ALT);+ let after = origin(&h);+ assert!(after.x < before.x && after.y < before.y, "{before:?} → {after:?}");+ assert!((before.x - after.x - 60.0 / zoom).abs() < 15.0 / zoom, "{before:?} → {after:?}");+ assert_eq!(h.state().app.session.doc().unwrap().selection.text, caret);+ assert!(h.state_mut().app.session.wants_text(), "still editing text");+ // Without Alt the same drag selects text and leaves the view alone.+ drag(&mut h, from, from + vec2(60.0, 40.0), Modifiers::NONE);+ assert_eq!(origin(&h), after);+ }}++#[cfg(test)]+mod pencil_preview_tests {+ use egui::{Pos2, pos2, vec2};++ /// Lines painted in `color` (egui paths) and the points they pass through.+ fn lines_in(h: &egui_kittest::Harness<'static, crate::test_window::Window>, color: egui::Color32) -> Vec<Vec<Pos2>> {+ fn walk(s: &egui::Shape, color: egui::Color32, out: &mut Vec<Vec<Pos2>>) {+ match s {+ egui::Shape::Path(p) if p.stroke.color == egui::epaint::ColorMode::Solid(color) && p.points.len() >= 2 => out.push(p.points.clone()),+ egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, color, out)),+ _ => {}+ }+ }+ let mut out = vec![];+ h.output().shapes.iter().for_each(|s| walk(&s.shape, color, &mut out));+ out+ }++ #[test]+ fn the_pencil_stroke_shows_while_drawing() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.run("file.new", serde_json::json!({})).unwrap();+ app.run("tool.select", serde_json::json!({"tool": "pencil"})).unwrap();+ let mut h = crate::test_window::open(app, vec2(1400.0, 900.0));+ let doc = &h.state().app.session.doc().unwrap().doc;+ let layer = doc.layers[0].color;+ let color = egui::Color32::from_rgb(layer[0], layer[1], layer[2]);+ let items = |h: &egui_kittest::Harness<'static, crate::test_window::Window>| h.state().app.session.doc().unwrap().doc.spreads[0].items.len();+ let before = items(&h);+ // Press on the page and drag, without letting go.+ let start = pos2(520.0, 380.0);+ h.hover_at(start);+ h.drag_at(start);+ h.run_steps(2);+ let path: Vec<Pos2> = (1..=12).map(|i| start + vec2(i as f32 * 12.0, (i as f32 * 0.6).sin() * 30.0)).collect();+ for p in &path {+ h.hover_at(*p);+ h.run_steps(1);+ }+ let drawn = lines_in(&h, color);+ let stroke = drawn.iter().max_by_key(|l| l.len()).expect("the stroke is painted while the button is down");+ let near = |a: Pos2, b: Pos2| (a - b).length() < 2.0;+ assert!(near(stroke[0], start), "it starts where the press was: {:?}", stroke[0]);+ assert!(path.iter().all(|p| stroke.iter().any(|q| near(*p, *q))), "it follows the pointer: {stroke:?}");+ assert_eq!(items(&h), before, "nothing is made before the release");+ // Letting go makes the path and ends the preview.+ h.drop_at(*path.last().unwrap());+ h.run_steps(3);+ assert_eq!(items(&h), before + 1);+ let app = &mut h.state_mut().app;+ let view = app.view_info();+ assert!(app.session.overlays(view).is_empty(), "the preview is gone");+ }+}