Merge pull request #9078 from dotCooCoo/fix/paste-keeps-unwritten-cut

Clipboard: Paste keeps a Copy or Cut whose system clipboard write failed
This commit is contained in:
BFlat authored and GitHub committed 2026-11-26 16:59:28 +07:00
commit d7982ef857
6 files changed
+270 -28

No files matched your search

+3 -2
View File
@@ -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,
}
{
+74 -23
View File
@@ -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<String>)>,
/// 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<String> {
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<Option<String>> {
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<Written, String> {
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::<bool>(egui::Id::unique("clipboard.pending-at-tick"))).unwrap_or(false);
ctx.data_mut(|d| d.remove::<bool>(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<String> {
// 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<String> {
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.
+43
View File
@@ -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();
+140
View File
@@ -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#"<svg xmlns="http://www.w3.org/2000/svg" width="400" height="300">"#);
for x in [10, 20, 30] {
svg.push_str(&format!(r##"<path d="M{x} 10h4v4h-4z" fill="#336699"/>"##));
}
svg.push_str(r#"<g><path d="M200 200h2v2h-2z"/><path d="M204 200h2v2h-2z"/></g>"#);
svg.push_str(r#"<path fill-rule="evenodd" d="M210 200h6v6h-6zM212 202h2v2h-2z"/></svg>"#);
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<Mutex<Board>>) -> 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<Mutex<Board>>, 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("<svg")), "{case}: the copy's text");
for (i, paste) in pastes.into_iter().enumerate() {
run(&mut app, paste, json!({}));
let p = pasted(&app);
assert_eq!(p.len(), objects, "{case}, {paste}: the copied art, not the other app's copy");
assert!(p.iter().all(|n| !matches!(n.kind, NodeKind::Text(_) | NodeKind::Image { .. })), "{case}, {paste}");
assert_eq!(count(&app), left + objects * (i + 1), "{case}, {paste}");
}
copy_elsewhere(&board, vec![(TEXT, b"Newer words".to_vec())]);
run(&mut app, "edit.paste", json!({}));
let NodeKind::Text(t) = &pasted(&app)[0].kind else { panic!("{case}: not the newer copy") };
assert_eq!(t.plain_text(), "Newer words", "{case}");
}
}
/// Copy returns before the system clipboard's formats are made: the background worker makes them
/// (here after another Copy's) and they are written when it is done. A paste meanwhile takes what
/// was copied, and neither the status bar nor `ui.inspect` shows the work.
@@ -654,6 +738,62 @@ fn the_menus_paste_into_a_field_waits_for_the_formats() {
background::wait_all(&mut app);
}
/// The Edit menu's Paste into a text field after a Copy whose formats have no text (On Copy:
/// Include SVG Code off) and could not be written: the field takes nothing, not the text another
/// app left on the clipboard, and the copied art is not pasted onto the canvas.
#[test]
fn the_menus_paste_into_a_field_after_a_refused_textless_copy_takes_nothing() {
let (mut app, board) = 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]}));
copy_elsewhere(&board, vec![(TEXT, b"Old".to_vec())]);
refuse_writes(&board, true);
run(&mut app, "edit.copy", json!({}));
background::wait_all(&mut app);
refuse_writes(&board, false);
let objects = count(&app);
// A text field with the keyboard; in the second frame Paste is chosen from the menu.
let (ctx, id, mut field) = (crate::testing::ui_context(), egui::Id::unique("field"), String::new());
for paste in [false, true] {
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
if paste {
craft::ui::runtime::commands::fire(ui.ctx(), "edit.paste", craft::ui::runtime::commands::FireSource::Menu);
for fired in &craft::ui::runtime::frame::take_output(ui.ctx()).fired {
crate::shortcuts::run_fired(&mut app, ui.ctx(), fired);
}
}
ui.add(egui::TextEdit::singleline(&mut field).id(id)).request_focus();
});
out.textures_delta.clear();
}
assert_eq!(field, "", "the field takes nothing");
assert_eq!(count(&app), objects, "nothing is pasted onto the canvas");
}
/// A Copy whose formats could not be written stops being what Paste takes once different text is
/// seen on the clipboard: when another app later puts the older text back, Paste takes that text,
/// not the copied art.
#[test]
fn a_refused_copy_stays_replaced_when_the_older_text_comes_back() {
let (mut app, board) = app();
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]}));
copy_elsewhere(&board, vec![(TEXT, b"Old".to_vec())]);
refuse_writes(&board, true);
run(&mut app, "edit.copy", json!({}));
background::wait_all(&mut app);
refuse_writes(&board, false);
copy_elsewhere(&board, vec![(TEXT, b"New".to_vec())]);
assert_eq!(app.written_clipboard_text().as_deref(), Some("New"));
copy_elsewhere(&board, vec![(TEXT, b"Old".to_vec())]);
assert_eq!(app.written_clipboard_text().as_deref(), Some("Old"), "a paste into text");
run(&mut app, "edit.paste", json!({}));
let NodeKind::Text(t) = &pasted(&app)[0].kind else { panic!("the copied art, not the clipboard's text") };
assert_eq!(t.plain_text(), "Old");
}
/// A paste chord into type being edited, before the formats are written: the formats are written
/// first, and the paste pastes their text whether the host read another app's text for it or found
/// no text (a picture), also when that paste comes a frame after they were written; with no text in
+3 -1
View File
@@ -816,7 +816,9 @@ lists to the system clipboard (once they are written, the status bar shows the f
another message has replaced the Copy or Cut's meanwhile), and every Paste command first loads what another app copied (`clipboard.importSvg`,
`importPdf`, `importEps`, `importText` or `importImage`, centred in the view; the desktop app reads PDF and EPS from
the Windows clipboard and, with SVG, from the macOS pasteboard, and an `.eps` file, or a `.ai` or `.ait` file that holds a PDF or PostScript, copied in a file manager anywhere; a copied `.ai` or `.ait` file that holds a PDF loads with `importPdf {editingData: true}`, which reads its editing data); an import error answers the Paste with that error
and pastes nothing. Cmd+V also pastes a bitmap or PDF with no text beside it (on the key's release, as egui sends no
and pastes nothing. After a Copy or Cut whose formats could not be written to the system clipboard, every Paste
command takes the internal clipboard instead until another app copies something (only while the clipboard held text
that could be read when the write failed). Cmd+V also pastes a bitmap or PDF with no text beside it (on the key's release, as egui sends no
Paste event for it). Screenshots paste on every platform: Windows reads `PNG`, else `CF_DIBV5`/`CF_DIB`, macOS the
pasteboard's PNG or TIFF, Linux `image/png`, and the web the picture the browser's paste event carries (#457).
In the desktop app a Paste from the menus or the keys (`ui.key`) decodes a bitmap off the UI thread: `ui.inspect` lists
+7 -2
View File
@@ -10379,8 +10379,13 @@ copied (SVG, then PDF, then text, then a bitmap; SVG markup in text counts as SV
formats and they are published when they are ready. While that thread has a save, an export, a print or a recovery
copy to finish, Copy and Cut make and publish them at once. When another Copy or Cut, or a copy of text in
VectorCraft, comes first, they are dropped. Pasting what VectorCraft copied keeps the lossless internal clipboard,
also before its formats are published. While a text field or the Type tool has the keyboard, the app waits for
them. Windows carries every format both ways and pastes a bitmap from PNG, else
also before its formats are published. When the formats could not be written (another app held the clipboard open
or refused the write), every Paste takes the internal clipboard until another app copies something, and a paste
into a text field or type takes the copy's text, or nothing when the formats have no text. The app notices that
copy only when it changes the clipboard's text, so Paste reads the system clipboard when it held only a picture, or
nothing that could be read, at the failed write. Once a paste has read the changed text, the older text coming back
does not restore the copy. While a
text field or the Type tool has the keyboard, the app waits for them. Windows carries every format both ways and pastes a bitmap from PNG, else
from the device-independent bitmap screenshots copy (`CF_DIBV5`, then `CF_DIB`; alpha kept, opaque when it is zero
throughout, at most 32768 px a side); macOS and Linux carry one format (the text, else the PNG) and paste text and
bitmaps (macOS the pasteboard's PNG, else TIFF, as screenshots copy them). A Paste from the menus or the keys decodes