DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Merge #84: Text editing, snapping and text threading (#23)
aiongg71074a987b59
diff --cc Cargo.lockindex 201a0cad9,9a27f0d7a..9a37745fb--- a/Cargo.lock+++ b/Cargo.lock@@@ -861,8 -855,9 +861,9 @@@ dependencies =[[package]]name = "designcraft"-version = "0.2.1"+version = "0.4.0"dependencies = [+ "arboard","designcraft-engine","designcraft-ui-egui","eframe",diff --cc crates/ui-egui/src/control.rsindex 33e7c1b97,d96f17773..b8cca617d--- a/crates/ui-egui/src/control.rs+++ b/crates/ui-egui/src/control.rs@@@ -377,101 -377,40 +392,139 @@@ pub fn save_screenshot(app: &mut Design}}+/// Parse explicit page indices without treating invalid values as omission.+pub(crate) fn page_index(p: &Value, default: usize, count: usize) -> Result<usize, String> {+ let page = match p.get("page") {+ None => default,+ Some(v) => v.as_u64().and_then(|n| usize::try_from(n).ok()).ok_or("`page` must be a nonnegative integer representable as a page index")?,+ };+ if page >= count {+ return Err(format!("no page {page} (the document has {count} pages, indices are 0-based)"));+ }+ Ok(page)+}++#[cfg(test)]+mod automation_contract_tests {+ use super::*;+ fn app() -> DesignApp {+ let mut app = DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", &json!({"pages":2})).unwrap();+ app+ }+ fn call(app: &mut DesignApp, ctx: &egui::Context, method: &str, params: Value) -> Value {+ let (req, _) = ControlRequest::new(method, params);+ match handle(app, ctx, &req) {+ Outcome::Done(v) => v,+ Outcome::Screenshot { .. } => panic!("unexpected screenshot"),+ }+ }+ fn frame(app: &mut DesignApp, ctx: &egui::Context, events: Vec<egui::Event>) {+ let mut output = ctx.run_ui(+ egui::RawInput {+ screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))),+ events,+ ..Default::default()+ },+ |ui| {+ app.logic(ui.ctx());+ app.ui(ui);+ },+ );+ output.textures_delta.clear();+ }+ #[test]+ fn control_typing_uses_explicit_caret_but_retains_widget_events() {+ let mut app = app();+ let ctx = egui::Context::default();+ assert_eq!(call(&mut app, &ctx, "ui.text", json!({"text":"X"}))["ok"], false);+ let f = app.session.execute("frame.create", &json!({"rect":[36,36,300,200],"content":"text","text":"Hello"})).unwrap();+ app.session.execute("text.select", &json!({"story":f["story"],"anchor":5})).unwrap();+ assert_eq!(app.session.tool_id(), "selection");+ assert_eq!(call(&mut app, &ctx, "ui.text", json!({"text":"X"}))["ok"], true);+ assert_eq!(app.session.execute("story.get", &json!({"story":f["story"]})).unwrap()["text"], "HelloX");+ app.session.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(app.session.execute("story.get", &json!({"story":f["story"]})).unwrap()["text"], "Hello");+ app.select_tool("type");+ assert!(app.session.wants_text(), "the document would receive ordinary typing without widget focus");+ app.ui.palette = Some(String::new());+ for _ in 0..3 {+ frame(&mut app, &ctx, vec![]);+ }+ assert!(ctx.text_edit_focused());+ assert_eq!(call(&mut app, &ctx, "ui.text", json!({"text":"field"}))["ok"], true);+ let events = std::mem::take(&mut app.synthetic);+ frame(&mut app, &ctx, events);+ assert_eq!(app.ui.palette.as_deref(), Some("field"));+ assert_eq!(app.session.execute("story.get", &json!({"story":f["story"]})).unwrap()["text"], "Hello");+ }+ #[test]+ fn control_pages_validate_before_writer_and_preserve_omission() {+ let mut app = app();+ let ctx = egui::Context::default();+ let writes = std::sync::Arc::new(std::sync::Mutex::new(Vec::new()));+ let sink = writes.clone();+ app.services.write = Some(Box::new(move |_, bytes| {+ sink.lock().unwrap().push(bytes.to_vec());+ Ok(())+ }));+ app.session.execute("frame.create", &json!({"rect":[36,36,300,200]})).unwrap();+ app.canvas_rect = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0)));+ crate::canvas::go_to_page(&mut app, 1);+ assert_eq!(crate::canvas::current_page(&app), Some(1));+ for method in ["ui.render", "app.export"] {+ for page in+ [json!(-1), json!(-2), json!(1.5), Value::Null, json!("0"), json!(true), json!(u64::MAX), json!(18446744073709551616_f64), json!(99)]+ {+ assert_eq!(call(&mut app, &ctx, method, json!({"page":page,"path":"unchanged.png","scale":0.1}))["ok"], false, "{method}: {page}");+ assert!(writes.lock().unwrap().is_empty());+ }+ assert_eq!(call(&mut app, &ctx, method, json!({"path":"omitted.png","scale":0.1}))["ok"], true);+ assert_eq!(call(&mut app, &ctx, method, json!({"page":1,"path":"explicit.png","scale":0.1}))["ok"], true);+ let mut bytes = writes.lock().unwrap();+ assert_eq!(bytes.len(), 2);+ assert_eq!(bytes[0], bytes[1]);+ bytes.clear();+ }+ assert!(app.run("app.exportPng", json!({"page":Value::Null,"path":"unchanged.png"})).is_err());+ assert!(writes.lock().unwrap().is_empty());+ }+}+++ #[cfg(test)]+ mod tests {+ use super::*;+ use std::sync::{+ Arc,+ atomic::{AtomicUsize, Ordering},+ };++ #[test]+ fn control_paste_never_reads_the_system_clipboard() {+ let calls = Arc::new(AtomicUsize::new(0));+ let seen = calls.clone();+ let services = crate::Services {+ clipboard_text: Some(Box::new(move || {+ seen.fetch_add(1, Ordering::SeqCst);+ Some("SECRET".into())+ })),+ ..Default::default()+ };+ let mut app = DesignApp::new(designcraft_engine::Session::new(), services);+ app.run("file.new", json!({})).unwrap();+ let r = app.run("frame.create", json!({"rect": [72, 72, 300, 200], "content": "text", "text": "words"})).unwrap();+ let sid = r["story"].as_u64().unwrap();+ assert!(app.session.active().unwrap().selection.text.is_some(), "the new frame is being typed in");+ let text = |app: &DesignApp| app.session.active().unwrap().doc.story(designcraft_doc::StoryId(sid)).unwrap().text.clone();+ let ctx = egui::Context::default();+ let (req, _rx) = ControlRequest::new("engine.execute", json!({"command": "edit.paste"}));+ let _ = handle(&mut app, &ctx, &req);+ assert_eq!(calls.load(Ordering::SeqCst), 0, "the control channel must not read the system clipboard");+ assert!(!text(&app).contains("SECRET"));+ assert!(!app.in_control);+ // The same command chosen by the user does paste the system clipboard.+ let _ = app.run("edit.paste", json!({}));+ assert_eq!(calls.load(Ordering::SeqCst), 1);+ assert!(text(&app).contains("SECRET"));+ }+ }diff --cc crates/ui-egui/src/dialogs.rsindex b3b202f00,8b4ed1c2a..57b3efa54--- a/crates/ui-egui/src/dialogs.rs+++ b/crates/ui-egui/src/dialogs.rs@@@ -1527,46 -1482,9 +1527,46 @@@ pub fn confirm(app: &mut DesignApp) ->}Ok(r)}+ "characterStyleOptions" => {+ let name = d.s("name");+ let mut chars = Map::new();+ for (k, v) in &d.fields {+ if let Some(a) = k.strip_prefix("c.") {+ chars.insert(a.into(), v.clone());+ }+ }+ let rename = d.s("rename").trim().to_string();+ let based = d.fields.get("basedOn").and_then(Value::as_str).map(str::to_string);+ let r = if d.b("new") {+ // A new style sets only what was filled in.+ chars.retain(|_, v| !v.is_null());+ let mut params = json!({"name": if rename.is_empty() { "Character Style 1" } else { rename.as_str() }, "chars": chars});+ if let Some(b) = based.filter(|b| b != designcraft_doc::NO_CHAR_STYLE) {+ params["basedOn"] = json!(b);+ }+ app.run("style.character.create", params)+ } else {+ let mut params = json!({"name": name, "chars": chars});+ if let Some(b) = based {+ params["basedOn"] = if b == designcraft_doc::NO_CHAR_STYLE { Value::Null } else { json!(b) };+ }+ if !rename.is_empty() && rename != name {+ params["rename"] = json!(rename);+ }+ app.run("style.character.edit", params)+ };+ if let Err(e) = &r {+ // Keep the dialog open with the reason (a taken name, a based-on loop).+ let mut d = d.clone();+ d.fields.insert("status".into(), json!(e));+ d.fields.insert("section".into(), json!("general"));+ app.ui.dialog = Some(d);+ }+ r+ }"colorPicker" => {let hex = d.s("hex");- app.run("object.color", json!({"color": hex, "target": d.s("target")}))+ app.run("object.color", json!({"color": hex, "target": d.s("target"), "text": d.b("text")}))}"layerOptions" => {let hidden: Vec<Value> = d.fields.get("layers").and_then(Value::as_array).map(|a| a.iter().filter(|l| l["visible"] == false).map(|l| l["name"].clone()).collect()).unwrap_or_default();diff --cc crates/ui-egui/src/lib.rsindex ab233773d,20c97e7fc..f63fac31c--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@@ -38,21 -38,11 +38,22 @@@ pub use control::{ControlRequest, Contrpub type ReadFn = Box<dyn Fn(&str) -> Result<Vec<u8>, String>>;pub type WriteFn = Box<dyn FnMut(&str, &[u8]) -> Result<(), String>>;pub type PickFn = Box<dyn FnMut(&str) -> Option<String>>;-pub type OpenAsyncFn = Box<dyn FnMut(&str)>;+/// Context captured before any host file-picker or read await.+#[derive(Clone, Debug)]+pub struct ImportRequest {+ pub purpose: String,+ pub target: Option<u64>,+}+pub struct ImportedFile {+ pub request: ImportRequest,+ pub name: String,+ pub bytes: Vec<u8>,+}+pub type OpenAsyncFn = Box<dyn FnMut(ImportRequest)>;pub type DownloadFn = Box<dyn FnMut(&str, &[u8])>;+ pub type ClipboardFn = Box<dyn FnMut() -> Option<String>>;-/// Files `(name, bytes)` delivered asynchronously by the host (web file picker, dropped files).-pub type Inbox = std::sync::Arc<std::sync::Mutex<Vec<(String, Vec<u8>)>>>;+/// Files delivered asynchronously with their original operation and document identity.+pub type Inbox = std::sync::Arc<std::sync::Mutex<Vec<ImportedFile>>>;/// Platform services injected by the host (desktop or web).#[derive(Default)]@@@ -69,8 -59,12 +70,11 @@@ pub struct Services/// Hand bytes to the user as a named file (browser download). When set, Save uses it/// instead of writing to a path.pub download: Option<DownloadFn>,- /// Files delivered asynchronously, drained every frame: `.designcraft` → `file.openBytes`,- /// anything else → `file.place`.+ /// Files delivered asynchronously, drained every frame with their captured request context.pub inbox: Option<Inbox>,+ /// The system clipboard's text, for Paste chosen from a menu (egui only delivers it with the+ /// paste keys, which a native menu bar takes first).+ pub clipboard_text: Option<ClipboardFn>,}#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]@@@ -198,14 -191,11 +202,17 @@@ pub struct UiStatepub smart_spacing: bool,#[serde(default = "default_zone")]pub snap_zone: f64,+ /// Tools panel: Formatting Affects Text (J): with text frames selected, colour edits go to+ /// their text instead of the frames.+ pub formatting_affects_text: bool,/// Window > Contextual Task Bar.pub task_bar: bool,+ /// Where the Contextual Task Bar is pinned: its top-left, in points from the canvas's top-left+ /// (`None`: it follows the selection).+ pub task_bar_pin: Option<[f32; 2]>,+ /// Where the Contextual Task Bar was last shown, like [`Self::task_bar_pin`].+ #[serde(skip)]+ pub task_bar_at: Option<[f32; 2]>,/// Help › About DesignCraft is open.pub about: bool,/// The About window's tab: 0 About, 1 Contributors, 2 Models (`about::ABOUT_TABS`).@@@ -280,9 -270,8 +287,10 @@@ impl Default for UiStatesmart_dimensions: true,smart_spacing: true,snap_zone: 4.0,+ formatting_affects_text: false,task_bar: true,+ task_bar_pin: None,+ task_bar_at: None,about: false,about_tab: 0,pending_urls: Vec::new(),diff --cc crates/ui-egui/src/menus.rsindex 4e1b149d0,56bfe5424..76c3f2ff3--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@@ -2499,78 -2415,56 +2534,128 @@@ mod testsassert_eq!(app.session.tool_id(), "rectangleFrame");}+ #[test]+ fn the_quick_apply_shortcut_opens_it_without_running_an_entry() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", &json!({})).unwrap();+ let ctx = egui::Context::default();+ let frame = |app: &mut crate::DesignApp, events: Vec<egui::Event>| {+ let input = egui::RawInput {+ screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))),+ events,+ ..Default::default()+ };+ let mut out = ctx.run_ui(input, |ui| {+ app.logic(&ui.ctx().clone());+ app.ui(ui);+ });+ out.textures_delta.clear();+ };+ let cmd_return =+ |pressed| egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::COMMAND };+ frame(&mut app, vec![]);+ frame(&mut app, vec![]);+ frame(&mut app, vec![cmd_return(true), cmd_return(false)]);+ frame(&mut app, vec![]);+ assert_eq!(app.ui.palette.as_deref(), Some(""), "Quick Apply stays open");+ assert_eq!(app.session.documents().len(), 1, "the first entry (New Document) didn't run");+ // Pressing the shortcut again, or holding it until it repeats, doesn't run it either.+ frame(&mut app, vec![cmd_return(true), cmd_return(false)]);+ let repeat = egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed: true, repeat: true, modifiers: egui::Modifiers::COMMAND };+ frame(&mut app, vec![repeat, cmd_return(false)]);+ assert_eq!(app.ui.palette.as_deref(), Some(""), "Quick Apply stays open");+ assert_eq!(app.session.documents().len(), 1, "a second ⌘Return or a repeat doesn't run the first entry");+ // A plain Return still does.+ let enter =+ |pressed| egui::Event::Key { key: egui::Key::Enter, physical_key: None, pressed, repeat: false, modifiers: egui::Modifiers::NONE };+ frame(&mut app, vec![enter(true), enter(false)]);+ assert_eq!(app.ui.palette, None, "Return runs the first entry and closes Quick Apply");+ assert_eq!(app.session.documents().len(), 2);+ }++ #[test]+ fn quick_apply_rows_are_left_aligned() {+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", &json!({})).unwrap();+ app.ui.palette = Some(String::new());+ let ctx = egui::Context::default();+ let mut shapes = Vec::new();+ for _ in 0..3 {+ let input =+ egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))), ..Default::default() };+ let mut out = ctx.run_ui(input, |ui| {+ app.logic(&ui.ctx().clone());+ app.ui(ui);+ });+ out.textures_delta.clear();+ shapes = out.shapes;+ }+ let label_x = |label: &str| {+ // The palette is painted last, over anything else with the same text.+ shapes.iter().rev().find_map(|s| match &s.shape {+ egui::Shape::Text(t) if t.galley.text() == label => Some(t.pos.x),+ _ => None,+ })+ };+ // Rows that show a shortcut or a style kind, and rows that show neither, among the first visible ones.+ let items = quick_apply_items(&app.session, "");+ let first = items.iter().take(10);+ let plain = first.clone().find(|it| it.shortcut.is_none() && it.kind.is_empty()).expect("a row without a shortcut");+ let with_sc = first.clone().find(|it| it.shortcut.is_some()).expect("a row with a shortcut");+ let (a, b) = (label_x(&plain.label).expect("plain row drawn"), label_x(&with_sc.label).expect("shortcut row drawn"));+ assert!((a - b).abs() < 0.5, "{:?} at x {a}, {:?} at x {b}", plain.label, with_sc.label);+ }++ #[test]+ fn copy_and_paste_keys_work_for_objects_without_a_native_menu() {+ // Without a native menu the paste key arrives only as a paste event, which needs text on+ // the system clipboard (#164, #185).+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", &json!({})).unwrap();+ let ctx = egui::Context::default();+ let frame = |app: &mut crate::DesignApp, events: Vec<egui::Event>| {+ let input = egui::RawInput {+ screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))),+ events,+ ..Default::default()+ };+ let mut out = ctx.run_ui(input, |ui| {+ app.logic(&ui.ctx().clone());+ app.ui(ui);+ });+ out.textures_delta.clear();+ out.platform_output.commands+ };+ let count = |app: &crate::DesignApp| app.session.active().unwrap().doc.spreads[0].items.len();+ frame(&mut app, vec![]);+ frame(&mut app, vec![]);+ let id = app.session.execute("frame.create", &json!({"rect": [72, 72, 200, 160]})).unwrap()["id"].clone();+ app.session.execute("selection.set", &json!({"ids": [id]})).unwrap();+ let n = count(&app);+ let copied = frame(&mut app, vec![egui::Event::Copy])+ .into_iter()+ .find_map(|c| match c {+ egui::OutputCommand::CopyText(t) => Some(t),+ _ => None,+ })+ .expect("copying objects puts text on the system clipboard");+ assert!(!copied.is_empty());+ frame(&mut app, vec![egui::Event::Paste(copied.clone())]);+ assert_eq!(count(&app), n + 1, "the paste key pastes the copied rectangle");++ // Pasting into text anchors the copied object; the clipboard placeholder isn't typed.+ let r = app.session.execute("frame.create", &json!({"rect": [72, 300, 400, 400], "content": "text", "text": "Hello"})).unwrap();+ let story = r["story"].as_u64().unwrap();+ app.session.execute("tool.select", &json!({"tool": "type"})).unwrap();+ app.session.execute("text.select", &json!({"story": story, "anchor": 5, "focus": 5})).unwrap();+ frame(&mut app, vec![egui::Event::Paste(copied.clone())]);+ // Shift pastes without formatting.+ frame(&mut app, vec![egui::Event::ModifiersChanged(egui::Modifiers::SHIFT), egui::Event::Paste(copied)]);+ let text = app.session.active().unwrap().doc.story(designcraft_doc::StoryId(story)).unwrap().text.clone();+ assert!(text.starts_with("Hello") && !text.contains('\u{FFFC}'), "{text:?}");+ assert!(text.contains(designcraft_doc::OBJECT_MARK), "{text:?}");+ }+#[test]fn sample_scripts_run() {let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());