Skip to content

DesignCraft: An open-source page and layout design editor written by scratch in pure Rust

Merge #849: Canvas: baseline grid draws only the lines on the page

aiongg4989cc6e2719
diff --cc crates/ui-egui/src/canvas.rs
index 89c2c8e56,45cfbbe68..9c95f9b33
--- a/crates/ui-egui/src/canvas.rs
+++ b/crates/ui-egui/src/canvas.rs
@@@ -3665,378 -1928,17 +3674,392 @@@ mod tests
assert!(h.query_by_label(" Points").is_none());
}
+ /// One frame of the whole app with `events`; returns what it asks of the system IME.
+ fn ime_frame(app: &mut DesignApp, ctx: &egui::Context, events: Vec<egui::Event>) -> Option<egui::output::IMEOutput> {
+ let raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1400.0, 900.0))), events, ..Default::default() };
+ let mut out = ctx.run_ui(raw, |ui| {
+ app.logic(ui.ctx());
+ app.ui(ui);
+ });
+ out.textures_delta.clear();
+ out.platform_output.ime
+ }
+
+ /// An edit patches the canvas texture in place only while that texture is at full resolution:
+ /// past the GPU's texture limit `upload` shrinks it, and a full-resolution patch written into
+ /// it is a renderer validation error.
+ #[test]
+ fn edits_patch_the_canvas_only_at_full_resolution() {
+ for (max_side, patches) in [(None, true), (Some(1024), false)] {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ let ctx = egui::Context::default();
+ let frame = |app: &mut DesignApp| {
+ // Wider than the limit (egui's font atlas needs at least 1024).
+ let mut raw = egui::RawInput { screen_rect: Some(Rect::from_min_size(Pos2::ZERO, vec2(1900.0, 900.0))), ..Default::default() };
+ if let Some(m) = max_side {
+ raw.max_texture_side = Some(m);
+ }
+ let mut out = ctx.run_ui(raw, |ui| {
+ app.logic(ui.ctx());
+ app.ui(ui);
+ });
+ out.textures_delta.clear();
+ };
+ app.run("file.new", json!({})).unwrap();
+ for _ in 0..3 {
+ frame(&mut app);
+ }
+ app.run("frame.create", json!({"rect": [36, 36, 60, 60]})).unwrap();
+ frame(&mut app);
+ let size = app.canvas.texture.as_ref().unwrap().size();
+ assert!(max_side.is_none_or(|m| size[0] <= m && size[1] <= m), "{size:?}");
+ assert_eq!(app.canvas.patches > 0, patches, "limit {max_side:?}");
+ }
+ }
+
+ /// The Type tool's caret at the end of a new text frame holding `text`, the app's first frames
+ /// drawn; returns the story id.
+ fn typing_app(app: &mut DesignApp, ctx: &egui::Context, text: &str) -> Value {
+ app.run("file.new", json!({})).unwrap();
+ let f = app.session.execute("frame.create", &json!({"rect": [36, 36, 300, 200], "content": "text", "text": text})).unwrap();
+ let sid = f["story"].clone();
+ app.session.execute("text.select", &json!({"story": sid, "anchor": text.len(), "focus": text.len()})).unwrap();
+ app.select_tool("type");
+ for _ in 0..4 {
+ ime_frame(app, ctx, vec![]);
+ }
+ sid
+ }
+
+ fn story_text(app: &mut DesignApp, sid: &Value) -> String {
+ app.session.execute("story.get", &json!({"story": sid})).unwrap()["text"].as_str().unwrap().to_string()
+ }
+
+ /// Spread point `p` on screen.
+ fn on_screen(app: &DesignApp, p: Point) -> Pos2 {
+ let st = app.session.active().unwrap();
+ let c = CanvasLayout::new(&st.doc, st.editing_parents).to_canvas(SpreadRef::Doc(0), p);
+ Xf::new(app.canvas_rect.unwrap(), app.view().unwrap()).to_screen(c)
+ }
+
+ fn preedit(t: &str, c: usize) -> egui::Event {
+ egui::Event::Ime(egui::ImeEvent::Preedit { text: t.into(), active_range_chars: Some(c..c) })
+ }
+
+ #[test]
+ #[allow(deprecated)] // `ImeEvent::Enabled` / `Disabled`: egui no longer sends them, other integrations may.
+ fn ime_events_compose_in_the_story_with_the_candidate_window_at_the_caret() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ let ctx = egui::Context::default();
+ let sid = typing_app(&mut app, &ctx, "曲:");
+ // At a text caret the IME is allowed, its window on the caret as the canvas draws it.
+ let ime = ime_frame(&mut app, &ctx, vec![]).expect("IME allowed at a text caret");
+ let (top, bottom) = {
+ let st = app.session.active().unwrap();
+ let cs = app.session.cache.get(&st.doc, designcraft_doc::StoryId(sid.as_u64().unwrap()), None);
+ let (fi, x, bl, asc, desc) = compose::caret(&cs, "曲:".len()).unwrap();
+ let fid = cs.frames[fi].frame;
+ let (a, _) = item_canvas_xf(&st.doc, &CanvasLayout::new(&st.doc, st.editing_parents), fid).unwrap();
+ let m = a * st.doc.text_xf(st.doc.item(fid).unwrap());
+ let xf = Xf::new(app.canvas_rect.unwrap(), app.view().unwrap());
+ (xf.to_screen(m * Point::new(x, bl - asc)), xf.to_screen(m * Point::new(x, bl + desc)))
+ };
+ assert!(ime.rect.expand(1.0).contains(top) && ime.rect.expand(1.0).contains(bottom), "{:?} vs {top:?}–{bottom:?}", ime.rect);
+ assert_eq!(ime.cursor_rect, ime.rect);
+ assert!(!ime.should_interrupt_composition);
+ assert!(app.canvas_ime(), "the web build keeps whole words typed at the caret");
+ // "ni" → に → 日, with the events winit sends.
+ ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Enabled), preedit("ni", 2)]);
+ assert_eq!(story_text(&mut app, &sid), "曲:ni", "marked text shows in place");
+ assert!(app.session.tool_composing());
+ // Keys, plain text, the clipboard and Undo (the native menu's ⌘Z) wait for the IME.
+ let steps = app.session.doc().unwrap().history.undo.len();
+ let key = |key, pressed| egui::Event::Key { key, physical_key: None, pressed, repeat: false, modifiers: Default::default() };
+ ime_frame(
+ &mut app,
+ &ctx,
+ vec![key(egui::Key::Backspace, true), key(egui::Key::Backspace, false), egui::Event::Text("x".into()), egui::Event::Paste("y".into())],
+ );
+ crate::menus::activate(&mut app, "edit.undo", &Value::Null);
+ assert!(!crate::menus::enabled(&app, "edit.undo"));
+ assert_eq!(story_text(&mut app, &sid), "曲:ni");
+ let ime2 = ime_frame(&mut app, &ctx, vec![preedit("に", 1)]).expect("IME allowed while composing");
+ assert_eq!(story_text(&mut app, &sid), "曲:に");
+ assert!(ime2.rect.center().x > ime.rect.center().x, "the window follows the IME's cursor: {:?} {:?}", ime2.rect, ime.rect);
+ ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("日".into())), egui::Event::Ime(egui::ImeEvent::Disabled)]);
+ assert_eq!(story_text(&mut app, &sid), "曲:日");
+ assert!(!app.session.tool_composing());
+ assert_eq!(app.session.doc().unwrap().history.undo.len(), steps + 1, "the commit is one undo step");
+ assert_eq!(app.session.journal.last(), Some(&("text.insert".to_string(), json!({"text": "日"}))));
+ // After the commit, typing and Undo work again.
+ ime_frame(&mut app, &ctx, vec![egui::Event::Text("!".into())]);
+ assert_eq!(story_text(&mut app, &sid), "曲:日!");
+ crate::menus::activate(&mut app, "edit.undo", &Value::Null);
+ crate::menus::activate(&mut app, "edit.undo", &Value::Null);
+ assert_eq!(story_text(&mut app, &sid), "曲:");
+ // Without a text caret the IME is off: single-key tool shortcuts keep working.
+ app.select_tool("selection");
+ assert!(ime_frame(&mut app, &ctx, vec![]).is_none());
+ assert!(!app.canvas_ime());
+ }
+
+ /// Both panes of a split window see the same keyboard events: only the pane last clicked
+ /// types them.
+ #[test]
+ fn a_split_window_types_once() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ let ctx = egui::Context::default();
+ let sid = typing_app(&mut app, &ctx, "ab");
+ app.run("window.split", json!({"on": true})).unwrap();
+ for _ in 0..3 {
+ ime_frame(&mut app, &ctx, vec![]);
+ }
+ assert!(app.other_pane.as_ref().and_then(|o| o.1).is_some(), "both panes are drawn");
+ ime_frame(&mut app, &ctx, vec![egui::Event::Text("c".into())]);
+ assert_eq!(story_text(&mut app, &sid), "abc");
+ let key = |pressed| egui::Event::Key { key: egui::Key::Backspace, physical_key: None, pressed, repeat: false, modifiers: Default::default() };
+ ime_frame(&mut app, &ctx, vec![key(true), key(false)]);
+ assert_eq!(story_text(&mut app, &sid), "ab");
+ ime_frame(&mut app, &ctx, vec![egui::Event::Paste("de".into())]);
+ assert_eq!(story_text(&mut app, &sid), "abde");
+ ime_frame(&mut app, &ctx, vec![preedit("に", 1)]);
+ assert_eq!(story_text(&mut app, &sid), "abdeに");
+ ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("日".into()))]);
+ assert_eq!(story_text(&mut app, &sid), "abde日");
+ }
+
+ #[test]
+ fn clicking_away_mid_composition_keeps_the_text_and_interrupts_the_ime() {
+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());
+ let ctx = egui::Context::default();
+ let sid = typing_app(&mut app, &ctx, "");
+ ime_frame(&mut app, &ctx, vec![preedit("しょうこ", 4)]);
+ assert!(app.session.tool_composing());
+ // A click in the frame (macOS and Windows send nothing for it): the marked text stays as
+ // typed and the IME is told to drop its composition, once.
+ let p = on_screen(&app, Point::new(150.0, 120.0));
+ let press = |pressed| egui::Event::PointerButton { pos: p, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
+ let ime = ime_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(p), press(true)]).expect("still at a text caret");
+ assert!(ime.should_interrupt_composition);
+ ime_frame(&mut app, &ctx, vec![press(false)]);
+ assert!(!app.session.tool_composing());
+ assert_eq!(story_text(&mut app, &sid), "しょうこ");
+ assert!(app.take_ime_discard(), "the host tells the system IME to drop its marked text");
+ assert!(!ime_frame(&mut app, &ctx, vec![]).expect("still at a text caret").should_interrupt_composition);
+ assert!(!app.take_ime_discard());
+ // A bare line break from the IME confirms a composition: the marked text, no new paragraph.
+ ime_frame(&mut app, &ctx, vec![preedit("がく", 2)]);
+ ime_frame(&mut app, &ctx, vec![egui::Event::Ime(egui::ImeEvent::Commit("\n".into()))]);
+ assert!(!app.session.tool_composing());
+ let typed = story_text(&mut app, &sid);
+ assert!(typed.contains("がく") && typed.contains("しょうこ") && !typed.contains('\n'), "{typed:?}");
+ }
+}
+
+#[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");
+ }
+}
+
+#[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);
+ }
++
+ #[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);
+ }
}