DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge #388: Show the Pencil stroke while drawing
aiongg153fa6005419
diff --cc crates/ui-egui/src/canvas.rsindex 819dfcc89,ec3a1e5ed..f218c25c2--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@@ -1267,67 -1212,43 +1267,99 @@@ 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::Path { .. } => {}+ Overlay::Path { path, color, dashed: d } => draw_path_overlay(painter, xf, &path, c32(color), d),+ Overlay::ContentGhost(id) => {+ if let Some(doc) = &doc {+ draw_content_ghost(painter, xf, doc, &layout, id);+ }+ }}}}+ /// 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));+ }+ }+ }++/// A frame's whole content drawn faintly over the canvas, the part outside the frame included,+/// with its bounds outlined (while the content moves inside the frame).+fn draw_content_ghost(painter: &egui::Painter, xf: &Xf, doc: &Document, layout: &CanvasLayout, id: designcraft_doc::ItemId) {+ let Some(it) = doc.item(id) else { return };+ let Some((a, _)) = item_canvas_xf(doc, layout, id) else { return };+ let outline = Stroke::new(1.0, Color32::from_rgb(196, 111, 43));+ let Content::Graphic(g) = &it.content else {+ for c in it.children() {+ let r = xf.rect((a * it.xf).transform_rect_bbox(c.bounds()));+ painter.rect_stroke(r, 0.0, outline, StrokeKind::Middle);+ }+ return;+ };+ let m = a * it.xf * g.xf;+ let (w, h) = g.size;+ let corners = [Point::new(0.0, 0.0), Point::new(w, 0.0), Point::new(w, h), Point::new(0.0, h)].map(|p| xf.to_screen(m * p));+ if corners.iter().any(|p| !p.x.is_finite() || !p.y.is_finite()) {+ return;+ }+ if let Some(tex) = ghost_texture(painter.ctx(), doc, g) {+ let mut mesh = egui::Mesh::with_texture(tex.id());+ let tint = Color32::from_white_alpha(90);+ for (p, uv) in corners.iter().zip([pos2(0.0, 0.0), pos2(1.0, 0.0), pos2(1.0, 1.0), pos2(0.0, 1.0)]) {+ mesh.vertices.push(egui::epaint::Vertex { pos: *p, uv, color: tint });+ }+ mesh.indices.extend([0, 1, 2, 0, 2, 3]);+ painter.add(egui::Shape::mesh(mesh));+ }+ painter.add(egui::Shape::closed_line(corners.to_vec(), outline));+}++/// A screen-resolution proxy of a placed graphic for the ghost, cached per asset.+fn ghost_texture(ctx: &egui::Context, doc: &Document, g: &designcraft_doc::Graphic) -> Option<egui::TextureHandle> {+ let asset = doc.assets.get(&g.asset)?;+ let key = egui::Id::new(("content_ghost", std::sync::Arc::as_ptr(&asset.data) as usize, asset.data.len(), asset.page));+ if let Some(t) = ctx.data(|d| d.get_temp::<egui::TextureHandle>(key)) {+ return Some(t);+ }+ // A 72 ppi proxy is enough for a faint preview.+ let pm = designcraft_render::images::mip(&asset.data, asset.page, g.size.0, 1.0)?;+ let (pw, ph) = (pm.width() as usize, pm.height() as usize);+ let max = ctx.input(|i| i.max_texture_side).min(4096);+ if pw == 0 || ph == 0 || pw > max || ph > max {+ return None;+ }+ let ci = egui::ColorImage::from_rgba_premultiplied([pw, ph], pm.data_as_u8_slice());+ let t = ctx.load_texture("content_ghost", ci, egui::TextureOptions::LINEAR);+ ctx.data_mut(|d| d.insert_temp(key, t.clone()));+ Some(t)+}+#[allow(clippy::too_many_arguments)]fn draw_rulers(app: &DesignApp, ui: &egui::Ui, full: Rect, rect: Rect, xf: &Xf, doc: &Document, layout: &CanvasLayout, t: &Tokens) {let painter = ui.painter_at(full);@@@ -2624,153 -1837,59 +2656,208 @@@ mod testsright_click(&mut h, pos2(rect.center().x, rect.min.y - RULER / 2.0));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+ }++ /// 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");+ }+ }