DesignCraft: An open-source page and layout design editor written by scratch in pure Rust
Paste: text from another app with no insertion point becomes a new text frame (#518)
aiongg162a7f14bbbe
diff --git a/crates/engine/src/cmd/edit.rs b/crates/engine/src/cmd/edit.rsindex e7190acb4..8bf12f06f 100644--- a/crates/engine/src/cmd/edit.rs+++ b/crates/engine/src/cmd/edit.rs@@ -20,13 +20,6 @@ fn has_clip(s: &Session) -> std::result::Result<(), String> {if s.clipboard.is_some() || text { Ok(()) } else { Err("clipboard is empty".into()) }}-fn has_clip_or_text(s: &Session) -> std::result::Result<(), String> {- if s.active().is_some_and(|d| d.selection.text.is_some()) {- return Ok(());- }- has_clip(s)-}-fn has_selection_or_text(s: &Session) -> std::result::Result<(), String> {if s.active().and_then(|d| d.selection.text).is_some_and(|t| !t.is_caret()) {return Ok(());@@ -91,6 +84,56 @@ fn paste_text(s: &mut Session, text: Option<String>, formatted: bool) -> Result<s.execute("text.insert", &json!({"text": text.replace("\r\n", "\n").replace('\r', "\n"), "raw": true}))}+/// Pasted text with no insertion point: a new text frame holding it, as wide as the first column+/// of the page's margin area and as tall as the text (at most the margin area's height), centred+/// on `at` (spread coordinates) or else on the margin area. The frame ends up selected.+fn paste_text_frame(s: &mut Session, p: &Value, text: &str) -> Result<Value> {+ use designcraft_geom::{Point, Rect, shapes};+ const LIMIT: f64 = 1.0e5;+ let sr = super::spread_param(p, "spread");+ let at = super::point_param(p, "at")+ .filter(|a| a.x.is_finite() && a.y.is_finite())+ .map(|a| Point::new(a.x.clamp(-LIMIT, LIMIT), a.y.clamp(-LIMIT, LIMIT)));+ let lid = s.doc()?.active_layer;+ let cache = s.cache.clone();+ let text = text.replace("\r\n", "\n").replace('\r', "\n");+ s.edit(|d, sel| {+ let sp = d.spread(sr).ok_or_else(|| super::bad("edit.paste", "no such spread"))?;+ let page = at.and_then(|a| sp.page_at_x(a.x)).and_then(|i| sp.pages.get(i)).or_else(|| sp.pages.first());+ let page = page.ok_or_else(|| super::bad("edit.paste", "the spread has no pages"))?;+ let margins = page.margin_rect();+ let column = page.column_rects().first().copied().unwrap_or(margins);+ let w = column.width().max(12.0);+ let max_h = margins.height().max(12.0);+ let c = at.unwrap_or(Point::new(column.center().x, margins.center().y));+ let rect = |h: f64| Rect::new(c.x - w / 2.0, c.y - h / 2.0, c.x + w / 2.0, c.y + h / 2.0);+ let para = designcraft_doc::ParaFormat { style: d.styles.default_paragraph.clone(), ..Default::default() };+ let (id, sid) = d.add_text_frame(sr, rect(max_h), lid, &text, para)?;+ // Shrink to the composed text unless it already fills the frame.+ let composed = cache.get(d, sid, None);+ if !composed.is_overset()+ && let Some(ft) = composed.frame(id)+ {+ let inset = d.item(id).and_then(|i| i.text_frame()).map_or(0.0, |tf| tf.options.inset[0] + tf.options.inset[2]);+ let h = (ft.content_height + inset + 0.5).clamp(12.0, max_h);+ if h.is_finite()+ && h < max_h+ && let Some(it) = d.item_mut(id)+ {+ it.path = shapes::rectangle(rect(h));+ // Keep the full height if the last line no longer fits.+ if cache.get(d, sid, None).is_overset()+ && let Some(it) = d.item_mut(id)+ {+ it.path = shapes::rectangle(rect(max_h));+ }+ }+ }+ *sel = Selection::items(vec![id]);+ Ok(json!({"id": id.0, "story": sid.0}))+ })+}+fn strip_objects(st: &designcraft_doc::Story) -> designcraft_doc::Story {let mut out = st.clone();let marks = [designcraft_doc::FOOTNOTE_REF, designcraft_doc::XREF_MARK, designcraft_doc::TABLE_ANCHOR];@@ -227,11 +270,16 @@ pub fn specs() -> Vec<CommandSpec> {"Paste",["Edit"],Some("Cmd+V"),- "{inPlace?: bool, text?: the system clipboard's text (pastes it unless it is what was copied here)}",- has_clip_or_text,+ "{inPlace?: bool, text?: the system clipboard's text (pastes it unless it is what was copied here; with no insertion point it becomes a new text frame), spread?, at?: [x, y] (spread coords: the new text frame's centre)}",+ // The system clipboard may hold text from another app, so Paste is always available.+ has_doc,|s, p| {+ let text = super::str_param(p, "text").filter(|t| !t.is_empty());if s.doc()?.selection.text.is_some() {- return paste_text(s, super::str_param(p, "text").map(str::to_string), true);+ return paste_text(s, text.map(str::to_string), true);+ }+ if let Some(text) = text {+ return paste_text_frame(s, p, text);}let Some(clip) = s.clipboard.clone() else {return Err(super::bad("edit.paste", "clipboard is empty"));@@ -316,6 +364,46 @@ mod text_clipboard_tests {s.doc().unwrap().doc.item(ItemId(r["id"].as_u64().unwrap())).unwrap().text_frame().unwrap().story}+ #[test]+ fn paste_text_with_no_insertion_point_makes_a_text_frame() {+ let mut s = Session::new();+ s.execute("file.new", &json!({})).unwrap();+ let items = |s: &Session| s.doc().unwrap().doc.spreads[0].items.len();+ // Text from another app, nothing copied here: a new, selected text frame.+ let r = s.execute("edit.paste", &json!({"text": "From elsewhere\r\nSecond line"})).unwrap();+ let id = ItemId(r["id"].as_u64().unwrap());+ let d = s.doc().unwrap();+ assert_eq!(d.selection.items, vec![id]);+ assert!(d.selection.text.is_none(), "selected as an object");+ let it = d.doc.item(id).unwrap();+ assert_eq!(d.doc.story(it.text_frame().unwrap().story).unwrap().text, "From elsewhere\nSecond line");+ let page = &d.doc.spreads[0].pages[0];+ let (b, m) = (it.bounds(), page.margin_rect());+ assert!((b.width() - page.column_rects()[0].width()).abs() < 1e-6, "{b:?}");+ assert!(b.height() < m.height() / 2.0, "fits two lines: {b:?}");+ assert!((b.center().y - m.center().y).abs() < 1e-6, "{b:?}");+ assert!(!s.cache.get(&d.doc, it.text_frame().unwrap().story, None).is_overset());+ s.execute("edit.undo", &json!({})).unwrap();+ assert_eq!(items(&s), 0, "one undo removes it");+ // Centred on `at`; hostile numbers are clamped.+ let r = s.execute("edit.paste", &json!({"text": "Here", "at": [200.0, 300.0]})).unwrap();+ let b = s.doc().unwrap().doc.item(ItemId(r["id"].as_u64().unwrap())).unwrap().bounds();+ assert!((b.center().x - 200.0).abs() < 1e-6 && (b.center().y - 300.0).abs() < 1e-6, "{b:?}");+ assert!(s.execute("edit.paste", &json!({"text": "Far", "at": [1e300, -1e300], "spread": 99})).is_err());+ s.execute("edit.paste", &json!({"text": "Far", "at": [1e300, -1e300]})).unwrap();+ // Copied objects paste when no text is given.+ s.execute("edit.deselectAll", &json!({})).unwrap();+ let rect = s.execute("frame.create", &json!({"rect": [72, 72, 200, 160]})).unwrap()["id"].clone();+ s.execute("selection.set", &json!({"ids": [rect]})).unwrap();+ s.execute("edit.copy", &json!({})).unwrap();+ let n = items(&s);+ let r = s.execute("edit.paste", &json!({})).unwrap();+ assert_eq!(r["ids"].as_array().unwrap().len(), 1);+ assert_eq!(items(&s), n + 1);+ assert!(s.doc().unwrap().doc.item(ItemId(r["ids"][0].as_u64().unwrap())).unwrap().text_frame().is_none());+ s.doc().unwrap().doc.check().unwrap();+ }+#[test]fn formatted_copy_paste_and_plain_paste() {let mut s = Session::new();diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rsindex 246061a5f..3d05062b0 100644--- a/crates/ui-egui/src/canvas.rs+++ b/crates/ui-egui/src/canvas.rs@@ -139,6 +139,17 @@ pub fn current_slot(app: &DesignApp, layout: &CanvasLayout) -> Option<usize> {.map(|(i, _)| i)}+/// The spread nearest the view centre and the centre in that spread's coordinates.+pub fn view_centre(app: &DesignApp) -> Option<(SpreadRef, Point)> {+ let st = app.session.active()?;+ let layout = CanvasLayout::new(&st.doc, st.editing_parents);+ let slot = layout.slots.get(current_slot(app, &layout)?)?;+ let v = app.view()?;+ let r = app.canvas_rect?;+ let c = Point::new(v.origin.x + r.width() as f64 / 2.0 / v.zoom, v.origin.y + r.height() as f64 / 2.0 / v.zoom);+ Some((slot.spread, slot.to_spread(c)))+}+/// Absolute page index under the view centre.pub fn current_page(app: &DesignApp) -> Option<usize> {let st = app.session.active()?;@@ -1508,13 +1519,14 @@ fn handle_input(app: &mut DesignApp, ui: &mut egui::Ui, resp: &egui::Response, r}// Without a native menu bar the copy and paste keys arrive only as these events.egui::Event::Copy | egui::Event::Cut | egui::Event::Paste(_) if !app.native_menu => {- let id = match e {- egui::Event::Copy => "edit.copy",- egui::Event::Cut => "edit.cut",- _ => "edit.paste",+ let (id, params) = match e {+ egui::Event::Copy => ("edit.copy", serde_json::Value::Null),+ egui::Event::Cut => ("edit.cut", serde_json::Value::Null),+ egui::Event::Paste(t) => ("edit.paste", json!({"text": t})),+ _ => continue,};if crate::menus::enabled(app, id) {- crate::menus::activate(app, id, &serde_json::Value::Null);+ crate::menus::activate(app, id, ¶ms);}}egui::Event::Key { key, pressed: true, modifiers, .. } => {diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rsindex dd75c94fc..756d4fe20 100644--- a/crates/ui-egui/src/lib.rs+++ b/crates/ui-egui/src/lib.rs@@ -497,8 +497,9 @@ pub struct DesignApp {/// A control-channel request is being handled: commands it runs never read or write the/// user's system clipboard (a control client must not see or replace it).pub(crate) in_control: bool,- /// What the last object copy put on the system clipboard (no native menu): without it the- /// paste keys produce no paste event. It is never pasted as text.+ /// The system clipboard's text that stands for the last object copy: what that copy put there+ /// (no native menu: without it the paste keys produce no paste event), or what it held then+ /// (native menu). It is never pasted as text: Paste with it pastes the copied objects.object_clip_text: Option<String>,}@@ -601,7 +602,10 @@ impl DesignApp {self.object_clip_text = Some(self.copied_objects_text());self.object_clip_text.clone()}- None => None,+ None => {+ self.object_clip_text = self.services.clipboard_text.as_mut().and_then(|f| f());+ None+ }};if let (Some(t), Some(ctx)) = (text, &self.egui_ctx) {ctx.copy_text(t);@@ -613,10 +617,12 @@ impl DesignApp {r}- /// Paste into text without the clipboard's text (a menu, not the paste keys): read it here.+ /// Paste without the clipboard's text (a menu, not the paste keys): read it here. With no+ /// insertion point, text that doesn't stand for copied objects becomes a new text frame+ /// centred in the view.fn with_system_clipboard(&mut self, id: &str, mut params: Value) -> Value {let typing = self.session.active().is_some_and(|d| d.selection.text.is_some());- if !typing || !matches!(id, "edit.paste" | "edit.pasteWithoutFormatting") {+ if !matches!(id, "edit.paste" | "edit.pasteWithoutFormatting") || !(typing || id == "edit.paste") {return params;}if params.get("text").is_none()@@ -633,6 +639,15 @@ impl DesignApp {{o.remove("text");}+ if !typing+ && params.get("text").and_then(Value::as_str).is_some_and(|t| !t.is_empty())+ && let Some((spread, at)) = canvas::view_centre(self)+ && let Ok(spread) = serde_json::to_value(spread)+ && let Some(o) = params.as_object_mut()+ {+ o.entry("spread").or_insert(spread);+ o.entry("at").or_insert(json!([at.x, at.y]));+ }params}diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rsindex fab03ddf3..062aca13a 100644--- a/crates/ui-egui/src/menus.rs+++ b/crates/ui-egui/src/menus.rs@@ -2910,6 +2910,67 @@ mod tests {assert!(text.contains(designcraft_doc::OBJECT_MARK), "{text:?}");}+ #[test]+ fn paste_with_no_insertion_point_makes_a_text_frame_from_other_apps_text() {+ // #518: text copied in another app pastes as a new, selected text frame; the text an+ // object copy stands for still pastes the objects. One paste each way, with and without+ // a native menu.+ let selected_text = |app: &crate::DesignApp| {+ let d = app.session.active().unwrap();+ let it = d.doc.item(*d.selection.items.first()?)?;+ Some(d.doc.story(it.text_frame()?.story)?.text.clone())+ };+ let ctx = egui::Context::default();+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());+ app.session.execute("file.new", &json!({})).unwrap();+ native_frame(&mut app, &ctx, vec![], None);+ native_frame(&mut app, &ctx, vec![], None);+ // The paste keys without a native menu: a paste event.+ native_frame(&mut app, &ctx, vec![egui::Event::Paste("From elsewhere".into())], None);+ assert_eq!(document_items(&app), (1, 1), "pasted once");+ assert_eq!(selected_text(&app).as_deref(), Some("From elsewhere"));+ 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 copied = native_frame(&mut app, &ctx, vec![egui::Event::Copy], None)+ .platform_output+ .commands+ .into_iter()+ .find_map(|c| match c {+ egui::OutputCommand::CopyText(t) => Some(t),+ _ => None,+ })+ .expect("copying objects puts text on the system clipboard");+ native_frame(&mut app, &ctx, vec![egui::Event::Paste(copied)], None);+ assert_eq!(document_items(&app), (3, 1));+ assert_eq!(selected_text(&app), None, "the copied rectangle, not a text frame");++ // A native menu: Paste reads the system clipboard.+ let clip = std::rc::Rc::new(std::cell::RefCell::new(Some("Menu text".to_string())));+ let read = clip.clone();+ let services = crate::Services { clipboard_text: Some(Box::new(move || read.borrow().clone())), ..Default::default() };+ let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), services);+ app.native_menu = true;+ app.session.execute("file.new", &json!({})).unwrap();+ native_frame(&mut app, &ctx, vec![], None);+ native_frame(&mut app, &ctx, vec![], None);+ native_frame(&mut app, &ctx, vec![], Some("edit.paste"));+ native_frame(&mut app, &ctx, vec![], None);+ assert_eq!(document_items(&app), (1, 1), "pasted once");+ assert_eq!(selected_text(&app).as_deref(), Some("Menu text"));+ // Objects copied since that text was copied paste as objects.+ 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();+ native_frame(&mut app, &ctx, vec![], Some("edit.copy"));+ native_frame(&mut app, &ctx, vec![], Some("edit.paste"));+ assert_eq!(document_items(&app), (3, 1));+ assert_eq!(selected_text(&app), None, "the copied rectangle, not a text frame");+ // Newer text from another app wins.+ *clip.borrow_mut() = Some("Newer".into());+ native_frame(&mut app, &ctx, vec![], Some("edit.paste"));+ assert_eq!(document_items(&app), (4, 1));+ assert_eq!(selected_text(&app).as_deref(), Some("Newer"));+ }+#[test]fn sample_scripts_run() {let mut app = crate::DesignApp::new(designcraft_engine::Session::new(), crate::Services::default());