Compare commits

..
Author SHA1 Message Date
skylartaylor f0cd3c14cc Release: bump WordCraft to v0.20.1 2026-12-04 17:39:02 +01:00
Martin BallandClaude Opus 5.5 3f33f90f31 #8838: a document window can be maximized and taken full screen again on Windows (#8871)
* #8838: a document window can be maximized and taken full screen again on Windows

Repin craft-libs from 5299d8d9 to ad10c35a: 5299d8d9 plus one fix
(storytold/craft-libs#5339). Since v0.20.0 a document is a child window,
and the runtime sent a maximized window its saved normal place on the word
of facts the root's input listed passes late; winit on Windows takes a
moved window out of the maximized state, so the maximize button, Win+Up
and snapping to the top shook the window and left it at its normal size,
and View > Full Screen slid it off to the side. The window's own pass now
notes its state with its place, and nothing is sent while it is maximized,
full screen or minimized.

Closes #8838, closes #8861

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* #8838: progress log and parity docs for the Windows maximize fix

ROADMAP progress log, hardware parity (windows row: maximize and full
screen, #8838) and UI parity (View > Window > Full Screen), each with its
status line and revision history.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-04 10:37:24 -06:00
yoriswind 3cef779801 Paste clipboard pixels when rich formats have no content
* Paste clipboard pixels when rich formats have no content

* fix(ui-egui): import the bitmap paste helper

* fix(paste): report fallback bitmap read errors
2026-12-04 09:31:54 -06:00
RickiNanoandFredApps 2d9790c374 #7887: hovering a tracked change shows its kind, author and time (#7967)
* #7887: hovering a tracked change shows its kind, author and time

Resting the pointer on a tracked insertion, deletion, move or formatting
change shows a tip with what the change is (Inserted, Deleted, Moved to,
Moved from, Formatted), its author and its time. Only changes the page
marks count: none with markup hidden, insertions and deletions while Show
Markup shows them, formatting while it shows formatting. A link's tip
comes first. The time is shown as written in w:date, as Word does, since
a revision has no UTC time beside it.

* #7887: tips for paragraph formatting changes, and in notes and text boxes

The hover tip resolves the story under the pointer as a click does, so a
change in a footnote or text box shows its tip while the caret is in the
body. A paragraph whose own formatting changed while tracking (alignment,
indents) shows a Formatted tip on its text when the character under the
pointer has no change of its own.

* #7887: the link tip looks in the story under the pointer too

A link in a footnote or endnote now shows its tip while the caret is in
the body, so the link's tip still comes before the tracked change tip
there.

* #7887: a change made here shows its time in local time

A change WordCraft makes keeps its UTC time beside the local w:date
(#6876's Revision::date_utc). revision_time now passes it to stamp, as
comment_time does, so the tip shows the user's local time for it. A
change from a file with only a Z date still shows as written.

changes_made_here_show_in_local_time builds the revision through
made_revision, as new_revision does, and reads it at UTC+2: 14:05 for
12:05Z. Without the fix it shows the machine's own wall time instead.
The canvas hover test sets a canned date, so it now clears date_utc
too, as a file's change has none.

* #7887: the tip's time is optional, and a w:date offset is converted (docs)

---------

Co-authored-by: FredApps <[email protected]>
2026-12-04 06:11:22 +01:00
Martin BallandClaude Opus 5.5 17da903053 packaging(linux): riscv64 smoke test sets MALLOC_TRIM_THRESHOLD_ so the CLI doesn't restart under QEMU (#8786)
Since #7914 the CLI restarts itself to set MALLOC_TRIM_THRESHOLD_. Under user-mode
qemu-riscv64 with no binfmt handler the restart can't run the riscv64 binary, glibc's
execvp hands it to /bin/sh, and the release job fails with 'Syntax error: word
unexpected'. Setting the variable skips the restart. Real riscv64 hosts are unaffected.


Claude-Session: https://claude.ai/code/session_01FypgCWNarDG3QfXK2YMzdx

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-12-04 02:27:27 +00:00
autocraft-bot[bot] 500e150132 Merge pull request #8733 2026-12-04 00:42:46 +00:00
autocraft-bot[bot] 416db1b645 Merge pull request #7727 2026-12-04 00:42:46 +00:00
autocraft-bot[bot] a1aa614bf1 Merge main (5073f8e7) into the pull request
Resolved the conflict in crates/ui-egui/Cargo.toml. I kept the pull requ

Resolved the conflict in crates/ui-egui/Cargo.toml. I kept the pull request's `craft-html = { workspace = true }` line and took main's craft-libs pin 5299d8d9 for craft-fonts-build, which matches the workspace pin. Cargo.lock already lists craft-html and craft-fonts-build under wordcraft-ui-egui and has no references to the old d73e274a pin, so I left it alone. No conflict markers remain. I couldn't build or test the result: `cargo check --offline` fails because the egui git dependency can't be checked out without network access.
2026-12-04 00:36:14 +00:00
yoriswind d53ba37903 Web: accept the screenshot helper inline data flag (#8726) 2026-12-03 14:28:42 -08:00
Khawar Zamman Wani 5c41ef2f08 Merge PR branch head into rich-clipboard paste fix
# Conflicts:
#	crates/ui-egui/Cargo.toml
2026-12-02 15:41:14 +05:30
FredApps 1955eea91d Merge current main into browser-image paste branch 2026-12-02 08:50:20 +01:00
Khawar Zamman Wani 664980b32b Preserve rich clipboard content during ordinary paste 2026-11-30 09:14:12 +05:30
Khawar Zamman Wani 349556de8a Merge upstream main into clipboard paste fix 2026-11-30 09:13:40 +05:30
FredApps 13dc60f05c Restore picture paste when Ctrl+V has image+HTML and no plain text
The merge of main into this branch dropped the post-fill hook in
commands.rs that pastes a clipboard picture when edit.paste has no
plain text. fill() only auto-inserts a bitmap when the HTML looks like
a single image offer, so a browser image plus fallback HTML failed
mod_v_pastes_rich_only_clipboard_and_preserves_picture_routing.
2026-11-28 07:03:14 +07:00
FredApps 2813a0961d Merge origin/main into fix/2909-browser-image-paste 2026-11-28 05:04:48 +07:00
Khawar Zamman Wani ddeab752da Prefer browser image pixels when the clipboard also offers RTF 2026-11-24 20:45:48 +05:30
Khawar Zamman Wani 81ed00867e Preserve picture-only Paste during equation editing 2026-11-24 18:10:19 +05:30
Khawar Zamman Wani 473942d205 Prefer the bitmap when pasting a browser image (#2909) 2026-11-24 16:59:31 +05:30
21 changed files with 627 additions and 104 deletions
Generated
+1
View File
@@ -9382,6 +9382,7 @@ dependencies = [
"chrono",
"craft",
"craft-fonts-build",
"craft-html",
"craft-ui-test-kit",
"craft-zip",
"eframe",
+4 -1
View File
File diff suppressed because one or more lines are too long
+1
View File
@@ -27,6 +27,7 @@ const POLL_MS: i32 = 16;
pub fn install(ctx: egui::Context) -> Receiver<ControlRequest> {
let (queue, requests) = channel::<ControlRequest>();
let request: Request = Rc::new(move |method, params| {
let params = super::page_params::control_params(&method, params);
let (control, reply) = ControlRequest::new(method, params);
if queue.send(control).is_err() {
return Box::pin(async { json!({"ok": false, "error": "the app is not running"}) });
+2
View File
@@ -23,6 +23,8 @@ mod prefs;
mod api;
#[cfg(target_arch = "wasm32")]
mod host;
#[cfg(any(target_arch = "wasm32", test))]
mod page_params;
#[cfg(target_arch = "wasm32")]
mod web;
+55
View File
@@ -0,0 +1,55 @@
use serde_json::Value;
pub(super) fn control_params(method: &str, mut params: Value) -> Value {
// The page helper asks for inline data. A screenshot without a path already returns it.
if method == "ui.screenshot"
&& let Some(fields) = params.as_object_mut()
&& !fields.contains_key("path")
&& fields.get("data") == Some(&Value::Bool(true))
{
fields.remove("data");
}
params
}
#[cfg(test)]
mod tests {
use craft::automation::screenshot::ScreenshotParams;
use serde_json::json;
use super::control_params;
#[test]
fn page_helper_requests_the_same_capture_as_a_direct_request() {
for (helper, direct) in
[(json!({"data": true}), json!({})), (json!({"data": true, "region": [10, 20, 100, 200]}), json!({"region": [10, 20, 100, 200]}))]
{
let params = control_params("ui.screenshot", helper);
assert_eq!(params, direct);
assert!(ScreenshotParams::from_params(&params).is_ok());
}
}
#[test]
fn page_helper_keeps_screenshot_validation() {
for (input, expected) in [
(json!({"data": true, "region": [100, 200, 10, 20]}), json!({"region": [100, 200, 10, 20]})),
(json!({"data": true, "viewport": "other"}), json!({"viewport": "other"})),
(json!({"data": true, "path": "capture.png"}), json!({"data": true, "path": "capture.png"})),
(json!({"data": true, "path": null}), json!({"data": true, "path": null})),
(json!({"data": false}), json!({"data": false})),
(json!({"data": "true"}), json!({"data": "true"})),
] {
let params = control_params("ui.screenshot", input);
assert_eq!(params, expected);
assert!(ScreenshotParams::from_params(&params).is_err());
}
}
#[test]
fn direct_requests_keep_their_parameters() {
for (method, params) in [("ui.screenshot", json!({"path": "capture.png"})), ("file.new", json!({"data": true}))] {
assert_eq!(control_params(method, params.clone()), params);
}
}
}
+1 -1
View File
@@ -337,7 +337,7 @@ fn clipboard_content(s: &mut Session, v: &Value) -> Result<Pasted, CmdError> {
let text = p::str(v, "text").map(|t| t.replace("\r\n", "\n"));
match text {
Some(t) if !t.is_empty() => Ok(Pasted::Text(t)),
_ => Err(CmdError::Failed("the clipboard is empty".into())),
_ => Err(CmdError::ClipboardEmpty),
}
}
+2
View File
@@ -84,6 +84,8 @@ pub enum CmdError {
Params(String),
#[error("not available: {0}")]
Disabled(String),
#[error("the clipboard is empty")]
ClipboardEmpty,
#[error("{0}")]
Failed(String),
}
+1
View File
@@ -16,6 +16,7 @@ craft = { workspace = true, features = [
"color", "color-ui", "control", "draw", "font-manager", "gpu", "menu", "pages", "print", "review", "table", "text",
"text-find", "web-api", "web-host", "window",
] }
craft-html = { workspace = true }
craft-fonts-build = { git = "https://github.com/storytold/craft-libs", rev = "ad10c35ae545f0fb816364381a1a8154012b2359" }
wordcraft-geom = { workspace = true, features = ["image"] }
wordcraft-doc = { workspace = true }
+2 -2
View File
@@ -2,8 +2,8 @@ use super::services::Services;
use super::state::{AutoSaveBlock, PromptSave, keeps_everything};
use super::{
DEFAULT_TAB, MAX_DICTIONARY, MAX_RECENT, SaveInFlight, Session, Status, Value, WordApp, applied_font, canvas, chrome, crop, dialogs, documents,
file_dialogs, i18n, json, panes, paste_picture, printing, push_recent_font, read_aloud, recent_fonts_from, ribbon, system_clipboard, table_pen,
theme, updates_ui, window_ui, windows, zotero,
file_dialogs, i18n, json, panes, printing, push_recent_font, read_aloud, recent_fonts_from, ribbon, system_clipboard, table_pen, theme,
updates_ui, window_ui, windows, zotero,
};
use craft::platform::clock::monotonic_ms;
use craft::theme::ComponentSet;
+25 -23
View File
@@ -5,10 +5,10 @@ use craft::quit::{CloseAnswer, CloseScope};
use super::command_board::command_enabled;
use super::{
MAX_RECENT, SaveInFlight, Value, WordApp, applied_font, chrome, crop, dialogs, file_dialogs, i18n, json, keeps_everything, panes, paste_picture,
printing, push_recent_font, system_clipboard, table_pen, theme, zotero,
MAX_RECENT, SaveInFlight, Value, WordApp, applied_font, chrome, crop, dialogs, file_dialogs, i18n, json, keeps_everything, panes, printing,
push_recent_font, system_clipboard, table_pen, theme, zotero,
};
use crate::colors;
use crate::{colors, paste_picture};
/// The document's own save stamps: zoom, last-modified-by, created, modified and revision.
type SaveStamps = (Option<wordcraft_doc::Zoom>, String, String, String, u32);
@@ -71,24 +71,16 @@ impl WordApp {
// PLAN: assumed shell-w8's `begin_closing(scope, documents, then, params) -> Result<Value, String>` opens the prompt.
return self.begin_closing(CloseScope::Close, vec![self.session.document_id()], id.to_string(), params);
}
// The ribbon and context-menu Paste commands send no text: read the system clipboard's, as
// Ctrl+V's paste event carries it (#584), and its HTML and RTF, which egui's paste event
// doesn't carry (#687).
// All ordinary Paste controls use the same system clipboard formats.
let mut params = params;
if let Some(r) = system_clipboard::fill(self, id, &mut params) {
return r;
}
// Paste without system clipboard text: a picture there is newer than our own copy (copying
// here replaces it with text), so it wins (#45).
if id == "edit.paste"
&& params.get("text").is_none()
&& let Some(r) = paste_picture::paste(self)
{
return r;
}
let bitmap_if_empty = match system_clipboard::fill(self, id, &mut params) {
system_clipboard::PasteFill::Continue => false,
system_clipboard::PasteFill::BitmapIfEmpty => true,
system_clipboard::PasteFill::Handled(result) => return result,
};
let applied = applied_font(id, &params);
let previous = std::mem::replace(&mut self.user_origin, true);
let r = self.execute_user(id, params);
let r = if bitmap_if_empty { self.execute_command(id, params, true) } else { self.execute_user(id, params) };
self.user_origin = previous;
// A save error already on the status line is the reason to see; the refusal shows otherwise.
if let (Some(e), true) = (refused, r.is_ok()) {
@@ -158,6 +150,10 @@ impl WordApp {
/// Run a command for a script or an agent (control channel, MCP bridge): never asks first.
/// UI-level commands (`ui.*`) are handled here, the rest by the engine.
pub fn execute(&mut self, id: &str, params: Value) -> Result<Value, String> {
self.execute_command(id, params, false)
}
fn execute_command(&mut self, id: &str, params: Value, bitmap_if_empty: bool) -> Result<Value, String> {
self.clear_command_targets(id);
if let Some(error) = self.document_required_error(id) {
return Err(error);
@@ -287,11 +283,17 @@ impl WordApp {
let math_session = self.session.math.as_ref().map(|m| m.session);
let composing_before = !self.canvas.ime_preedit.is_empty();
let old_path = self.session.path.clone();
let r = if self.ime_origin {
self.session.run_ime(id, &params).map_err(|e| e.to_string())
} else {
self.session.run(id, &params).map_err(|e| e.to_string())
};
let r = if self.ime_origin { self.session.run_ime(id, &params) } else { self.session.run(id, &params) };
// Only the engine's no-content result can fall back. Protection and insertion failures
// still report their own error, and the empty paste did not create an undo step.
if bitmap_if_empty
&& matches!(&r, Err(wordcraft_engine::CmdError::ClipboardEmpty))
&& let Some(clip) = system_clipboard::handle(self)
&& let Some(png) = paste_picture::bitmap_png(&clip).inspect_err(|e| self.status(e.clone()))?
{
return paste_picture::insert_bitmap(self, &png);
}
let r = r.map_err(|e| e.to_string());
if self.session.ime_body_epoch() != body_epoch {
self.canvas.ime_interrupted_preedit |= composing_before;
// The body (or the whole document) was replaced under the same id — setText, a
+1
View File
@@ -46,6 +46,7 @@ mod navigation;
mod pages;
mod reading;
mod reading_metrics;
mod revision_tip;
pub(crate) mod rulers;
mod source;
mod story;
+15 -2
View File
@@ -9,6 +9,7 @@ use craft::ui::canvas::{CanvasTool, ToolAction, ToolContext, ToolPath, ToolPoint
use craft::ui::primitives::Draw;
use super::links::{field_showing_code, follow_link, is_generated_bookmark_link, link_under};
use super::revision_tip::revision_under;
use super::story::{enters_header_footer, in_text_box, part_kind, text_box_host};
use super::{CanvasState, DocLayout, PartKind, Pos, Pos2, StoryRef, WordApp, json};
use crate::objects::ObjectGesture;
@@ -163,12 +164,23 @@ impl<'a> PageTextTool<'a> {
let (page, x, y) = page_of(self.body.pages, pos)?;
let layout = &*self.layout;
// A linked picture or shape under the pointer comes first: it lies over the text (#5267).
let story = app.session.sel.focus.story;
// The text is the story under the pointer, as for the tracked change tip that follows.
let story = pointer_story(app, layout, page, x, y, app.session.sel.focus.story);
let link = crate::objects::link_at(app, layout, self.body, pos)
.or_else(|| layout.hit(page, x, y, story).and_then(|at| link_under(app, layout, page, x, y, &at)))?;
let target = if is_generated_bookmark_link(&link) { tl!("Current Document").to_string() } else { link };
Some(format!("{target}\n{}", crate::i18n::fmt(tl!("{key}+Click to follow link"), &[("key", self.link_key)])))
}
/// The tip for the tracked change under `pos`: its kind, author and time (#7887).
fn revision_tip(&self, pos: Pos2) -> Option<String> {
let (page, x, y) = page_of(self.body.pages, pos)?;
let layout = &*self.layout;
// The story under the pointer, as a click there takes it: a note or text box over the body.
let story = pointer_story(&*self.app, layout, page, x, y, self.app.session.sel.focus.story);
let at = layout.hit(page, x, y, story)?;
revision_under(&*self.app, layout, page, x, y, &at)
}
}
impl CanvasTool for PageTextTool<'_> {
@@ -249,7 +261,8 @@ impl CanvasTool for PageTextTool<'_> {
fn hover(&mut self, pointer: &ToolPointer, cx: &mut ToolContext<'_>) {
// PLAN: assumed `ToolContext::tip(&mut self, tip: impl Into<Tooltip>)` (canvas-w1, S-L238).
if let Some(tip) = self.link_tip(pointer.pos) {
// A link's tip comes first: following the link is what a click there can do.
if let Some(tip) = self.link_tip(pointer.pos).or_else(|| self.revision_tip(pointer.pos)) {
cx.tip(tip);
}
}
+90
View File
@@ -0,0 +1,90 @@
//! The hover tip on a tracked change (#7887): what kind of change it is, who made it and when.
use super::{DocLayout, Pos, WordApp};
use wordcraft_doc::props::CharProps;
use wordcraft_layout::display::MarkupOptions;
/// The tip for the tracked change under the pointer at (x, y) on `page`, where `pos` is the caret
/// position the point hits: its kind, its author and its time, a line each. Only changes the page
/// marks count: none with markup hidden, insertions, deletions and moves while Show Markup shows
/// them, formatting changes while it shows formatting. As with a link, the point must be on a
/// character, not beside, above or below it: on the changed character itself, or anywhere in the
/// text of a paragraph whose own formatting changed (its alignment, indents…) when the character
/// has no change of its own.
pub(super) fn revision_under(app: &WordApp, layout: &DocLayout, page: usize, x: f32, y: f32, pos: &Pos) -> Option<String> {
let session = &app.session;
if !session.view.show_markup {
return None;
}
let markup = &session.prefs.markup;
let doc = &session.doc;
let para = doc.para_at(pos)?;
let para_change = para.props.fmt_change.as_ref().filter(|_| markup.formatting).map(|c| (c.rev, tl!("Formatted")));
let at = wordcraft_geom::Point::new(x, y);
// The caret falls between characters: the one under the point is on either side of it.
[(pos.off, para.next_boundary(pos.off)), (para.prev_boundary(pos.off), pos.off)].into_iter().filter(|(a, b)| a < b).find_map(|(a, b)| {
let (rev, kind) = change_of(para.props_of_char(a), markup, |i| doc.move_name(Some(i)).is_some()).or(para_change)?;
let rev = doc.revisions.get(usize::try_from(rev).ok()?)?;
let (from, to) = (Pos { off: a, ..pos.clone() }, Pos { off: b, ..pos.clone() });
let hit = layout.selection_rects(doc, &from, &to, page).into_iter().any(|(pi, r)| pi == page && r.contains(at));
hit.then(|| tip(kind, &rev.author, &crate::local_time::revision_time(rev)))
})
}
/// The revision a character's marks point to and what to call it, when the markup shown marks it.
/// A deletion lies over an insertion it removes (inserted, then deleted by someone else): the
/// deletion is the change the page shows.
fn change_of(props: &CharProps, markup: &MarkupOptions, is_move: impl Fn(u32) -> bool) -> Option<(u32, &'static str)> {
if markup.insertions_deletions {
if let Some(i) = props.del {
return Some((i, if is_move(i) { tl!("Moved from") } else { tl!("Deleted") }));
}
if let Some(i) = props.ins {
return Some((i, if is_move(i) { tl!("Moved to") } else { tl!("Inserted") }));
}
}
props.fmt_change.as_ref().filter(|_| markup.formatting).map(|c| (c.rev, tl!("Formatted")))
}
/// The tip's lines: the change's kind, its author (or "Author" when the file names none, as the
/// balloons do) and its time, left out when the file gives none.
fn tip(kind: &str, author: &str, when: &str) -> String {
let author = if author.trim().is_empty() { tl!("Author") } else { author };
let mut lines = vec![kind, author];
if !when.is_empty() {
lines.push(when);
}
lines.join("\n")
}
#[cfg(test)]
mod tests {
use super::*;
use wordcraft_doc::props::PropChange;
/// A deletion over an insertion is the change shown; formatting counts only while the markup
/// shows formatting, and insertions and deletions only while it shows them.
#[test]
fn the_shown_markup_picks_the_change() {
let all = MarkupOptions { insertions_deletions: true, formatting: true, ..Default::default() };
let no_move = |_| false;
let both = CharProps { ins: Some(0), del: Some(1), ..Default::default() };
assert_eq!(change_of(&both, &all, no_move), Some((1, "Deleted")));
assert_eq!(change_of(&both, &all, |i| i == 1), Some((1, "Moved from")));
let inserted = CharProps { ins: Some(2), ..Default::default() };
assert_eq!(change_of(&inserted, &all, no_move), Some((2, "Inserted")));
assert_eq!(change_of(&inserted, &all, |_| true), Some((2, "Moved to")));
let formatted = CharProps { fmt_change: PropChange::boxed(3, CharProps::default()), ..Default::default() };
assert_eq!(change_of(&formatted, &all, no_move), Some((3, "Formatted")));
assert_eq!(change_of(&formatted, &MarkupOptions { formatting: false, ..all.clone() }, no_move), None);
assert_eq!(change_of(&inserted, &MarkupOptions { insertions_deletions: false, ..all.clone() }, no_move), None);
assert_eq!(change_of(&CharProps::default(), &all, no_move), None);
}
/// The tip's lines; an unnamed author reads "Author", and a missing time is left out.
#[test]
fn the_tip_names_kind_author_and_time() {
assert_eq!(tip("Inserted", "Ada", "2026-11-20 14:05"), "Inserted\nAda\n2026-11-20 14:05");
assert_eq!(tip("Deleted", " ", ""), "Deleted\nAuthor");
}
}
+88
View File
@@ -889,3 +889,91 @@ fn a_right_click_keeps_selected_cells_only_on_them() {
assert_menu(&h, &["Split Cells"], true);
assert_menu(&h, &["Merge Cells"], false);
}
// ---------------------------------------------------------------------------------------
// Tracked change tips
// ---------------------------------------------------------------------------------------
/// #7887: resting the pointer on a tracked insertion shows a tip with the change's kind, its
/// author and its time; beside the change, or with markup hidden, there is none.
#[test]
fn hovering_a_tracked_change_shows_its_author_and_time() {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("Plain words here")), Default::default());
a.session.author = "Ada Reviewer".into();
a.run("caret.docStart", json!({})).unwrap();
a.run("review.trackChanges", json!({"value": true})).unwrap();
a.run("text.insert", json!({"text": "Inserted "})).unwrap();
assert_eq!(a.session.doc.revisions.len(), 1, "one tracked insertion");
// A fixed time with no UTC time beside it, as a file's change has, so it shows as written
// whatever the machine's zone (`local_time` covers the changes made here).
a.session.doc.revisions[0].date = "2026-11-20T14:05:00Z".into();
a.session.doc.revisions[0].date_utc = None;
let mut h = window(a);
let point_at = |h: &mut H, off: usize| {
let c = h.state_mut().session.layout().caret(&Pos { story: StoryRef::Body, path: wordcraft_doc::Path::top(0), off }).unwrap();
let at = screen(h, c.x, c.top + c.height / 2.0);
h.event(egui::Event::PointerMoved(at));
super::rest_for_tip(h);
};
let tips = |h: &H| h.query_all_by_label_contains("Inserted Ada Reviewer 2026-11-20 14:05").count();
// Between "Inserted" and its "e", then on "words", which was there before tracking began.
point_at(&mut h, 2);
assert!(tips(&h) > 0, "the inserted text's tip says it was inserted, by whom and when");
point_at(&mut h, "Inserted Plain w".len());
assert_eq!(tips(&h), 0, "text that wasn't changed has no tip");
h.state_mut().session.view.show_markup = false;
point_at(&mut h, 2);
assert_eq!(tips(&h), 0, "with markup hidden the change isn't marked, so it has no tip");
}
/// #7887: a paragraph whose own formatting changed while tracking (here its alignment) shows a
/// Formatted tip on its text, while the markup shows formatting.
#[test]
fn hovering_a_paragraph_with_tracked_formatting_shows_formatted() {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("A centred line")), Default::default());
a.session.author = "Ada Reviewer".into();
a.run("review.trackChanges", json!({"value": true})).unwrap();
a.run("para.alignCenter", json!({})).unwrap();
assert!(a.session.doc.body[0].as_para().is_some_and(|p| p.props.fmt_change.is_some()), "the alignment is a tracked change");
let mut h = window(a);
let point_at = |h: &mut H| {
let c = h.state_mut().session.layout().caret(&Pos { story: StoryRef::Body, path: wordcraft_doc::Path::top(0), off: 4 }).unwrap();
let at = screen(h, c.x, c.top + c.height / 2.0);
h.event(egui::Event::PointerMoved(at));
super::rest_for_tip(h);
};
let tips = |h: &H| h.query_all_by_label_contains("Formatted Ada Reviewer").count();
point_at(&mut h);
assert!(tips(&h) > 0, "the paragraph's text shows its formatting change");
h.state_mut().session.prefs.markup.formatting = false;
// The canvas asks for a tip again only when the pointer moves: away to the toggle and back.
h.event(egui::Event::PointerGone);
point_at(&mut h);
assert_eq!(tips(&h), 0, "with formatting markup off the change isn't marked, so it has no tip");
}
/// #7887 review: a link in a footnote shows its tip while the caret is in the body. The hover
/// looks in the story under the pointer, so the link's tip still comes before the tracked
/// change tip there.
#[test]
fn a_footnote_link_shows_its_tip_with_the_caret_in_the_body() {
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("Body text")), Default::default());
a.run("caret.docEnd", json!({})).unwrap();
a.run("review.trackChanges", json!({"value": true})).unwrap();
a.run("references.footnote", json!({"text": "Note link"})).unwrap();
let note = a.session.sel.focus.story;
let pos = |off: usize| json!({"story": note, "path": [0], "off": off});
a.run("select.range", json!({"anchor": pos(5), "focus": pos(9)})).unwrap();
a.run("insert.link", json!({"url": "https://example.com/note"})).unwrap();
a.run("caret.set", json!({"pos": {"block": 0, "off": 2}})).unwrap();
assert_eq!(a.session.sel.focus.story, StoryRef::Body);
// The whole page in the window, footnote area and all.
a.run("view.zoom", json!({"value": 40})).unwrap();
let mut h = window(a);
let c = h.state_mut().session.layout().caret(&Pos { story: note, path: wordcraft_doc::Path::top(0), off: 7 }).unwrap();
let at = screen(&mut h, c.x, c.top + c.height / 2.0);
h.event(egui::Event::PointerMoved(at));
super::rest_for_tip(&mut h);
assert!(h.query_all_by_label_contains("https://example.com/note").count() > 0, "the footnote's link shows its tip (pointer at {at:?})");
assert_eq!(h.query_all_by_label_contains("Inserted ").count(), 0, "not the tracked insertion's tip");
}
+3 -19
View File
@@ -1,7 +1,6 @@
// PLAN: the Insert key has no editor input, so the overtype switch is the shortcut layer's (shell-w6).
use craft::behavior::editor::{EditorInput, SurroundingUnit};
use craft::behavior::intent::{EditCommand, Granularity, MoveMods, NavMove};
use craft::platform::clipboard::{HTML, RGBA8, RTF, URI_LIST};
use craft::ui::canvas::ToolPass;
use craft::ui::runtime::commands::{ClipItem, ClipboardHandle};
@@ -633,7 +632,9 @@ fn edit_command(app: &mut WordApp, ctx: &egui::Context, cmd: EditCommand) {
let _ = app.run("edit.copy", json!({}));
}
}
EditCommand::Paste => paste(app, ctx),
EditCommand::Paste => {
let _ = app.run("edit.paste", json!({}));
}
EditCommand::SelectAll => {
let _ = app.run("select.all", json!({}));
}
@@ -650,23 +651,6 @@ fn edit_command(app: &mut WordApp, ctx: &egui::Context, cmd: EditCommand) {
}
}
/// Paste from the clipboard: copied picture files insert as pictures (#45), text, rich text
/// (HTML/RTF) and a clipboard picture go through `edit.paste`.
fn paste(app: &mut WordApp, ctx: &egui::Context) {
let clip = ClipboardHandle::of(ctx);
let text = clip.read_text().ok().flatten();
if text.is_none() && !clip.has(&[RGBA8, URI_LIST, HTML, RTF]) {
return;
}
if let Some(t) = &text
&& crate::paste_picture::paste_named_files(app, t)
{
return;
}
let params = text.map_or_else(|| json!({}), |t| json!({"text": t}));
let _ = app.run("edit.paste", params);
}
/// Escape: the nearest thing that takes it first (a painter, a pen, a table pen, an object, a text
/// box, a header), then Focus or Full Screen.
fn cancel(app: &mut WordApp, ctx: &egui::Context) {
+31 -12
View File
@@ -452,19 +452,33 @@ fn mod_v_released_mod_first_pastes_the_clipboard_picture() {
assert_eq!(body(h.state()), "external");
assert!(is_bold(&mut h), "Mod+V keeps the HTML's formatting");
let mut h = picture_app();
let mut h = alt_frame_app();
let before = h.state().session.doc.clone();
let url = "https://example.test/picture.png";
offer(
&h,
vec![
ClipItem::Image(std::sync::Arc::new(egui::ColorImage::from_rgba_unmultiplied([4, 4], &[200u8; 4 * 4 * 4]))),
ClipItem::Html(format!(r#"<img src="{url}">"#).into()),
ClipItem::Text(url.into()),
],
);
mods_frame(&mut h, ctrl, vec![key_event(Key::ControlLeft, true, ctrl), key_event(Key::V, true, ctrl)]);
mods_frame(&mut h, Modifiers::NONE, vec![key_event(Key::ControlLeft, false, Modifiers::NONE)]);
mods_frame(&mut h, Modifiers::NONE, vec![key_event(Key::V, false, Modifiers::NONE)]);
assert_eq!(pictures(h.state_mut()), 1);
run(&mut h, "edit.undo", json!({}));
assert!(before.same_content(&h.state().session.doc), "one Undo restores the document before paste");
assert_eq!(pictures(h.state_mut()), 0);
// A plain V afterwards is not a paste.
mods_frame(&mut h, Modifiers::NONE, vec![key_event(Key::V, true, Modifiers::NONE)]);
mods_frame(&mut h, Modifiers::NONE, vec![key_event(Key::V, false, Modifiers::NONE)]);
assert_eq!(pictures(h.state_mut()), 1);
assert_eq!(pictures(h.state_mut()), 0);
}
/// #5859: Mod+V admits a rich-only clipboard (HTML or RTF with no plain-text or picture flavor)
/// and still routes an image+HTML clipboard with no plain-text flavor to picture paste.
/// #5859: Mod+V admits a rich-only clipboard (HTML or RTF with no plain-text or picture flavor).
/// With no plain text, a single-image HTML offer pastes its bitmap, while a formatted selection
/// offered beside a bitmap keeps its formatting.
#[test]
fn mod_v_pastes_rich_only_clipboard_and_preserves_picture_routing() {
let ctrl = mod_held();
@@ -483,19 +497,24 @@ fn mod_v_pastes_rich_only_clipboard_and_preserves_picture_routing() {
assert_eq!(body(h.state()), "rtf-only", "Mod+V pastes RTF-only clipboard");
assert!(is_bold(&mut h), "RTF-only paste keeps formatting");
let image = || ClipItem::Image(std::sync::Arc::new(egui::ColorImage::from_rgba_unmultiplied([4, 4], &[200u8; 4 * 4 * 4])));
let img = r#"<img src="https://example.test/picture.png">"#;
let mut h = alt_frame_app();
offer(
&h,
vec![
ClipItem::Image(std::sync::Arc::new(egui::ColorImage::from_rgba_unmultiplied([4, 4], &[200u8; 4 * 4 * 4]))),
ClipItem::Html("<p><b>fallback</b></p>".into()),
],
);
offer(&h, vec![image(), ClipItem::Html(img.into())]);
mods_frame(&mut h, ctrl, vec![key_event(Key::V, true, ctrl)]);
mods_frame(&mut h, Modifiers::NONE, vec![key_event(Key::V, false, Modifiers::NONE)]);
assert_eq!(pictures(h.state_mut()), 1, "image+HTML with no plain text routes to picture paste");
assert_eq!(pictures(h.state_mut()), 1, "a single-image HTML offer with no plain text pastes its bitmap");
assert_eq!(body(h.state()), "", "picture paste does not fall back to HTML text");
let mut h = alt_frame_app();
offer(&h, vec![image(), ClipItem::Html(format!("<p><b>fallback</b>{img}</p>").into())]);
mods_frame(&mut h, ctrl, vec![key_event(Key::V, true, ctrl)]);
mods_frame(&mut h, Modifiers::NONE, vec![key_event(Key::V, false, Modifiers::NONE)]);
assert_eq!(pictures(h.state_mut()), 0, "a formatted selection with no plain text is not replaced by its bitmap");
assert_eq!(body(h.state()), "fallback");
assert!(is_bold(&mut h), "the formatted selection keeps its bold");
let dir = std::env::temp_dir().join(format!("wc-mod-v-uri-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let png = dir.join("clip.png");
+35
View File
@@ -29,6 +29,19 @@ pub(crate) fn comment_time(c: &wordcraft_doc::Comment) -> String {
stamp(&c.date, c.date_utc.as_deref(), offset_minutes)
}
/// A tracked change's time for its hover tip, read as [`comment_time`] reads a comment: the UTC
/// time (`date_utc`, Word's `w16du:dateUtc`, which WordCraft keeps for the changes it makes) wins
/// and shows in local time. Without it (`w:date` only), Word writes local time there with a `Z`
/// it doesn't mean and shows it as written, so it shows as written here too; a time with an
/// offset (`±HH:MM`) is converted. Empty when it isn't a date.
pub(crate) fn revision_time(r: &wordcraft_doc::Revision) -> String {
revision_stamp(r, offset_minutes)
}
fn revision_stamp(r: &wordcraft_doc::Revision, offset: impl Fn(i64) -> i32) -> String {
stamp(&r.date, r.date_utc.as_deref(), offset)
}
fn stamp(date: &str, date_utc: Option<&str>, offset: impl Fn(i64) -> i32) -> String {
let utc = date_utc.and_then(parse).filter(|t| t.timed).map(|t| Time { zone: Some(t.zone.unwrap_or(0)), ..t });
let local_date = || parse(date).map(|t| if date.trim_end().ends_with(['Z', 'z']) { Time { zone: None, ..t } } else { t });
@@ -185,6 +198,28 @@ mod tests {
assert_eq!(stamp("2026-10-12Z", Some("2026-10-12"), |_| -4 * 60), "2026-10-12");
}
/// A change WordCraft makes keeps its UTC time, so its tip shows the user's local time, here
/// two hours east of UTC; a change from a file with only a `Z` date still shows as written
/// (#7887).
#[test]
fn changes_made_here_show_in_local_time() {
let utc_plus_2 = |_: i64| 2 * 60;
let made = wordcraft_engine::cmd::made_revision(wordcraft_doc::RevisionKind::Insert, "Ada".into(), "2026-11-20T12:05:00Z".into());
assert_eq!(revision_stamp(&made, utc_plus_2), "2026-11-20 14:05");
let imported = wordcraft_doc::Revision::new(wordcraft_doc::RevisionKind::Insert, "Ada", "2026-11-20T12:05:00Z");
assert_eq!(revision_stamp(&imported, utc_plus_2), "2026-11-20 12:05");
}
/// A tracked change from a file with only its `w:date` (#7887): shown as written, `Z` or not,
/// as Word shows it.
#[test]
fn revision_times_show_as_written() {
let at = |date: &str| revision_time(&wordcraft_doc::Revision::new(wordcraft_doc::RevisionKind::Insert, "Ada", date));
assert_eq!(at("2026-11-20T14:05:00Z"), "2026-11-20 14:05");
assert_eq!(at("2026-11-20"), "2026-11-20");
assert_eq!(at("not a date"), "");
}
/// Whatever a file holds, a stamp is a date or nothing, never a panic.
#[test]
fn hostile_times_show_nothing() {
+163 -23
View File
@@ -10,6 +10,7 @@ use std::path::{Path, PathBuf};
// PLAN(app-hub): the `craft` facade dependency of ui-egui (`craft::platform` = craft-platform), as in system_clipboard.rs
use craft::platform::clipboard::ClipboardError;
use craft::ui::runtime::commands::ClipboardHandle;
use serde_json::{Value, json};
use crate::{WordApp, system_clipboard};
@@ -77,27 +78,16 @@ fn paste_files(app: &mut WordApp, files: Vec<PathBuf>) -> Option<Result<Value, S
Some(r)
}
/// Paste the picture on the system clipboard: copied picture files, else its bitmap. `None` when
/// there is none (or no clipboard): the caller pastes as usual.
pub(crate) fn paste(app: &mut WordApp) -> Option<Result<Value, String>> {
/// Paste copied picture files, or the bitmap if allowed and there are no copied files.
pub(crate) fn paste(app: &mut WordApp, allow_bitmap: bool) -> Option<Result<Value, String>> {
let clip = system_clipboard::handle(app)?;
let r = match clip.read_files().ok().flatten().filter(|f| !f.is_empty()) {
Some(files) => paste_files(app, files)?,
None => match clip.read_image() {
None if !allow_bitmap => return None,
None => match bitmap_png(&clip) {
Ok(Some(png)) => return Some(insert_bitmap(app, &png)),
Ok(None) => return None,
Ok(Some(image)) => match png_from_rgba(image.width as usize, image.height as usize, image.rgba) {
Ok(png) => app.execute("insert.picture", json!({"data": wordcraft_engine::cmd::insert::base64_encode(&png)})),
Err(e) => {
log::warn!("clipboard picture: {e}");
app.status(e.clone());
Err(e)
}
},
Err(e) => {
let e = match e {
ClipboardError::TooLarge { .. } => "the clipboard picture is too large to paste".to_string(),
e => crate::i18n::fmt(tl!("The picture on the clipboard couldn't be read: {error}"), &[("error", &e.to_string())]),
};
log::warn!("clipboard picture: {e}");
app.status(e.clone());
Err(e)
@@ -109,6 +99,21 @@ pub(crate) fn paste(app: &mut WordApp) -> Option<Result<Value, String>> {
Some(r)
}
/// Encode the bounded native bitmap through the same path for ordinary and mixed clipboard pastes.
pub(crate) fn bitmap_png(clip: &ClipboardHandle) -> Result<Option<Vec<u8>>, String> {
let image = clip.read_image().map_err(|e| match e {
ClipboardError::TooLarge { .. } => "the clipboard picture is too large to paste".to_string(),
e => crate::i18n::fmt(tl!("The picture on the clipboard couldn't be read: {error}"), &[("error", &e.to_string())]),
})?;
image.map(|image| png_from_rgba(image.width as usize, image.height as usize, image.rgba)).transpose()
}
pub(crate) fn insert_bitmap(app: &mut WordApp, png: &[u8]) -> Result<Value, String> {
let r = app.execute("insert.picture", json!({"data": wordcraft_engine::cmd::insert::base64_encode(png)}));
app.select_inserted_picture(&r);
r
}
/// The picture on the system clipboard as PNG (or the first copied picture file's bytes), for
/// Paste Special to offer. `None` when there is none, or it is too large or unreadable.
pub(crate) fn clipboard_png(app: &WordApp) -> Option<Vec<u8>> {
@@ -127,16 +132,10 @@ fn read_picture_file(path: &Path, limit: u64) -> Option<Vec<u8>> {
wordcraft_engine::io::read_regular_file_within(path, limit)
}
/// Paste text naming copied picture files: insert the pictures when the clipboard holds those
/// files. False leaves the text to the usual paste.
pub(crate) fn paste_named_files(app: &mut WordApp, text: &str) -> bool {
names_picture_files(text) && paste(app).is_some()
}
#[cfg(test)]
mod tests {
use super::*;
use crate::system_clipboard::testing::{app_holding, rgba8};
use crate::system_clipboard::testing::{app_holding, app_holding_with_image_error, rgba8};
use craft::platform::clipboard::{Flavor, RGBA8, URI_LIST};
fn pictures(a: &mut WordApp) -> usize {
@@ -189,6 +188,16 @@ mod tests {
assert!(!names_picture_files("see /tmp/b.png") && !names_picture_files("notes.txt") && !names_picture_files(""));
}
#[test]
fn bitmap_only_paste_inserts_a_picture_during_equation_editing() {
let mut app = app_holding(&[rgba8(4, 4, 200)]);
app.run("insert.equation", json!({"linear": "abc"})).unwrap();
assert!(app.session.math.is_some());
app.run("edit.paste", json!({})).unwrap();
let objects = app.session.run("arrange.selectionPane", &json!({})).unwrap();
assert!(objects.as_array().is_some_and(|objects| objects.iter().any(|object| object["kind"] == "picture")));
}
/// Text on the clipboard wins over a picture beside it (#584).
#[test]
fn paste_without_text_reads_the_system_clipboard() {
@@ -203,6 +212,137 @@ mod tests {
assert!(r["formats"].as_array().is_some_and(|f| f.iter().any(|x| x["id"] == "text")), "{r}");
}
#[test]
fn ordinary_paste_prefers_pixels_for_a_single_image_offer() {
use craft::platform::clipboard::HTML;
let url = "https://example.test/picture.png";
let html = format!(r#"<meta http-equiv="content-type" content="text/html; charset=utf-8"><img src="{url}" alt="A &amp; B">"#);
let url_and_alt = format!("{url}\r\nA & B");
for text in [url, "A & B", &url_and_alt] {
let mut app = app_holding(&[Flavor::text(text), Flavor::new(HTML, html.as_bytes().to_vec()), rgba8(4, 4, 200)]);
app.run("edit.paste", json!({})).unwrap();
assert_eq!(pictures(&mut app), 1);
assert!(!app.session.doc.plain_text(wordcraft_doc::StoryRef::Body).contains(text));
app.run("edit.undo", json!({})).unwrap();
assert_eq!(pictures(&mut app), 0);
}
}
#[test]
fn single_image_offer_with_rtf_prefers_readable_pixels() {
use craft::platform::clipboard::{HTML, RGBA8, RTF};
let url = "https://example.test/picture.png";
let html = Flavor::new(HTML, format!(r#"<img src="{url}">"#).into_bytes());
let rtf = Flavor::new(RTF, br"{\rtf1\ansi Image fallback}".to_vec());
let malformed = Flavor::new(RGBA8, vec![1, 0, 0, 0, 1, 0, 0, 0]);
let paste = |bitmap| {
let mut app = app_holding(&[Flavor::text(url), html.clone(), rtf.clone(), bitmap]);
app.run("edit.paste", json!({})).unwrap();
app
};
assert_eq!(pictures(&mut paste(rgba8(4, 4, 200))), 1);
let mut app = paste(malformed);
assert_eq!(pictures(&mut app), 0);
assert_eq!(app.session.doc.plain_text(wordcraft_doc::StoryRef::Body), "Image fallback");
}
#[test]
fn ordinary_paste_falls_back_to_pixels_when_rich_formats_have_no_content() {
use craft::platform::clipboard::{HTML, RTF};
let linked_image = br#"<a href="https://example.test/"><img src="https://example.test/picture.png"></a>"#;
for markup in [Flavor::new(HTML, linked_image.to_vec()), Flavor::new(RTF, br"{\rtf1\ansi}".to_vec())] {
let mut app = app_holding(&[rgba8(4, 4, 200), markup]);
let before = app.session.undo_depth();
app.run("edit.paste", json!({})).unwrap();
assert_eq!(pictures(&mut app), 1);
assert_eq!(wordcraft_render::image_size(app.session.doc.media.values().next().unwrap()), Some((4, 4)));
assert_eq!(app.session.undo_depth(), before + 1);
app.run("edit.undo", json!({})).unwrap();
assert_eq!(pictures(&mut app), 0);
assert_eq!(app.session.undo_depth(), before);
}
}
#[test]
fn empty_rich_paste_distinguishes_unreadable_and_absent_bitmaps() {
use craft::platform::clipboard::RTF;
use wordcraft_doc::StoryRef;
let empty_rtf = Flavor::new(RTF, br"{\rtf1\ansi}".to_vec());
let malformed = Flavor::new(RGBA8, vec![1, 0, 0, 0, 1, 0, 0, 0]);
let mut absent = app_holding(std::slice::from_ref(&empty_rtf));
let before = absent.session.undo_depth();
let nothing = system_clipboard::nothing_to_paste(&absent);
assert_eq!(absent.run("edit.paste", json!({})).unwrap_err(), nothing);
assert_eq!(absent.session.undo_depth(), before);
let mut unreadable = app_holding_with_image_error(&[empty_rtf.clone(), malformed.clone()], Some("malformed bitmap"));
let before = unreadable.session.undo_depth();
let error = unreadable.run("edit.paste", json!({})).unwrap_err();
assert!(error.contains("malformed bitmap"), "{error}");
assert_eq!(unreadable.status_message().unwrap().text.as_str(), error);
assert_eq!(unreadable.session.undo_depth(), before);
assert_eq!(pictures(&mut unreadable), 0);
let mut with_text = app_holding_with_image_error(&[empty_rtf, malformed, Flavor::text("usable text")], Some("malformed bitmap"));
with_text.run("edit.paste", json!({})).unwrap();
assert_eq!(with_text.session.doc.plain_text(StoryRef::Body), "usable text");
assert_eq!(pictures(&mut with_text), 0);
}
#[test]
fn fallback_pixels_do_not_override_rich_content_or_a_refused_paste() {
use craft::platform::clipboard::{HTML, RTF};
use wordcraft_doc::StoryRef;
let empty_rtf = Flavor::new(RTF, br"{\rtf1\ansi}".to_vec());
let rich_html = Flavor::new(HTML, b"<p><strong>Rich content</strong></p>".to_vec());
let mut app = app_holding(&[rgba8(4, 4, 200), rich_html]);
app.run("edit.paste", json!({})).unwrap();
assert_eq!(app.session.doc.plain_text(StoryRef::Body), "Rich content");
assert_eq!(pictures(&mut app), 0);
let mut app = app_holding(&[rgba8(4, 4, 200), empty_rtf.clone()]);
app.session.doc.settings.protection = Some("readOnly".into());
let err = app.run("edit.paste", json!({})).unwrap_err();
assert!(err.contains("edit.paste:") && err.contains("read only"), "{err}");
assert_eq!(pictures(&mut app), 0);
let mut app = app_holding(&[rgba8(4, 4, 200), empty_rtf]);
app.run("insert.equation", json!({"linear": "abc"})).unwrap();
assert!(app.session.math.is_some());
assert!(app.run("edit.paste", json!({})).is_err());
assert_eq!(pictures(&mut app), 0);
}
#[test]
fn ordinary_paste_preserves_urls_rich_selections_and_unreadable_images() {
use craft::platform::clipboard::{HTML, RGBA8};
let url = "https://example.test/picture.png";
let img = format!(r#"<img src="{url}">"#);
let rich = format!("<p><strong>Caption</strong>{img}</p>");
let good = rgba8(4, 4, 200);
let bad = Flavor::new(RGBA8, vec![1, 0, 0, 0, 1, 0, 0, 0]);
for (markup, bitmap, text, expected) in
[(None, good.clone(), url, url), (Some(rich.as_str()), good, "Caption", "Caption"), (Some(img.as_str()), bad, url, url)]
{
let mut flavors = vec![Flavor::text(text), bitmap];
if let Some(markup) = markup {
flavors.push(Flavor::new(HTML, markup.as_bytes().to_vec()));
}
let mut app = app_holding(&flavors);
app.run("edit.paste", json!({})).unwrap();
assert_eq!(pictures(&mut app), 0);
assert_eq!(app.session.doc.plain_text(wordcraft_doc::StoryRef::Body), expected);
}
}
/// Copied picture files insert as pictures, not as their paths; a folder entry and a
/// non-picture file are skipped, and files that aren't pictures leave Paste to the usual path.
#[test]
+100 -17
View File
@@ -47,39 +47,83 @@ fn read_markup(clip: &ClipboardHandle, mime: &str) -> Option<String> {
Some(String::from_utf8_lossy(&flavor.data).into_owned()).filter(|t| !t.trim().is_empty())
}
/// A browser image copy can carry a source address or the image's alt text alongside the bitmap.
fn single_image_offer(html: &str, text: Option<&str>) -> bool {
use craft_html::{Lexer, Token, unescape};
use wordcraft_engine::cmd::paste::html_fragment;
let fragment = html_fragment(html);
if fragment.len() > 64 << 10 {
return false;
}
let mut image = None;
let wrapper = |name: &str| matches!(name, "html" | "body" | "head" | "div" | "span" | "p");
for token in Lexer::new(fragment) {
match token {
Token::Start(tag) if tag.name == "img" && image.is_none() => {
image = Some((tag.attr("src").unwrap_or_default(), tag.attr("alt").unwrap_or_default()));
}
Token::Start(tag) if wrapper(&tag.name) && tag.attrs.is_empty() => {}
Token::Start(tag) if tag.name == "meta" && tag.attrs.len() == 1 && tag.has("charset") => {}
Token::Start(tag)
if tag.name == "meta"
&& tag.attrs.len() == 2
&& tag.raw_attr("http-equiv").is_some_and(|value| value.eq_ignore_ascii_case("content-type"))
&& tag.has("content") => {}
Token::End(name) if wrapper(&name) => {}
Token::Text(text) if unescape(text).trim().is_empty() => {}
_ => return false,
}
}
let Some((src, alt)) = image else { return false };
let text = text.unwrap_or_default().trim();
let alt = alt.trim();
let src = src.trim();
text.is_empty()
|| text == alt
|| text == src
|| text.split_once('\n').is_some_and(|(address, description)| address.trim() == src && description.trim() == alt)
}
pub(crate) enum PasteFill {
Continue,
BitmapIfEmpty,
Handled(Result<Value, String>),
}
/// Add what the system clipboard holds to a paste command's params: its text (the ribbon and
/// context-menu Paste send none), its HTML and RTF, and for Paste Special its picture. Params a
/// caller already gave are kept. `Some` when the paste was done here instead (copied picture
/// files, which reach us as their paths).
pub(crate) fn fill(app: &mut WordApp, id: &str, params: &mut Value) -> Option<Result<Value, String>> {
/// caller already gave are kept. For ordinary desktop Paste, unusable rich formats may leave
/// a bitmap to try after the engine checks the content.
pub(crate) fn fill(app: &mut WordApp, id: &str, params: &mut Value) -> PasteFill {
if !is_paste(id) {
return None;
return PasteFill::Continue;
}
let clip = handle(app)?;
let o = params.as_object_mut()?;
let (Some(clip), Some(o)) = (handle(app), params.as_object_mut()) else { return PasteFill::Continue };
let explicit = ["text", "html", "rtf", "picture"].iter().any(|k| o.contains_key(*k));
// A caller that captured ownership already (Paste Special's dialog) keeps that value.
if !o.contains_key("privateClipboard") {
let own = app.clipboard_published && clip.holds_ours();
o.insert("privateClipboard".into(), Value::Bool(own));
}
let owned = app.session.clipboard.is_some() && o.get("privateClipboard").and_then(Value::as_bool) == Some(true);
let ordinary = id == "edit.paste" && !explicit && !owned;
if !o.contains_key("text")
&& let Some(text) = clip.read_text().ok().flatten().filter(|t| !t.is_empty())
{
// Picture files copied in a file manager reach us as their paths: paste the pictures,
// as Ctrl+V does.
if id == "edit.paste"
if ordinary
&& app.session.math.is_none()
&& paste_picture::names_picture_files(&text)
&& let Some(r) = paste_picture::paste(app)
&& let Some(r) = paste_picture::paste(app, true)
{
return Some(r);
return PasteFill::Handled(r);
}
o.insert("text".into(), Value::String(text));
}
// Keep Text Only needs nothing more; a caller that passed formats of its own (an agent, Paste
// Special's OK) has them already.
if id == "edit.pasteText" || ["html", "rtf", "picture"].iter().any(|k| o.contains_key(*k)) {
return None;
return PasteFill::Continue;
}
if let Some(html) = read_markup(&clip, HTML) {
o.insert("html".into(), Value::String(html));
@@ -87,9 +131,32 @@ pub(crate) fn fill(app: &mut WordApp, id: &str, params: &mut Value) -> Option<Re
if let Some(rtf) = read_markup(&clip, RTF) {
o.insert("rtf".into(), Value::String(rtf));
}
if ordinary {
let text = o.get("text").and_then(Value::as_str);
let html = o.get("html").and_then(Value::as_str);
if text.is_none() && html.is_none() && !o.contains_key("rtf") {
return paste_picture::paste(app, true).map_or(PasteFill::Continue, PasteFill::Handled);
}
if text.is_none()
&& app.session.math.is_none()
&& let Some(r) = paste_picture::paste(app, false)
{
return PasteFill::Handled(r);
}
if app.session.math.is_none()
&& !cfg!(target_arch = "wasm32")
&& html.is_some_and(|html| single_image_offer(html, text))
&& let Ok(Some(png)) = paste_picture::bitmap_png(&clip)
{
return PasteFill::Handled(paste_picture::insert_bitmap(app, &png));
}
if text.is_none() && app.session.math.is_none() && !cfg!(target_arch = "wasm32") {
return PasteFill::BitmapIfEmpty;
}
}
// Native bitmap/image formats are for other programs. Our own paste keeps the original
// fragment (size, cropping and floating-picture properties), while its owner mark lasts.
if app.session.clipboard.is_some() && o.get("privateClipboard").and_then(Value::as_bool) == Some(true) {
if owned {
o.insert("text".into(), Value::String(app.session.clipboard_text.clone()));
}
if id == "edit.pasteSpecial"
@@ -100,7 +167,7 @@ pub(crate) fn fill(app: &mut WordApp, id: &str, params: &mut Value) -> Option<Re
o.insert("picture".into(), Value::String(data));
}
}
None
PasteFill::Continue
}
/// Return whether the command result `r` contains any copied payload (text, HTML, RTF, or MathML).
@@ -255,8 +322,7 @@ pub(crate) mod testing {
/// [`MemoryClipboard`] that also answers `read_files` from a held `text/uri-list`, as the system and event
/// clipboards do (the framework's memory clipboard answers none, so a test of copied files would find the
/// clipboard holding only the list's text).
#[derive(Default)]
struct FilesClipboard(MemoryClipboard);
struct FilesClipboard(MemoryClipboard, Option<&'static str>);
impl ClipboardBackend for FilesClipboard {
fn write(&mut self, flavors: &[Flavor]) -> Result<usize, ClipboardError> {
@@ -268,6 +334,9 @@ pub(crate) mod testing {
}
fn read_image(&mut self, limit: u64) -> Result<Option<ClipboardImage>, ClipboardError> {
if let Some(error) = self.1 {
return Err(ClipboardError::Other(error.into()));
}
self.0.read_image(limit)
}
@@ -292,7 +361,12 @@ pub(crate) mod testing {
/// An empty document whose window's clipboard holds `flavors`.
pub(crate) fn app_holding(flavors: &[Flavor]) -> WordApp {
let mut clipboard = Clipboard::new(FilesClipboard::default());
app_holding_with_image_error(flavors, None)
}
/// Supply a backend read error for bitmap offers the memory clipboard would treat as absent.
pub(crate) fn app_holding_with_image_error(flavors: &[Flavor], image_error: Option<&'static str>) -> WordApp {
let mut clipboard = Clipboard::new(FilesClipboard(MemoryClipboard::default(), image_error));
if !flavors.is_empty() {
let _ = clipboard.write(flavors).unwrap();
}
@@ -357,6 +431,15 @@ mod tests {
}
}
#[test]
fn explicit_html_takes_precedence_over_the_system_bitmap() {
let mut a = app_holding(&[rgba8(4, 4, 200)]);
a.run("edit.paste", json!({"html": "<b>explicit</b>"})).unwrap();
assert_eq!(first_para(&a), "explicit");
assert!(bold_at(&a, 0));
assert!(a.session.doc.media.is_empty());
}
/// Paste Special lists a picture on the system clipboard and pastes it.
#[test]
fn paste_special_offers_the_clipboard_picture() {
+3 -2
View File
@@ -1,6 +1,6 @@
# Hardware parity with Microsoft Word
> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-11-09 · **Change:** trivial (touchpad and mouse-wheel scroll speed preferences, Slow / Normal / Fast, #6146); previously trivial (newly opened window dimensions are constrained to fit available screen dimensions, #5871); previously trivial (print helpers erase loaded plaintext inputs before driver work, #5710); previously trivial (Windows print submissions use isolated helpers so a cancelled driver cannot block a retry, #5710); previously trivial (print cancellation remains available without a document; sending-boundary limitation clarified, #5710); previously trivial (a print job waiting on its driver can be cancelled, and quitting doesn't wait for it, #5710); previously trivial (the printer list no longer waits on printer drivers, #5710); previously trivial (Linux Read Aloud: a sentence a screen reader cuts off is said again); previously trivial (ink page lookup work, #3614); previously trivial (only the PDF sent to the printer has no link annotations; Save these pages as PDF keeps them, #4734); previously trivial (a document with links prints: the print job's PDF has no link annotations, #4734; previously trivial: Pen / stylus row: two-stroke and closed-head arrows; previously trivial: Pen / stylus row: ink, eraser and Ink to Shape incl. arrows landed; previously trivial: a window too big for its screen shrinks to fit when it opens, #1215; previously trivial: 32-bit Windows starts on OpenGL; previously major: first version) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 and Word for Windows
> **Last reviewed:** 2026-10-12 · **Last updated:** 2026-12-04 · **Change:** trivial (Windows: a document window maximizes and goes full screen again, #8838); previously trivial (touchpad and mouse-wheel scroll speed preferences, Slow / Normal / Fast, #6146); previously trivial (newly opened window dimensions are constrained to fit available screen dimensions, #5871); previously trivial (print helpers erase loaded plaintext inputs before driver work, #5710); previously trivial (Windows print submissions use isolated helpers so a cancelled driver cannot block a retry, #5710); previously trivial (print cancellation remains available without a document; sending-boundary limitation clarified, #5710); previously trivial (a print job waiting on its driver can be cancelled, and quitting doesn't wait for it, #5710); previously trivial (the printer list no longer waits on printer drivers, #5710); previously trivial (Linux Read Aloud: a sentence a screen reader cuts off is said again); previously trivial (ink page lookup work, #3614); previously trivial (only the PDF sent to the printer has no link annotations; Save these pages as PDF keeps them, #4734); previously trivial (a document with links prints: the print job's PDF has no link annotations, #4734; previously trivial: Pen / stylus row: two-stroke and closed-head arrows; previously trivial: Pen / stylus row: ink, eraser and Ink to Shape incl. arrows landed; previously trivial: a window too big for its screen shrinks to fit when it opens, #1215; previously trivial: 32-bit Windows starts on OpenGL; previously major: first version) · **Target:** Microsoft Word (Microsoft 365) for Mac 16.113.4 and Word for Windows
> **Printing update:** 2026-10-12 · direct desktop printing through craft-print; details below.
@@ -15,7 +15,7 @@ pens, microphones (Dictate) and speakers (Read Aloud), and displays.
| Printers: native print dialog, printer choice, copies, duplex, page ranges, tray, scaling | ✅ (`WordPDE.plugin` print-dialog extension on Mac) | 🟡 Direct CUPS printing; printer, copies, collation, duplex, ranges, grayscale, scale to paper size, N-up and booklets; on every desktop the PDF sent to the printer leaves out link annotations, which the spooler can't fit to the paper; Save these pages as PDF keeps them (#4734) | 🟡 Direct spooler printing; printer, copies, collation, duplex, ranges, grayscale, scale to paper size, N-up and booklets; on every desktop the PDF sent to the printer leaves out link annotations, which the spooler can't fit to the paper; Save these pages as PDF keeps them (#4734) | 🟡 Direct spooler printing; printer, copies, collation, duplex, ranges, grayscale, scale to paper size, N-up and booklets; on every desktop the PDF sent to the printer leaves out link annotations, which the spooler can't fit to the paper; Save these pages as PDF keeps them (#4734) | ✅ browser print dialog (#209) | 35% | 5–8 |
| GPU rendering, HiDPI/Retina, pixel-aligned text | ✅ | ✅ wgpu + vello_cpu rasteriser, whole-pixel text (#110, #165) | ✅ DirectX 12 default (#50), OpenGL when DirectX 12 has no GPU driver (#316) or on 32-bit; startup crash on Intel UHD (#170) | ✅ (soft text on KDE at some zooms, #140) | ✅ | 80% | 3–5 (bugs) |
| Pen / stylus: ink, pressure, eraser, ink to shape/math | ✅ (Draw tab, `InkRender.bundle`) | 🟡 ink, stroke eraser, Ink to Shape incl. one- and two-stroke arrows with open or closed heads (#307, #395); pressure and Ink to Math missing | 🟡 same | 🟡 same | 🟡 same | 50% | (Draw tab, 15–25) |
| Multiple monitors, per-monitor DPI, remembered window position, a window that fits its screen | ✅ | ✅ (#38, #76, #1215) | ✅ (winit DPI fix pending, #155) | ✅ | — | 85% | 1 |
| Multiple monitors, per-monitor DPI, remembered window position, a window that fits its screen, maximize and full screen | ✅ | ✅ (#38, #76, #1215, #8838) | ✅ (winit DPI fix pending, #155) | ✅ | — | 85% | 1 |
| Microphone: Dictate | ✅ (cloud speech service) | ❌ | ❌ | ❌ | ❌ | 0% | 8–15 + owner (speech model choice) |
| Speakers: Read Aloud | ✅ | ✅ system speech, speed, sentence skip (#190) | ✅ | 🟡 espeak-ng, then espeak, then Speech Dispatcher (over its socket), each sentence in its language's voice; packages recommend a speech program; silent in the Flatpak (no audio access, no speech program) | 🟡 | 75% | 1–2 |
| Touch screens and touchpads: pinch zoom, inertial scroll | ✅ | ✅ pinch (#179) | ✅ | ✅ inertial scroll (#252), touchpad and wheel scroll speed settings (#6146) | ✅ | 85% | 0–1 |
@@ -28,6 +28,7 @@ File > Print offers 2, 4, 6, 9 or 16 logical pages per physical sheet side and l
| Date | Change | Summary |
|---|---|---|
| 2026-12-04 | trivial | Windows: a document window maximizes (button, Win+Up, snap to the top) and goes full screen again (#8838, #8861); since v0.20.0 the window was sent back to its normal place after the system maximized it. Fixed in craft-libs#5339, repinned. |
| 2026-11-09 | trivial | Touchpad and mouse-wheel scroll speed preferences (Slow, Normal, Fast): scales Wayland touchpad point input by default (4×) so swiping matches desktop speed, and scales mouse wheel line distance; File › Options › Advanced › Scrolling (#6146) |
| 2026-11-07 | trivial | Newly opened secondary windows constrain their initial viewport dimensions to the monitor's usable area, preventing windows from exceeding screen width on scaled displays (#5871) |
| 2026-11-06 | trivial | Print helpers remove loaded PDF/settings files before driver work, tolerate prior removal and report cleanup errors; a held-driver regression checks the files are already absent (#5710) |
+4 -2
View File
File diff suppressed because one or more lines are too long