diff --git a/crates/ui-egui/src/shortcuts.rs b/crates/ui-egui/src/shortcuts.rs index eaa0065ba4..decf0abcfa 100644 --- a/crates/ui-egui/src/shortcuts.rs +++ b/crates/ui-egui/src/shortcuts.rs @@ -30,13 +30,14 @@ pub(crate) fn run_fired(app: &mut VectorcraftApp, ctx: &egui::Context, fired: &F return; } // A menu's Cut, Copy or Paste that no framework part took, while an egui text field has the keys, goes to that - // field as its clipboard event, as its keys would; Paste pastes the text of a Copy's formats, written first. + // field as its clipboard event, as its keys would; Paste pastes the text of a Copy's formats, written first, or + // nothing when they could not be written and have no text ([`VectorcraftApp::field_paste_text`]). if fired.source == FireSource::Menu && let Some(field) = ctx.memory(|m| m.focused()).filter(|&id| egui::TextEdit::load_state(ctx, id).is_some()) && let Some(event) = match fired.command.id.as_str() { "edit.copy" => Some(egui::Event::Copy), "edit.cut" => Some(egui::Event::Cut), - "edit.paste" | "edit.pasteWithoutFormatting" => app.written_clipboard_text().map(egui::Event::Paste), + "edit.paste" | "edit.pasteWithoutFormatting" => app.field_paste_text().map(egui::Event::Paste), _ => None, } { diff --git a/crates/ui-egui/src/sysclip.rs b/crates/ui-egui/src/sysclip.rs index cc214b08dd..9371e118fd 100644 --- a/crates/ui-egui/src/sysclip.rs +++ b/crates/ui-egui/src/sysclip.rs @@ -85,8 +85,8 @@ pub(crate) struct Publishing { /// The latest one's formats wait to be written. pending: bool, /// The latest one's formats could not be written: what the system clipboard's text was when the - /// write failed, and the text of those formats. - unwritten: Option<(Held, String)>, + /// write failed, and the text of those formats, if they have text. + unwritten: Option<(Held, Option)>, /// The status bar's message when the latest one ran, with [`crate::state::UiState::status_sets`] /// then. Its formats' notes replace the message only while the status bar still shows it and /// nothing has set the status since. @@ -120,6 +120,22 @@ impl Publishing { fn shows_status(&self, ui: &crate::state::UiState) -> bool { ui.status == self.status.0 && ui.status_sets == self.status.1 } + + /// Is the latest Copy or Cut one whose formats could not be written to `cb`, with nothing + /// copied since ([`VectorcraftApp::holds_unwritten_copy`])? Different text read from `cb` shows + /// a later copy: the record of the failed write is then dropped, so the clipboard holding the + /// older text again later does not bring it back. Text that could not be read keeps the record. + fn holds_unwritten(&mut self, cb: &mut Clipboard) -> bool { + let Some((held, _)) = &self.unwritten else { return false }; + let now = held_text(cb); + if now == *held { + return true; + } + if now.is_some() { + self.unwritten = None; + } + false + } } /// The status bar's line after a Copy (or with `cut`, a Cut) whose formats have `n` notes, the @@ -185,14 +201,31 @@ impl VectorcraftApp { || self.clipboard.holds_ours() } + /// Is the latest Copy or Cut one whose formats could not be written to the system clipboard, + /// with nothing copied since? Paste then takes the internal clipboard, and a paste into type or + /// a text field takes that copy's text (nothing when its formats have no text), until another + /// app copies something. A copy is noticed only when it changes the clipboard's text, so the + /// copy is kept only when the clipboard held text when the write failed. When it held only a + /// picture, or nothing that could be read, Paste takes what the clipboard holds. + fn holds_unwritten_copy(&mut self) -> bool { + self.clipboard_publishing.holds_unwritten(&mut self.clipboard) + } + /// The text of the latest Copy or Cut whose formats could not be written to the system - /// clipboard, while nothing has been copied since that Copy or Cut. A paste into type or a text - /// field takes this text until another app copies something. A copy is noticed only when it - /// changes the clipboard's text, so the copy is kept only when the clipboard held text when the - /// write failed. + /// clipboard, while nothing has been copied since that Copy or Cut + /// ([`Self::holds_unwritten_copy`]). pub(crate) fn unwritten_clipboard_text(&mut self) -> Option { - let (held, text) = self.clipboard_publishing.unwritten.as_ref()?; - (held_text(&mut self.clipboard) == *held).then(|| text.clone()) + self.clipboard_publishing.unwritten.as_ref()?.1.as_ref()?; + self.unwritten_copy().flatten() + } + + /// While [`Self::holds_unwritten_copy`]: the text of that copy's formats, `None` inside when + /// they have no text. + fn unwritten_copy(&mut self) -> Option> { + if !self.holds_unwritten_copy() { + return None; + } + self.clipboard_publishing.unwritten.as_ref().map(|(_, text)| text.clone()) } /// After Copy or Cut: offer the copied objects to other apps. The background worker makes the @@ -279,8 +312,8 @@ impl VectorcraftApp { /// Writes `formats` to the system clipboard; `before` is the clipboard's text at the Copy or Cut. /// When that fails, another app may hold the clipboard open: it keeps what it held (or what the - /// failed write left), and a paste into text takes this copy's text until something else is - /// copied ([`Self::unwritten_clipboard_text`]). + /// failed write left). Until something else is copied, Paste takes this copy, and a paste into + /// text takes its text ([`Self::holds_unwritten_copy`]). fn write_formats(&mut self, formats: &[Flavor], before: &Held) -> Result { let cb = &mut self.clipboard; let before_write = held_text(cb); @@ -306,7 +339,7 @@ impl VectorcraftApp { // A clipboard with no text can't show a later copy of a picture, or tell an empty clipboard // from one that couldn't be read: unless it held text the write emptied, and it reads. let trackable = held.is_some() || (before_write.is_some() && cb.read(&[TEXT]).is_ok()); - self.clipboard_publishing.unwritten = text.filter(|_| current && left_by_write && trackable).map(|text| (held, text)); + self.clipboard_publishing.unwritten = (current && left_by_write && trackable).then_some((held, text)); Err(e.to_string()) } @@ -389,17 +422,20 @@ impl VectorcraftApp { let waited = ctx.data(|d| d.get_temp::(egui::Id::unique("clipboard.pending-at-tick"))).unwrap_or(false); ctx.data_mut(|d| d.remove::(egui::Id::unique("clipboard.pending-at-tick"))); if !(self.clipboard_publishing.pending || waited) { - // A copy whose formats could not be written: a paste takes its text, not the text the - // clipboard kept ([`Self::unwritten_clipboard_text`]). + // A copy whose formats could not be written: a paste takes its text, or nothing when + // they have none, not the text the clipboard kept ([`Self::unwritten_copy`]). let pasting = textless || ctx.input(|i| i.events.iter().any(|e| matches!(e, egui::Event::Paste(_)))); - if pasting && let Some(text) = self.unwritten_clipboard_text() { + if pasting && let Some(text) = self.unwritten_copy() { ctx.input_mut(|i| { - for e in &mut i.events { - if let egui::Event::Paste(t) = e { - t.clone_from(&text); + i.events.retain_mut(|e| match (e, &text) { + (egui::Event::Paste(t), Some(text)) => { + t.clone_from(text); + true } - } - if textless { + (egui::Event::Paste(_), None) => false, + _ => true, + }); + if textless && let Some(text) = text { i.events.insert(0, egui::Event::Paste(text)); } }); @@ -474,7 +510,10 @@ impl VectorcraftApp { // A picture or file the host read from the paste. Some(f) if f.mime != TEXT => import_command(&f, center), _ if self.clipboard.readable_any_time() => { - if self.clipboard_publishing.pending || self.clipboard.holds_ours() { + // After a Copy or Cut whose formats could not be written, with nothing copied + // since, what the clipboard still holds is older than the internal clipboard. + let publishing = &mut self.clipboard_publishing; + if publishing.pending || publishing.holds_unwritten(&mut self.clipboard) || self.clipboard.holds_ours() { return Ok(None); } // Art and text load at once, so a paste that waits behind another takes them as it was given; only a @@ -554,12 +593,24 @@ impl VectorcraftApp { } /// The text on the system clipboard once the formats a Copy or Cut is making are written, for a - /// paste into a text field or type. When they could not be written, their text - /// ([`Self::unwritten_clipboard_text`]). + /// paste into a text field or type. When they could not be written, their text, or `None` when + /// they have none ([`Self::unwritten_copy`]). pub(crate) fn written_clipboard_text(&mut self) -> Option { // Only other copies' formats are ahead of them on the worker ([`Self::publish_clipboard`]). background::wait_until(self, |app| !app.clipboard_publishing.pending); - self.unwritten_clipboard_text().or_else(|| self.system_clipboard_text()) + self.unwritten_copy().unwrap_or_else(|| self.system_clipboard_text()) + } + + /// The text a paste from the Edit menu gives a focused text field ([`Self::written_clipboard_text`]): + /// empty when the formats of a Copy or Cut could not be written and have no text, so the field + /// takes nothing and the art is not pasted onto the canvas. `None` when the system clipboard + /// holds no text. + pub(crate) fn field_paste_text(&mut self) -> Option { + background::wait_until(self, |app| !app.clipboard_publishing.pending); + match self.unwritten_copy() { + Some(text) => Some(text.unwrap_or_default()), + None => self.system_clipboard_text(), + } } /// The text on the system clipboard, if any. diff --git a/crates/ui-egui/src/tests/clipboard.rs b/crates/ui-egui/src/tests/clipboard.rs index f54e222b98..240a578ac5 100644 --- a/crates/ui-egui/src/tests/clipboard.rs +++ b/crates/ui-egui/src/tests/clipboard.rs @@ -474,6 +474,49 @@ fn type_paste_drops_a_refused_copy_it_cannot_track() { assert_eq!(paste_at(&mut app, 5), "Own: "); } +/// After a Copy whose formats have no text (On Copy: Include SVG Code off) and could not be +/// written, a paste into type takes nothing, from the menu or a paste event, not the text another +/// app left on the clipboard. A later copy in another app still pastes. +#[test] +fn a_paste_into_type_after_a_refused_textless_copy_takes_nothing() { + use vectorcraft_engine::cmd::clipboard::TEXT; + let _guard = TEST_CLIP_LOCK.lock().unwrap(); + let (mut app, board) = super::sysclip::app(); + run(&mut app, "prefs.set", json!({"key": "copyAsSvg", "value": false})); + let rect = run(&mut app, "shape.rectangle", json!({"x": 10, "y": 10, "width": 40, "height": 20}))["id"].clone(); + run(&mut app, "select.set", json!({"ids": [rect]})); + super::sysclip::copy_elsewhere(&board, vec![(TEXT, b"Old".to_vec())]); + super::sysclip::refuse_writes(&board, true); + run(&mut app, "edit.copy", json!({})); + crate::background::wait_all(&mut app); + super::sysclip::refuse_writes(&board, false); + + let destination = + run(&mut app, "text.create", json!({"x": 20, "y": 60, "text": "Own: ", "size": 12, "color": "#000000"}))["id"].as_u64().unwrap(); + let v = app.view_info(); + let text = |app: &VectorcraftApp| { + let node = app.session.doc().unwrap().doc.node(NodeId(destination)).unwrap(); + let vectorcraft_doc::NodeKind::Text(t) = &node.kind else { panic!() }; + t.plain_text() + }; + let place = |app: &mut VectorcraftApp| { + app.session.select_tool("selection", v).unwrap(); + app.session.select_tool("type", v).unwrap(); + app.session.set_tool_option("textSelection", &json!({"id": destination, "start": 5, "end": 5})); + }; + place(&mut app); + crate::panels::character::intercept_text_command(&mut app, "edit.paste"); + assert_eq!(text(&app), "Own: ", "the menu's Paste"); + place(&mut app); + super::sysclip::frame(&mut app, vec![egui::Event::Paste("Old".into())]); + assert_eq!(text(&app), "Own: ", "a paste event"); + + super::sysclip::copy_elsewhere(&board, vec![(TEXT, b"New".to_vec())]); + place(&mut app); + crate::panels::character::intercept_text_command(&mut app, "edit.paste"); + assert_eq!(text(&app), "Own: New", "the later copy"); +} + #[test] fn a_paste_event_waiting_on_a_refused_copy_pastes_that_copy() { let _guard = TEST_CLIP_LOCK.lock().unwrap(); diff --git a/crates/ui-egui/src/tests/sysclip.rs b/crates/ui-egui/src/tests/sysclip.rs index baa21396ed..38efb55e1f 100644 --- a/crates/ui-egui/src/tests/sysclip.rs +++ b/crates/ui-egui/src/tests/sysclip.rs @@ -398,6 +398,90 @@ fn our_own_copy_pastes_the_lossless_internal_clipboard() { assert!(matches!(pasted(&app)[0].kind, NodeKind::Path { .. })); } +/// SVG markup of three closed paths, a group of two more and a compound path with a hole: five +/// objects. +fn closed_paths_svg() -> String { + let mut svg = String::from(r#""#); + for x in [10, 20, 30] { + svg.push_str(&format!(r##""##)); + } + svg.push_str(r#""#); + svg.push_str(r#""#); + svg +} + +/// Paste the objects of [`closed_paths_svg`] from another app and select them all → their count. +fn paste_closed_paths(app: &mut VectorcraftApp, board: &Arc>) -> usize { + copy_elsewhere(board, vec![(SVG, closed_paths_svg().into_bytes())]); + run(app, "edit.paste", json!({})); + run(app, "select.all", json!({})); + let objects = count(app); + assert_eq!(app.session.active().unwrap().selection.objects.len(), objects); + objects +} + +/// A Copy or Cut whose formats can't be written to the system clipboard (another app holds it +/// open, or refuses the write) stays what every Paste command takes while nothing else is copied, +/// also when its formats have no text; the clipboard's older text does not replace it, and a paste +/// into text takes the copy's text, or nothing. A later copy in another app still wins. A later copy is +/// noticed only when it changes the clipboard's text, so when the clipboard held only a picture, +/// or could not be read (another app holds it open), Paste takes what the clipboard holds. +#[test] +fn a_copy_the_system_clipboard_refused_still_pastes_the_copied_art() { + type Fail = fn(&Arc>, bool); + // Case, Copy or Cut, how the write fails, On Copy: Include SVG Code, the other app's copy + // before it is a picture, Paste takes the copied art. + let cases: [(&str, &str, Fail, bool, bool, bool); 5] = [ + ("refused", "edit.cut", refuse_writes, true, false, true), + ("refused, no text", "edit.cut", refuse_writes, false, false, true), + ("refused copy", "edit.copy", refuse_writes, true, false, true), + ("locked", "edit.cut", lock, true, false, false), + ("refused, over a picture", "edit.cut", refuse_writes, true, true, false), + ]; + let pastes = + ["edit.paste", "edit.pasteInFront", "edit.pasteInBack", "edit.pasteInPlace", "edit.pasteOnAllArtboards", "edit.pasteWithoutFormatting"]; + for (case, op, fail, svg_text, over_picture, kept) in cases { + let (mut app, board) = app(); + run(&mut app, "prefs.set", json!({"key": "copyAsSvg", "value": svg_text})); + let objects = paste_closed_paths(&mut app, &board); + if over_picture { + copy_elsewhere(&board, vec![(PNG, blue_png())]); + } else { + copy_elsewhere(&board, vec![(TEXT, b"Words another app copied".to_vec())]); + } + fail(&board, true); + run(&mut app, op, json!({})); + background::wait_all(&mut app); + fail(&board, false); + assert!(app.ui.status.starts_with("Couldn't copy to the system clipboard"), "{case}: {}", app.ui.status); + let left = if op == "edit.cut" { 0 } else { objects }; + assert_eq!(count(&app), left, "{case}"); + if !kept { + run(&mut app, "edit.paste", json!({})); + match &pasted(&app)[0].kind { + NodeKind::Image { .. } => assert!(over_picture, "{case}: the picture"), + NodeKind::Text(t) => assert_eq!((over_picture, t.plain_text().as_str()), (false, "Words another app copied"), "{case}"), + kind => panic!("{case}: not what the clipboard holds: {kind:?}"), + } + continue; + } + let text = app.written_clipboard_text(); + assert_eq!(text.is_some(), svg_text, "{case}: a paste into text takes the copy's text, or nothing: {text:?}"); + assert!(text.is_none_or(|t| t.contains("