Compare commits

...
Author SHA1 Message Date
e2df2d64cd Tables in a header or footer: borders, handles, selection arrows, pen and eraser work while it is edited (#5558) (#5576)
Lands #5576 rebased onto main; only docs conflicts were resolved (both sides kept).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: D13GOOOO <106814760+D13GOOOO@users.noreply.github.com>
2026-11-17 04:04:48 +00:00
Mex b3f31666d3 M14: align release guide with scheduled dry runs (#6682) 2026-11-17 05:00:18 +01:00
Mex 68f758928e M14: keep the type_text description in one MCP table row (#6683) 2026-11-17 04:45:21 +01:00
Mex 840efd03fb M14: link PDF revision guidance to the workspace manifest (#6685) 2026-11-17 04:30:24 +01:00
Mex 8e8ab631fd M14: document optional run commands and PNG save options (#6687) 2026-11-17 04:16:20 +01:00
Mex 8a9d04eeb1 M14: restore save stamps after immediate web-save errors (#6824) 2026-11-17 03:59:04 +01:00
Mex 266407e840 M14: expose file-browser row names and selection (#6790) 2026-11-17 03:46:09 +01:00
Valentin KleinandClaude Sonnet 5.5 c817cc95c6 Render: keep a metafile with huge bitmaps in the cache instead of parsing it on every repaint (#5494)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-17 03:32:02 +01:00
Diego GueriniandClaude Opus 5.5 ff0823f40d Track Changes: a deleted list item's number is drawn as deleted text (#4828) (#4836)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-17 03:19:00 +01:00
Mex 211f62231d M14: correct control protocol parameter examples (#6684) 2026-11-17 03:03:15 +01:00
RickiNano 9144b9bfda Insert › Shapes: the Arrow tile is the block arrow it inserts (#6768) (#6882) 2026-11-17 02:45:40 +01:00
RickiNano a61cef5d45 edit.replace reports whether it replaced and what it selected (#6877) (#6879) 2026-11-17 02:29:41 +01:00
Mex 739491f5c7 M14: list xtask version and point layering help at public docs (#6688) 2026-11-17 02:13:51 +01:00
Mex 8377ea8e8f M7: document the explicit stop flag for protection (#6690) 2026-11-17 01:59:18 +01:00
Mex 4357166531 M14: report the supported ICO image bounds (#6694) 2026-11-17 01:28:39 +01:00
Mex 5d871d0519 M14: document the selection collapse end parameter (#6695) 2026-11-17 01:15:46 +01:00
Mex ae2d2b43d6 M3: describe the 32-bit comment identifier limit (#6696) 2026-11-17 01:03:22 +01:00
Mex cd23034f65 M14: clarify when layout tests need explicit font initialization (#6697) 2026-11-17 00:52:01 +01:00
Mex b2306fe5ef M3: explain invalid font name values (#6698) 2026-11-17 00:36:03 +01:00
Mex 646fbc7cd5 M10: clarify Zotero command response shapes (#6700) 2026-11-17 00:20:17 +01:00
Mex 4a347e070a M14: expose required command inputs in discovery (#6703) 2026-11-17 00:07:55 +01:00
Mex 3bf4c05461 M14: explain the bookmark name rules in validation errors (#6706) 2026-11-16 23:54:32 +01:00
Mex 7b26a94193 M14: clarify dictionary-folder auto reset (#6709) 2026-11-16 23:39:06 +01:00
Mex ace000b4a4 M14: expose table-style formatting names and selection (#6711) 2026-11-16 23:26:12 +01:00
Mex 7adbdc574c M14: describe canvas member listing without an index (#6714) 2026-11-16 23:12:16 +01:00
Mex f77eef9cb6 M14: expose the keyboard shortcut capture name and current key (#6716) 2026-11-16 22:57:20 +01:00
Mex a2f41d728e M14: distinguish font file and unpacked size limits in errors (#6719) 2026-11-16 22:41:53 +01:00
Mex 9fe9bd5042 M14: clarify initial and pane spelling-review wrapping (#6720) 2026-11-16 22:26:23 +01:00
Mex 83c3b5890b M14: describe all accepted mail-merge sort forms (#6724) 2026-11-16 22:15:32 +01:00
Mex f472620ac0 M14: explain invalid field code values (#6725) 2026-11-16 22:03:39 +01:00
FredApps 5467f998a0 Tests: set the fit-one-page fixtures in bundled Inter so FreeBSD pages them like other hosts (#6887)
* Tests: set the fit-one-page fixtures in bundled Inter

The fit-one-page fixtures count pages to the line, but they were set in the
default Aptos, which each host substitutes with whatever it has installed:
Arial on Windows, Liberation Sans on the Linux runners, DejaVu Sans on the
FreeBSD image (its only candidate). DejaVu Sans is taller, so at 11 pt it fits
27 of the fixture lines on a page where Arial fits 28, and the nightly FreeBSD
job failed fit_one_page_respects_step_pt and
fit_one_page_preserves_budget_across_document_serialization.

Set the fixtures in the bundled Inter, whose metrics keep a page boundary for
each 0.5 pt step, recount the fixed line counts for it, and start the boundary
searches below the boundary. The two tests that failed also assert that the
body is laid out in Inter, not a substitute.

* Tests: keep 7 to 12 body lines on the line-numbered fixture's final page

A boundary search left one body line on the final page, so counting the
line-number decorations too would still have stayed under the 12-line limit and
the test could not catch it. Use 33 lines, 8 on the final page in Inter, and
assert the body-only count is between 7 and 12.
2026-11-16 21:51:07 +01:00
Mex 78dfa8f648 M14: label Alt Text pane inputs for assistive technology (#6726) 2026-11-16 21:48:11 +01:00
Mex 82f0c467be M14: describe encrypted OpenDocument command support (#6776) 2026-11-16 21:32:11 +01:00
Mex 837a610133 M14: explain hyperlink URL input limits (#6789) 2026-11-16 21:20:15 +01:00
FredApps de977bcde6 Merge pull request #6658 from dotCooCoo/fix/issue-6636
Metafiles: draw EMF+ bitmaps, pattern fills, clips and pen styles from craft-metafile (#6636)
2026-11-16 17:28:06 +01:00
FredApps 4ba0595760 Merge pull request #6863 from storytold/refactor/shared-tiff-compression
geom: delegate TIFF compression inspection to craft-tiff
2026-11-16 16:48:47 +01:00
dotCooCoo e6e8c61dbf Merge main into fix/issue-6636 2026-11-14 12:11:53 -08:00
dotCooCoo 1d150004f7 Tests: EMF+ only bitmaps are drawn over their EmfPlusDrawImage rectangle
The two EMF+ bitmap tests checked only that the bitmap is embedded. They now
also read the page through hayro's interpreter and check that the page draws
each bitmap over the right half of the picture, where its EmfPlusDrawImage
rectangle places it.
2026-11-14 11:40:21 -08:00
dotCooCoo 7ccfd4caef Tests: EMF+ only bitmaps in ARGB, RGB, PNG and JPEG are drawn
The page renderer and the PDF exporter each get a test that draws an
EmfPlusDrawImage bitmap in PixelFormat32bppARGB, 24bppRGB and 32bppRGB,
and a compressed PNG and JPEG bitmap, from an EMF+ only file.
2026-11-14 07:40:12 -08:00
dotCooCoo 7b3b6f8041 Merge main into fix/issue-6636 2026-11-14 07:32:49 -08:00
dotCooCoo fecb717f99 Metafiles: read WMF, EMF and EMF+ with craft-metafile (#6636)
crates/metafile is deleted. formats, layout, render and pdf take their
WMF, EMF and EMF+ reader from craft-metafile (craft-libs 9dcbd90c, the
rev craft-docx is already pinned at), so EMF+ records are read: an EMF+
only file's DrawImage of a 32bppPARGB bitmap draws its pixels.

render and pdf draw what the shared model adds: pattern and hatch fills,
clip regions and clip paths, pen caps, joins, miter limits and dashes,
turned, skewed or mirrored bitmaps, and the opaque background behind
text. The text layout and the default font for a file that names none
(Arial, a 16-unit cell) move to layout, next to metafile_text_run.

layout/src/metafile.rs holds the rules both outputs follow: a negative
crop side draws as no crop, as before; a cosmetic pen's shortest dash
or gap is one output pixel; a dash pattern whose period is under a
pixel, or that would split a path into more than 100,000 pieces, draws
solid; and an invalid miter limit is 10. On screen, a pattern tile whose
sides are both under 1.5 device pixels fills with its average color,
computed once a tile, and the vector cache counts each item's clip
region, clip list and dash pattern.

Fixes #6636
2026-11-14 05:16:52 -08:00
65 changed files with 2581 additions and 326 deletions
+5 -1
View File
File diff suppressed because one or more lines are too long
+3 -2
View File
@@ -35,10 +35,11 @@ USAGE:
--strict writes nothing and exits 3 if a character on the
page can't be drawn or a picture is missing or undecodable
(report on stderr, as for convert --strict)
wordcraft-cli run [--file F | --template T] [--script FILE|-] --cmd 'id={json}' [--cmd …]
[--save OUT] [--print] [--author NAME]
wordcraft-cli run [--file F | --template T] [--script FILE|-] [--cmd 'id={json}' …]
[--save OUT] [--page N] [--scale S] [--print] [--author NAME]
run commands headlessly, then save (--author names
who tracked changes and comments are by).
PNG saves use --page (1-based, default 1) and --scale (default 2).
--script runs a JSON file (- is stdin) first:
{\"file\"?, \"template\"?, \"commands\": [{\"command\": id,
\"params\"?: {…}} | id, …], \"save\"?: [OUT, …]}; save
+2 -2
View File
@@ -79,7 +79,7 @@ pub fn specs() -> Vec<CommandSpec> {
.when(has_canvas)
.pure(),
CommandSpec::new("canvas.member", "Canvas Member", "Shape Format › Drawing Canvas", member)
.params(r#"{"index": n, "x"?: pt, "y"?: pt, "width"?: pt, "height"?: pt, "delete"?: bool} (moves, resizes or removes member `index` of the selected canvas; x/y from the canvas's top-left; with no change, returns the members)"#)
.params(r#"{"index"?: n, "x"?: pt, "y"?: pt, "width"?: pt, "height"?: pt, "delete"?: bool} (moves, resizes or removes member `index` of the selected canvas; x/y from the canvas's top-left; without index, returns the members)"#)
.when(has_canvas),
]
}
@@ -211,7 +211,7 @@ fn scale(s: &mut Session, v: &Value) -> CmdResult {
result(&o)
}
/// `canvas.member`: move, resize or remove one member; with no change, list the members.
/// `canvas.member`: move, resize or remove one member; without index, list the members.
fn member(s: &mut Session, v: &Value) -> CmdResult {
let pos = canvas_pos(s)?;
let Some(i) = p::u64(v, "index").and_then(|i| usize::try_from(i).ok()) else {
+1
View File
@@ -68,6 +68,7 @@ pub fn specs() -> Vec<CommandSpec> {
sel_result(s)
})
.key("Escape")
.params(r#"{"end"?: bool (default false: collapse to the start; true: to the end)}"#)
.pure(),
]
}
+2 -1
View File
@@ -63,7 +63,8 @@ pub fn specs() -> Vec<CommandSpec> {
let t = THEMES.iter().find(|t| t.0.eq_ignore_ascii_case(name)).ok_or_else(|| CmdError::Params(format!("unknown colours `{name}`")))?;
set_accent(s, t.3[0]);
sel_result(s)
}),
})
.params(r#"{"name": string (see design.themes)}"#),
CommandSpec::new("design.styleSet", "Style Set", "Design › Document Formatting", style_set)
.params(r#"{"name": "default|basic|lines|shaded|casual|centered|minimalist|title"}"#),
CommandSpec::new("design.paragraphSpacing", "Paragraph Spacing", "Design › Document Formatting", para_spacing)
+15 -4
View File
@@ -141,7 +141,9 @@ pub fn specs() -> Vec<CommandSpec> {
.key(super::mac_or("Mod+Shift+G / Mod+PageUp", "Mod+PageUp"))
.params(r#"{"text"?: string, "matchCase"?: bool, "wholeWord"?: bool, "regex"?: bool}"#)
.pure(),
CommandSpec::new("edit.replace", "Replace", "Home › Editing", replace).params(r#"{"text": string, "with": string, …options of edit.replaceAll}"#),
CommandSpec::new("edit.replace", "Replace", "Home › Editing", replace).params(
r#"{"text": string, "with": string, …options of edit.replaceAll} — Word's Replace button: replaces the match only when it is already selected, then selects the next one. The first call on a caret replaces nothing; call again to replace the selected match, or use edit.replaceAll for every match. Returns {"replaced": 0 | 1, "remaining": n, "selected": {start, end} | null}"#,
),
// Ctrl+H, Home › Replace: the Find and Replace dialog on its Replace tab (#712). Opening
// it changes nothing, so it is its own command and never marks the document edited.
CommandSpec::new("edit.findReplace", "Find and Replace", "Home › Editing", |s, v| {
@@ -746,12 +748,21 @@ fn replace(s: &mut Session, v: &Value) -> CmdResult {
let story = s.sel.focus.story;
let results = search_full(s, story, true)?;
let (a, b) = s.sel.ordered();
// Replace the current match if selected, then move to the next.
// Replace the current match if selected, then move to the next. The result says which
// happened (#6877): a first call that only selects a match reads as `replaced: 0`.
let mut replaced = 0;
if let Some(f) = results.into_iter().find(|f| f.a == a && f.b == b) {
super::paste_text(s, &f.rep.unwrap_or_default())?;
replaced = 1;
}
let _ = step(s, 1);
Ok(json!({"remaining": search(s, story)?.len()}))
let selected = match step(s, 1) {
Ok(_) => {
let (start, end) = s.sel.ordered();
json!({"start": pos_json(&start), "end": pos_json(&end)})
}
Err(_) => Value::Null,
};
Ok(json!({"replaced": replaced, "remaining": search(s, story)?.len(), "selected": selected}))
}
/// Every match replaced, last first so earlier positions stay valid (one undo step). A `\r` in
+5 -2
View File
@@ -154,7 +154,7 @@ pub fn show_results(s: &mut Session) -> Result<(), CmdError> {
fn set_code(s: &mut Session, v: &Value) -> CmdResult {
let code = p::req_str(v, "code")?.trim().to_string();
if code.is_empty() || code.len() > MAX_CODE || code.contains(OBJ) {
return Err(CmdError::Params("bad field code".into()));
return Err(CmdError::Params("`code` must be non-empty, at most 4096 UTF-8 bytes, and contain no U+FFFC object markers".into()));
}
let Some(f) = selected(s).into_iter().next() else { return Err(none_selected()) };
with_field(s, &f.at, |o| match o {
@@ -441,7 +441,10 @@ mod tests {
s.run("fields.setCode", &json!({"code": "TITLE"})).unwrap();
let objs = |s: &Session| s.doc.body.first().and_then(|b| b.as_para()).map(|p| p.objects.clone()).unwrap_or_default();
assert!(matches!(objs(&s).first(), Some(InlineObject::Field { instr, result, .. }) if instr == "TITLE" && result == "Report"));
assert!(s.run("fields.setCode", &json!({"code": ""})).is_err());
assert!(matches!(
s.run("fields.setCode", &json!({"code": ""})),
Err(crate::CmdError::Params(message)) if message == "`code` must be non-empty, at most 4096 UTF-8 bytes, and contain no U+FFFC object markers"
));
// A locked field keeps its result.
s.run("fields.lock", &json!({})).unwrap();
+4 -4
View File
@@ -90,7 +90,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("file.new", "New", "File", new).key("Mod+N").params(r#"{"template"?: "blank|sample|letter|resume|report"}"#).pure(),
CommandSpec::new("file.open", "Open", "File", open)
.key("Mod+O / Mod+F12 / Mod+Alt+F2")
.params(r#"{"path": string, "data"?: base64 (the file's bytes; `path` then only names it), "password"?: string (for a password-protected Word document)}"#)
.params(r#"{"path": string, "data"?: base64 (the file's bytes; `path` then only names it), "password"?: string (for a password-protected Word or OpenDocument text file)}"#)
.pure(),
CommandSpec::new("file.save", "Save", "File", save)
.key("Mod+S / Shift+F12 / Alt+Shift+F2")
@@ -100,7 +100,7 @@ pub fn specs() -> Vec<CommandSpec> {
// Pure: the password must not land in Repeat or a recorded macro, and it isn't an edit
// to undo; it marks the document as changed itself.
CommandSpec::new("file.encrypt", "Encrypt with Password", "File › Info › Protect Document", encrypt)
.params(r#"{"password": string (Word documents are saved encrypted with it) | null or "" (saved unencrypted)}"#)
.params(r#"{"password": string (Word packages and OpenDocument text files (.odt, .ott) are saved encrypted with it) | null or "" (saved unencrypted)}"#)
.pure(),
CommandSpec::new("file.exportPdf", "Export PDF", "File › Export", |s, v| {
// No path (the command search, say): the app asks where to save, as File › Export
@@ -368,8 +368,8 @@ fn close_document(s: &mut Session, v: &Value) -> CmdResult {
Ok(json!({"closed": id, "active": s.document_id(), "documents": s.documents()}))
}
/// File › Info › Protect Document › Encrypt with Password: the password Word documents are saved
/// with from now on, or none.
/// File › Info › Protect Document › Encrypt with Password: the password Word packages and
/// OpenDocument text files (.odt, .ott) are saved with from now on, or none.
fn encrypt(s: &mut Session, v: &Value) -> CmdResult {
let password = match v.get("password") {
Some(Value::Null) => None,
+1 -1
View File
@@ -336,7 +336,7 @@ fn font(s: &mut Session, v: &Value) -> CmdResult {
let Some(n) = v.get(k) else { return Ok(None) };
let n = n.as_str().map(str::trim).unwrap_or("");
if n.is_empty() || n.len() > 128 {
return Err(CmdError::Params(format!("bad font name `{k}`")));
return Err(CmdError::Params(format!("`{k}` must be a non-empty font name of at most 128 bytes")));
}
Ok(Some(n.to_string()))
};
+4 -2
View File
@@ -51,7 +51,7 @@ pub(super) fn link(s: &mut Session, v: &Value) -> CmdResult {
},
};
if url.is_empty() || url.len() > 4096 {
return Err(CmdError::Params("bad url".into()));
return Err(CmdError::Params("`url` must be non-empty and at most 4096 UTF-8 bytes".into()));
}
let style = Some("Hyperlink".to_string());
if s.sel.is_collapsed() {
@@ -188,7 +188,9 @@ pub(super) fn delete_bookmark(s: &mut Session, v: &Value) -> CmdResult {
pub(super) fn bookmark(s: &mut Session, v: &Value) -> CmdResult {
let name = p::req_str(v, "name")?.trim().to_string();
if !bookmark_name_ok(&name) {
return Err(CmdError::Params("bookmark names start with a letter, have no spaces and at most 40 characters".into()));
return Err(CmdError::Params(
"bookmark names start with a letter or underscore, contain only letters, numbers or underscores, and have at most 40 characters".into(),
));
}
// Replace an existing bookmark of the same name.
remove_bookmark(s, &name)?;
+3 -2
View File
@@ -110,7 +110,7 @@ pub fn specs() -> Vec<CommandSpec> {
apply_filter(s);
filter_result(s)
})
.params(r#"{"rules"?: [{"field": string, "op": "equal|notEqual|less|greater|lessOrEqual|greaterOrEqual|blank|notBlank|contains|notContains", "value"?: string, "join"?: "and|or" (with the rule before; And binds tighter)}], "sort"?: [{"field": string, "descending"?: bool}]} (replaces the filter; `sort` too when given; {} clears both). Preview, Finish & Merge and labels use only the matching records, in sort order"#)
.params(r#"{"rules"?: [{"field": string, "op": "equal|notEqual|less|greater|lessOrEqual|greaterOrEqual|blank|notBlank|contains|notContains", "value"?: string, "join"?: "and|or" (with the rule before; And binds tighter)}], "sort"?: [{"field": string, "descending"?: bool}]} (replaces the filter; `sort` too when given; `sort` also accepts a field name, one key object or null; array entries may also be field names; {} clears both). Preview, Finish & Merge and labels use only the matching records, in sort order"#)
.when(has_list)
.pure(),
CommandSpec::new("mailings.sortRecipients", "Sort Recipients", "Mailings › Start Mail Merge › Edit Recipient List", |s, v| {
@@ -118,7 +118,7 @@ pub fn specs() -> Vec<CommandSpec> {
apply_filter(s);
filter_result(s)
})
.params(r#"{"sort"?: [{"field": string, "descending"?: bool}]} | {"field": string, "descending"?: bool} (no params: the list's own order)"#)
.params(r#"{"sort"?: [{"field": string, "descending"?: bool}]} | {"field": string, "descending"?: bool} (`sort` also accepts a field name, one key object or null; array entries may also be field names; no params: the list's own order)"#)
.when(has_list)
.pure(),
CommandSpec::new("mailings.insertField", "Insert Merge Field", "Mailings › Write & Insert Fields", |s, v| {
@@ -192,6 +192,7 @@ pub fn specs() -> Vec<CommandSpec> {
refresh(s);
Ok(json!({"record": idx + 1}))
})
.params(r#"{"text": string}"#)
.when(has_recipients),
CommandSpec::new("mailings.checkErrors", "Check for Errors", "Mailings › Finish", |s, _| {
let mut missing = Vec::new();
+1 -1
View File
@@ -255,7 +255,7 @@ pub(super) fn parse_sort(headers: &[String], v: Option<&Value>) -> Result<Vec<So
None | Some(Value::Null) => return Ok(Vec::new()),
Some(Value::Array(a)) => a.clone(),
Some(o @ (Value::Object(_) | Value::String(_))) => vec![o.clone()],
Some(_) => return Err(CmdError::Params("`sort` must be an array of {field, descending}".into())),
Some(_) => return Err(CmdError::Params("`sort` must be a field name, a {field, descending} object, an array of those, or null".into())),
};
if arr.len() > MAX_SORT_KEYS {
return Err(CmdError::Params(format!("at most {MAX_SORT_KEYS} sort keys")));
+1 -1
View File
@@ -22,7 +22,7 @@ pub fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec::new("file.options", "Options", "File", options)
.params(
r#"{"pane"?: "general|display|proofing|save|language|accessibility|advanced|agents", "author"?: string, "initials"?: string, "units"?: "inches|centimeters|millimeters|points|picas|auto" (auto: the region's), "region"?: string (a locale tag like pl-PL, saved: the paper File › New starts on, the default units and the decimal separator; auto: the system's), "typingReplacesSelection"?: bool, "insertKeyOvertype"?: bool, "overtype"?: bool, "marks"?: {"tabs"?: bool, "spaces"?: bool, "paragraphs"?: bool, "hidden"?: bool}, "checkSpelling"?: bool, "markGrammar"?: bool, "ignoreUppercase"?: bool, "ignoreNumbers"?: bool, "ignoreInternet"?: bool, "dictionariesFolder"?: string (a folder of Hunspell .aff/.dic files searched first, saved; auto: the system locations only), "userTemplatesFolder"?: string (the folder File › New lists personal templates from, saved; auto: the app's own Templates folder; not a network folder), "addWords"?: [string], "removeWords"?: [string]} — with any setting it changes them and opens nothing; without, it opens File › Options (at `pane`). Returns the settings."#,
r#"{"pane"?: "general|display|proofing|save|language|accessibility|advanced|agents", "author"?: string, "initials"?: string, "units"?: "inches|centimeters|millimeters|points|picas|auto" (auto: the region's), "region"?: string (a locale tag like pl-PL, saved: the paper File › New starts on, the default units and the decimal separator; auto: the system's), "typingReplacesSelection"?: bool, "insertKeyOvertype"?: bool, "overtype"?: bool, "marks"?: {"tabs"?: bool, "spaces"?: bool, "paragraphs"?: bool, "hidden"?: bool}, "checkSpelling"?: bool, "markGrammar"?: bool, "ignoreUppercase"?: bool, "ignoreNumbers"?: bool, "ignoreInternet"?: bool, "dictionariesFolder"?: string (a folder of Hunspell .aff/.dic files searched first, saved; auto: clear the configured folder), "userTemplatesFolder"?: string (the folder File › New lists personal templates from, saved; auto: the app's own Templates folder; not a network folder), "addWords"?: [string], "removeWords"?: [string]} — with any setting it changes them and opens nothing; without, it opens File › Options (at `pane`). Returns the settings."#,
)
.pure(),
CommandSpec::new("text.overtype", "Overtype", "File › Options › Advanced", |s, v| {
+2 -1
View File
@@ -274,7 +274,8 @@ pub fn specs() -> Vec<CommandSpec> {
st.quick = on;
}
sel_result(s)
}),
})
.params(r#"{"style": string (name or id), "value"?: bool (default true)}"#),
// Advanced paragraph tools (#5043, as in WPS Office): conversions and cleanup over the
// selection, or the whole document with `scope: "all"`. One undo step per command.
CommandSpec::new("para.convertBreaks", "Convert Line Breaks to Paragraphs", "Home › Paragraph › Paragraph Tools", convert_breaks)
+1 -1
View File
@@ -22,7 +22,7 @@ const MODES: [&str; 5] = ["none", "readOnly", "comments", "trackedChanges", "for
pub fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec::new("review.restrict", "Restrict Editing", "Review › Protect", restrict).params(
r#"{"mode"?: "none|readOnly|comments|trackedChanges|forms" (start enforcing; "none" stops), "formatting"?: bool (limit formatting to unlocked styles), "lockedStyles"?: [style id or name] (the styles that can't be applied; every other style is unlocked), "password"?: string (set when enforcing; required to stop a password-protected document), "stop"?: bool, "exception"?: "add" (the selection stays editable for everyone) | "remove" (exceptions touching the selection) | "removeAll"} → state"#,
r#"{"mode"?: "none|readOnly|comments|trackedChanges|forms" (editing restriction; use "none" with "formatting": true for formatting-only protection), "formatting"?: bool (limit formatting to unlocked styles), "lockedStyles"?: [style id or name] (the styles that can't be applied; every other style is unlocked), "password"?: string (set when enforcing; required to stop a password-protected document), "stop"?: bool (true: stop protection), "exception"?: "add" (the selection stays editable for everyone) | "remove" (exceptions touching the selection) | "removeAll"} → state"#,
),
]
}
+4 -4
View File
@@ -28,12 +28,12 @@ pub fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec::new("review.newComment", "New Comment", "Review › Comments", new_comment).key(super::mac_or("Mod+Alt+A / Mod+Alt+M", "Mod+Alt+M")).params(r#"{"text": string}"#),
CommandSpec::new("review.reply", "Reply", "Review › Comments", reply)
.params(r#"{"id": non-negative JSON integer, "text": string}"#)
.params(r#"{"id": non-negative 32-bit JSON integer, "text": string}"#)
.when(comments_change),
CommandSpec::new("review.editComment", "Edit Comment", "Review › Comments", edit_comment)
.params(r#"{"id": non-negative JSON integer, "text": string}"#)
.params(r#"{"id": non-negative 32-bit JSON integer, "text": string}"#)
.when(comments_change),
CommandSpec::new("review.deleteComment", "Delete", "Review › Comments", delete_comment).params(r#"{"id"?: non-negative JSON integer (omit to use the caret), "all"?: bool}"#),
CommandSpec::new("review.deleteComment", "Delete", "Review › Comments", delete_comment).params(r#"{"id"?: non-negative 32-bit JSON integer (omit to use the caret), "all"?: bool}"#),
CommandSpec::new("review.resolveComment", "Resolve", "Review › Comments", |s, v| {
validate_comment_id(v)?;
let id = p::u64(v, "id").map(|x| x as u32).or_else(|| comment_at_caret(s)).ok_or_else(|| CmdError::Params("`id` required".into()))?;
@@ -41,7 +41,7 @@ pub fn specs() -> Vec<CommandSpec> {
c.resolved = p::bool(v, "value").unwrap_or(!c.resolved);
sel_result(s)
})
.params(r#"{"id"?: non-negative JSON integer (omit to use the caret), "value"?: bool (omit to toggle)}"#),
.params(r#"{"id"?: non-negative 32-bit JSON integer (omit to use the caret), "value"?: bool (omit to toggle)}"#),
CommandSpec::new("review.nextComment", "Next", "Review › Comments", |s, _| nav_comment(s, 1)).pure(),
CommandSpec::new("review.previousComment", "Previous", "Review › Comments", |s, _| nav_comment(s, -1)).pure(),
CommandSpec::new("review.comments", "Show Comments", "Review › Comments", list_comments).pure(),
+54 -26
View File
@@ -9,9 +9,10 @@ use wordcraft_doc::props::{HeightRule, VMerge};
use wordcraft_doc::table::{MAX_COLS, MAX_ROWS};
use wordcraft_doc::{Block, Cell, Path, Pos, StoryRef, Table, para_block};
use wordcraft_geom::Rect;
use wordcraft_layout::{DocLayout, Placed};
use wordcraft_layout::DocLayout;
use super::sel_result;
use super::table_resize::Reach;
use crate::{CmdError, CmdResult, CommandSpec, Selection, Session, p};
/// A drag shorter than this (points) both ways isn't a rectangle.
@@ -29,7 +30,7 @@ pub fn specs() -> Vec<CommandSpec> {
r#"{"page": n, "x0": pt, "y0": pt, "x1": pt, "y1": pt, "story"?: StoryRef} (a pen stroke in page points, 0-based page: a rectangle at least 12 pt each way outside any table inserts a one-cell table of that size at the paragraph under its start; a straight vertical or horizontal line inside a table splits the cells it crosses there. In the app the button turns the pen on.)"#,
),
CommandSpec::new("table.eraser", "Eraser", "Table Layout › Draw", eraser).params(
r#"{"page": n, "x": pt, "y": pt} (removes the border between two cells within 4 pt of the point: cells that make one rectangle merge, including cells merged down the same rows; otherwise the border is hidden along the whole edge. In the app the button turns the eraser on.)"#,
r#"{"page": n, "x": pt, "y": pt, "story"?: StoryRef} (removes the border between two cells within 4 pt of the point, of a table in `story` (default: the caret's; a header's or footer's while one is edited): cells that make one rectangle merge, including cells merged down the same rows; otherwise the border is hidden along the whole edge. In the app the button turns the eraser on.)"#,
),
]
}
@@ -55,16 +56,12 @@ struct CellBox {
cell: usize,
}
fn cell_boxes(l: &DocLayout, page: usize) -> Vec<CellBox> {
let Some(pg) = l.pages.get(page) else { return Vec::new() };
pg.items
.iter()
.filter_map(|it| match it {
Placed::Cell { rect, table, row, cell, story, .. } => {
Some(CellBox { rect: *rect, table: table.clone(), story: *story, row: *row, cell: *cell })
}
_ => None,
})
/// The table cells on a page the pen and eraser reach ([`Reach`]: a header's and footer's while
/// one of them is edited, #5558).
fn cell_boxes(l: &DocLayout, page: usize, reach: Reach) -> Vec<CellBox> {
super::table_resize::cell_boxes_in(l, page, reach)
.into_iter()
.map(|b| CellBox { rect: b.rect, table: b.table, story: b.story, row: b.row, cell: b.cell })
.collect()
}
@@ -79,13 +76,22 @@ fn table_at(boxes: &[CellBox], x: f32, y: f32) -> Option<(StoryRef, Path)> {
/// Classify a pen stroke: a straight line inside a table, a rectangle outside one, else `None`.
pub fn stroke(l: &DocLayout, page: usize, x0: f32, y0: f32, x1: f32, y1: f32) -> Option<Stroke> {
stroke_in(l, page, Reach::Body, x0, y0, x1, y1)
}
/// [`stroke`] while `editing` is edited: across a header's or footer's tables then (#5558).
pub fn stroke_in(l: &DocLayout, page: usize, tables: Reach, x0: f32, y0: f32, x1: f32, y1: f32) -> Option<Stroke> {
stroke_among(&cell_boxes(l, page, tables), x0, y0, x1, y1)
}
/// [`stroke`] across the tables of `boxes`.
fn stroke_among(boxes: &[CellBox], x0: f32, y0: f32, x1: f32, y1: f32) -> Option<Stroke> {
if ![x0, y0, x1, y1].iter().all(|v| v.is_finite()) {
return None;
}
let (dx, dy) = ((x1 - x0).abs(), (y1 - y0).abs());
let boxes = cell_boxes(l, page);
let (mx, my) = ((x0 + x1) / 2.0, (y0 + y1) / 2.0);
if table_at(&boxes, x0, y0).is_some() || table_at(&boxes, mx, my).is_some() {
if table_at(boxes, x0, y0).is_some() || table_at(boxes, mx, my).is_some() {
if dy >= dx && dy >= MIN_LINE && dx <= MIN_RECT.max(dy * 0.2) {
return Some(Stroke::Vertical { x: mx, y0: y0.min(y1), y1: y0.max(y1) });
}
@@ -97,6 +103,19 @@ pub fn stroke(l: &DocLayout, page: usize, x0: f32, y0: f32, x1: f32, y1: f32) ->
(dx >= MIN_RECT && dy >= MIN_RECT).then(|| Stroke::Rect(Rect::new(x0.min(x1), y0.min(y1), dx, dy)))
}
/// The cells a pen or eraser command reaches: those of the tables its `story` (default: the
/// caret's) reaches ([`Reach`]), and of those only `story`'s own when the command names one: a
/// caller that names a story means its tables, not a table of another drawn there.
fn command_boxes(s: &Session, l: &DocLayout, v: &Value, page: usize) -> Vec<CellBox> {
let story = super::story_param(s, v);
let boxes = cell_boxes(l, page, Reach::of(l, &s.doc, story, page));
let named = v.get("story").and_then(|x| serde_json::from_value::<StoryRef>(x.clone()).ok());
match named {
Some(named) => boxes.into_iter().filter(|b| b.story == named).collect(),
None => boxes,
}
}
fn page_param(v: &Value) -> Result<usize, CmdError> {
p::u64(v, "page").map(|n| usize::try_from(n).unwrap_or(usize::MAX)).ok_or_else(|| CmdError::Params("`page` (number) is required".into()))
}
@@ -108,10 +127,11 @@ fn draw(s: &mut Session, v: &Value) -> CmdResult {
if l.pages.get(page).is_none() {
return Err(CmdError::Params(format!("no page {page}")));
}
match stroke(&l, page, x0, y0, x1, y1) {
let boxes = command_boxes(s, &l, v, page);
match stroke_among(&boxes, x0, y0, x1, y1) {
Some(Stroke::Rect(r)) => draw_table(s, v, &l, page, (x0, y0), r),
Some(Stroke::Vertical { x, y0, y1 }) => split_columns(s, &l, page, x, (y0, y1)),
Some(Stroke::Horizontal { y, x0, x1 }) => split_rows(s, &l, page, y, (x0, x1)),
Some(Stroke::Vertical { x, y0, y1 }) => split_columns(s, &boxes, x, (y0, y1)),
Some(Stroke::Horizontal { y, x0, x1 }) => split_rows(s, &boxes, y, (x0, x1)),
None => Err(CmdError::Failed(
"draw a rectangle (at least 12 pt each way) outside a table, or a straight horizontal or vertical line across table cells".into(),
)),
@@ -276,13 +296,12 @@ fn hide_edge(t: &mut Table, vertical: bool, line: usize, (lo, hi): (usize, usize
}
/// A vertical line at page `x`: split each crossed cell into two columns there.
fn split_columns(s: &mut Session, l: &DocLayout, page: usize, x: f32, (ya, yb): (f32, f32)) -> CmdResult {
let boxes = cell_boxes(l, page);
fn split_columns(s: &mut Session, boxes: &[CellBox], x: f32, (ya, yb): (f32, f32)) -> CmdResult {
let hit = |r: &Rect| {
let overlap = yb.min(r.bottom()) - ya.max(r.y);
x > r.x + SNAP && x < r.right() - SNAP && overlap >= r.h * 0.5
};
let Some((story, tp, cells)) = crossed(&boxes, (x, (ya + yb) / 2.0), hit) else {
let Some((story, tp, cells)) = crossed(boxes, (x, (ya + yb) / 2.0), hit) else {
return Err(CmdError::Failed("the line doesn't cross a table cell".into()));
};
let Some(&(r0, c0, rect0)) = cells.first() else { return Err(CmdError::Failed("the line doesn't cross a table cell".into())) };
@@ -372,13 +391,12 @@ fn split_columns(s: &mut Session, l: &DocLayout, page: usize, x: f32, (ya, yb):
/// A horizontal line at page `y`: split the row it crosses there. Crossed cells become two;
/// the row's other cells span both rows (a vertical merge).
fn split_rows(s: &mut Session, l: &DocLayout, page: usize, y: f32, (xa, xb): (f32, f32)) -> CmdResult {
let boxes = cell_boxes(l, page);
fn split_rows(s: &mut Session, boxes: &[CellBox], y: f32, (xa, xb): (f32, f32)) -> CmdResult {
let hit = |r: &Rect| {
let overlap = xb.min(r.right()) - xa.max(r.x);
y > r.y + SNAP && y < r.bottom() - SNAP && overlap >= r.w * 0.5
};
let Some((story, tp, cells)) = crossed(&boxes, ((xa + xb) / 2.0, y), hit) else {
let Some((story, tp, cells)) = crossed(boxes, ((xa + xb) / 2.0, y), hit) else {
return Err(CmdError::Failed("the line doesn't cross a table cell".into()));
};
let Some(&(r, c0, _)) = cells.first() else { return Err(CmdError::Failed("the line doesn't cross a table cell".into())) };
@@ -459,17 +477,26 @@ pub struct EraseTarget {
/// The border between two cells nearest page point (`x`, `y`), within [`ERASER_REACH`].
pub fn erase_target(l: &DocLayout, page: usize, x: f32, y: f32) -> Option<EraseTarget> {
erase_target_in(l, page, Reach::Body, x, y)
}
/// [`erase_target`] while `editing` is edited: a header's or footer's tables then (#5558).
pub fn erase_target_in(l: &DocLayout, page: usize, tables: Reach, x: f32, y: f32) -> Option<EraseTarget> {
erase_among(&cell_boxes(l, page, tables), x, y)
}
/// [`erase_target`] among the tables of `boxes`.
fn erase_among(boxes: &[CellBox], x: f32, y: f32) -> Option<EraseTarget> {
if !x.is_finite() || !y.is_finite() {
return None;
}
let boxes = cell_boxes(l, page);
let mut best: Option<(f32, usize, EraseTarget)> = None;
let mut offer = |d: f32, depth: usize, e: EraseTarget| {
if d <= ERASER_REACH && best.as_ref().is_none_or(|(bd, bdepth, _)| d < *bd - 0.01 || (d <= *bd + 0.01 && depth > *bdepth)) {
best = Some((d, depth, e));
}
};
for a in &boxes {
for a in boxes {
let (ar, ab) = (a.rect.right(), a.rect.bottom());
let same = |b: &&CellBox| b.story == a.story && b.table == a.table;
// The border on a's right, shared with the next cell of its row.
@@ -518,7 +545,7 @@ fn eraser(s: &mut Session, v: &Value) -> CmdResult {
if l.pages.get(page).is_none() {
return Err(CmdError::Params(format!("no page {page}")));
}
let e = erase_target(&l, page, x, y).ok_or_else(|| CmdError::Failed("there's no border between two cells there".into()))?;
let e = erase_among(&command_boxes(s, &l, v, page), x, y).ok_or_else(|| CmdError::Failed("there's no border between two cells there".into()))?;
let (story, tp) = (e.story, e.table.clone());
let t = s.doc.table_mut(story, &tp)?;
let ((r, c), (r2, c2)) = (e.first, e.second);
@@ -581,6 +608,7 @@ fn eraser(s: &mut Session, v: &Value) -> CmdResult {
mod tests {
use super::*;
use serde_json::json;
use wordcraft_layout::Placed;
/// Each row's cell spans.
fn shape(t: &Table) -> Value {
+21 -16
View File
@@ -16,7 +16,7 @@ use wordcraft_doc::{Document, Path, Pos, StoryRef, Table};
use wordcraft_geom::{Point, Rect};
use wordcraft_layout::{DocLayout, Placed};
use super::table_resize::{self, CellBox, Edge, REACH, ResizeTarget};
use super::table_resize::{self, CellBox, Edge, REACH, Reach, ResizeTarget};
use super::{sel_result, table};
use crate::{CellRange, CmdError, CmdResult, CommandSpec, Selection, Session, p};
@@ -54,7 +54,7 @@ pub fn specs() -> Vec<CommandSpec> {
r#"{"page": n, "x": pt, "y": pt, "toX": pt, "toY": pt, "reach"?: pt} (a drag from the move handle past a table's top-left corner: the table floats where it's dropped, the text wrapping around it; tables in the main text only)"#,
),
CommandSpec::new("table.fitColumn", "AutoFit Column by Double-Clicking", "Table Layout › Cell Size", fit_column).params(
r#"{"page": n, "x": pt, "y": pt, "reach"?: pt} (a double-click on a column border: the column left of it fits its contents and the columns right of it keep their widths, moving with the border, so the table narrows or widens (up to the right margin), as in Word)"#,
r#"{"page": n, "x": pt, "y": pt, "reach"?: pt} (a double-click on a column border of a table in the caret's story: the column left of it fits its contents and the columns right of it keep their widths, moving with the border, so the table narrows or widens (up to the right margin), as in Word)"#,
),
]
}
@@ -205,11 +205,12 @@ pub fn target_at(l: &DocLayout, doc: &Document, story: StoryRef, page: usize, x:
return None;
}
let reach = clean_reach(reach);
if table_resize::resize_target(l, doc, page, x, y, reach).is_some() {
let tables = Reach::of(l, doc, story, page);
if table_resize::resize_target_in(l, doc, page, x, y, reach, tables).is_some() {
return None;
}
let boxes = table_resize::cell_boxes(l, page);
table_resize::tables_on(l, doc, page)
let boxes = table_resize::cell_boxes_in(l, page, tables);
table_resize::tables_on_in(l, doc, page, tables)
.into_iter()
.filter(|g| g.story == story)
.filter_map(|geom| {
@@ -226,7 +227,7 @@ pub fn handle_table(l: &DocLayout, doc: &Document, story: StoryRef, page: usize,
return None;
}
let pad = clean_reach(reach) / 2.0;
table_resize::tables_on(l, doc, page)
table_resize::tables_on_in(l, doc, page, Reach::of(l, doc, story, page))
.into_iter()
.filter(|g| {
let h = handle(g);
@@ -242,7 +243,7 @@ pub fn caret_handles(l: &DocLayout, doc: &Document, story: StoryRef, table: &Pat
let rows = doc.table(story, table).map_or(0, |t| t.rows.len());
let has_row = |p: usize, r: usize| {
l.pages.get(p).is_some_and(|pg| {
pg.items.iter().any(|it| matches!(it, Placed::Cell { table: t, story: st, row, .. } if *st == story && t == table && *row == r))
pg.story_items(story).any(|it| matches!(it, Placed::Cell { table: t, story: st, row, .. } if *st == story && t == table && *row == r))
})
};
// A repeated header row, or a row running on to the next page, is drawn on more than one
@@ -253,7 +254,9 @@ pub fn caret_handles(l: &DocLayout, doc: &Document, story: StoryRef, table: &Pat
return (None, None);
}
// The table's geometry on this page that the pointer handles are drawn and grabbed from.
let Some(g) = table_resize::tables_on(l, doc, page).into_iter().find(|g| g.story == story && g.table == *table) else {
let Some(g) =
table_resize::tables_on_in(l, doc, page, Reach::of(l, doc, story, page)).into_iter().find(|g| g.story == story && g.table == *table)
else {
return (None, None);
};
(first.then(|| handle(&g)), last.then(|| g.handle()))
@@ -298,7 +301,7 @@ pub fn cell_rects(l: &DocLayout, doc: &Document, range: &CellRange) -> Vec<(usiz
let picked: std::collections::BTreeSet<(usize, usize)> = range.cells(t).into_iter().collect();
let mut out = Vec::new();
for (pi, pg) in l.pages.iter().enumerate() {
for it in &pg.items {
for it in pg.story_items(range.story) {
// A vertically merged cell's box spans its rows (#640); its continuation rows'
// `covered` boxes would shade it twice.
if let Placed::Cell { rect, table, row, cell, story, covered: false, .. } = it
@@ -326,7 +329,7 @@ pub fn selection_rects(l: &DocLayout, doc: &Document, a: &Pos, b: &Pos, page_hin
let mut seen = BTreeMap::new();
let mut cells = Vec::new();
for (pi, pg) in l.pages.iter().enumerate() {
for it in &pg.items {
for it in pg.story_items(a.story) {
// A vertically merged cell's box spans its rows (#640), as in `cell_rects`.
if let Placed::Cell { rect, table, row, story, covered: false, .. } = it
&& *story == a.story
@@ -510,7 +513,7 @@ fn insert_at(s: &mut Session, v: &Value) -> CmdResult {
/// Where table `table` of `story` is first drawn: its page and top-left corner.
pub fn corner(l: &DocLayout, story: StoryRef, table: &Path) -> Option<(usize, f32, f32)> {
l.pages.iter().enumerate().find_map(|(pi, pg)| {
let cells = pg.items.iter().filter_map(|it| match it {
let cells = pg.story_items(story).filter_map(|it| match it {
Placed::Cell { rect, table: t, story: st, .. } if *st == story && t == table => Some(*rect),
_ => None,
});
@@ -565,10 +568,12 @@ fn move_drag(s: &mut Session, v: &Value) -> CmdResult {
fn fit_column(s: &mut Session, v: &Value) -> CmdResult {
let (page, x, y, reach) = point(v)?;
let l = s.layout();
let Some((target, line)) = table_resize::resize_target(&l, &s.doc, page, x, y, reach).and_then(|t| match t.edge {
Edge::Column(line) => Some((t, line)),
_ => None,
}) else {
let Some((target, line)) = table_resize::resize_target_in(&l, &s.doc, page, x, y, reach, Reach::of(&l, &s.doc, s.sel.focus.story, page))
.and_then(|t| match t.edge {
Edge::Column(line) => Some((t, line)),
_ => None,
})
else {
return Err(CmdError::Failed("there's no column border there".into()));
};
let t = s.doc.table(target.story, &target.table).ok_or_else(|| CmdError::Failed("there's no table there".into()))?;
@@ -595,7 +600,7 @@ fn room_right(l: &DocLayout, doc: &Document, page: usize, target: &ResizeTarget)
let margin = l.pages.get(page).map_or(target.right(), |pg| pg.body.right());
let Some((outer, row, cell)) = target.table.cell() else { return margin };
let Some(t) = doc.table(target.story, &outer) else { return margin };
let boxes = table_resize::cell_boxes(l, page);
let boxes = table_resize::story_cell_boxes(l, page, target.story);
let Some(b) = boxes.iter().find(|b| b.story == target.story && b.table == outer && b.row == row && b.cell == cell) else {
return margin;
};
+77 -19
View File
@@ -9,7 +9,7 @@
use serde_json::Value;
use wordcraft_doc::props::{Align, HeightRule, VMerge};
use wordcraft_doc::table::MAX_COLS;
use wordcraft_doc::{Cell, Document, Path, StoryRef, Table};
use wordcraft_doc::{Cell, Document, PartKind, Path, StoryRef, Table};
use wordcraft_geom::Rect;
use wordcraft_layout::{DocLayout, Placed};
@@ -29,7 +29,7 @@ const MAX_LEN: f32 = 1584.0;
pub fn specs() -> Vec<CommandSpec> {
vec![CommandSpec::new("table.resizeDrag", "Resize Table by Dragging", "Table Layout › Cell Size", resize_drag).params(
r#"{"page": n, "x": pt, "y": pt, "toX": pt, "toY": pt, "shift"?: bool, "ctrl"?: bool, "reach"?: pt} (a mouse drag in page points, 0-based page, starting on a table border or the resize handle: a column border moves (the column to its right gives or takes the difference, so the table keeps its width; with ctrl the columns right of it share it in proportion; with shift, or on the table's right edge, only the column left of it changes); the table's left edge moves a left-aligned table's indent, the first column making up the difference (a centred or right-aligned table keeps its alignment: only the first column changes); with cells of the table selected, a border of theirs moves only in their rows; a row's bottom border sets that row's height; the handle just outside the bottom-right corner scales every column and the rows on that page. `reach` (default 3) is how near the start has to be.)"#,
r#"{"page": n, "x": pt, "y": pt, "toX": pt, "toY": pt, "shift"?: bool, "ctrl"?: bool, "reach"?: pt} (a mouse drag in page points, 0-based page, starting on a border or the resize handle of a table in the caret's story (a header's or footer's tables while one is edited): a column border moves (the column to its right gives or takes the difference, so the table keeps its width; with ctrl the columns right of it share it in proportion; with shift, or on the table's right edge, only the column left of it changes); the table's left edge moves a left-aligned table's indent, the first column making up the difference (a centred or right-aligned table keeps its alignment: only the first column changes); with cells of the table selected, a border of theirs moves only in their rows; a row's bottom border sets that row's height; the handle just outside the bottom-right corner scales every column and the rows on that page. `reach` (default 3) is how near the start has to be.)"#,
)]
}
@@ -327,17 +327,53 @@ pub(crate) struct CellBox {
pub(crate) cell: usize,
}
pub(crate) fn cell_boxes(l: &DocLayout, page: usize) -> Vec<CellBox> {
/// Which of a page's tables the pointer reaches (#5558): the body's, with its text boxes' and
/// notes', while those are edited; a header's and footer's, with the text boxes in them, while
/// a header or footer (or a text box in one) is, and then not the dimmed body's.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Reach {
Body,
HeaderFooter,
}
impl Reach {
/// The reach while `editing` is edited, around `page` (where a text box's host is looked for).
pub fn of(l: &DocLayout, doc: &Document, editing: StoryRef, page: usize) -> Reach {
let kind = |s: StoryRef| match s {
StoryRef::Part(id) => doc.parts.get(&id).map(|p| p.kind),
StoryRef::Body => None,
};
let host = match editing {
StoryRef::Part(id) if kind(editing) == Some(PartKind::TextBox) => l.text_box(id, page).map_or(editing, |o| o.story),
_ => editing,
};
if matches!(kind(host), Some(PartKind::Header | PartKind::Footer)) { Reach::HeaderFooter } else { Reach::Body }
}
}
/// The table cells on a page that the pointer reaches ([`Reach`]).
pub(crate) fn cell_boxes_in(l: &DocLayout, page: usize, reach: Reach) -> Vec<CellBox> {
let Some(pg) = l.pages.get(page) else { return Vec::new() };
pg.items
.iter()
.filter_map(|it| match it {
Placed::Cell { rect, table, row, cell, story, .. } => {
Some(CellBox { rect: *rect, table: table.clone(), story: *story, row: *row, cell: *cell })
}
_ => None,
})
.collect()
let items: Box<dyn Iterator<Item = &Placed>> = match reach {
Reach::Body => Box::new(pg.items.iter()),
Reach::HeaderFooter => Box::new(pg.header.iter().chain(pg.footer.iter())),
};
items.filter_map(cell_box).collect()
}
/// The cells of `story`'s tables on a page, wherever that story is drawn.
pub(crate) fn story_cell_boxes(l: &DocLayout, page: usize, story: StoryRef) -> Vec<CellBox> {
let Some(pg) = l.pages.get(page) else { return Vec::new() };
pg.story_items(story).filter_map(cell_box).filter(|b| b.story == story).collect()
}
fn cell_box(it: &Placed) -> Option<CellBox> {
match it {
Placed::Cell { rect, table, row, cell, story, .. } => {
Some(CellBox { rect: *rect, table: table.clone(), story: *story, row: *row, cell: *cell })
}
_ => None,
}
}
/// The drawn geometry of one table on a page, from its cells' boxes.
@@ -403,8 +439,14 @@ fn geometry(t: &Table, boxes: &[&CellBox]) -> Option<(Vec<f32>, Vec<DrawnRow>)>
}
/// Every table drawn on a page, with its geometry there (`edge` is a placeholder).
#[cfg(test)]
pub(crate) fn tables_on(l: &DocLayout, doc: &Document, page: usize) -> Vec<ResizeTarget> {
let boxes = cell_boxes(l, page);
tables_on_in(l, doc, page, Reach::Body)
}
/// Every table drawn on a page that the pointer reaches ([`Reach`]).
pub(crate) fn tables_on_in(l: &DocLayout, doc: &Document, page: usize, reach: Reach) -> Vec<ResizeTarget> {
let boxes = cell_boxes_in(l, page, reach);
let mut tables: Vec<(StoryRef, &Path)> = Vec::new();
for b in &boxes {
if !tables.iter().any(|(s, p)| *s == b.story && **p == b.table) {
@@ -431,11 +473,17 @@ fn on_handle(t: &ResizeTarget, x: f32, y: f32, reach: f32) -> bool {
/// The innermost table under page point (`x`, `y`) whose resize handle is on this page, or whose
/// handle is under the point: the one whose handle the app shows.
pub fn table_under(l: &DocLayout, doc: &Document, page: usize, x: f32, y: f32, reach: f32) -> Option<ResizeTarget> {
table_under_in(l, doc, page, x, y, reach, Reach::Body)
}
/// [`table_under`] among the tables `tables` reaches: a header's or footer's while one is edited
/// (#5558).
pub fn table_under_in(l: &DocLayout, doc: &Document, page: usize, x: f32, y: f32, reach: f32, tables: Reach) -> Option<ResizeTarget> {
if !x.is_finite() || !y.is_finite() {
return None;
}
let reach = if reach.is_finite() { reach.clamp(0.5, 24.0) } else { REACH };
tables_on(l, doc, page)
tables_on_in(l, doc, page, tables)
.into_iter()
.filter(|t| t.ends_here && ((x >= t.left() && x <= t.right() && y >= t.top() && y <= t.bottom()) || on_handle(t, x, y, reach)))
.max_by_key(|t| t.table.0.len())
@@ -444,12 +492,18 @@ pub fn table_under(l: &DocLayout, doc: &Document, page: usize, x: f32, y: f32, r
/// The table border or resize handle within `reach` points of page point (`x`, `y`): the
/// nearest, and of nested tables the innermost.
pub fn resize_target(l: &DocLayout, doc: &Document, page: usize, x: f32, y: f32, reach: f32) -> Option<ResizeTarget> {
resize_target_in(l, doc, page, x, y, reach, Reach::Body)
}
/// [`resize_target`] among the tables `tables` reaches: a header's or footer's while one is
/// edited (#5558).
pub fn resize_target_in(l: &DocLayout, doc: &Document, page: usize, x: f32, y: f32, reach: f32, tables: Reach) -> Option<ResizeTarget> {
if !x.is_finite() || !y.is_finite() {
return None;
}
let reach = if reach.is_finite() { reach.clamp(0.5, 24.0) } else { REACH };
let mut best: Option<(f32, usize, ResizeTarget)> = None;
for mut target in tables_on(l, doc, page) {
for mut target in tables_on_in(l, doc, page, tables) {
let depth = target.table.0.len();
let mut offer = |d: f32, edge: Edge, target: &mut ResizeTarget| {
if d <= reach && best.as_ref().is_none_or(|(bd, bdepth, _)| d < *bd - 0.01 || (d <= *bd + 0.01 && depth > *bdepth)) {
@@ -500,8 +554,8 @@ fn resize_drag(s: &mut Session, v: &Value) -> CmdResult {
if l.pages.get(page).is_none() {
return Err(CmdError::Params(format!("no page {page}")));
}
let mut target =
resize_target(&l, &s.doc, page, x, y, reach).ok_or_else(|| CmdError::Failed("there's no table border or resize handle there".into()))?;
let mut target = resize_target_in(&l, &s.doc, page, x, y, reach, Reach::of(&l, &s.doc, s.sel.focus.story, page))
.ok_or_else(|| CmdError::Failed("there's no table border or resize handle there".into()))?;
target.limit_to_selection(s, y);
let plan = target.plan(to_x - x, to_y - y, share);
if plan.widths.is_none() && plan.heights.is_empty() && plan.cells.is_empty() {
@@ -647,7 +701,11 @@ fn regrid(t: &mut Table, cols: &[f32], rows: &[(usize, Vec<f32>)]) -> Result<(),
/// The page x of the target table's left edge on `page`, as drawn.
fn drawn_left(l: &DocLayout, page: usize, target: &ResizeTarget) -> Option<f32> {
cell_boxes(l, page).iter().filter(|b| b.story == target.story && b.table == target.table).map(|b| b.rect.x).min_by(f32::total_cmp)
story_cell_boxes(l, page, target.story)
.iter()
.filter(|b| b.story == target.story && b.table == target.table)
.map(|b| b.rect.x)
.min_by(f32::total_cmp)
}
/// Make `widths` (one per grid column) the table's column widths, as drawn: no preferred table
@@ -663,7 +721,7 @@ pub(crate) fn set_widths(t: &mut Table, widths: Vec<f32>) {
/// The drawn height of each of the target table's rows on `page`.
fn drawn_heights(l: &DocLayout, doc: &Document, page: usize, target: &ResizeTarget) -> Vec<(usize, f32)> {
tables_on(l, doc, page)
tables_on_in(l, doc, page, Reach::of(l, doc, target.story, page))
.into_iter()
.find(|t| t.story == target.story && t.table == target.table)
.map(|t| t.rows.iter().map(|r| (r.row, r.bottom - r.top)).collect())
+1 -1
View File
@@ -464,7 +464,7 @@ pub fn save_bytes_opts(name: &str, doc: &Document, opts: &ExportOptions) -> Resu
}
/// [`save_bytes`], encrypted with `password` when there is one and the format is a Word package
/// (other formats are copies and are written as they are).
/// or OpenDocument text file (.odt, .ott); other formats are copies and are written as they are.
pub fn save_bytes_with(name: &str, doc: &Document, password: Option<&str>, opts: &ExportOptions) -> Result<Vec<u8>, String> {
let bytes = save_bytes_opts(name, doc, opts)?;
match password {
+1 -1
View File
@@ -39,7 +39,7 @@ pub struct Prefs {
pub region: Option<String>,
/// A folder searched for Hunspell dictionaries before the system locations (File › Options ›
/// Language, #1063): an app started from Finder or the Dock doesn't see
/// `WORDCRAFT_DICTIONARIES`. `None` searches the system locations only.
/// `WORDCRAFT_DICTIONARIES`. `None` means no configured folder.
pub dictionaries_folder: Option<String>,
/// The user templates folder File › New lists personal templates from and Save as Word
/// Template starts in (File › Options › Advanced › File locations, #2852). `None`: the app's
+197
View File
@@ -1108,6 +1108,26 @@ fn replace_under_track_changes_skips_deleted_text() {
assert_eq!(text(&s), "one dog two dog");
}
#[test]
fn replace_reports_whether_it_replaced_and_what_it_selected() {
// Replace follows Word's button: the first call only selects a match. Agents read
// `remaining` alone as done (#6877), so the result says whether anything was replaced.
let mut s = s();
run(&mut s, "document.setText", json!({"text": "alpha XX beta XX gamma XX"}));
run(&mut s, "caret.docStart", json!({}));
let calls: Vec<_> = (0..5).map(|_| run(&mut s, "edit.replace", json!({"text": "XX", "with": "YY"}))).collect();
let replaced: Vec<_> = calls.iter().map(|r| r["replaced"].clone()).collect();
assert_eq!(replaced, [json!(0), json!(1), json!(1), json!(1), json!(0)]);
let remaining: Vec<_> = calls.iter().map(|r| r["remaining"].clone()).collect();
assert_eq!(remaining, [json!(3), json!(2), json!(1), json!(0), json!(0)]);
let selected: Vec<_> = calls.iter().map(|r| (r["selected"]["start"]["off"].clone(), r["selected"]["end"]["off"].clone())).collect();
assert_eq!(selected[0], (json!(6), json!(8)));
assert_eq!(selected[1], (json!(14), json!(16)));
assert_eq!(selected[2], (json!(23), json!(25)));
assert!(calls[3]["selected"].is_null() && calls[4]["selected"].is_null(), "no match is left to select");
assert_eq!(text(&s), "alpha YY beta YY gamma YY");
}
#[test]
fn find_reads_the_text_around_tracked_deletions() {
// `edits` are (start, end) byte ranges deleted with Track Changes on, last first.
@@ -13384,6 +13404,183 @@ fn page_down_extends_a_selection_that_ends_in_collapsed_outline_text() {
assert!(s.layout().caret(&s.sel.focus).is_some(), "to a place the outline shows");
}
/// #5558: a table in the header is edited like one in the body (typing in its cells, Table
/// Layout's rows and columns), and a table copied from the body is pasted into the header as a
/// table, not as its text.
#[test]
fn a_header_table_is_edited_and_a_copied_table_pastes_into_the_header() {
let mut s = s();
run(&mut s, "text.insert", json!({"text": "Body"}));
let id = run(&mut s, "insert.header", json!({"text": "Head"}))["story"].as_u64().unwrap() as u32;
let hf = StoryRef::Part(id);
run(&mut s, "insert.table", json!({"rows": 2, "cols": 2}));
assert_eq!(s.sel.focus.story, hf, "the caret stays in the header");
assert!(s.sel.focus.path.cell().is_some(), "the caret is in the new table: {:?}", s.sel.focus);
run(&mut s, "text.insert", json!({"text": "Cell"}));
run(&mut s, "table.insertRowBelow", json!({}));
run(&mut s, "table.insertColumnRight", json!({}));
let tables = |s: &Session| {
s.doc
.story(hf)
.map(|b| b.iter().filter_map(|b| b.as_table().map(|t| (t.rows.len(), t.rows[0].cells.len()))).collect::<Vec<_>>())
.unwrap_or_default()
};
assert_eq!(tables(&s), vec![(3, 3)]);
assert!(s.doc.plain_text(hf).contains("Cell"));
// Its column border drags, as a body table's does: the border is in the page's header.
let first = s.layout().pages[0].header.iter().find_map(|it| match it {
wordcraft_layout::Placed::Cell { rect, row: 0, cell: 0, story, .. } if *story == hf => Some(*rect),
_ => None,
});
let first = first.expect("the header's table is laid out");
let grid = |s: &Session| s.doc.story(hf).and_then(|b| b.iter().find_map(|b| b.as_table().map(|t| t.grid.clone()))).unwrap_or_default();
let before = grid(&s);
let (x, y) = (first.right(), first.y + first.h / 2.0);
run(&mut s, "table.resizeDrag", json!({"page": 0, "x": x, "y": y, "toX": x + 30.0, "toY": y}));
let after = grid(&s);
assert!(after[0] > before[0] + 20.0, "the header table's first column widened: {before:?} → {after:?}");
// While the body is edited, the dimmed header's table doesn't take the pointer.
assert!(crate::cmd::table_resize::resize_target_in(&s.layout(), &s.doc, 0, x, y, 4.0, crate::cmd::table_resize::Reach::Body).is_none());
// The Draw Table pen splits the header table's cell it crosses, as in the body.
let first = s.layout().pages[0].header.iter().find_map(|it| match it {
wordcraft_layout::Placed::Cell { rect, row: 0, cell: 0, story, .. } if *story == hf => Some(*rect),
_ => None,
});
let first = first.expect("the header's table is still laid out");
let mid = first.x + first.w / 2.0;
run(&mut s, "table.draw", json!({"page": 0, "x0": mid, "y0": first.y + 1.0, "x1": mid, "y1": first.bottom() - 1.0}));
assert_eq!(grid(&s).len(), 4, "the pen split a column of the header's table");
// A table copied from the body pastes into the header as a table.
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 4)}));
run(&mut s, "insert.table", json!({"rows": 1, "cols": 2}));
run(&mut s, "text.insert", json!({"text": "Copied"}));
run(&mut s, "table.selectTable", json!({}));
run(&mut s, "edit.copy", json!({}));
// The end of the header's "Head" paragraph, after its table.
let head = s.doc.story(hf).map_or(0, |b| b.len().saturating_sub(1));
let at = Pos { story: hf, path: wordcraft_doc::Path::top(head), off: 4 };
assert_eq!(s.doc.para_at(&at).map(|p| p.text.as_str()), Some("Head"));
run(&mut s, "caret.set", json!({"pos": at}));
run(&mut s, "edit.paste", json!({}));
let mut found = tables(&s);
found.sort();
assert_eq!(found, vec![(1, 2), (3, 4)], "{:?}", s.doc.story(hf));
assert!(s.doc.plain_text(hf).contains("Copied"));
}
/// #5558 review: a body text box and a footnote share the body's editing. With the caret in
/// one, the body's table still takes the pointer (border drags, the pen) and the dimmed header's
/// doesn't; with the caret in the footer, the footer's table takes it and the body's doesn't.
#[test]
fn body_tables_keep_the_pointer_from_a_text_box_or_a_note_and_a_footer_table_takes_it() {
use crate::cmd::table_resize::{Reach, resize_target_in};
use wordcraft_layout::Placed;
let mut s = s();
run(&mut s, "text.insert", json!({"text": "Body"}));
run(&mut s, "insert.table", json!({"rows": 2, "cols": 2}));
let head = run(&mut s, "insert.header", json!({"text": "Head"}))["story"].as_u64().unwrap() as u32;
run(&mut s, "insert.table", json!({"rows": 1, "cols": 2}));
let foot = run(&mut s, "insert.footer", json!({"text": "Foot"}))["story"].as_u64().unwrap() as u32;
run(&mut s, "insert.table", json!({"rows": 1, "cols": 2}));
run(&mut s, "insert.closeHeader", json!({}));
// The middle of the right border of `story`'s first cell on page 1.
let border = |s: &mut Session, story: StoryRef| {
let l = s.layout();
let pg = &l.pages[0];
let r = pg.items.iter().chain(&pg.header).chain(&pg.footer).find_map(|it| match it {
Placed::Cell { rect, row: 0, cell: 0, story: st, .. } if *st == story => Some(*rect),
_ => None,
});
let r = r.unwrap_or_else(|| panic!("{story:?}'s table is laid out"));
(r.right(), r.y + r.h / 2.0, r)
};
let grabbed = |s: &mut Session, (x, y): (f32, f32)| {
let l = s.layout();
let reach = Reach::of(&l, &s.doc, s.sel.focus.story, 0);
resize_target_in(&l, &s.doc, 0, x, y, 4.0, reach).map(|t| t.story)
};
let grid = |s: &Session, story: StoryRef| {
s.doc.story(story).and_then(|b| b.iter().find_map(|b| b.as_table().map(|t| t.grid.clone()))).unwrap_or_default()
};
// A text box in the body (the borders are measured once it is in).
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 0)}));
let boxed = run(&mut s, "insert.textBox", json!({"text": "in box"}))["story"].as_u64().unwrap() as u32;
assert_eq!(s.sel.focus.story, StoryRef::Part(boxed));
let (bx, by, _) = border(&mut s, StoryRef::Body);
let (hx, hy, _) = border(&mut s, StoryRef::Part(head));
assert_eq!(grabbed(&mut s, (bx, by)), Some(StoryRef::Body), "the body's table, from a body text box");
assert_eq!(grabbed(&mut s, (hx, hy)), None, "not the dimmed header's");
let before = grid(&s, StoryRef::Body);
run(&mut s, "table.resizeDrag", json!({"page": 0, "x": bx, "y": by, "toX": bx + 20.0, "toY": by}));
assert!(grid(&s, StoryRef::Body)[0] > before[0] + 10.0, "the drag widened the body's column");
// A footnote.
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 4)}));
run(&mut s, "references.footnote", json!({"text": "note"}));
let note = s.doc.parts.iter().find(|(_, p)| p.kind == wordcraft_doc::PartKind::Footnote).map(|(id, _)| *id).expect("the footnote's story");
run(&mut s, "caret.set", json!({"pos": Pos { story: StoryRef::Part(note), path: wordcraft_doc::Path::top(0), off: 0 }}));
let (bx, by, _) = border(&mut s, StoryRef::Body);
assert_eq!(grabbed(&mut s, (bx, by)), Some(StoryRef::Body), "the body's table, from a footnote");
assert_eq!(grabbed(&mut s, (hx, hy)), None);
// The pen still splits the body's cell it crosses instead of drawing a new table.
let (_, _, cell) = border(&mut s, StoryRef::Body);
let mid = cell.x + cell.w / 2.0;
let cols = grid(&s, StoryRef::Body).len();
run(&mut s, "table.draw", json!({"page": 0, "x0": mid, "y0": cell.y + 1.0, "x1": mid, "y1": cell.bottom() - 1.0}));
assert_eq!(grid(&s, StoryRef::Body).len(), cols + 1, "the pen split a body column");
// The footer, while it is edited: its table, not the body's.
run(&mut s, "caret.set", json!({"pos": Pos { story: StoryRef::Part(foot), path: wordcraft_doc::Path::top(0), off: 0 }}));
let (bx, by, _) = border(&mut s, StoryRef::Body);
let (fx, fy, _) = border(&mut s, StoryRef::Part(foot));
assert_eq!(grabbed(&mut s, (fx, fy)), Some(StoryRef::Part(foot)), "the footer's table, while the footer is edited");
assert_eq!(grabbed(&mut s, (bx, by)), None, "not the dimmed body's");
let before = grid(&s, StoryRef::Part(foot));
run(&mut s, "table.resizeDrag", json!({"page": 0, "x": fx, "y": fy, "toX": fx + 20.0, "toY": fy}));
assert!(grid(&s, StoryRef::Part(foot))[0] > before[0] + 10.0, "the drag widened the footer's column");
}
/// #5558 review: `table.eraser` and `table.draw` with a `story` work on that story's tables only:
/// a border of another story's table drawn there (a table in a body text box, among the body's
/// items) is left alone; the named story's own is erased.
#[test]
fn the_eraser_and_the_pen_keep_to_the_story_they_are_given() {
use wordcraft_layout::Placed;
let mut s = s();
run(&mut s, "text.insert", json!({"text": "Body"}));
run(&mut s, "insert.table", json!({"rows": 1, "cols": 2}));
// A text box in the body with a table of its own.
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 0)}));
let boxed = StoryRef::Part(run(&mut s, "insert.textBox", json!({"text": "Box"}))["story"].as_u64().unwrap() as u32);
run(&mut s, "insert.table", json!({"rows": 1, "cols": 2}));
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 0)}));
let first = |s: &mut Session, story: StoryRef| {
let l = s.layout();
let r = l.pages[0].items.iter().find_map(|it| match it {
Placed::Cell { rect, row: 0, cell: 0, story: st, .. } if *st == story => Some(*rect),
_ => None,
});
r.unwrap_or_else(|| panic!("{story:?}'s table is laid out"))
};
let cols = |s: &Session, story: StoryRef| {
s.doc.story(story).and_then(|b| b.iter().find_map(|b| b.as_table().map(|t| t.rows[0].cells.len()))).unwrap_or(0)
};
let body = serde_json::to_value(StoryRef::Body).unwrap();
// Named the body: the text box's table, though drawn among the body's items, is left alone.
let b = first(&mut s, boxed);
let erase = json!({"page": 0, "x": b.right(), "y": b.y + b.h / 2.0, "story": body.clone()});
assert!(s.run("table.eraser", &erase).is_err(), "no body border there");
let mid = b.x + b.w / 2.0;
let line = json!({"page": 0, "x0": mid, "y0": b.y + 1.0, "x1": mid, "y1": b.bottom() - 1.0, "story": body.clone()});
assert!(s.run("table.draw", &line).is_err(), "no body table to split there");
assert_eq!(cols(&s, boxed), 2, "the text box's table is as it was");
// The body's own border is erased.
let t = first(&mut s, StoryRef::Body);
run(&mut s, "table.eraser", json!({"page": 0, "x": t.right(), "y": t.y + t.h / 2.0, "story": body}));
assert_eq!(cols(&s, StoryRef::Body), 1, "the body table's two cells merged");
}
/// A picture an OpenDocument file gives no size is shown at its own, fitted to the text as other
/// formats' are; one with a stated size keeps it, in line too.
#[test]
+77 -51
View File
@@ -5,13 +5,40 @@ use wordcraft_doc::props::CharProps;
use crate::Session;
/// Creates a document with `lines` lines of text.
/// The bundled face the fixtures are set in. Their page counts are exact to a line, so they must
/// not depend on the face the host substitutes for the default Aptos: at 11 pt, Arial and
/// Liberation Sans fit 28 of these lines on a page and DejaVu Sans, the only candidate on a bare
/// FreeBSD system, fits 27. Inter is the bundled face whose metrics give each 0.5 pt step its own
/// page boundary at this page size.
const FIXTURE_FONT: &str = "Inter";
/// Creates a document with `lines` lines of text in [`FIXTURE_FONT`]. Inter fits 25 lines on a
/// page at 12 pt, 26 at 11.5 pt and 27 at 11 pt.
fn create_multiline_doc(lines: usize) -> Session {
let mut text = String::new();
for i in 1..=lines {
text.push_str(&format!("Line {i}: The quick brown fox jumps over the lazy dog.\n"));
}
Session::new(Document::from_text(&text))
let mut doc = Document::from_text(&text);
std::sync::Arc::make_mut(&mut doc.styles).default_chr.font = Some(FIXTURE_FONT.into());
Session::new(doc)
}
/// Asserts the body is laid out in the bundled [`FIXTURE_FONT`], not a substitute.
fn assert_fixture_font(s: &mut Session) {
let layout = s.layout();
let mut runs = 0;
for page in &layout.pages {
for item in &page.items {
if let wordcraft_layout::Placed::Lines { story: wordcraft_doc::StoryRef::Body, para, .. } = item {
for style in &para.styles {
runs += 1;
assert_eq!(style.face.family, FIXTURE_FONT, "the fixture must not fall back to another family");
}
}
}
}
assert!(runs > 0, "the font check must inspect laid-out body text");
}
#[test]
@@ -39,7 +66,7 @@ fn fit_one_page_fails_on_hard_page_break() {
#[test]
fn fit_one_page_refuses_page_break_before_before_search() {
let mut s = create_multiline_doc(27);
let mut s = create_multiline_doc(26);
assert_eq!(s.layout().pages.len(), 2);
if let wordcraft_doc::Block::Para(p) = std::sync::Arc::make_mut(&mut s.doc.body[1]) {
p.props.page_break_before = Some(true);
@@ -74,7 +101,7 @@ fn fit_one_page_fails_on_next_page_section_break() {
#[test]
fn fit_one_page_condenses_slight_overflow_and_undoes() {
// Find the boundary where the document just spills onto page 2
let mut lines = 30;
let mut lines = 20;
let mut s = create_multiline_doc(lines);
while s.layout().pages.len() < 2 && lines < 80 {
lines += 2;
@@ -102,7 +129,7 @@ fn fit_one_page_condenses_slight_overflow_and_undoes() {
#[test]
fn fit_one_page_respects_max_delta() {
let mut s = create_multiline_doc(27);
let mut s = create_multiline_doc(26);
assert_eq!(s.layout().pages.len(), 2, "must start as 2-page document");
let doc_backup = s.doc.clone();
@@ -117,11 +144,7 @@ fn fit_one_page_respects_max_delta() {
#[test]
fn fit_one_page_respects_step_pt() {
let mut text = String::new();
for i in 1..=28 {
text.push_str(&format!("Line {i}: The quick brown fox jumps over the lazy dog.\n"));
}
let mut s = Session::new(Document::from_text(&text));
let mut s = create_multiline_doc(27);
for b in &mut s.doc.body {
if let wordcraft_doc::Block::Para(p) = std::sync::Arc::make_mut(b) {
p.mark.size = Some(11.4);
@@ -131,6 +154,7 @@ fn fit_one_page_respects_step_pt() {
}
}
assert_eq!(s.layout().pages.len(), 2, "must start as 2-page document at 11.4 pt");
assert_fixture_font(&mut s);
// Both calls hold maxDeltaPt constant at 0.4 and disable spacing adjustments.
// Default 0.5 pt step generates no candidates <= 0.4 pt, so it must fail.
@@ -147,7 +171,7 @@ fn fit_one_page_respects_step_pt() {
#[test]
fn fit_one_page_allows_spacing_only_at_font_floor() {
let mut lines = 35;
let mut lines = 20;
let mut s = create_multiline_doc(lines);
let set_font = |s: &mut Session| {
for b in &mut s.doc.body {
@@ -178,7 +202,7 @@ fn fit_one_page_allows_spacing_only_at_font_floor() {
#[test]
fn fit_one_page_fails_when_body_font_already_at_minimum_readable_size() {
let mut lines = 35;
let mut lines = 20;
let mut s = create_multiline_doc(lines);
let set_font = |s: &mut Session| {
for b in &mut s.doc.body {
@@ -208,7 +232,7 @@ fn fit_one_page_fails_when_body_font_already_at_minimum_readable_size() {
#[test]
fn fit_one_page_bounds_fine_step_loop() {
let mut lines = 28;
let mut lines = 20;
let mut s = create_multiline_doc(lines);
while s.layout().pages.len() < 2 && lines < 80 {
lines += 1;
@@ -224,7 +248,7 @@ fn fit_one_page_bounds_fine_step_loop() {
#[test]
fn fit_one_page_supports_max_delta_above_2pt() {
let mut lines = 28;
let mut lines = 20;
let mut s = create_multiline_doc(lines);
while s.layout().pages.len() < 2 && lines < 80 {
lines += 1;
@@ -244,7 +268,7 @@ fn fit_one_page_supports_max_delta_above_2pt() {
#[test]
fn fit_one_page_anti_compound_guard_prevents_repeated_invocations() {
let mut lines = 28;
let mut lines = 20;
let mut s = create_multiline_doc(lines);
loop {
for b in &mut s.doc.body {
@@ -314,7 +338,7 @@ fn fit_one_page_already_fits_wins_over_exhausted_budget() {
#[test]
fn fit_one_page_checks_complex_script_font_floor() {
let mut lines = 28;
let mut lines = 20;
let mut s = create_multiline_doc(lines);
while s.layout().pages.len() < 2 && lines < 80 {
lines += 1;
@@ -340,7 +364,7 @@ fn fit_one_page_checks_complex_script_font_floor() {
#[test]
fn fit_one_page_checks_editable_text_box_font_floor() {
let mut lines = 28;
let mut lines = 20;
let mut s = create_multiline_doc(lines);
while s.layout().pages.len() < 2 && lines < 80 {
lines += 1;
@@ -386,7 +410,7 @@ fn fit_one_page_checks_editable_text_box_font_floor() {
#[test]
fn fit_one_page_fails_when_overflow_exceeds_limits() {
let mut lines = 28;
let mut lines = 20;
let mut s = create_multiline_doc(lines);
while s.layout().pages.len() < 2 {
lines += 1;
@@ -566,7 +590,7 @@ fn fit_one_page_fails_with_failed_cmd_error() {
#[test]
fn fit_one_page_never_populates_custom_props() {
let mut lines = 30;
let mut lines = 20;
let mut s = create_multiline_doc(lines);
while s.layout().pages.len() < 2 && lines < 80 {
lines += 2;
@@ -582,7 +606,7 @@ fn fit_one_page_never_populates_custom_props() {
fn fit_one_page_allows_subsequent_fit_after_typography_reset() {
use std::sync::Arc;
let mut lines = 28;
let mut lines = 20;
let mut s = create_multiline_doc(lines);
while s.layout().pages.len() < 2 && lines < 80 {
lines += 1;
@@ -625,7 +649,7 @@ fn fit_one_page_allows_subsequent_fit_after_typography_reset() {
#[test]
fn fit_one_page_small_paragraph_mark_with_runs_never_blocks_fit() {
let mut lines = 30;
let mut lines = 20;
let mut s = create_multiline_doc(lines);
while s.layout().pages.len() < 2 && lines < 80 {
lines += 2;
@@ -646,7 +670,7 @@ fn fit_one_page_small_paragraph_mark_with_runs_never_blocks_fit() {
#[test]
fn fit_one_page_small_comment_font_never_blocks_body_fit() {
let mut lines = 30;
let mut lines = 20;
let mut s = create_multiline_doc(lines);
while s.layout().pages.len() < 2 && lines < 80 {
lines += 2;
@@ -666,7 +690,7 @@ fn fit_one_page_small_comment_font_never_blocks_body_fit() {
#[test]
fn fit_one_page_anti_compound_caps_total_reduction_across_runs() {
let mut s = create_multiline_doc(27);
let mut s = create_multiline_doc(26);
assert_eq!(s.layout().pages.len(), 2);
// Initial fit with -0.5 pt font reduction (spacing disabled so font budget is exercised)
@@ -688,7 +712,7 @@ fn fit_one_page_anti_compound_caps_total_reduction_across_runs() {
#[test]
fn fit_one_page_tracks_reduced_text_provenance_without_global_minimum() {
let mut s = create_multiline_doc(27);
let mut s = create_multiline_doc(26);
// Add a 9.0 pt run to the first paragraph alongside 11.0 pt runs
if let wordcraft_doc::Block::Para(p) = std::sync::Arc::make_mut(&mut s.doc.body[0]) {
p.runs.push(wordcraft_doc::para::Run { len: 5, props: CharProps { size: Some(9.0), ..Default::default() } });
@@ -725,7 +749,7 @@ fn fit_one_page_tracks_reduced_text_provenance_without_global_minimum() {
#[test]
fn fit_one_page_allows_spill_with_bottom_placed_footnote() {
let mut lines = 28;
let mut lines = 20;
let mut s = create_multiline_doc(lines);
while s.layout().pages.len() < 2 && lines < 80 {
lines += 1;
@@ -751,7 +775,7 @@ fn fit_one_page_allows_spill_with_bottom_placed_footnote() {
#[test]
fn fit_one_page_with_final_page_footnote() {
let mut lines = 28;
let mut lines = 20;
let mut s = create_multiline_doc(lines);
while s.layout().pages.len() < 2 && lines < 80 {
lines += 1;
@@ -784,7 +808,7 @@ fn fit_one_page_with_final_page_footnote() {
#[test]
fn fit_one_page_skips_deleted_text_when_markup_hidden() {
let mut s = create_multiline_doc(27);
let mut s = create_multiline_doc(26);
assert_eq!(s.layout().pages.len(), 2);
// Insert a deleted text run with small font (e.g. 6.0 pt, below the 8.5 pt floor)
@@ -815,7 +839,7 @@ fn fit_one_page_skips_deleted_text_when_markup_hidden() {
#[test]
fn fit_one_page_tracks_reduced_complex_script_font_sizes() {
let mut s = create_multiline_doc(27);
let mut s = create_multiline_doc(26);
assert_eq!(s.layout().pages.len(), 2);
let styles_before = s.doc.styles.clone();
@@ -853,8 +877,9 @@ fn fit_one_page_tracks_reduced_complex_script_font_sizes() {
#[test]
fn fit_one_page_preserves_budget_across_document_serialization() {
let mut s = create_multiline_doc(27);
let mut s = create_multiline_doc(26);
assert_eq!(s.layout().pages.len(), 2);
assert_fixture_font(&mut s);
// Apply fit
let res = s.run("layout.fitOnePage", &json!({"maxDeltaPt": 0.5, "adjustSpacing": false}));
@@ -900,7 +925,7 @@ fn fit_one_page_enforces_durable_limit_when_fit_state_missing() {
s.touch();
s.relayout();
};
let mut lines = 27;
let mut lines = 20;
let mut s = create_multiline_doc(lines);
set_font(&mut s);
while s.layout().pages.len() < 2 && lines < 120 {
@@ -924,7 +949,7 @@ fn fit_one_page_enforces_durable_limit_when_fit_state_missing() {
#[test]
fn fit_one_page_skips_hidden_text_when_hidden_marks_off() {
let mut s = create_multiline_doc(27);
let mut s = create_multiline_doc(26);
assert_eq!(s.layout().pages.len(), 2);
// Insert a hidden text run with small font (6.0 pt, below the 8.5 pt floor) into an existing paragraph
@@ -958,7 +983,7 @@ fn fit_one_page_skips_hidden_text_when_hidden_marks_off() {
#[test]
fn fit_one_page_accounts_for_vertical_alignment_padding() {
let mut s = create_multiline_doc(26);
let mut s = create_multiline_doc(25);
let extra_p = wordcraft_doc::Paragraph::with_text("Spill line on page 2.", CharProps::default());
s.doc.body.push(wordcraft_doc::para_block(extra_p));
@@ -977,7 +1002,7 @@ fn fit_one_page_accounts_for_vertical_alignment_padding() {
#[test]
fn fit_one_page_accounts_for_note_separator_decor_story() {
let mut lines = 28;
let mut lines = 20;
let mut s = create_multiline_doc(lines);
while s.layout().pages.len() < 2 && lines < 80 {
lines += 1;
@@ -1012,7 +1037,7 @@ fn fit_one_page_accounts_for_note_separator_decor_story() {
#[test]
fn fit_one_page_tracks_fixed_spacing_independent_of_paragraph_mark_size() {
let mut lines = 28;
let mut lines = 20;
let mut s = create_multiline_doc(lines);
let set_spacing = |s: &mut Session| {
for b in &mut s.doc.body {
@@ -1053,7 +1078,7 @@ fn fit_one_page_tracks_fixed_spacing_independent_of_paragraph_mark_size() {
#[test]
fn fit_one_page_reports_search_exhaustion_when_candidates_cannot_remove_page() {
let mut s = create_multiline_doc(27);
let mut s = create_multiline_doc(26);
assert_eq!(s.layout().pages.len(), 2);
// Calling with zero maxDeltaPt and adjustSpacing: false produces no candidate steps
@@ -1068,23 +1093,24 @@ fn fit_one_page_reports_search_exhaustion_when_candidates_cannot_remove_page() {
#[test]
fn fit_one_page_excludes_line_number_decorations_from_final_page_limits() {
let mut lines = 33;
let enable_line_numbers = |s: &mut Session| {
s.doc.last_section.line_numbers = Some(wordcraft_doc::section::LineNumbering::default());
s.touch();
s.relayout();
};
let mut s = create_multiline_doc(lines);
enable_line_numbers(&mut s);
while s.layout().pages.len() < 2 && lines < 60 {
lines += 1;
s = create_multiline_doc(lines);
enable_line_numbers(&mut s);
}
let mut s = create_multiline_doc(33);
s.doc.last_section.line_numbers = Some(wordcraft_doc::section::LineNumbering::default());
s.touch();
s.relayout();
assert_eq!(s.layout().pages.len(), 2);
// Every body line on the final page also places a line-number decoration. Counting those as
// content would double the final-page line count and refuse before any candidate is tried.
// content would double the final-page line count and refuse before any candidate is tried:
// between 7 and 12 body lines are within the 12-line limit, and twice as many are not.
let body_lines: usize = s.layout().pages[1]
.items
.iter()
.map(|item| match item {
wordcraft_layout::Placed::Lines { story: wordcraft_doc::StoryRef::Body, l0, l1, .. } => l1 - l0,
_ => 0,
})
.sum();
assert!((7..=12).contains(&body_lines), "the final page must carry 7 to 12 body lines, has {body_lines}");
let decorated = s.layout().pages[1]
.items
.iter()
@@ -1099,7 +1125,7 @@ fn fit_one_page_excludes_line_number_decorations_from_final_page_limits() {
#[test]
fn fit_one_page_counts_side_by_side_footnote_cells_once() {
let mut s = create_multiline_doc(27);
let mut s = create_multiline_doc(26);
assert_eq!(s.layout().pages.len(), 2);
// A footnote table whose row's cells sit side by side: their text occupies one vertical
@@ -1134,7 +1160,7 @@ fn fit_one_page_counts_side_by_side_footnote_cells_once() {
#[test]
fn fit_one_page_refuses_when_formatting_changes_cannot_be_tracked() {
let mut s = create_multiline_doc(27);
let mut s = create_multiline_doc(26);
assert_eq!(s.layout().pages.len(), 2);
s.doc.settings.track_changes = true;
s.prefs.markup.track_formatting = true;
+7 -1
View File
@@ -63,7 +63,13 @@ impl std::fmt::Display for UserFontError {
match self {
UserFontError::Empty => write!(f, "the font file is empty"),
UserFontError::TooLarge { bytes } => {
write!(f, "the font file is too large ({} MB; at most {} MB)", bytes.div_ceil(1 << 20), MAX_FONT_FILE_BYTES >> 20)
write!(
f,
"the font is too large ({} MB; file limit {} MB, unpacked limit {} MB)",
bytes.div_ceil(1 << 20),
MAX_FONT_FILE_BYTES >> 20,
MAX_DECODED_BYTES >> 20
)
}
UserFontError::NotAFont => write!(f, "not a font file (TrueType, OpenType, TTC, WOFF or WOFF2)"),
UserFontError::BadWebFont(e) => write!(f, "the web font couldn't be read: {e}"),
+6 -2
View File
@@ -210,7 +210,9 @@ fn woff1_claiming(orig: u32) -> Vec<u8> {
fn a_woff_claiming_a_huge_table_is_refused_before_inflating() {
// #3703: the decoder sizes a table's buffer from the directory before inflating it.
for orig in [200 << 20, u32::MAX] {
assert!(matches!(decode_font_file(&woff1_claiming(orig)), Err(UserFontError::TooLarge { .. })), "{orig}");
let error = decode_font_file(&woff1_claiming(orig)).unwrap_err();
assert!(matches!(&error, UserFontError::TooLarge { .. }), "{orig}");
assert!(error.to_string().contains("unpacked limit 128 MB"), "{error}");
}
// A small claim reaches the decoder, which finds the data doesn't inflate to it.
assert!(matches!(decode_font_file(&woff1_claiming(64)), Err(UserFontError::BadWebFont(_))));
@@ -311,7 +313,9 @@ fn junk_is_rejected_without_adding_anything() {
assert_eq!(db.families().len(), n + db.user_fonts().iter().map(|u| u.families().len()).sum::<usize>());
let mut big = regular.clone();
big.resize(MAX_FONT_FILE_BYTES + 1, 0);
assert!(matches!(db.install_font("big.ttf", &big), Err(UserFontError::TooLarge { .. })));
let error = db.install_font("big.ttf", &big).unwrap_err();
assert!(matches!(&error, UserFontError::TooLarge { .. }));
assert!(error.to_string().contains("file limit 50 MB"), "{error}");
}
#[test]
+1 -1
View File
@@ -307,7 +307,7 @@ fn decode_alpha(bytes: &[u8], decoded: &mut u64) -> Result<Option<Alpha>, OverBu
fn alpha_in_crop(img: &Alpha, crop: [f32; 4]) -> Option<Vec<(f32, f32)>> {
let (iw, ih) = (img.w, img.h);
// The part the renderers draw (#1899): a sliver keeps its partly covered pixels.
let [cl, ct, vw, vh] = craft_metafile::crop_window(crop);
let [cl, ct, vw, vh] = crate::crop_window(crop);
let (fw, fh) = (f64::from(iw), f64::from(ih));
let x0 = ((fw * cl) as u32).min(iw);
let y0 = ((fh * ct) as u32).min(ih);
+53 -4
View File
@@ -470,12 +470,41 @@ fn character_backgrounds(ctx: &LineContext<'_, '_, '_>, out: &mut Vec<Draw>) {
}
fn draw_label_and_hyphen(ctx: &LineContext<'_, '_, '_>, out: &mut Vec<Draw>) {
// A list number goes with its paragraph mark: when the mark is a tracked deletion the number
// is drawn as deleted text is, in the deletion's colour and with its mark (struck through by
// default, a caret, #s, bold…), and not at all where deletions aren't shown (#4828). Only
// when the item is deleted whole, its text too: a deleted mark alone joins the item to the
// next one, and its text and number stay as they are.
let m = &ctx.opts.revisions;
let whole = ctx.para.is_some_and(|p| p.runs.iter().all(|r| r.len == 0 || r.props.del.is_some()));
let mark_del = ctx.para.filter(|_| whole).and_then(|p| p.mark.del);
let moved = mark_del.is_some() && ctx.doc.move_name(mark_del).is_some();
let hidden = mark_del.is_some() && (!ctx.opts.markup || m.hides_deletion(moved));
let deleted = mark_del.filter(|_| ctx.opts.markup && m.insertions_deletions);
let del_mark = deleted.map(|_| if moved { m.move_from_mark } else { m.delete_mark });
// Moved-away text marked (none) is plain text, and so is its number.
let plain_move = moved && del_mark == Some(DeleteMark::None);
let del_color =
deleted.filter(|_| !plain_move).map(|r| if moved { m.move_from_color } else { m.delete_color }.unwrap_or_else(|| ctx.authors.color(r)));
if ctx.li == ctx.pl.label_line()
&& !hidden
&& let Some(label) = &ctx.pl.label
{
let gx = ctx.x + label.x;
let first = label.runs.first().and_then(|r| ctx.pl.styles.get(r.style as usize));
if let (Some(DeleteMark::Caret), Some(color), Some(style)) = (del_mark, del_color, first) {
// A caret where the number was, instead of the number.
let (h, w, y) = (style.size * 0.3, (style.size / 18.0).max(0.6), ctx.base + 1.0);
for (x0, y0, x1, y1) in [(gx - h * 0.6, y, gx, y - h), (gx, y - h, gx + h * 0.6, y)] {
out.push(Draw::Line { x0, y0, x1, y1, width: w, color, stroke: Stroke::Solid, alpha: ctx.alpha, text_bg: None });
}
return draw_hyphen(ctx, out);
}
for run in &label.runs {
let Some(style) = ctx.pl.styles.get(run.style as usize) else { continue };
let color = del_color.unwrap_or_else(|| ctx.ink(&style.rc.color, None));
// Each deleted character shows as #.
let hash = (del_mark == Some(DeleteMark::Hash)).then(|| style.face.glyph_for('#'));
out.push(Draw::Glyphs {
face: style.face,
size: style.size,
@@ -484,12 +513,12 @@ fn draw_label_and_hyphen(ctx: &LineContext<'_, '_, '_>, out: &mut Vec<Draw>) {
.get(run.glyphs.clone())
.into_iter()
.flatten()
.map(|g| (g.gid, gx + g.dx, ctx.base - style.shift - g.dy))
.map(|g| (hash.unwrap_or(g.gid), gx + g.dx, ctx.base - style.shift - g.dy))
.collect(),
color: ctx.ink(&style.rc.color, None),
color,
alpha: ctx.alpha,
synth_bold: style.synth_bold,
synth_italic: style.synth_italic,
synth_bold: style.synth_bold || del_mark == Some(DeleteMark::Bold),
synth_italic: style.synth_italic || del_mark == Some(DeleteMark::Italic),
text: run.text.clone(),
link: None,
ranges: Vec::new(),
@@ -497,7 +526,27 @@ fn draw_label_and_hyphen(ctx: &LineContext<'_, '_, '_>, out: &mut Vec<Draw>) {
x_scale: 1.0,
});
}
// Struck through or underlined once, across the whole number, in its first run's size.
if let (Some(color), Some(mark), Some(style)) = (del_color, del_mark, first) {
let strike_y = ctx.base - style.shift - style.size * 0.28;
let under_y = ctx.base - style.shift + style.size * 0.12;
let line = match mark {
DeleteMark::Strikethrough => Some((strike_y, Stroke::Solid)),
DeleteMark::DoubleStrikethrough => Some((strike_y, Stroke::Double)),
DeleteMark::Underline => Some((under_y, Stroke::Solid)),
DeleteMark::DoubleUnderline => Some((under_y, stroke_of(Underline::Double))),
_ => None,
};
if let Some((y, stroke)) = line {
let width = (style.size / 18.0).max(0.5);
out.push(Draw::Line { x0: gx, y0: y, x1: gx + label.width, y1: y, width, color, stroke, alpha: ctx.alpha, text_bg: None });
}
}
}
draw_hyphen(ctx, out);
}
fn draw_hyphen(ctx: &LineContext<'_, '_, '_>, out: &mut Vec<Draw>) {
if let Some((style_index, glyph, advance)) = ctx.line.hyphen
&& let Some(style) = ctx.pl.styles.get(style_index as usize)
{
+10 -7
View File
@@ -264,18 +264,21 @@ impl<'a> PartPages<'a> {
/// The items of `page` that `story`'s pieces are among (each one looked at counted as a step of
/// [`crate::work`]).
fn items_of(page: &Page, story: StoryRef) -> Box<dyn Iterator<Item = &Placed> + '_> {
let items = story_items(page, story);
let items = page.story_items(story);
#[cfg(test)]
let items: Box<dyn Iterator<Item = &Placed> + '_> = Box::new(items.inspect(|_| crate::work::steps(1)));
items
}
fn story_items(page: &Page, story: StoryRef) -> Box<dyn Iterator<Item = &Placed> + '_> {
match story {
StoryRef::Body => Box::new(page.items.iter()),
// Headers and footers, and the text boxes in them, are drawn with the page's header and
// footer; everything else is in its items.
StoryRef::Part(_) => Box::new(page.header.iter().chain(page.footer.iter()).chain(page.items.iter())),
impl Page {
/// The items `story`'s pieces are among: the page's items for the body; for a header,
/// footer or text box, its header and footer too (they hold the header's and footer's
/// pieces, and the text boxes in them).
pub fn story_items(&self, story: StoryRef) -> Box<dyn Iterator<Item = &Placed> + '_> {
match story {
StoryRef::Body => Box::new(self.items.iter()),
StoryRef::Part(_) => Box::new(self.header.iter().chain(self.footer.iter()).chain(self.items.iter())),
}
}
}
+2
View File
@@ -59,6 +59,7 @@ mod ctx;
mod floats;
mod flow;
mod headers;
mod metafile;
mod missing;
mod notes;
mod page;
@@ -85,6 +86,7 @@ use headers::MAX_HEADER_ITEMS;
#[cfg(test)]
use headers::placed_cost;
use headers::placed_cost_by;
pub use metafile::{MAX_METAFILE_DASHES, crop_sides, crop_window, metafile_average_color, metafile_dashes, metafile_miter_limit};
pub use missing::{MAX_MISSING_GLYPHS, MissingGlyphs, metafile_text_run, missing_watermark_glyphs, watermark_run};
pub use notes::DECOR_STORY;
pub(crate) use notes::NOTE_SEP_W;
+75
View File
@@ -0,0 +1,75 @@
//! Drawing rules the page renderer and the PDF export share for metafile pictures and picture
//! crops, so the two outputs draw the same file the same way.
/// Most dashes and gaps one metafile stroke is split into. A path that a pen's pattern would split
/// into more draws solid.
pub const MAX_METAFILE_DASHES: f64 = 100_000.0;
/// The crop sides a picture is drawn with: each side of `crop` (left, top, right, bottom fractions
/// of the source) at least 0. A negative side draws as no crop, not as padding around the source.
pub fn crop_sides(crop: [f32; 4]) -> [f32; 4] {
crop.map(|v| if v.is_finite() { v.max(0.0) } else { 0.0 })
}
/// The part of a picture's source that `crop` keeps, as fractions of the source: [left, top,
/// width, height] (`craft_metafile::crop_window` of [`crop_sides`]).
pub fn crop_window(crop: [f32; 4]) -> [f64; 4] {
craft_metafile::crop_window(crop_sides(crop))
}
/// The miter limit a metafile pen is drawn with: its own when it is finite and at least 1,
/// otherwise 10.
pub fn metafile_miter_limit(limit: f32) -> f32 {
if limit.is_finite() && limit >= 1.0 { limit } else { 10.0 }
}
/// The dash lengths (page points) a metafile pen draws a path `length` points long with, or None
/// for a solid line. `dash` is the placed pen's pattern (`craft_metafile::LineStyle::dash`, page
/// points) and `pixel` is one output pixel in points.
///
/// A cosmetic pen (`cosmetic`: width 0) has its pattern scaled so that its shortest dash or gap is
/// one pixel, at any zoom. A pattern with a negative or non-finite length draws solid, and so does
/// one whose period is shorter than a pixel or that would split the path into more than
/// [`MAX_METAFILE_DASHES`] dashes and gaps.
pub fn metafile_dashes(dash: &[f32], cosmetic: bool, pixel: f64, length: f64) -> Option<Vec<f64>> {
if dash.is_empty() || !pixel.is_finite() || pixel <= 0.0 {
return None;
}
let mut out: Vec<f64> = dash.iter().map(|d| f64::from(*d)).collect();
if !out.iter().all(|d| d.is_finite() && *d >= 0.0) {
return None;
}
if cosmetic {
let shortest = out.iter().copied().filter(|d| *d > 0.0).fold(f64::INFINITY, f64::min);
if !shortest.is_finite() {
return None;
}
let k = pixel / shortest;
out.iter_mut().for_each(|d| *d *= k);
}
let period: f64 = out.iter().sum();
if !period.is_finite() || period < pixel {
return None;
}
// Each length of the pattern starts a new dash or gap.
let pieces = out.len() as f64 * if length.is_finite() { length.max(0.0) / period } else { f64::INFINITY };
(pieces <= MAX_METAFILE_DASHES).then_some(out)
}
/// The alpha-weighted average color of straight RGBA pixels (transparent when there are none): a
/// metafile pattern fill whose tile is too small to show is filled with it.
pub fn metafile_average_color(px: &[u8]) -> [u8; 4] {
let (mut r, mut g, mut b, mut a, mut n) = (0u64, 0u64, 0u64, 0u64, 0u64);
for p in px.as_chunks::<4>().0 {
let w = u64::from(p[3]);
r += u64::from(p[0]) * w;
g += u64::from(p[1]) * w;
b += u64::from(p[2]) * w;
a += w;
n += 1;
}
if a == 0 || n == 0 {
return [0; 4];
}
[(r / a) as u8, (g / a) as u8, (b / a) as u8, (a / n) as u8]
}
+36 -13
View File
@@ -151,13 +151,37 @@ pub fn watermark_run(wm: &wordcraft_doc::Watermark, max_chars: usize) -> Option<
/// in the face its font name resolves to (no fallback face), so a character that face lacks shapes
/// to glyph id 0. Strict export checks these same glyphs, so the check and the exporters can't
/// drift.
pub fn metafile_text_run(t: &craft_metafile::Text) -> (wordcraft_fonts::FaceRef, Vec<ShapedGlyph>) {
let family = t.font.family.trim();
let family = if family.is_empty() { METAFILE_DEFAULT_FONT } else { family };
let face = wordcraft_fonts::word::resolve(family, t.font.weight >= 600, t.font.italic).face;
let shaped = wordcraft_fonts::shape(&face, &t.text, &[], |c| c);
(face, shaped)
}
/// The face a metafile font with no face name is drawn in.
const METAFILE_DEFAULT_FONT: &str = "Arial";
/// The cell height (text units) of a metafile font whose height is 0, the file's default size.
const METAFILE_DEFAULT_HEIGHT: f64 = 16.0;
/// A metafile text run laid out with a font's metrics: the em size (text units), the baseline's y
/// and each glyph's (x, y), alignment included, in the run's text space (see
/// `craft_metafile::Text::transform`).
pub struct MetafileTextLayout {
pub em: f64,
pub baseline: f64,
pub glyphs: Vec<(f64, f64)>,
/// The rectangle of the character cells (x0, y0, x1, y1): from the leftmost to the rightmost
/// pen position of the run, the font's ascent above the baseline and its descent below. An
/// opaque background fills it.
pub cell: [f64; 4],
}
/// Lay out shaped glyphs for a metafile text run.
/// Lays out the shaped glyphs of `t`, given as (cluster byte offset, x advance, x offset, y offset)
/// in font units of a font with `upem` units per em, `ascent` above and `descent` below the
/// baseline. The font height is the em size when negative and the cell height (ascent plus
/// descent) when positive. The per-character advances `dx` place each cluster when there is one
/// per character. None when the size is not finite and positive.
pub fn layout_metafile_text(
t: &craft_metafile::Text,
upem: f64,
@@ -166,10 +190,9 @@ pub fn layout_metafile_text(
glyphs: &[(usize, f64, f64, f64)],
) -> Option<MetafileTextLayout> {
let upem = if upem.is_finite() && upem > 0.0 { upem } else { 1000.0 };
let cell_h = ascent + descent;
let size = if t.font.height == 0.0 { 12.0 } else { f64::from(t.font.height.abs()) };
let cell = t.font.height > 0.0;
let em = if cell && cell_h.is_finite() && cell_h > 0.0 { size * upem / cell_h } else { size };
let height = if t.font.height == 0.0 { METAFILE_DEFAULT_HEIGHT } else { f64::from(t.font.height) };
let cell = ascent + descent;
let em = if height > 0.0 && cell.is_finite() && cell > 0.0 { height * upem / cell } else { height.abs() };
if !em.is_finite() || em <= 0.0 {
return None;
}
@@ -187,6 +210,8 @@ pub fn layout_metafile_text(
});
let mut out = Vec::with_capacity(glyphs.len());
let (mut pen, mut cluster_pen, mut last) = (0.0, 0.0, None);
// The leftmost and rightmost pen positions: advances can move backward.
let (mut lo, mut hi) = (0.0f64, 0.0f64);
for &(cluster, adv, xo, yo) in glyphs {
let ci = starts.partition_point(|&b| b <= cluster).saturating_sub(1);
if last != Some(ci) {
@@ -199,6 +224,10 @@ pub fn layout_metafile_text(
};
out.push((x + xo * k, -yo * k));
pen += adv * k;
(lo, hi) = (lo.min(pen), hi.max(pen));
}
if let Some(cum) = &dx {
(lo, hi) = cum.iter().fold((0.0f64, 0.0f64), |(l, h), x| (l.min(*x), h.max(*x)));
}
let width = dx.as_ref().and_then(|c| c.last().copied()).unwrap_or(pen);
let hoff = match t.h_align {
@@ -212,14 +241,8 @@ pub fn layout_metafile_text(
craft_metafile::VAlign::Bottom => -descent * k,
};
let glyphs = out.into_iter().map(|(x, y)| (x + hoff, y + baseline)).collect();
Some(MetafileTextLayout { em, baseline, glyphs })
}
pub fn metafile_text_run(t: &craft_metafile::Text) -> (wordcraft_fonts::FaceRef, Vec<ShapedGlyph>) {
let bold = t.font.weight >= 600;
let face = wordcraft_fonts::word::resolve(&t.font.family, bold, t.font.italic).face;
let shaped = wordcraft_fonts::shape(&face, &t.text, &[], |c| c);
(face, shaped)
let cell = [hoff + lo, baseline - ascent * k, hoff + hi, baseline + descent * k];
Some(MetafileTextLayout { em, baseline, glyphs, cell })
}
/// The characters of the watermark that draw as an empty box (glyph id 0), counted as
+102
View File
@@ -1997,6 +1997,108 @@ fn break_only_list_has_no_label() {
}
}
/// #4828: a list item deleted whole (its text and its mark) under Track Changes shows its number
/// as deleted text, in the deletion's colour and struck through, with markup shown; without
/// markup the number is drawn no more than the text.
#[test]
fn a_deleted_list_items_number_is_drawn_as_deleted_text() {
let mut d = Document::from_text("Intro\nChapter two\nBody");
d.revisions.push(wordcraft_doc::Revision {
kind: wordcraft_doc::RevisionKind::Delete,
author: "Ana".into(),
date: String::new(),
move_name: None,
});
let id = std::sync::Arc::make_mut(&mut d.numbering).add_list(wordcraft_doc::ListKind::Numbered);
d.format_paragraphs(&Pos::body(1, 0), &Pos::body(1, 3), &|p| p.numbering = Some(wordcraft_doc::props::NumRef { num: id, level: 0 })).unwrap();
d.format_range(&Pos::body(1, 0), &Pos::body(1, 11), &|c| c.del = Some(0)).unwrap();
d.para_mut(StoryRef::Body, &Path::top(1)).unwrap().mark.del = Some(0);
let l = lay(&d);
let draws = |markup: bool| display::page_display(&d, &l.pages[0], &display::DisplayOptions { markup, ..Default::default() });
let glyph_color = |items: &[display::Draw], want: &str| {
items.iter().find_map(|i| match i {
display::Draw::Glyphs { text, color, glyphs, .. } if text.contains(want) => Some((*color, glyphs.first().map_or(0.0, |g| g.1))),
_ => None,
})
};
let marked = draws(true);
let (number, nx) = glyph_color(&marked, "1.").expect("the number is drawn with markup");
let (text, _) = glyph_color(&marked, "Chapter").expect("the deleted text is drawn with markup");
assert_eq!(number, text, "the number takes the deletion's colour");
let struck = marked
.iter()
.any(|i| matches!(i, display::Draw::Line { x0, x1, y0, y1, .. } if (y0 - y1).abs() < 0.01 && *x0 <= nx + 0.01 && *x1 > nx + 1.0));
assert!(struck, "the number is struck through");
// The number takes the other deletion marks as its text does.
let with_mark = |mark: display::DeleteMark| {
let mut o = display::DisplayOptions { markup: true, ..Default::default() };
o.revisions.delete_mark = mark;
display::page_display(&d, &l.pages[0], &o)
};
let caret = with_mark(display::DeleteMark::Caret);
assert!(glyph_color(&caret, "1.").is_none(), "a caret replaces the number");
assert!(caret.iter().any(|i| matches!(i, display::Draw::Line { x1, .. } if (*x1 - nx).abs() < 0.01)), "the caret is where the number was");
let bold = with_mark(display::DeleteMark::Bold);
assert!(bold.iter().any(|i| matches!(i, display::Draw::Glyphs { text, synth_bold: true, .. } if text.contains("1."))));
let hashed = with_mark(display::DeleteMark::Hash);
let ids = |items: &[display::Draw], want: &str| {
items.iter().find_map(|i| match i {
display::Draw::Glyphs { text, glyphs, .. } if text.contains(want) => Some(glyphs.iter().map(|g| g.0).collect::<Vec<_>>()),
_ => None,
})
};
let (numbers, hashes) = (ids(&marked, "1.").unwrap(), ids(&hashed, "1.").unwrap());
assert!(hashes.len() == numbers.len() && hashes.windows(2).all(|w| w[0] == w[1]) && hashes != numbers, "each character shows as #");
let plain_label = |items: &[display::Draw]| {
items.iter().any(|i| matches!(i, display::Draw::Line { x0, x1, y0, y1, .. } if (y0 - y1).abs() < 0.01 && *x0 <= nx + 0.01 && *x1 > nx + 1.0))
};
assert!(!plain_label(&with_mark(display::DeleteMark::ColorOnly)), "colour only: no line through or under the number");
// Moved-away text marked (none) is plain, its number too.
let mut moved = d.clone();
if let Some(r) = moved.revisions.get_mut(0) {
r.move_name = Some("move1".into());
}
let mut o = display::DisplayOptions { markup: true, ..Default::default() };
o.revisions.move_from_mark = display::DeleteMark::None;
let shown = display::page_display(&moved, &l.pages[0], &o);
let (moved_number, _) = glyph_color(&shown, "1.").expect("the moved number is drawn");
let (moved_text, _) = glyph_color(&shown, "Chapter").expect("the moved text is drawn");
assert_eq!(moved_number, moved_text, "plain, like its text");
assert!(!plain_label(&shown));
// With markup but deletions hidden in Track Changes Options, the number isn't drawn either.
assert!(glyph_color(&with_mark(display::DeleteMark::Hidden), "1.").is_none(), "deletions marked hidden");
let mut o = display::DisplayOptions { markup: true, ..Default::default() };
o.revisions.insertions_deletions = false;
assert!(glyph_color(&display::page_display(&d, &l.pages[0], &o), "1.").is_none(), "insertions and deletions not shown");
// Without markup neither the text nor its number is drawn.
let plain = draws(false);
assert!(glyph_color(&plain, "Chapter").is_none() && glyph_color(&plain, "1.").is_none());
// A number whose paragraph mark isn't deleted is drawn as before.
let mut kept = Document::from_text("Intro\nChapter two\nBody");
let id = std::sync::Arc::make_mut(&mut kept.numbering).add_list(wordcraft_doc::ListKind::Numbered);
kept.format_paragraphs(&Pos::body(1, 0), &Pos::body(1, 3), &|p| p.numbering = Some(wordcraft_doc::props::NumRef { num: id, level: 0 })).unwrap();
let kl = lay(&kept);
let plain = display::page_display(&kept, &kl.pages[0], &display::DisplayOptions { markup: false, ..Default::default() });
assert!(glyph_color(&plain, "1.").is_some());
// #4828 review: only the paragraph mark deleted (Delete at the end of the item): the text
// stays, and so does its number, plain, with markup and without (and in print, where markup
// is off).
let mut joined = kept.clone();
joined.revisions = d.revisions.clone();
joined.para_mut(StoryRef::Body, &Path::top(1)).unwrap().mark.del = Some(0);
let jl = lay(&joined);
for markup in [false, true] {
let shown = display::page_display(&joined, &jl.pages[0], &display::DisplayOptions { markup, ..Default::default() });
let (number, jx) = glyph_color(&shown, "1.").unwrap_or_else(|| panic!("markup {markup}: the number stays"));
let (text, _) = glyph_color(&shown, "Chapter").unwrap_or_else(|| panic!("markup {markup}: the text stays"));
assert_eq!(number, text, "markup {markup}: in the text's colour");
let struck = shown
.iter()
.any(|i| matches!(i, display::Draw::Line { x0, x1, y0, y1, .. } if (y0 - y1).abs() < 0.01 && *x0 <= jx + 0.01 && *x1 > jx + 1.0));
assert!(!struck, "markup {markup}: not struck through");
}
}
#[test]
fn empty_list_paragraph_with_a_hidden_mark_counts_but_shows_nothing() {
// Word (#3982): a list item whose paragraph mark is hidden, and whose text is empty or hidden
+59
View File
@@ -242,3 +242,62 @@ fn an_equation_run_names_each_glyphs_characters() {
assert!(found.iter().any(|(t, g, _)| (t.contains('\u{1D44E}') || t == "ab") && *g == 2), "{found:?}");
assert!(found.iter().all(|(_, g, r)| g == r), "{found:?}");
}
/// A metafile text run with the given font height and advances, left-aligned at the baseline.
fn meta_text(height: f32, dx: Vec<f32>) -> craft_metafile::Text {
craft_metafile::Text {
transform: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0],
text: "ab".into(),
dx,
font: craft_metafile::Font { family: "Arial".into(), height, ..Default::default() },
color: [0, 0, 0, 255],
background: Some([255, 255, 255, 255]),
h_align: craft_metafile::HAlign::Left,
v_align: craft_metafile::VAlign::Baseline,
clip: None,
region: None,
clips: Vec::new(),
}
}
/// A metafile font height of 0 is the file's default size: a 16-unit cell. A negative height is
/// the em size, and a positive one the cell (ascent plus descent, 1200 units of a 1000-unit em
/// here).
#[test]
fn metafile_text_heights() {
let glyphs = [(0, 500.0, 0.0, 0.0), (1, 500.0, 0.0, 0.0)];
let em = |h| crate::layout_metafile_text(&meta_text(h, Vec::new()), 1000.0, 900.0, 300.0, &glyphs).map(|l| l.em);
let near = |a: Option<f64>, b: f64| a.is_some_and(|a| (a - b).abs() < 1e-9);
assert!(near(em(0.0), 16.0 * 1000.0 / 1200.0), "{:?}", em(0.0));
assert!(near(em(-10.0), 10.0), "{:?}", em(-10.0));
assert!(near(em(24.0), 20.0), "a positive height is the cell: {:?}", em(24.0));
}
/// A cosmetic pen's dashes become whole output pixels (the shortest one pixel), a period under a
/// pixel draws solid, and so does a pattern that would split the path into too many pieces.
#[test]
fn metafile_dashes_follow_the_output_pixel() {
let cosmetic = crate::metafile_dashes(&[0.75, 0.25], true, 0.5, 100.0).unwrap_or_default();
assert!(cosmetic.len() == 2 && (cosmetic[0] - 1.5).abs() < 1e-6 && (cosmetic[1] - 0.5).abs() < 1e-6, "{cosmetic:?}");
assert_eq!(crate::metafile_dashes(&[3.0, 1.0], false, 0.5, 100.0), Some(vec![3.0, 1.0]));
assert_eq!(crate::metafile_dashes(&[0.2, 0.2], false, 0.5, 100.0), None, "a period under a pixel");
assert_eq!(crate::metafile_dashes(&[1.0, 1.0], false, 0.5, 1e6), None, "a million pieces");
assert_eq!(crate::metafile_dashes(&[1.0, -1.0], false, 0.5, 100.0), None, "a negative length");
assert_eq!(crate::metafile_dashes(&[0.0, 0.0], true, 0.5, 100.0), None, "no length at all");
}
/// A negative crop side is no crop; the others stay as they are.
#[test]
fn negative_crop_sides_are_no_crop() {
assert_eq!(crate::crop_sides([-0.5, 0.25, f32::NAN, 1.5]), [0.0, 0.25, 0.0, 1.5]);
assert_eq!(crate::crop_window([-0.5, 0.0, 0.0, 0.0]), [0.0, 0.0, 1.0, 1.0]);
}
/// The opaque background of a run whose advances move backward covers every pen position, not
/// only the run's total advance.
#[test]
fn metafile_text_cell_spans_backward_advances() {
let glyphs = [(0, 500.0, 0.0, 0.0), (1, 500.0, 0.0, 0.0)];
let lay = crate::layout_metafile_text(&meta_text(-10.0, vec![50.0, -40.0]), 1000.0, 800.0, 200.0, &glyphs).expect("a layout");
assert_eq!(lay.cell, [0.0, -8.0, 50.0, 2.0]);
}
+1 -1
View File
@@ -320,7 +320,7 @@ impl Exporter<'_> {
s.set_fill(None);
return;
};
let [cl, ct, vis_w, vis_h] = craft_metafile::crop_window(*crop).map(|v| v as f32);
let [cl, ct, vis_w, vis_h] = wordcraft_layout::crop_window(*crop).map(|v| v as f32);
let (fw, fh) = (rect.w / vis_w, rect.h / vis_h);
let Some(size) = Size::from_wh(fw.max(0.01), fh.max(0.01)) else { return };
let fade = alpha < 0.999;
+12 -3
View File
@@ -1,6 +1,6 @@
use super::{
Exporter, FaceRef, Fill, FillRule, KrillaGlyph, Point, Rgb, Stroke, Surface, Transform, baseline, cluster_ends, fill, glyph_id, glyph_outlines,
left_to_right, norm, ok, paint_of, rgb, split_clusters, visual_order,
Exporter, FaceRef, Fill, FillRule, KrillaGlyph, Point, Rect, Rgb, Stroke, Surface, Transform, baseline, cluster_ends, fill, glyph_id,
glyph_outlines, left_to_right, norm, ok, paint_of, rect_path, rgb, split_clusters, visual_order,
};
/// How a run of glyphs is painted: its colour, opacity and synthetic bold and italic.
@@ -181,7 +181,7 @@ impl Exporter<'_> {
}
/// Draws a metafile text run as PDF text (outlines when the font cannot be embedded). `tf` maps
/// the run's own space (see [`PlacedItem::Text`]) to the page.
/// its text space (`craft_metafile::Text::transform`) to the page.
pub(crate) fn vector_text(&mut self, s: &mut Surface, t: &craft_metafile::Text, tf: kurbo::Affine) {
let (face, shaped) = wordcraft_layout::metafile_text_run(t);
let glyphs: Vec<_> = shaped.iter().map(|g| (g.cluster, f64::from(g.x_advance), f64::from(g.x_offset), f64::from(g.y_offset))).collect();
@@ -198,6 +198,15 @@ impl Exporter<'_> {
let (paint, opacity) = paint_of(t.color);
s.push_transform(&Transform::from_row(c[0], c[1], c[2], c[3], c[4], c[5]));
s.set_stroke(None);
// An opaque background mode fills the character cells first.
if let Some(bg) = t.background {
let [x0, y0, x1, y1] = lay.cell.map(|v| v as f32);
if let Some(cell) = rect_path(&Rect { x: x0, y: y0, w: x1 - x0, h: y1 - y0 }) {
let (paint, opacity) = paint_of(bg);
s.set_fill(Some(Fill { paint: paint.into(), opacity, rule: FillRule::NonZero }));
s.draw_path(&cell);
}
}
s.set_fill(Some(Fill { paint: paint.into(), opacity, rule: FillRule::NonZero }));
match font {
Some(font) => {
+145 -26
View File
@@ -1,28 +1,51 @@
use super::exporter::Exporter;
use super::paint::{append_path, norm};
use super::{
Arc, Fill, FillRule, Image, LineCap, LineJoin, NormalizedF32, Path, PathBuilder, Picture, PlacedItem, Rect, Size, Stroke, Surface, Transform, rgb,
Arc, Fill, FillRule, Image, LineCap, LineJoin, NormalizedF32, Path, PathBuilder, Picture, PlacedItem, Rect, Size, Stroke, StrokeDash, Surface,
Transform, krilla, rgb,
};
use craft_metafile::Item;
use kurbo::Shape as _;
use wordcraft_doc::picfx::PicFx;
/// Largest picture side we embed (pixels).
const MAX_IMAGE_SIDE: u32 = 30_000;
/// A metafile picture, parsed once. The geometry comes placed by the metafile crate; the bitmaps are
/// embedded images, one per picture item (None for paths and undecodable bitmaps).
/// A metafile picture, parsed once. The geometry comes placed by the metafile crate; the bitmaps and
/// pattern tiles are embedded images, one per picture item (None for paths, text and undecodable
/// bitmaps). Fills that share a tile share its image. `averages` holds each pattern fill's tile
/// average color (transparent for other items), computed once a tile.
pub(crate) struct Vector {
pic: Picture,
images: Vec<Option<Image>>,
averages: Vec<[u8; 4]>,
}
/// Parses a metafile and embeds its bitmaps. None when the picture has no usable size.
/// Parses a metafile and embeds its bitmaps and pattern tiles. None when the picture has no usable
/// size.
pub(crate) fn build_vector(bytes: &[u8]) -> Option<Vector> {
let mut pic = craft_metafile::parse(bytes).ok()?;
if !pic.has_size() {
return None;
}
let images = pic.items.iter_mut().map(|it| it.take_pixels().map(|(w, h, px)| Image::from_rgba8(px, w, h))).collect();
Some(Vector { pic, images })
let mut tiles: std::collections::HashMap<usize, (Option<Image>, [u8; 4])> = std::collections::HashMap::new();
let (images, averages) = pic
.items
.iter_mut()
.map(|it| match it {
Item::Pattern { tile, .. } => tiles
.entry(Arc::as_ptr(tile) as usize)
.or_insert_with(|| {
let n = (tile.width as usize).saturating_mul(tile.height as usize).saturating_mul(4);
let img = (tile.width > 0 && tile.height > 0 && tile.rgba.len() == n)
.then(|| Image::from_rgba8(tile.rgba.clone(), tile.width, tile.height));
(img, wordcraft_layout::metafile_average_color(&tile.rgba))
})
.clone(),
_ => (it.take_pixels().map(|(w, h, px)| Image::from_rgba8(px, w, h)), [0; 4]),
})
.unzip();
Some(Vector { pic, images, averages })
}
/// A straight RGBA colour as a krilla colour and opacity.
@@ -36,9 +59,10 @@ pub(crate) fn paint_of(c: [u8; 4]) -> (rgb::Color, NormalizedF32) {
const HAIRLINE: f64 = 0.25;
/// Draws a metafile picture into the clip (the picture frame): paths are filled and stroked in page
/// space (strokes keep their width under non-uniform scaling), bitmaps stretched, all faded by `alpha`.
/// Every path sets its fill and stroke, so none carries over; strokes have round caps and joins. Text
/// runs are drawn as text.
/// space (strokes keep their width under non-uniform scaling), bitmaps stretched (or turned by their
/// transform), pattern fills tiled, each item inside its clip region and clip paths, all faded by
/// `alpha`. Every path sets its fill and stroke, so none carries over; strokes take the pen's caps,
/// joins and dashes. Text runs are drawn as text.
pub(crate) fn vector_picture(ex: &mut Exporter, s: &mut Surface, v: &Vector, r: &Rect, crop: &[f32; 4], clip: &Path, alpha: f32) {
let target = kurbo::Rect::new(f64::from(r.x), f64::from(r.y), f64::from(r.x + r.w), f64::from(r.y + r.h));
let fade = alpha < 0.999;
@@ -46,9 +70,9 @@ pub(crate) fn vector_picture(ex: &mut Exporter, s: &mut Surface, v: &Vector, r:
s.push_opacity(norm(alpha));
}
s.push_clip_path(clip, &FillRule::NonZero);
for it in v.pic.place(target, *crop) {
for it in v.pic.place(target, wordcraft_layout::crop_sides(*crop)) {
match it {
PlacedItem::Path { path, fill, stroke, even_odd, .. } => {
PlacedItem::Path { path, fill, stroke, line, even_odd, region, clips } => {
let Some(p) = path_from(&path) else { continue };
let fill = fill.map(|c| {
let (paint, opacity) = paint_of(c);
@@ -57,31 +81,63 @@ pub(crate) fn vector_picture(ex: &mut Exporter, s: &mut Surface, v: &Vector, r:
});
let stroke = stroke.map(|(c, w)| {
let (paint, opacity) = paint_of(c);
Stroke {
paint: paint.into(),
width: w.max(HAIRLINE) as f32,
opacity,
line_cap: LineCap::Round,
line_join: LineJoin::Round,
..Default::default()
}
pen(paint.into(), opacity, w, &line, &path)
});
let Some(n) = push_clips(s, region.as_deref(), &clips) else { continue };
s.set_fill(fill);
s.set_stroke(stroke);
s.draw_path(&p);
pop_clips(s, n);
}
PlacedItem::Bitmap { index, rect, .. } => {
PlacedItem::Bitmap { index, rect, transform, region, clips } => {
let Some(Some(img)) = v.images.get(index) else { continue };
let Some(size) = Size::from_wh(rect.width() as f32, rect.height() as f32) else { continue };
s.push_transform(&Transform::from_translate(rect.x0 as f32, rect.y0 as f32));
let c = transform.as_coeffs();
// Upright and not mirrored: the bitmap fills `rect`.
let upright = c[1] == 0.0 && c[2] == 0.0 && c[0] > 0.0 && c[3] > 0.0;
let (tf, size) = if upright {
(Transform::from_translate(rect.x0 as f32, rect.y0 as f32), Size::from_wh(rect.width() as f32, rect.height() as f32))
} else {
// A turned, skewed or mirrored bitmap: `transform` maps the unit square onto its place.
let c = c.map(|v| v as f32);
(Transform::from_row(c[0], c[1], c[2], c[3], c[4], c[5]), Size::from_wh(1.0, 1.0))
};
let Some(size) = size else { continue };
let Some(n) = push_clips(s, region.as_deref(), &clips) else { continue };
s.push_transform(&tf);
s.draw_image(img.clone(), size);
s.pop();
pop_clips(s, n);
}
PlacedItem::Pattern { .. } => {}
PlacedItem::Text { index, transform, .. } => {
if let Some(craft_metafile::Item::Text(t)) = v.pic.items.get(index) {
ex.vector_text(s, t, transform);
PlacedItem::Pattern { index, path, even_odd, tile, region, clips } => {
let Some(p) = path_from(&path) else { continue };
let Some(craft_metafile::Item::Pattern { tile: t, .. }) = v.pic.items.get(index) else { continue };
let rule = if even_odd { FillRule::EvenOdd } else { FillRule::NonZero };
let paint = match v.images.get(index) {
Some(Some(img)) => tile_pattern(s, img, t.width, t.height, tile).map(|p| (p.into(), norm(1.0))),
_ => None,
};
let (paint, opacity) = paint.unwrap_or_else(|| {
let (c, o) = paint_of(v.averages.get(index).copied().unwrap_or([0; 4]));
(c.into(), o)
});
let Some(n) = push_clips(s, region.as_deref(), &clips) else { continue };
s.set_fill(Some(Fill { paint, opacity, rule }));
s.set_stroke(None);
s.draw_path(&p);
pop_clips(s, n);
}
PlacedItem::Text { index, transform, clip, region, clips } => {
let Some(craft_metafile::Item::Text(t)) = v.pic.items.get(index) else { continue };
let Some(n) = push_clips(s, region.as_deref(), &clips) else { continue };
let text_clip = clip.and_then(|c| path_from(&c.to_path(0.1)));
if let Some(c) = &text_clip {
s.push_clip_path(c, &FillRule::NonZero);
}
ex.vector_text(s, t, transform);
if text_clip.is_some() {
s.pop();
}
pop_clips(s, n);
}
}
}
@@ -93,6 +149,69 @@ pub(crate) fn vector_picture(ex: &mut Exporter, s: &mut Surface, v: &Vector, r:
}
}
/// Pushes a metafile item's clip region and clip paths; pop them with [`pop_clips`] and the count
/// returned. None (nothing pushed) when a clip has no area to draw in.
fn push_clips(s: &mut Surface, region: Option<&kurbo::BezPath>, clips: &[Arc<craft_metafile::PlacedClip>]) -> Option<usize> {
let mut paths = Vec::with_capacity(clips.len() + 1);
if let Some(region) = region {
paths.push((path_from(region)?, FillRule::NonZero));
}
for c in clips {
paths.push((path_from(&c.path)?, if c.even_odd { FillRule::EvenOdd } else { FillRule::NonZero }));
}
for (p, rule) in &paths {
s.push_clip_path(p, rule);
}
Some(paths.len())
}
fn pop_clips(s: &mut Surface, n: usize) {
for _ in 0..n {
s.pop();
}
}
/// A metafile pen for `path`: `width` (points, at least [`HAIRLINE`]), the pen's caps, joins,
/// miter limit and dashes (`wordcraft_layout::metafile_dashes`, with the hairline as the pixel).
fn pen(paint: krilla::paint::Paint, opacity: NormalizedF32, width: f64, line: &craft_metafile::LineStyle, path: &kurbo::BezPath) -> Stroke {
let line_cap = match line.cap {
craft_metafile::Cap::Round => LineCap::Round,
craft_metafile::Cap::Square => LineCap::Square,
craft_metafile::Cap::Flat => LineCap::Butt,
};
let line_join = match line.join {
craft_metafile::Join::Round => LineJoin::Round,
craft_metafile::Join::Bevel => LineJoin::Bevel,
craft_metafile::Join::Miter => LineJoin::Miter,
};
let dash = if line.dash.is_empty() { None } else { wordcraft_layout::metafile_dashes(&line.dash, width == 0.0, HAIRLINE, path.perimeter(1.0)) };
Stroke {
paint,
width: width.max(HAIRLINE) as f32,
miter_limit: wordcraft_layout::metafile_miter_limit(line.miter_limit),
line_cap,
line_join,
opacity,
dash: dash.map(|d| StrokeDash { array: d.iter().map(|v| *v as f32).collect(), offset: 0.0 }),
}
}
/// A tiling pattern of `img` (`w` × `h` pixels); `tile` maps tile pixels to page space. None when
/// the mapping is not finite.
fn tile_pattern(s: &mut Surface, img: &Image, w: u32, h: u32, tile: kurbo::Affine) -> Option<krilla::paint::Pattern> {
let c = tile.as_coeffs().map(|v| v as f32);
if !c.iter().all(|v| v.is_finite()) {
return None;
}
let size = Size::from_wh(w as f32, h as f32)?;
let mut sb = s.stream_builder();
let mut ps = sb.surface();
ps.draw_image(img.clone(), size);
ps.finish();
let stream = sb.finish();
Some(krilla::paint::Pattern { stream, transform: Transform::from_row(c[0], c[1], c[2], c[3], c[4], c[5]), width: w as f32, height: h as f32 })
}
/// A kurbo path as a krilla path (None when empty).
fn path_from(b: &kurbo::BezPath) -> Option<Path> {
let mut pb = PathBuilder::new();
+250
View File
@@ -1305,6 +1305,211 @@ fn emf_rec(typ: u32, fields: &[i32]) -> Vec<u8> {
v
}
/// The PDF of a document holding one 70 pt metafile picture, uncompressed.
fn metafile_pdf(emf: Vec<u8>) -> String {
String::from_utf8_lossy(&metafile_pdf_bytes(emf)).into_owned()
}
fn metafile_pdf_bytes(emf: Vec<u8>) -> Vec<u8> {
export(&metafile_doc(emf), &PdfOptions { compress: false, tagged: false, ..Default::default() }).unwrap()
}
/// The uncompressed PDF of a document holding one 70 pt metafile picture, and the picture's box
/// on the first page in PDF space (points, y up).
fn metafile_pdf_and_box(emf: Vec<u8>) -> (Vec<u8>, kurbo::Rect) {
let d = metafile_doc(emf);
let bytes = export(&d, &PdfOptions { compress: false, tagged: false, ..Default::default() }).unwrap();
let lay = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default());
let page = &lay.pages[0];
let h = f64::from(page.h);
let r = wordcraft_layout::display::page_display(&d, page, &DisplayOptions::default())
.into_iter()
.find_map(|item| if let Draw::Image { rect, .. } = item { Some(rect) } else { None })
.expect("the picture is laid out");
let (x, y, w, ph) = (f64::from(r.x), f64::from(r.y), f64::from(r.w), f64::from(r.h));
(bytes, kurbo::Rect::new(x, h - y - ph, x + w, h - y))
}
/// The right half of a box.
fn right_half(r: kurbo::Rect) -> kurbo::Rect {
kurbo::Rect::new((r.x0 + r.x1) / 2.0, r.y0, r.x1, r.y1)
}
/// Whether two boxes have the same edges, to within half a point.
fn same_box(a: kurbo::Rect, b: kurbo::Rect) -> bool {
[a.x0 - b.x0, a.y0 - b.y0, a.x1 - b.x1, a.y1 - b.y1].iter().all(|d| d.abs() < 0.5)
}
fn metafile_doc(emf: Vec<u8>) -> Document {
let mut d = Document::new();
let media = d.add_media(emf, "emf");
let mut p = Paragraph::with_text("Figure: ", CharProps::default());
let n = p.len();
p.insert_object(
n,
InlineObject::Image {
media,
w: 70.0,
h: 70.0,
alt: String::new(),
float: Default::default(),
crop: [0.0; 4],
fx: Default::default(),
ole: None,
},
&CharProps::default(),
)
.unwrap();
d.body = vec![para_block(p)];
d
}
/// #6636: an EMF+ only file whose EmfPlusDrawImage draws a 32bppPARGB bitmap: the bitmap is
/// embedded as an image, and the page draws it into the EmfPlusDrawImage rectangle.
#[test]
fn emf_plus_only_bitmap_is_embedded() {
let plus_rec = |typ: u16, flags: u16, data: &[u8]| {
let mut v = typ.to_le_bytes().to_vec();
v.extend(flags.to_le_bytes());
v.extend(((12 + data.len()) as u32).to_le_bytes());
v.extend((data.len() as u32).to_le_bytes());
v.extend(data);
v
};
let le32 = |vals: &[i32]| -> Vec<u8> { vals.iter().flat_map(|v| v.to_le_bytes()).collect() };
let header = plus_rec(0x4001, 0, &le32(&[0xDBC0_1002_u32 as i32, 1, 96, 96]));
let mut image = le32(&[0xDBC0_1002_u32 as i32, 1, 2, 2, 8, 0x000E_200B, 0]);
image.extend([0u8, 0, 255, 255].repeat(4));
let object = plus_rec(0x4008, 0x0500, &image);
let mut draw = le32(&[-1, 2]);
draw.extend([0.0f32, 0.0, 2.0, 2.0, 50.0, 0.0, 50.0, 100.0].iter().flat_map(|v| v.to_le_bytes()));
let draw = plus_rec(0x401A, 0, &draw);
let mut comment = 0x2B46_4D45u32.to_le_bytes().to_vec();
comment.extend([header, object, draw, plus_rec(0x4002, 0, &[])].concat());
let mut rec = 70u32.to_le_bytes().to_vec();
rec.extend(((12 + comment.len()) as u32).to_le_bytes());
rec.extend((comment.len() as u32).to_le_bytes());
rec.extend(comment);
let (bytes, pic) = metafile_pdf_and_box(emf_file(&[rec, emf_rec(14, &[0; 3])]));
let images = pdf_images(&bytes);
assert!(images.iter().any(|(w, h, ..)| (*w, *h) == (2, 2)), "the 2 × 2 bitmap is embedded");
let drawn = pdf_drawn_images(&bytes);
assert!(
drawn.iter().any(|&(w, h, r)| (w, h) == (2, 2) && same_box(r, right_half(pic))),
"the page draws the bitmap over the right half of the picture at {pic:?}: {drawn:?}"
);
assert!(!String::from_utf8_lossy(&bytes).contains("0.8156"), "the gray placeholder box is not drawn");
}
/// #6636: an EMF+ only file whose EmfPlusDrawImage draws a bitmap in PixelFormat32bppARGB,
/// 24bppRGB or 32bppRGB, or a compressed PNG or JPEG bitmap: the bitmap is embedded as an image,
/// and the page draws it into the EmfPlusDrawImage rectangle.
#[test]
fn emf_plus_only_bitmap_formats_are_embedded() {
let plus_rec = |typ: u16, flags: u16, data: &[u8]| {
let mut v = typ.to_le_bytes().to_vec();
v.extend(flags.to_le_bytes());
v.extend(((12 + data.len()) as u32).to_le_bytes());
v.extend((data.len() as u32).to_le_bytes());
v.extend(data);
v
};
let le32 = |vals: &[i32]| -> Vec<u8> { vals.iter().flat_map(|v| v.to_le_bytes()).collect() };
let encoded = |png: bool| {
let red = [255u8, 0, 0].repeat(15);
if png {
let img = image::RgbImage::from_raw(5, 3, red).unwrap();
wordcraft_geom::picture::encode_png(&image::DynamicImage::from(img)).unwrap()
} else {
wordcraft_geom::picture::encode_jpeg(&red, 5, 3, 100).unwrap()
}
};
// Name, width, height, stride, pixel format, bitmap type (0 pixels, 1 compressed) and data.
let cases: [(&str, i32, i32, i32, u32, i32, Vec<u8>); 5] = [
("32bppARGB", 2, 2, 8, 0x0026_200A, 0, [0u8, 0, 255, 255].repeat(4)),
("24bppRGB", 2, 2, 8, 0x0002_1808, 0, [0u8, 0, 255, 0, 0, 255, 0, 0].repeat(2)),
("32bppRGB", 2, 2, 8, 0x0002_2009, 0, [0u8, 0, 255, 0].repeat(4)),
("PNG", 5, 3, 0, 0, 1, encoded(true)),
("JPEG", 5, 3, 0, 0, 1, encoded(false)),
];
for (name, w, h, stride, format, kind, data) in cases {
let header = plus_rec(0x4001, 0, &le32(&[0xDBC0_1002_u32 as i32, 1, 96, 96]));
let mut image = le32(&[0xDBC0_1002_u32 as i32, 1, w, h, stride, format as i32, kind]);
image.extend(data);
// Records are a multiple of 4 bytes long.
image.resize(image.len().next_multiple_of(4), 0);
let object = plus_rec(0x4008, 0x0500, &image);
let mut draw = le32(&[-1, 2]);
draw.extend([0.0f32, 0.0, w as f32, h as f32, 50.0, 0.0, 50.0, 100.0].iter().flat_map(|v| v.to_le_bytes()));
let draw = plus_rec(0x401A, 0, &draw);
let mut comment = 0x2B46_4D45u32.to_le_bytes().to_vec();
comment.extend([header, object, draw, plus_rec(0x4002, 0, &[])].concat());
let mut rec = 70u32.to_le_bytes().to_vec();
rec.extend(((12 + comment.len()) as u32).to_le_bytes());
rec.extend((comment.len() as u32).to_le_bytes());
rec.extend(comment);
let (bytes, pic) = metafile_pdf_and_box(emf_file(&[rec, emf_rec(14, &[0; 3])]));
let images = pdf_images(&bytes);
assert!(images.iter().any(|(iw, ih, ..)| (*iw, *ih) == (w as u32, h as u32)), "{name}: the {w} × {h} bitmap is embedded");
let drawn = pdf_drawn_images(&bytes);
assert!(
drawn.iter().any(|&(iw, ih, r)| (iw, ih) == (w as u32, h as u32) && same_box(r, right_half(pic))),
"{name}: the page draws the bitmap over the right half of the picture at {pic:?}: {drawn:?}"
);
assert!(!String::from_utf8_lossy(&bytes).contains("0.8156"), "{name}: the gray placeholder box is not drawn");
}
}
/// A dotted cosmetic pen (CREATEPEN, PS_DOT, width 0) draws hairline dots: its dashes and gaps are
/// the hairline's width, not the file's device units scaled to the frame (0.7 pt here).
#[test]
fn metafile_cosmetic_dotted_pen_draws_hairline_dots() {
let recs = [emf_rec(38, &[1, 2, 0, 0, 0]), emf_rec(37, &[1]), emf_rec(27, &[0, 50]), emf_rec(54, &[100, 50]), emf_rec(14, &[0; 3])];
let raw = metafile_pdf(emf_file(&recs));
assert!(raw.contains("[0.25 0.25]0 d"), "the dots are hairline-sized");
}
/// A geometric PS_USERSTYLE pen whose dashes and gaps are far below the hairline draws its line
/// solid: no dash array is written.
#[test]
fn metafile_sub_pixel_dashes_draw_solid() {
let mut emf = emf_file(&[]);
// 10,000 device pixels over 250 mm: a device unit is 0.025 mm. The picture is 1000 units wide.
let le32 = |vals: &[i32]| -> Vec<u8> { vals.iter().flat_map(|v| v.to_le_bytes()).collect() };
emf[8..24].copy_from_slice(&le32(&[0, 0, 1000, 1000]));
emf[72..80].copy_from_slice(&le32(&[10_000, 10_000]));
let pen = emf_rec(95, &[1, 0, 0, 0, 0, 0x0001_0207, 80, 0, 0, 0, 2, 1, 1]);
let recs = [pen, emf_rec(37, &[1]), emf_rec(27, &[0, 500]), emf_rec(54, &[1000, 500]), emf_rec(14, &[0; 3])];
emf.extend(recs.concat());
let raw = metafile_pdf(emf);
assert!(raw.contains(" w ") && !raw.contains("]0 d"), "a stroke with no dash array");
}
/// A clip region (INTERSECTCLIPRECT) adds a clip around the rectangle it clips.
#[test]
fn metafile_clip_region_is_a_clip() {
let clips = |raw: &str| raw.matches("\nW\nn").count() + raw.matches("\nW*\nn").count();
let draw = |clip: bool| {
let mut recs = vec![emf_rec(39, &[1, 0, 0x0000_00FF, 0]), emf_rec(37, &[1])];
if clip {
recs.push(emf_rec(30, &[0, 0, 50, 100]));
}
recs.extend([emf_rec(43, &[0, 0, 100, 100]), emf_rec(14, &[0; 3])]);
metafile_pdf(emf_file(&recs))
};
let (with, without) = (clips(&draw(true)), clips(&draw(false)));
assert!(without > 0 && with == without + 1, "one clip more with the region: {with} and {without}");
}
/// A hatched brush (CREATEBRUSHINDIRECT, BS_HATCHED) fills through a tiling pattern, not with a
/// solid color.
#[test]
fn metafile_hatch_brush_is_a_tiling_pattern() {
let recs = [emf_rec(39, &[1, 2, 0x0000_00FF, 1]), emf_rec(37, &[1]), emf_rec(43, &[0, 0, 100, 100]), emf_rec(14, &[0; 3])];
let raw = metafile_pdf(emf_file(&recs));
assert!(raw.contains("/PatternType 1"), "the hatch is a tiling pattern");
}
#[test]
fn metafile_strokes_use_round_caps_and_joins() {
// A 4-unit black pen (handle 1) outlines a rectangle, so the stroke is drawn with round caps and joins.
@@ -1425,6 +1630,17 @@ fn emf_text_records(text: &str) -> Vec<Vec<u8>> {
vec![font, emf_rec(37, &[1]), emf_rec(24, &[0]), out]
}
/// With the opaque background mode (the default) and a red background color (SETBKCOLOR), a text
/// run's character cells are filled red behind the text.
#[test]
fn metafile_text_fills_its_opaque_background() {
let mut recs = vec![emf_rec(25, &[0x0000_00FF])];
recs.extend(emf_text_records("Hi"));
recs.push(emf_rec(14, &[0; 3]));
let raw = metafile_pdf(emf_file(&recs));
assert!(raw.contains("1 0 0 rg"), "the character cells are filled red");
}
/// #1764: the text of an EMF picture (EXTTEXTOUTW) is drawn, so it is in the PDF's text layer.
#[test]
fn metafile_text_records_are_drawn_as_text() {
@@ -2159,6 +2375,40 @@ fn pdf_images(bytes: &[u8]) -> Vec<(u32, u32, Vec<String>, Vec<Vec<u8>>)> {
out
}
/// The images the pages draw, through hayro's interpreter: pixel width and height, and the box each
/// one is drawn into, in PDF space (points, y up).
fn pdf_drawn_images(bytes: &[u8]) -> Vec<(u32, u32, kurbo::Rect)> {
use hayro_interpret::font::Glyph;
use hayro_interpret::{
BlendMode, ClipPath, Context, Device, GlyphDrawMode, Image, InterpreterCache, InterpreterSettings, Paint, PathDrawMode, SoftMask,
interpret_page,
};
struct Ex(Vec<(u32, u32, kurbo::Rect)>);
impl Device<'_> for Ex {
fn set_soft_mask(&mut self, _: Option<SoftMask<'_>>) {}
fn set_blend_mode(&mut self, _: BlendMode) {}
fn draw_path(&mut self, _: &kurbo::BezPath, _: kurbo::Affine, _: &Paint<'_>, _: &PathDrawMode) {}
fn push_clip_path(&mut self, _: &ClipPath) {}
fn push_transparency_group(&mut self, _: f32, _: Option<SoftMask<'_>>, _: BlendMode) {}
fn draw_glyph(&mut self, _: &Glyph<'_>, _: kurbo::Affine, _: kurbo::Affine, _: &Paint<'_>, _: &GlyphDrawMode) {}
fn draw_image(&mut self, image: Image<'_, '_>, t: kurbo::Affine) {
// The transform maps the image's pixel grid onto the page.
let (w, h) = (image.width(), image.height());
self.0.push((w, h, t.transform_rect_bbox(kurbo::Rect::new(0.0, 0.0, f64::from(w), f64::from(h)))));
}
fn pop_clip_path(&mut self) {}
fn pop_transparency_group(&mut self) {}
}
let pdf = hayro_syntax::Pdf::new(bytes.to_vec()).expect("parse");
let cache = InterpreterCache::new();
let mut ex = Ex(Vec::new());
for page in pdf.pages().iter() {
let mut ctx = Context::new(kurbo::Affine::IDENTITY, kurbo::Rect::new(0.0, 0.0, 1.0, 1.0), &cache, pdf.xref(), InterpreterSettings::default());
interpret_page(page, &mut ctx, &mut ex);
}
ex.0
}
/// The fill opacities (`ca`) of the PDF's graphics states.
fn pdf_fill_opacities(bytes: &[u8]) -> Vec<f32> {
use hayro_syntax::object::Object;
+1 -1
View File
@@ -856,7 +856,7 @@ fn draw_image(ctx: &mut RenderContext, fr: &Frame, it: &Draw) {
return;
};
let (pw, ph) = (pm.width().max(1) as f64, pm.height().max(1) as f64);
let [cl, ct, vis_w, vis_h] = craft_metafile::crop_window(*crop);
let [cl, ct, vis_w, vis_h] = wordcraft_layout::crop_window(*crop);
let sx = r.width() / (pw * vis_w);
let sy = r.height() / (ph * vis_h);
ctx.set_transform(view);
+255 -37
View File
@@ -1,4 +1,6 @@
use super::{Affine, Arc, Document, FontDb, HashMap, Item, Mutex, Page, Picture, Pixmap, PlacedItem, RenderContext, Seg, Shape, Weak, kurbo, peniko};
use craft_metafile::{ClipPath, Tile};
use std::collections::HashSet;
/// Upper bound on the bytes the two decoded-media caches keep together (about 256 MB), half each;
/// past its half a cache starts over.
@@ -140,29 +142,70 @@ pub fn metafile_size(bytes: &[u8]) -> Option<(f32, f32, &'static str)> {
Some((w * k, h * k, ext))
}
/// A metafile (WMF/EMF) picture, parsed once. The geometry comes placed by the metafile crate; the
/// bitmaps are pixmaps, one per picture item (None for paths and undecodable bitmaps).
/// A metafile (WMF/EMF/EMF+) picture, parsed once. The geometry comes placed by the metafile crate;
/// the bitmaps and pattern tiles are pixmaps, one per picture item (None for paths, text and
/// undecodable bitmaps). Fills that share a tile share its pixmap. `averages` holds each pattern
/// fill's tile average color (transparent for other items), computed once a tile.
pub(crate) struct Vector {
pic: Picture,
pixmaps: Vec<Option<Arc<Pixmap>>>,
averages: Vec<[u8; 4]>,
}
impl Vector {
/// Approximate memory held: pixels and path segments.
fn bytes(&self) -> usize {
let px: usize = self.pixmaps.iter().flatten().map(|p| p.width() as usize * p.height() as usize * 4).sum();
let segs: usize = self
.pic
.items
/// Approximate memory held: pixels (a tile shared by several fills once), path segments and the
/// per-item bookkeeping.
pub(crate) fn bytes(&self) -> usize {
let mut seen: HashSet<*const Pixmap> = HashSet::new();
let px: usize = self.pixmaps.iter().flatten().filter(|p| seen.insert(Arc::as_ptr(p))).map(|p| bitmap_bytes(p)).sum();
px.saturating_add(self.averages.capacity() * 4).saturating_add(geometry_bytes(&self.pic))
}
}
/// Memory held by one decoded bitmap: its pixels plus the pixmap and its `Arc` header.
fn bitmap_bytes(p: &Pixmap) -> usize {
usize::from(p.width()) * usize::from(p.height()) * 4 + std::mem::size_of::<Pixmap>() + 2 * std::mem::size_of::<usize>()
}
/// Approximate memory held by a picture's items: path segments and text (charged by capacity, as a
/// parsed vector keeps its growth slack), the item itself (a bitmap
/// item stays in the list after its pixels move out), a path's dash array, a text's boxed record and
/// font name, the pixmap slot kept for it, a pattern's path
/// and tile, and every item's clip rectangles and clip paths. Tiles and clip paths are shared between
/// the items that use them, so each is charged once.
pub(crate) fn geometry_bytes(pic: &Picture) -> usize {
let slot = std::mem::size_of::<Option<Arc<Pixmap>>>();
let seg = std::mem::size_of::<Seg>();
let mut tiles: HashSet<*const Tile> = HashSet::new();
let mut clip_paths: HashSet<*const ClipPath> = HashSet::new();
let mut total = 0usize;
for it in &pic.items {
let (region, clips): (&Option<Vec<[f32; 4]>>, &[Arc<ClipPath>]) = match it {
Item::Path { region, clips, .. } | Item::Bitmap { region, clips, .. } | Item::Pattern { region, clips, .. } => (region, clips),
Item::Text(t) => (&t.region, &t.clips),
};
let own = match it {
Item::Path { segs, line, .. } => (segs.capacity() * seg).saturating_add(line.dash.capacity() * std::mem::size_of::<f32>()),
Item::Bitmap { .. } => 0,
Item::Pattern { segs, tile, .. } => {
let tile_bytes = if tiles.insert(Arc::as_ptr(tile)) { tile.rgba.len().saturating_add(std::mem::size_of::<Tile>()) } else { 0 };
(segs.capacity() * seg).saturating_add(tile_bytes)
}
Item::Text(t) => {
std::mem::size_of::<craft_metafile::Text>() + t.text.len() + t.dx.len() * std::mem::size_of::<f32>() + t.font.family.len()
}
};
let region_bytes = region.as_ref().map_or(0, |r| r.len() * std::mem::size_of::<[f32; 4]>());
let clip_bytes: usize = clips
.iter()
.map(|it| match it {
Item::Path { segs, .. } => segs.len() * std::mem::size_of::<Seg>(),
Item::Bitmap { .. } | Item::Pattern { .. } => 0,
Item::Text(t) => t.text.len() + t.dx.len() * 4,
.map(|c| {
let arc = std::mem::size_of::<usize>() * 2 + std::mem::size_of::<Arc<ClipPath>>();
if clip_paths.insert(Arc::as_ptr(c)) { arc + std::mem::size_of::<ClipPath>() + c.segs.capacity() * seg } else { arc }
})
.sum();
px + segs
total = total.saturating_add(slot + std::mem::size_of::<Item>()).saturating_add(own).saturating_add(region_bytes).saturating_add(clip_bytes);
}
total
}
/// The metafile picture for a media key. None when the bytes are not a metafile or do not parse, so
@@ -184,25 +227,94 @@ pub(crate) fn vector_for(doc: &Document, key: &str) -> Option<Arc<Vector>> {
v
}
/// Parses a metafile and decodes its bitmaps. None when the picture has no usable size.
fn build_vector(bytes: &[u8]) -> Option<Vector> {
/// Parses a metafile and decodes its bitmaps and pattern tiles. None when the picture has no
/// usable size.
pub(crate) fn build_vector(bytes: &[u8]) -> Option<Vector> {
let mut pic = craft_metafile::parse(bytes).ok()?;
if !pic.has_size() {
return None;
}
// The pixels move into the pixmaps; the picture keeps only the geometry.
let pixmaps = pic.items.iter_mut().map(|it| it.take_pixels().and_then(|(w, h, px)| premul_pixmap(w, h, &px)).map(Arc::new)).collect();
Some(Vector { pic, pixmaps })
// The pixels move into the pixmaps; the picture keeps only the geometry. A tile shared by
// several fills is converted and averaged once. Only the bitmaps are fitted to the cache: a
// tile is small and stays as it is, but counts against the budget.
let mut tiles: HashMap<usize, (Option<Arc<Pixmap>>, [u8; 4])> = HashMap::new();
let mut tile_bytes = 0usize;
let mut bitmaps: Vec<Option<Pixmap>> = Vec::with_capacity(pic.items.len());
let mut averages: Vec<[u8; 4]> = Vec::with_capacity(pic.items.len());
let mut patterns: Vec<Option<Arc<Pixmap>>> = Vec::with_capacity(pic.items.len());
for it in pic.items.iter_mut() {
if let Item::Pattern { tile, .. } = it {
let key = Arc::as_ptr(tile) as usize;
let fresh = !tiles.contains_key(&key);
let (pm, avg) = tiles
.entry(key)
.or_insert_with(|| {
(premul_pixmap(tile.width, tile.height, &tile.rgba).map(Arc::new), wordcraft_layout::metafile_average_color(&tile.rgba))
})
.clone();
if fresh {
tile_bytes = tile_bytes.saturating_add(pm.as_ref().map_or(0, |p| bitmap_bytes(p)));
}
bitmaps.push(None);
patterns.push(pm);
averages.push(avg);
} else {
bitmaps.push(it.take_pixels().and_then(|(w, h, px)| premul_pixmap(w, h, &px)));
patterns.push(None);
averages.push([0; 4]);
}
}
let bitmaps = fit_cache(bitmaps, geometry_bytes(&pic).saturating_add(tile_bytes));
let pixmaps = bitmaps.into_iter().zip(patterns).map(|(b, t)| b.map(Arc::new).or(t)).collect();
Some(Vector { pic, pixmaps, averages })
}
/// The bitmaps of a metafile at a size its whole picture is kept in the cache. When geometry and
/// bitmaps together are past the cache budget (a metafile with a 6000 x 6000 bitmap is 144 MB), the
/// cache would refuse the picture and every repaint would parse and decode the file again, so the
/// bitmaps are box-averaged down to an eighth of the budget between them, in proportion to their
/// size, as large raster pictures are (#3665, which uses half). An eighth because the cache starts
/// over when full: several huge pictures on screen together must fit side by side, and not clear
/// the small ones with them. Geometry that is itself an eighth or more still leaves the bitmaps a
/// sixteenth, as long as the whole budget has room for it. A picture that still cannot fit after shrinking stays uncached,
/// as before. Pictures within the budget keep their full resolution. Printing (`render_page`) draws
/// the shrunk bitmaps too, as it does large raster pictures; PDF export parses the metafile itself
/// and is unaffected.
pub(crate) fn fit_cache(mut pixmaps: Vec<Option<Pixmap>>, geometry: usize) -> Vec<Option<Pixmap>> {
let pixels = |p: &Pixmap| usize::from(p.width()) * usize::from(p.height()) * 4;
let total: usize = pixmaps.iter().flatten().map(pixels).sum();
let fixed: usize = pixmaps.iter().flatten().map(|p| bitmap_bytes(p) - pixels(p)).sum();
if total.saturating_add(fixed).saturating_add(geometry) <= CACHE_BYTES {
return pixmaps;
}
// The bitmaps get what is left of an eighth, but never less than a sixteenth (so the allowance does
// not drop to nothing as geometry reaches the eighth) and never more than the whole budget leaves.
let target = CACHE_BYTES / 8;
let allowance = target.saturating_sub(geometry).max(target / 2).min(CACHE_BYTES.saturating_sub(geometry));
let room = allowance.saturating_sub(fixed) / 4;
for pm in pixmaps.iter_mut().flatten() {
// This bitmap's share of the pixels that fit.
let share = (room as u128 * pixels(pm) as u128 / total.max(1) as u128) as u64;
if let Some(small) = shrink(pm, share) {
*pm = small;
}
}
pixmaps
}
fn rgba_color(c: [u8; 4]) -> peniko::Color {
peniko::Color::from_rgba8(c[0], c[1], c[2], c[3])
}
/// Pattern tiles smaller than this (device pixels on both sides) are drawn as the tile's average
/// color: a sub-pixel pattern would only alias.
const MIN_TILE_PX: f64 = 1.5;
/// Draws a metafile picture into `r` (page points): fills and strokes in page space (so strokes keep
/// their width under non-uniform scaling), bitmaps stretched, all clipped to `r` and faded by `alpha`.
/// Strokes have round caps and joins, as GDI draws them, and are at least one device pixel wide, so
/// cosmetic (width 0) pens show as hairlines at any zoom.
/// their width under non-uniform scaling), bitmaps stretched (or turned by their transform),
/// pattern fills tiled, each item inside its clip region and clip paths, all clipped to `r` and
/// faded by `alpha`. Strokes take the pen's caps, joins and dashes and are at least one device
/// pixel wide, so cosmetic (width 0) pens show as hairlines at any zoom.
pub(crate) fn draw_vector(ctx: &mut RenderContext, v: &Vector, r: &kurbo::Rect, crop: &[f32; 4], alpha: f32, view: Affine) {
ctx.set_transform(view);
let alpha = if alpha.is_finite() { alpha.clamp(0.0, 1.0) } else { 1.0 };
@@ -212,9 +324,9 @@ pub(crate) fn draw_vector(ctx: &mut RenderContext, v: &Vector, r: &kurbo::Rect,
}
ctx.push_clip_layer(&r.to_path(0.1));
let pixel = device_pixel(view);
for it in v.pic.place(*r, *crop) {
for it in v.pic.place(*r, wordcraft_layout::crop_sides(*crop)) {
match it {
PlacedItem::Path { path, fill, stroke, even_odd, .. } => {
PlacedItem::Path { path, fill, stroke, line, even_odd, region, clips } => clipped(ctx, region.as_deref(), &clips, |ctx| {
if let Some(f) = fill {
ctx.set_paint(rgba_color(f));
ctx.set_fill_rule(if even_odd { peniko::Fill::EvenOdd } else { peniko::Fill::NonZero });
@@ -222,26 +334,71 @@ pub(crate) fn draw_vector(ctx: &mut RenderContext, v: &Vector, r: &kurbo::Rect,
}
if let Some((s, w)) = stroke {
ctx.set_paint(rgba_color(s));
ctx.set_stroke(kurbo::Stroke::new(w.max(pixel)).with_caps(kurbo::Cap::Round).with_join(kurbo::Join::Round));
ctx.set_stroke(pen(w, pixel, &line, &path));
ctx.stroke_path(&path);
}
}
PlacedItem::Bitmap { index, rect, .. } => {
let Some(Some(pm)) = v.pixmaps.get(index) else { continue };
}),
PlacedItem::Bitmap { index, rect, transform, region, clips } => clipped(ctx, region.as_deref(), &clips, |ctx| {
let Some(Some(pm)) = v.pixmaps.get(index) else { return };
let (pw, ph) = (pm.width().max(1) as f64, pm.height().max(1) as f64);
ctx.set_paint(vello_cpu::Image {
image: vello_cpu::ImageSource::Pixmap(pm.clone()),
sampler: peniko::ImageSampler::default().with_quality(peniko::ImageQuality::Medium),
});
ctx.set_paint_transform(Affine::translate((rect.x0, rect.y0)) * Affine::scale_non_uniform(rect.width() / pw, rect.height() / ph));
ctx.fill_rect(&rect);
ctx.reset_paint_transform();
}
PlacedItem::Pattern { .. } => {}
PlacedItem::Text { index, transform, .. } => {
if let Some(Item::Text(t)) = v.pic.items.get(index) {
draw_vector_text(ctx, t, view * transform);
let c = transform.as_coeffs();
// Upright and not mirrored: the bitmap fills `rect`.
if c[1] == 0.0 && c[2] == 0.0 && c[0] > 0.0 && c[3] > 0.0 {
ctx.set_paint_transform(Affine::translate((rect.x0, rect.y0)) * Affine::scale_non_uniform(rect.width() / pw, rect.height() / ph));
ctx.fill_rect(&rect);
} else {
// A turned, skewed or mirrored bitmap: `transform` maps the unit square onto its place.
ctx.set_paint_transform(transform * Affine::scale_non_uniform(1.0 / pw, 1.0 / ph));
ctx.fill_path(&(transform * kurbo::Rect::new(0.0, 0.0, 1.0, 1.0).to_path(0.1)));
}
ctx.reset_paint_transform();
}),
PlacedItem::Pattern { index, path, even_odd, tile, region, clips } => clipped(ctx, region.as_deref(), &clips, |ctx| {
let Some(Item::Pattern { tile: t, .. }) = v.pic.items.get(index) else { return };
ctx.set_fill_rule(if even_odd { peniko::Fill::EvenOdd } else { peniko::Fill::NonZero });
// `tile` maps one tile pixel to page points: the tile's sides are its columns and
// its rows under that, in device pixels. The tile is drawn when either side is at
// least `MIN_TILE_PX`.
let c = (view * tile).as_coeffs();
let across = c[0].hypot(c[1]) * f64::from(t.width);
let down = c[2].hypot(c[3]) * f64::from(t.height);
match v.pixmaps.get(index) {
Some(Some(pm)) if across.max(down) >= MIN_TILE_PX => {
ctx.set_paint(vello_cpu::Image {
image: vello_cpu::ImageSource::Pixmap(pm.clone()),
sampler: peniko::ImageSampler {
x_extend: peniko::Extend::Repeat,
y_extend: peniko::Extend::Repeat,
quality: peniko::ImageQuality::Low,
alpha: 1.0,
},
});
ctx.set_paint_transform(tile);
ctx.fill_path(&path);
ctx.reset_paint_transform();
}
_ => {
ctx.set_paint(rgba_color(v.averages.get(index).copied().unwrap_or([0; 4])));
ctx.fill_path(&path);
}
}
}),
PlacedItem::Text { index, transform, clip, region, clips } => {
clipped(ctx, region.as_deref(), &clips, |ctx| {
let Some(Item::Text(t)) = v.pic.items.get(index) else { return };
if let Some(c) = clip {
ctx.push_clip_layer(&c.to_path(0.1));
}
draw_vector_text(ctx, t, view * transform);
ctx.set_transform(view);
if clip.is_some() {
ctx.pop_layer();
}
});
ctx.set_transform(view);
}
}
@@ -253,15 +410,76 @@ pub(crate) fn draw_vector(ctx: &mut RenderContext, v: &Vector, r: &kurbo::Rect,
}
}
/// Draws a metafile text run: `tf` maps the run's own space (see [`PlacedItem::Text`]) to the device.
/// Draws `draw` inside a metafile item's clip region and every one of its clip paths (page
/// points, under the current transform). No region is the default clip.
fn clipped(
ctx: &mut RenderContext,
region: Option<&kurbo::BezPath>,
clips: &[Arc<craft_metafile::PlacedClip>],
draw: impl FnOnce(&mut RenderContext),
) {
if let Some(region) = region {
ctx.set_fill_rule(peniko::Fill::NonZero);
ctx.push_clip_layer(region);
}
for c in clips {
ctx.set_fill_rule(if c.even_odd { peniko::Fill::EvenOdd } else { peniko::Fill::NonZero });
ctx.push_clip_layer(&c.path);
}
ctx.set_fill_rule(peniko::Fill::NonZero);
draw(ctx);
for _ in 0..clips.len() + usize::from(region.is_some()) {
ctx.pop_layer();
}
}
/// A metafile pen for `path` as a stroke `width` wide (page points, at least one device `pixel`):
/// its caps, joins, miter limit and dashes (`wordcraft_layout::metafile_dashes`).
fn pen(width: f64, pixel: f64, line: &craft_metafile::LineStyle, path: &kurbo::BezPath) -> kurbo::Stroke {
let cap = match line.cap {
craft_metafile::Cap::Round => kurbo::Cap::Round,
craft_metafile::Cap::Square => kurbo::Cap::Square,
craft_metafile::Cap::Flat => kurbo::Cap::Butt,
};
let join = match line.join {
craft_metafile::Join::Round => kurbo::Join::Round,
craft_metafile::Join::Bevel => kurbo::Join::Bevel,
craft_metafile::Join::Miter => kurbo::Join::Miter,
};
let stroke = kurbo::Stroke::new(width.max(pixel))
.with_caps(cap)
.with_join(join)
.with_miter_limit(f64::from(wordcraft_layout::metafile_miter_limit(line.miter_limit)));
if line.dash.is_empty() {
return stroke;
}
match wordcraft_layout::metafile_dashes(&line.dash, width == 0.0, pixel, path.perimeter(1.0)) {
Some(dash) => stroke.with_dashes(0.0, dash),
None => stroke,
}
}
/// Draws a metafile text run: `tf` maps its text space (`craft_metafile::Text::transform`) to the
/// device.
fn draw_vector_text(ctx: &mut RenderContext, t: &craft_metafile::Text, tf: Affine) {
let (face, shaped) = wordcraft_layout::metafile_text_run(t);
let glyphs: Vec<_> = shaped.iter().map(|g| (g.cluster, f64::from(g.x_advance), f64::from(g.x_offset), f64::from(g.y_offset))).collect();
let Some(lay) = wordcraft_layout::layout_metafile_text(t, face.upem, face.ascent, face.descent, &glyphs) else { return };
let k = lay.em / face.upem.max(1.0);
let canvas = kurbo::Rect::new(0.0, 0.0, f64::from(ctx.width()), f64::from(ctx.height()));
// An opaque background mode fills the character cells first.
if let Some(bg) = t.background {
let [x0, y0, x1, y1] = lay.cell;
let cell = tf * kurbo::Rect::new(x0, y0, x1, y1).to_path(0.1);
let b = cell.bounding_box();
if x1 > x0 && [b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite() && v.abs() <= MAX_GLYPH_PIXELS * 16.0) && b.overlaps(canvas) {
ctx.set_transform(Affine::IDENTITY);
ctx.set_paint(rgba_color(bg));
ctx.fill_path(&cell);
}
}
ctx.set_paint(rgba_color(t.color));
let db = FontDb::global();
let canvas = kurbo::Rect::new(0.0, 0.0, f64::from(ctx.width()), f64::from(ctx.height()));
let mut oversized = 0usize;
for (g, (x, y)) in shaped.iter().zip(&lay.glyphs) {
let o = db.outline(&face, g.gid);
+547
View File
@@ -1,4 +1,5 @@
use super::*;
use crate::media::fit_cache;
use wordcraft_layout::display::page_display;
use wordcraft_layout::{LayoutCache, LayoutOptions, layout};
@@ -1041,6 +1042,393 @@ fn metafile_picture_is_drawn_as_vectors() {
assert!(left[..3].iter().all(|c| *c > 200), "left half should be paper, not the grey box: {left:?}");
}
/// An EMF whose only record is one `w` x `h` 1 bpp black and white bitmap over the whole picture.
fn emf_with_1bpp_bitmap(w: i32, h: i32) -> Vec<u8> {
let mut hdr = vec![0u8; 88];
hdr[0..4].copy_from_slice(&1u32.to_le_bytes());
hdr[4..8].copy_from_slice(&88u32.to_le_bytes());
hdr[8..24].copy_from_slice(&le32(&[0, 0, 100, 100]));
hdr[24..40].copy_from_slice(&le32(&[0, 0, 2500, 2500]));
hdr[40..44].copy_from_slice(&0x464D_4520u32.to_le_bytes());
hdr[72..88].copy_from_slice(&le32(&[1000, 1000, 250, 250]));
let stride = (w as usize).div_ceil(32) * 4;
let mut payload = vec![0u8; 16];
payload.extend(le32(&[0, 0, 0, 0, w, h, 80, 48, 128, (stride * h as usize) as i32, 0, 0x00CC_0020, 100, 100]));
payload.extend(le32(&[40, w, h, 1 | (1 << 16), 0, 0, 0, 0, 0, 0]));
payload.extend([0, 0, 0, 0, 255, 255, 255, 0]);
payload.extend((0..stride * h as usize).map(|i| (i * 31) as u8));
[hdr, emf_rec(81, &payload), emf_rec(14, &[0; 12])].concat()
}
/// #5482: a metafile whose bitmaps are past the whole cache budget was parsed and decoded again on
/// every repaint, because the cache refused it. It is now kept (its bitmaps at a smaller size).
#[test]
fn a_metafile_with_a_huge_bitmap_is_parsed_once() {
// 8000 x 5000 is 160 MB of RGBA, past the 128 MB cache, from a 5 MB file.
let mut d = Document::new();
// A key of its own: the vector cache is global and tests running in threads share `image1.emf`.
let key = "huge-parsed-once.emf";
d.media.insert(key.to_string(), Arc::new(emf_with_1bpp_bitmap(8000, 5000)));
let first = vector_for(&d, key).expect("the metafile reads");
let again = vector_for(&d, key).expect("the metafile reads");
assert!(Arc::ptr_eq(&first, &again), "the second repaint reuses the parsed picture");
assert!(first.bytes() <= CACHE_BYTES / 8, "{} bytes", first.bytes());
}
/// Several huge metafiles on screen together (zoomed-out pages, thumbnails) sit side by side in the
/// cache instead of clearing it, so a small metafile drawn with them stays a hit.
#[test]
fn huge_metafiles_do_not_push_a_small_one_out_of_the_cache() {
let mut d = Document::new();
let small = "evict-small.emf";
d.media.insert(small.to_string(), Arc::new(emf_with_1bpp_bitmap(64, 64)));
let huge: Vec<String> = (0..4).map(|n| format!("evict-huge-{n}.emf")).collect();
for (n, k) in huge.iter().enumerate() {
// Distinct bytes per file (the width differs; 8000 x 5000 is the most pixels a metafile decodes), so each is its own cache entry.
d.media.insert(k.clone(), Arc::new(emf_with_1bpp_bitmap(8000 - n as i32, 5000)));
}
let small_first = vector_for(&d, small).expect("the small metafile reads");
for round in 0..2 {
for k in &huge {
assert!(vector_for(&d, k).is_some(), "round {round}");
}
}
let kept: Vec<_> = huge.iter().map(|k| vector_for(&d, k).unwrap()).collect();
let again: Vec<_> = huge.iter().map(|k| vector_for(&d, k).unwrap()).collect();
for (a, b) in kept.iter().zip(&again) {
assert!(Arc::ptr_eq(a, b), "a huge metafile is parsed once while four are drawn together");
}
assert!(Arc::ptr_eq(&small_first, &vector_for(&d, small).unwrap()), "the small metafile is still cached");
}
/// Time of three repaints of a picture with a 160 MB bitmap:
/// `cargo test -p wordcraft-render --release -- --ignored --nocapture huge_metafile_repaint_time`.
#[test]
#[ignore = "timing only"]
fn huge_metafile_repaint_time() {
let mut d = Document::new();
let key = d.add_media(emf_with_1bpp_bitmap(8000, 5000), "emf");
for n in 1..=4 {
let t = std::time::Instant::now();
assert!(vector_for(&d, &key).is_some());
eprintln!("repaint {n}: vector_for {:.1} ms", t.elapsed().as_secs_f64() * 1e3);
}
}
#[test]
fn bitmaps_are_shrunk_in_proportion_only_when_the_picture_is_past_the_cache() {
let px = vello_cpu::color::PremulRgba8 { r: 1, g: 2, b: 3, a: 255 };
let pm = |w: u16, h: u16| Some(Pixmap::from_parts(vec![px; usize::from(w) * usize::from(h)], w, h));
let bytes = |v: &[Option<Pixmap>]| v.iter().flatten().map(|p| usize::from(p.width()) * usize::from(p.height()) * 4).sum::<usize>();
// Within the budget: untouched.
let kept = fit_cache(vec![pm(1000, 1000), None, pm(2000, 2000)], 1_000_000);
assert_eq!(kept.iter().flatten().map(|p| (p.width(), p.height())).collect::<Vec<_>>(), [(1000, 1000), (2000, 2000)]);
assert!(kept[1].is_none(), "a path item keeps its place in the list");
// A 144 MB and a 36 MB bitmap: both shrink by the same factor.
let fit = fit_cache(vec![pm(6000, 6000), pm(3000, 3000)], 4_000_000);
assert!(bytes(&fit) + 4_000_000 <= CACHE_BYTES / 8, "{} bytes", bytes(&fit));
let (a, b) = (fit[0].as_ref().unwrap(), fit[1].as_ref().unwrap());
assert_eq!((a.width(), b.width()), (1500, 750), "each bitmap keeps its share of the pixels that fit");
assert!(a.data().iter().all(|p| (p.r, p.g, p.b, p.a) == (1, 2, 3, 255)), "flat stays flat");
}
/// Geometry of an eighth of the budget or more leaves the bitmaps a positive allowance, so the
/// picture is still kept (and reused) when it fits the whole budget after shrinking; one whose
/// geometry alone fills the budget stays uncached.
#[test]
fn heavy_geometry_still_leaves_the_bitmaps_a_cacheable_size() {
let px = vello_cpu::color::PremulRgba8 { r: 1, g: 2, b: 3, a: 255 };
let pm = |w: u16, h: u16| Some(Pixmap::from_parts(vec![px; usize::from(w) * usize::from(h)], w, h));
let bytes = |v: &[Option<Pixmap>]| v.iter().flatten().map(|p| usize::from(p.width()) * usize::from(p.height()) * 4).sum::<usize>();
let geometry = CACHE_BYTES / 8 + 4_000_000;
let fit = fit_cache(vec![pm(6000, 6000)], geometry);
let size = bytes(&fit);
assert!(size > 0 && size < 6000 * 6000 * 4, "shrunk, not dropped: {size} bytes");
assert!(size + geometry <= CACHE_BYTES, "{size} bytes");
// The shrunk picture is accepted by the cache and hit again.
let src = Arc::new(vec![0u8; 1]);
let mut c: MediaCache<u8> = MediaCache { map: Default::default(), bytes: 0 };
c.insert("heavy", &src, 7, size + geometry);
assert_eq!(c.get("heavy", &src), Some(7));
// Just under and just over the eighth: both shrink the bitmap to a positive size, none to nothing.
for g in [CACHE_BYTES / 8 - 1, CACHE_BYTES / 8, CACHE_BYTES / 8 + 1] {
let size = bytes(&fit_cache(vec![pm(6000, 6000)], g));
assert!(size > 0 && size < 6000 * 6000 * 4 && size + g <= CACHE_BYTES / 4, "geometry {g}: {size} bytes");
}
// Geometry that takes the whole budget leaves nothing to shrink to: the bitmap stays as it is.
let full = fit_cache(vec![pm(6000, 6000)], CACHE_BYTES);
assert_eq!(bytes(&full), 6000 * 6000 * 4);
}
/// #6636: an EMF+ only file (no plain EMF drawing records) whose EmfPlusDrawImage draws a
/// 32bppPARGB bitmap over the right half: the bitmap's pixels are drawn.
#[test]
fn emf_plus_only_bitmap_is_drawn() {
// EmfPlusObject 0, an image (type 5): a 2 × 1 bitmap in PixelFormat32bppPARGB, opaque red
// and then red at half opacity (premultiplied BGRA 0, 0, 128, 128).
let mut image = le32(&[0xDBC0_1002_u32 as i32, 1, 2, 1, 8, 0x000E_200B, 0]);
image.extend([0u8, 0, 255, 255, 0, 0, 128, 128]);
let object = plus_rec(0x4008, 0x0500, &image);
// EmfPlusDrawImage of image 0: the whole bitmap (pixel units) into x 50..100, y 0..100.
let mut draw = le32(&[-1, 2]);
draw.extend([0.0f32, 0.0, 2.0, 1.0, 50.0, 0.0, 50.0, 100.0].iter().flat_map(|v| v.to_le_bytes()));
let emf = emf_plus_file(&[object, plus_rec(0x401A, 0, &draw)]);
let (img, rect) = emf_on_page(emf, [0.0; 4], 1.0);
let at = |fx: f32| img.pixel((rect.x + rect.w * fx) as u32, (rect.y + rect.h * 0.5) as u32);
let (opaque, half, left) = (at(0.6), at(0.9), at(0.25));
assert!(is_red(opaque), "the bitmap's opaque red is drawn on the right half: {opaque:?}");
// Premultiplied half-opacity red over white paper is (255, 127, 127); read as straight
// color it would be about (191, 127, 127).
assert!(half[0] > 235 && (110..145).contains(&half[1]) && (110..145).contains(&half[2]), "half-opacity red: {half:?}");
assert!(is_paper(left), "left half should be paper: {left:?}");
}
/// #6636: EmfPlusDrawImage draws a bitmap in PixelFormat32bppARGB, 24bppRGB and 32bppRGB, and a
/// compressed PNG or JPEG bitmap, in an EMF+ only file.
#[test]
fn emf_plus_only_bitmap_formats_are_drawn() {
let encoded = |png: bool| {
let red = [255u8, 0, 0].repeat(64);
if png {
let img = image::RgbImage::from_raw(8, 8, red).unwrap();
wordcraft_geom::picture::encode_png(&image::DynamicImage::from(img)).unwrap()
} else {
wordcraft_geom::picture::encode_jpeg(&red, 8, 8, 100).unwrap()
}
};
// Name, width, height, stride, pixel format, bitmap type (0 pixels, 1 compressed) and data.
let cases: [(&str, i32, i32, i32, u32, i32, Vec<u8>); 5] = [
("32bppARGB", 2, 1, 8, 0x0026_200A, 0, [0u8, 0, 255, 255].repeat(2)),
("24bppRGB", 2, 1, 8, 0x0002_1808, 0, vec![0, 0, 255, 0, 0, 255, 0, 0]),
("32bppRGB", 2, 1, 8, 0x0002_2009, 0, [0u8, 0, 255, 0].repeat(2)),
("PNG", 8, 8, 0, 0, 1, encoded(true)),
("JPEG", 8, 8, 0, 0, 1, encoded(false)),
];
for (name, w, h, stride, format, kind, data) in cases {
let mut image = le32(&[0xDBC0_1002_u32 as i32, 1, w, h, stride, format as i32, kind]);
image.extend(data);
// Records are a multiple of 4 bytes long.
image.resize(image.len().next_multiple_of(4), 0);
let mut draw = le32(&[-1, 2]);
draw.extend([0.0f32, 0.0, w as f32, h as f32, 50.0, 0.0, 50.0, 100.0].iter().flat_map(|v| v.to_le_bytes()));
let emf = emf_plus_file(&[plus_rec(0x4008, 0x0500, &image), plus_rec(0x401A, 0, &draw)]);
let (img, rect) = emf_on_page(emf, [0.0; 4], 1.0);
let at = |fx: f32| img.pixel((rect.x + rect.w * fx) as u32, (rect.y + rect.h * 0.5) as u32);
let (right, left) = (at(0.75), at(0.25));
assert!(is_red(right), "{name}: the red bitmap is drawn on the right half: {right:?}");
assert!(is_paper(left), "{name}: left half should be paper: {left:?}");
}
}
/// An EMF+ record for [`emf_plus_file`]: type, flags and data.
fn plus_rec(typ: u16, flags: u16, data: &[u8]) -> Vec<u8> {
let mut v = typ.to_le_bytes().to_vec();
v.extend(flags.to_le_bytes());
v.extend(((12 + data.len()) as u32).to_le_bytes());
v.extend((data.len() as u32).to_le_bytes());
v.extend(data);
v
}
/// An EMF+ only file with the frame of [`red_right_half_emf`]: an EmfPlusHeader (96 dpi), then
/// `records`, then EmfPlusEndOfFile, in one comment record.
fn emf_plus_file(records: &[Vec<u8>]) -> Vec<u8> {
let mut comment = 0x2B46_4D45u32.to_le_bytes().to_vec();
comment.extend(plus_rec(0x4001, 0, &le32(&[0xDBC0_1002_u32 as i32, 1, 96, 96])));
comment.extend(records.concat());
comment.extend(plus_rec(0x4002, 0, &[]));
let mut payload = (comment.len() as u32).to_le_bytes().to_vec();
payload.extend(comment);
let mut emf = red_right_half_emf()[..88].to_vec();
emf.extend([emf_rec(70, &payload), emf_rec(14, &[0; 12])].concat());
emf
}
/// Renders a document holding one 70 pt metafile picture with `crop` at `scale`: the page and the
/// picture's frame (points).
fn emf_on_page(emf: Vec<u8>, crop: [f32; 4], scale: f32) -> (Rendered, wordcraft_geom::Rect) {
emf_on_page_sized(emf, (70.0, 70.0), crop, scale)
}
/// [`emf_on_page`] with the picture `size` (points).
fn emf_on_page_sized(emf: Vec<u8>, size: (f32, f32), crop: [f32; 4], scale: f32) -> (Rendered, wordcraft_geom::Rect) {
let mut d = Document::new();
let media = d.add_media(emf, "emf");
let mut p = wordcraft_doc::Paragraph::new();
let obj = wordcraft_doc::para::InlineObject::Image {
media,
w: size.0,
h: size.1,
alt: String::new(),
float: Default::default(),
crop,
fx: Default::default(),
ole: None,
};
p.insert_object(0, obj, &Default::default()).unwrap();
d.body = vec![wordcraft_doc::para_block(p)];
let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default());
let opts = RenderOptions::default();
let rect = page_display(&d, &l.pages[0], &opts.display)
.iter()
.find_map(|i| match i {
Draw::Image { rect, .. } => Some(*rect),
_ => None,
})
.expect("a picture on the page");
(render_page(&d, &l.pages[0], scale, &opts), rect)
}
/// Whether a pixel is close to pure red.
fn is_red(p: [u8; 4]) -> bool {
p[0] > 200 && p[1] < 60 && p[2] < 60
}
/// Whether a pixel is paper.
fn is_paper(p: [u8; 4]) -> bool {
p[..3].iter().all(|c| *c > 200)
}
/// A clip region (INTERSECTCLIPRECT to the left half) keeps a red rectangle over the whole
/// picture to that half; once RESTOREDC drops it, a second rectangle across the bottom shows on
/// both halves.
#[test]
fn metafile_clip_region_clips_and_ends() {
let mut emf = red_right_half_emf()[..88].to_vec();
let brush = emf_rec(39, &le32(&[1, 0, 0x0000_00FF, 0]));
let recs = [
brush,
emf_rec(37, &le32(&[1])),
emf_rec(33, &[]),
emf_rec(30, &le32(&[0, 0, 50, 100])),
emf_rec(43, &le32(&[0, 0, 100, 60])),
emf_rec(34, &le32(&[-1])),
emf_rec(43, &le32(&[0, 80, 100, 100])),
emf_rec(14, &[0; 12]),
];
emf.extend(recs.concat());
let (img, rect) = emf_on_page(emf, [0.0; 4], 1.0);
let at = |fx: f32, fy: f32| img.pixel((rect.x + rect.w * fx) as u32, (rect.y + rect.h * fy) as u32);
assert!(is_red(at(0.25, 0.3)), "inside the clip: {:?}", at(0.25, 0.3));
assert!(is_paper(at(0.75, 0.3)), "outside the clip: {:?}", at(0.75, 0.3));
assert!(is_red(at(0.75, 0.9)), "after the clip is restored away: {:?}", at(0.75, 0.9));
}
/// The vector cache counts each item's copy of the clip region: 100 rectangles drawn inside a
/// clip region hold 100 copies of its rectangle more than without it.
#[test]
fn metafile_cache_counts_clip_regions() {
let bytes = |clip: bool| {
let mut emf = red_right_half_emf()[..88].to_vec();
if clip {
emf.extend(emf_rec(30, &le32(&[0, 0, 50, 100])));
}
for i in 0..100 {
emf.extend(emf_rec(43, &le32(&[i % 50, 0, i % 50 + 10, 10])));
}
emf.extend(emf_rec(14, &[0; 12]));
media::build_vector(&emf).map(|v| v.bytes())
};
let (with, without) = (bytes(true).expect("a picture"), bytes(false).expect("a picture"));
assert!(with >= without + 100 * 16, "{with} and {without}");
}
/// A hatch tile squeezed to well under a pixel tall but several pixels wide (the picture is 70 pt
/// wide and 2 pt tall) keeps its vertical lines: the row crosses red lines and the background
/// between them, not one blended color.
#[test]
fn metafile_narrow_hatch_tile_keeps_its_lines() {
let mut emf = red_right_half_emf()[..88].to_vec();
let brush = emf_rec(39, &le32(&[1, 2, 0x0000_00FF, 1]));
// The stock NULL_PEN leaves the rectangle without an outline.
let no_pen = emf_rec(37, &le32(&[0x8000_0008_u32 as i32]));
emf.extend([brush, emf_rec(37, &le32(&[1])), no_pen, emf_rec(43, &le32(&[0, 0, 100, 100])), emf_rec(14, &[0; 12])].concat());
let (img, rect) = emf_on_page_sized(emf, (70.0, 2.0), [0.0; 4], 1.0);
let y = (rect.y + rect.h / 2.0) as u32;
let row: Vec<u8> = ((rect.x + 2.0) as u32..(rect.x + rect.w - 2.0) as u32).map(|x| img.pixel(x, y)[1]).collect();
assert!(row.iter().any(|g| *g < 160) && row.iter().any(|g| *g > 240), "red lines and background: {row:?}");
}
/// A clip path (a rectangle path over the left half, SELECTCLIPPATH with RGN_COPY) keeps a red
/// rectangle over the whole picture to that half.
#[test]
fn metafile_clip_path_clips() {
let mut emf = red_right_half_emf()[..88].to_vec();
let brush = emf_rec(39, &le32(&[1, 0, 0x0000_00FF, 0]));
let recs = [
brush,
emf_rec(37, &le32(&[1])),
emf_rec(59, &[]),
emf_rec(43, &le32(&[0, 0, 50, 100])),
emf_rec(60, &[]),
emf_rec(67, &le32(&[5])),
emf_rec(43, &le32(&[0, 0, 100, 100])),
emf_rec(14, &[0; 12]),
];
emf.extend(recs.concat());
let (img, rect) = emf_on_page(emf, [0.0; 4], 1.0);
let at = |fx: f32| img.pixel((rect.x + rect.w * fx) as u32, (rect.y + rect.h * 0.5) as u32);
assert!(is_red(at(0.25)), "inside the clip path: {:?}", at(0.25));
assert!(is_paper(at(0.75)), "outside the clip path: {:?}", at(0.75));
}
/// A bitmap under a world transform that turns it a quarter turn clockwise about the picture's
/// center (EmfPlusSetWorldTransform): its left pixel (red) is drawn at the top and its right pixel
/// (blue) at the bottom.
#[test]
fn emf_plus_turned_bitmap_is_drawn_turned() {
let mut image = le32(&[0xDBC0_1002_u32 as i32, 1, 2, 1, 8, 0x000E_200B, 0]);
// BGRA: red, then blue.
image.extend([0u8, 0, 255, 255, 255, 0, 0, 255]);
let turn = plus_rec(0x402A, 0, &[0.0f32, 1.0, -1.0, 0.0, 100.0, 0.0].iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<_>>());
let mut draw = le32(&[-1, 2]);
draw.extend([0.0f32, 0.0, 2.0, 1.0, 25.0, 25.0, 50.0, 50.0].iter().flat_map(|v| v.to_le_bytes()));
let emf = emf_plus_file(&[plus_rec(0x4008, 0x0500, &image), turn, plus_rec(0x401A, 0, &draw)]);
let (img, rect) = emf_on_page(emf, [0.0; 4], 1.0);
let at = |fx: f32, fy: f32| img.pixel((rect.x + rect.w * fx) as u32, (rect.y + rect.h * fy) as u32);
let (top_right, bottom_left) = (at(0.65, 0.37), at(0.35, 0.62));
assert!(is_red(top_right), "red at the top: {top_right:?}");
assert!(bottom_left[2] > 200 && bottom_left[0] < 60, "blue at the bottom: {bottom_left:?}");
}
/// A geometric PS_USERSTYLE pen whose dashes and gaps are far below a pixel draws its line solid
/// instead of splitting it into dashes too small to see.
#[test]
fn metafile_sub_pixel_dashes_draw_solid() {
let mut emf = red_right_half_emf()[..88].to_vec();
// 10,000 device pixels over 250 mm: a device unit is 0.025 mm. The picture is 1000 units wide.
emf[8..24].copy_from_slice(&le32(&[0, 0, 1000, 1000]));
emf[72..80].copy_from_slice(&le32(&[10_000, 10_000]));
// EXTCREATEPEN 1: PS_GEOMETRIC | PS_ENDCAP_FLAT | PS_USERSTYLE, 80 units wide, black, two
// entries of 1 unit.
let pen = emf_rec(95, &le32(&[1, 0, 0, 0, 0, 0x0001_0207, 80, 0, 0, 0, 2, 1, 1]));
let recs = [pen, emf_rec(37, &le32(&[1])), emf_rec(27, &le32(&[0, 500])), emf_rec(54, &le32(&[1000, 500])), emf_rec(14, &[0; 12])];
emf.extend(recs.concat());
let (img, rect) = emf_on_page(emf, [0.0; 4], 1.0);
let y = (rect.y + rect.h * 0.5) as u32;
let (x0, x1) = ((rect.x + 5.0) as u32, (rect.x + rect.w - 5.0) as u32);
let dark = (x0..x1).filter(|&x| img.pixel(x, y)[..3].iter().all(|c| *c < 60)).count();
assert_eq!(dark, (x1 - x0) as usize, "the line is solid black");
}
/// A hatched brush (CREATEBRUSHINDIRECT, BS_HATCHED, HS_VERTICAL) fills with its red lines over
/// the background, not with a solid red.
#[test]
fn metafile_hatch_brush_draws_its_lines() {
let mut emf = red_right_half_emf()[..88].to_vec();
let brush = emf_rec(39, &le32(&[1, 2, 0x0000_00FF, 1]));
emf.extend([brush, emf_rec(37, &le32(&[1])), emf_rec(43, &le32(&[0, 0, 100, 100])), emf_rec(14, &[0; 12])].concat());
let scale = 4.0;
let (img, rect) = emf_on_page(emf, [0.0; 4], scale);
let y = ((rect.y + rect.h / 2.0) * scale) as u32;
let (x0, x1) = (((rect.x + 2.0) * scale) as u32, ((rect.x + rect.w - 2.0) * scale) as u32);
let red = (x0..x1).filter(|&x| img.pixel(x, y)[1] < 128).count();
let n = (x1 - x0) as usize;
assert!(red > 0 && red < n * 3 / 4, "the row crosses red lines and the background between them: {red} of {n} red");
}
/// #1899: a crop that keeps a sliver of the picture (3% here; a header's bar can be 2.7% of a
/// page-sized metafile) stretches that sliver over the frame, as the file says, for vector and
/// bitmap pictures alike. Both pictures are paper on the left half and red on the right.
@@ -1084,6 +1472,43 @@ fn a_crop_keeping_a_sliver_fills_the_frame_with_it() {
}
}
/// A negative crop side draws as no crop on that side, for vector and bitmap pictures alike: a
/// left side of -0.5 does not pad the source, so the frame at 55% shows the source at 55% (red).
#[test]
fn a_negative_crop_side_draws_uncropped() {
let img = image::RgbaImage::from_fn(100, 100, |x, _| image::Rgba(if x >= 50 { [255, 0, 0, 255] } else { [255; 4] }));
let png = wordcraft_geom::picture::encode_png(&image::DynamicImage::from(img)).unwrap();
for (bytes, ext) in [(red_right_half_emf(), "emf"), (png, "png")] {
let mut d = Document::new();
let media = d.add_media(bytes, ext);
let mut p = wordcraft_doc::Paragraph::new();
let obj = wordcraft_doc::para::InlineObject::Image {
media,
w: 70.0,
h: 70.0,
alt: String::new(),
float: Default::default(),
crop: [-0.5, 0.0, 0.0, 0.0],
fx: Default::default(),
ole: None,
};
p.insert_object(0, obj, &Default::default()).unwrap();
d.body = vec![wordcraft_doc::para_block(p)];
let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default());
let opts = RenderOptions::default();
let rect = page_display(&d, &l.pages[0], &opts.display)
.iter()
.find_map(|i| match i {
Draw::Image { rect, .. } => Some(*rect),
_ => None,
})
.expect("a picture on the page");
let img = render_page(&d, &l.pages[0], 1.0, &opts);
let px = img.pixel((rect.x + rect.w * 0.55) as u32, (rect.y + rect.h * 0.5) as u32);
assert!(is_red(px), "{ext}: {px:?}");
}
}
#[test]
fn cosmetic_metafile_pen_is_one_device_pixel_wide() {
// MOVETO (0, 50), LINETO (100, 50) with the default cosmetic black pen: a hairline across the middle.
@@ -1168,6 +1593,29 @@ fn metafile_text_records_are_painted() {
assert!(dark > 50, "the text is painted inside the picture: {dark} dark pixels");
}
/// With the opaque background mode (the default) and a red background color (SETBKCOLOR), a text
/// run's character cells are filled red behind the black text.
#[test]
fn metafile_text_fills_its_opaque_background() {
let mut font = emf_rec(82, &le32(&[1, -20, 0, 0, 0, 400, 0, 0]));
let mut name: Vec<u8> = "Arial".encode_utf16().flat_map(|u| u.to_le_bytes()).collect();
name.resize(64, 0);
font.extend(name);
font[4..8].copy_from_slice(&104u32.to_le_bytes());
let mut text = emf_rec(84, &le32(&[0, 0, 100, 100, 1, 0, 0, 5, 40, 4, 76, 0, 0, 0, 0, 0, 0]));
text.extend("WWWW".encode_utf16().flat_map(|u| u.to_le_bytes()));
text[4..8].copy_from_slice(&84u32.to_le_bytes());
let mut emf = red_right_half_emf()[..88].to_vec();
let bk = emf_rec(25, &le32(&[0x0000_00FF]));
emf.extend([bk, font, emf_rec(37, &le32(&[1])), emf_rec(24, &le32(&[0])), text, emf_rec(14, &[0; 12])].concat());
let scale = 2.0;
let (img, rect) = emf_on_page(emf, [0.0; 4], scale);
let (x0, y0) = ((rect.x * scale) as u32, (rect.y * scale) as u32);
let (x1, y1) = (((rect.x + rect.w) * scale) as u32, ((rect.y + rect.h) * scale) as u32);
let red = (y0..y1).flat_map(|y| (x0..x1).map(move |x| (x, y))).filter(|&(x, y)| is_red(img.pixel(x, y))).count();
assert!(red > 50, "the character cells are filled red: {red} red pixels");
}
/// An EMF text run whose anchor sits inside the picture but whose font is billions of units
/// tall: each glyph's curves would span billions of device pixels, which the rasteriser
/// subdivides for ever. Glyphs that big (or off the raster) are left out; the page renders.
@@ -1528,3 +1976,102 @@ fn undecodable_pictures_keep_their_grey_box_pixels() {
let h = img.pixels.iter().fold(0xcbf29ce484222325u64, |h, b| (h ^ u64::from(*b)).wrapping_mul(0x100000001b3));
assert_eq!(h, 0x79f9f1d3602a9925, "{h:#x}");
}
/// The cache charge for a metafile's geometry covers what its items keep after their pixels move
/// out: a pattern's path and tile, and the clip rectangles and clip paths of every kind of item.
/// A tile or clip path shared by several items is charged once.
#[test]
fn geometry_bytes_counts_pattern_tiles_and_clips_once() {
use craft_metafile::{ClipPath, Tile};
let segs = |n: usize| vec![Seg::Line(0.0, 0.0); n];
let pic = |items: Vec<Item>| Picture { width: 10.0, height: 10.0, items, skipped_records: 0 };
let base = crate::media::geometry_bytes(&pic(vec![]));
let tile = Arc::new(Tile { width: 1000, height: 1000, rgba: vec![0; 4_000_000], cell: [1.0, 1.0], origin: [0.0, 0.0] });
let pattern = |tile: &Arc<Tile>| Item::Pattern { segs: segs(1000), even_odd: false, tile: tile.clone(), region: None, clips: vec![] };
let one = crate::media::geometry_bytes(&pic(vec![pattern(&tile)]));
assert!(one - base >= 4_000_000 + 1000 * std::mem::size_of::<Seg>(), "{} bytes", one - base);
// Two fills of the same brush keep one tile.
let two = crate::media::geometry_bytes(&pic(vec![pattern(&tile), pattern(&tile)]));
assert!(two - one < 1_000_000, "the shared tile is charged once: {} bytes more", two - one);
// A clip path shared by two bitmaps is charged once; a clip region is charged per item.
let clip = Arc::new(ClipPath { segs: segs(100_000), even_odd: false });
let bitmap = |clips: Vec<Arc<ClipPath>>, region: Option<Vec<[f32; 4]>>| Item::Bitmap {
rect: [0.0; 4],
transform: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0],
width: 0,
height: 0,
rgba: vec![],
region,
clips,
};
let plain = crate::media::geometry_bytes(&pic(vec![bitmap(vec![], None)]));
let clipped = crate::media::geometry_bytes(&pic(vec![bitmap(vec![clip.clone()], None), bitmap(vec![clip.clone()], None)]));
let clip_bytes = 100_000 * std::mem::size_of::<Seg>();
assert!(clipped - 2 * plain >= clip_bytes && clipped - 2 * plain < 2 * clip_bytes, "{} bytes", clipped - 2 * plain);
let region = crate::media::geometry_bytes(&pic(vec![bitmap(vec![], Some(vec![[0.0; 4]; 1000]))]));
assert!(region - plain >= 1000 * 16, "{} bytes", region - plain);
}
/// The parser collects segments and dashes without shrinking them, so the charge follows the
/// capacity a vector keeps, not only its length.
#[test]
fn geometry_bytes_charges_the_capacity_of_segment_and_dash_vectors() {
use craft_metafile::LineStyle;
let pic = |items: Vec<Item>| Picture { width: 10.0, height: 10.0, items, skipped_records: 0 };
let path = |segs: Vec<Seg>, dash: Vec<f32>| Item::Path {
segs,
fill: None,
stroke: Some(([0, 0, 0, 255], 1.0)),
line: LineStyle { dash, ..LineStyle::default() },
even_odd: false,
region: None,
clips: vec![],
};
let tight = crate::media::geometry_bytes(&pic(vec![path(vec![Seg::Line(0.0, 0.0); 2], vec![1.0; 2])]));
let mut segs = Vec::with_capacity(10_000);
segs.extend([Seg::Line(0.0, 0.0); 2]);
let mut dash = Vec::with_capacity(1_000);
dash.extend([1.0f32; 2]);
let slack = crate::media::geometry_bytes(&pic(vec![path(segs, dash)]));
assert!(slack - tight >= 9_000 * std::mem::size_of::<Seg>(), "{} bytes more", slack - tight);
}
/// A stroked path keeps its dash array on the heap, and a text item keeps its boxed record and font
/// name; the cache charge counts both, so many dashed paths or text records are not under-counted.
#[test]
fn geometry_bytes_counts_dash_arrays_and_text_records() {
use craft_metafile::{Font, HAlign, LineStyle, Text, VAlign};
let pic = |items: Vec<Item>| Picture { width: 10.0, height: 10.0, items, skipped_records: 0 };
let path = |dash: usize| Item::Path {
segs: vec![Seg::Line(0.0, 0.0); 2],
fill: None,
stroke: Some(([0, 0, 0, 255], 1.0)),
line: LineStyle { dash: vec![1.0; dash], ..LineStyle::default() },
even_odd: false,
region: None,
clips: vec![],
};
let solid = crate::media::geometry_bytes(&pic(vec![path(0)]));
let dashed = crate::media::geometry_bytes(&pic(vec![path(16)]));
assert_eq!(dashed - solid, 16 * std::mem::size_of::<f32>());
let text = |family: &str| {
Item::Text(Box::new(Text {
transform: [1.0, 0.0, 0.0, 1.0, 0.0, 0.0],
text: "ab".into(),
dx: vec![1.0; 2],
font: Font { family: family.into(), ..Font::default() },
color: [0, 0, 0, 255],
background: None,
h_align: HAlign::default(),
v_align: VAlign::default(),
clip: None,
region: None,
clips: vec![],
}))
};
let bare = crate::media::geometry_bytes(&pic(vec![text("")]));
let named = crate::media::geometry_bytes(&pic(vec![text("Some Long Face Name")]));
assert_eq!(named - bare, "Some Long Face Name".len());
let empty = crate::media::geometry_bytes(&pic(vec![]));
assert!(bare - empty >= std::mem::size_of::<Text>(), "the boxed Text struct is charged: {} bytes", bare - empty);
}
+82 -7
View File
@@ -90,7 +90,8 @@ pub fn alt_text(app: &mut WordApp, ui: &mut Ui) {
let decorative = obj.is_decorative();
ui.label(egui::RichText::new(tl!("Describe what this object shows, for people who can't see it.")).weak());
ui.add_space(4.0);
if let Some(text) = draft_box(ui, ("alt_obj", &pos), obj.alt_text(), !decorative, true)
let label = ui.label(tl!("Description:"));
if let Some(text) = draft_box(ui, ("alt_obj", &pos), label.id, obj.alt_text(), !decorative, true)
&& still_selected(app, &pos)
{
let _ = app.run("object.altText", json!({"text": text}));
@@ -111,13 +112,13 @@ pub fn alt_text(app: &mut WordApp, ui: &mut Ui) {
if let Some((tp, caption, description)) = table {
ui.label(egui::RichText::new(tl!("Describe what this table shows, for people who can't see it.")).weak());
ui.add_space(4.0);
ui.label(tl!("Title:"));
if let Some(t) = draft_box(ui, ("alt_table_title", &tp), caption.as_deref().unwrap_or(""), true, false) {
let label = ui.label(tl!("Title:"));
if let Some(t) = draft_box(ui, ("alt_table_title", &tp), label.id, caption.as_deref().unwrap_or(""), true, false) {
let _ = app.run("table.altText", json!({"title": t}));
}
ui.add_space(4.0);
ui.label(tl!("Description:"));
if let Some(t) = draft_box(ui, ("alt_table_text", &tp), description.as_deref().unwrap_or(""), true, true) {
let label = ui.label(tl!("Description:"));
if let Some(t) = draft_box(ui, ("alt_table_text", &tp), label.id, description.as_deref().unwrap_or(""), true, true) {
let _ = app.run("table.altText", json!({"text": t}));
}
return;
@@ -131,11 +132,18 @@ fn still_selected(app: &WordApp, pos: &Pos) -> bool {
/// A text box editing `current`; the draft lives in egui memory while it has focus (frame-local
/// buffers lose keystrokes). Returns the new text when editing ends with a change.
fn draft_box(ui: &mut Ui, key: impl std::hash::Hash + std::fmt::Debug, current: &str, enabled: bool, multiline: bool) -> Option<String> {
fn draft_box(
ui: &mut Ui,
key: impl std::hash::Hash + std::fmt::Debug,
label: egui::Id,
current: &str,
enabled: bool,
multiline: bool,
) -> Option<String> {
let key = egui::Id::unique(key);
let mut text = ui.data(|d| d.get_temp::<String>(key)).unwrap_or_else(|| current.to_string());
let edit = if multiline { egui::TextEdit::multiline(&mut text).desired_rows(5) } else { egui::TextEdit::singleline(&mut text) };
let r = ui.add_enabled(enabled, edit.desired_width(f32::INFINITY));
let r = ui.add_enabled(enabled, edit.desired_width(f32::INFINITY)).labelled_by(label);
if r.changed() {
ui.data_mut(|d| d.insert_temp(key, text.clone()));
}
@@ -148,3 +156,70 @@ fn draft_box(ui: &mut Ui, key: impl std::hash::Hash + std::fmt::Debug, current:
}
None
}
#[cfg(test)]
mod tests {
use super::*;
use egui::accesskit::Role;
use egui_kittest::kittest::{NodeT, Queryable};
fn harness(app: WordApp) -> egui_kittest::Harness<'static, WordApp> {
let mut fonts = false;
let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(400.0, 400.0)).build_ui_state(
move |ui, app: &mut WordApp| {
if fonts {
alt_text(app, ui);
} else {
crate::theme::install_fonts_for(ui.ctx(), false);
fonts = true;
}
},
app,
);
h.run_steps(4);
h
}
#[test]
fn object_description_is_named_commits_and_disables_when_decorative() {
let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), crate::Services::default());
app.run("insert.shape", json!({"kind": "ellipse"})).unwrap();
let mut h = harness(app);
h.get_by_role_and_label(Role::MultilineTextInput, "Description:").click();
h.run_steps(2);
h.get_by_role_and_label(Role::MultilineTextInput, "Description:").type_text("A green circle");
h.run_steps(2);
assert_eq!(h.get_by_role_and_label(Role::MultilineTextInput, "Description:").value().as_deref(), Some("A green circle"));
h.get_by_role_and_label(Role::CheckBox, "Mark as decorative").click();
h.run_steps(2);
let (_, object) = wordcraft_engine::cmd::objects::selected(&h.state().session).unwrap();
assert_eq!(object.alt_text(), "A green circle");
assert!(object.is_decorative());
assert!(h.get_by_role_and_label(Role::MultilineTextInput, "Description:").accesskit_node().is_disabled());
}
#[test]
fn table_title_and_description_are_named_and_commit_independently() {
let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), crate::Services::default());
app.run("insert.table", json!({"rows": 1, "cols": 1})).unwrap();
let mut h = harness(app);
h.get_by_role_and_label(Role::TextInput, "Title:").click();
h.run_steps(2);
h.get_by_role_and_label(Role::TextInput, "Title:").type_text("Prices");
h.run_steps(2);
assert_eq!(h.get_by_role_and_label(Role::TextInput, "Title:").value().as_deref(), Some("Prices"));
h.get_by_role_and_label(Role::MultilineTextInput, "Description:").click();
h.run_steps(2);
h.get_by_role_and_label(Role::MultilineTextInput, "Description:").type_text("Prices by year");
h.run_steps(2);
assert_eq!(h.get_by_role_and_label(Role::MultilineTextInput, "Description:").value().as_deref(), Some("Prices by year"));
h.get_by_role_and_label(Role::TextInput, "Title:").click();
h.run_steps(2);
let app = h.state();
let focus = &app.session.sel.focus;
let (path, _, _) = focus.path.cell().unwrap();
let table = app.session.doc.table(focus.story, &path).unwrap();
assert_eq!(table.props.caption.as_deref(), Some("Prices"));
assert_eq!(table.props.description.as_deref(), Some("Prices by year"));
}
}
+28 -1
View File
@@ -157,6 +157,14 @@ impl WordApp {
}
self.session.run("file.encrypt", &json!({"password": pw})).map_err(|e| e.to_string())?;
}
// Like a failed native save, a failed serialization or delivery keeps the save stamps.
let before_stamp = (
self.session.doc.settings.zoom,
self.session.doc.core.last_modified_by.clone(),
self.session.doc.core.created.clone(),
self.session.doc.core.modified.clone(),
self.session.doc.core.revision,
);
// A save is a save, download or not: advance the revision and modified stamp (#262).
if matches!(id, "file.save" | "file.saveAs") {
self.session.stamp_save();
@@ -165,7 +173,19 @@ impl WordApp {
let password =
if matches!(id, "file.save" | "file.saveAs") { self.session.password.as_ref().map(wordcraft_engine::Password::as_str) } else { None };
let opts = wordcraft_engine::cmd::file::export_options(&self.session, &params);
let bytes = wordcraft_engine::io::save_bytes_with(&name, &self.session.doc, password, &opts)?;
let bytes = match wordcraft_engine::io::save_bytes_with(&name, &self.session.doc, password, &opts) {
Ok(bytes) => bytes,
Err(error) => {
(
self.session.doc.settings.zoom,
self.session.doc.core.last_modified_by,
self.session.doc.core.created,
self.session.doc.core.modified,
self.session.doc.core.revision,
) = before_stamp;
return Err(error);
}
};
// A ticket left over from an earlier call isn't this save's.
let saves = self.services.async_saves.clone();
if let Some(saves) = &saves {
@@ -185,6 +205,13 @@ impl WordApp {
(None, None) => Ok(()),
};
if let Err(e) = delivered {
(
self.session.doc.settings.zoom,
self.session.doc.core.last_modified_by,
self.session.doc.core.created,
self.session.doc.core.modified,
self.session.doc.core.revision,
) = before_stamp;
let msg = i18n::fmt(tl!("Couldn't download {name}: {error}"), &[("name", &name), ("error", &e)]);
log::error!("download of {name} failed: {e}");
self.status(msg.clone());
+22 -3
View File
@@ -234,8 +234,9 @@ pub fn customize_keyboard(app: &mut WordApp, ui: &mut Ui, f: &mut KeyboardForm)
}
});
crate::rtl::vertical(ui, |ui| {
ui.label(tl!("New shortcut:"));
close = capture(ui, f);
let label = tl!("New shortcut:");
ui.label(label);
close = capture(ui, f, label);
ui.add_space(4.0);
if !f.pressed.is_empty() {
let owner = match app.session.keymap.resolve(&reg, &f.pressed) {
@@ -291,7 +292,7 @@ pub fn customize_keyboard(app: &mut WordApp, ui: &mut Ui, f: &mut KeyboardForm)
/// The "New shortcut" box: takes keyboard focus and records the combination pressed.
/// True when plain Escape asks to close the dialog.
fn capture(ui: &mut Ui, f: &mut KeyboardForm) -> bool {
fn capture(ui: &mut Ui, f: &mut KeyboardForm, label: &str) -> bool {
let t = Tokens::get(ui.ctx());
let (rect, resp) = ui.allocate_exact_size(vec2(300.0, 26.0), Sense::click());
// Keys belong to the box whenever nothing else in the dialog has focus, so a shortcut pressed
@@ -312,6 +313,8 @@ fn capture(ui: &mut Ui, f: &mut KeyboardForm) -> bool {
f.pressed = k;
}
}
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::TextInput, ui.is_enabled(), label));
ui.ctx().accesskit_node_builder(resp.id, |node| node.set_value(key_text(&f.pressed)));
let stroke = egui::Stroke::new(if focused { 1.5 } else { 1.0 }, if focused { t.accent } else { t.input_border });
ui.painter().rect(rect, 2.0, t.input, stroke, egui::StrokeKind::Inside);
let (text, color) = if f.pressed.is_empty() { (tl!("Press a key combination").to_string(), t.text_dim) } else { (key_text(&f.pressed), t.text) };
@@ -416,6 +419,22 @@ mod tests {
h
}
/// The shortcut capture field has a name and reports the combination it records.
#[test]
fn shortcut_capture_exposes_its_name_and_current_value() {
use egui::accesskit::Role;
use egui_kittest::kittest::Queryable;
let mut h = harness("", Some("format.bold"));
let input = h.get_by_role_and_label(Role::TextInput, "New shortcut:");
assert_eq!(input.value().as_deref(), Some(""));
input.focus();
h.run_steps(2);
h.key_press(egui::Key::F6);
h.run_steps(2);
assert_eq!(h.state().1.pressed, "F6");
assert_eq!(h.get_by_role_and_label(Role::TextInput, "New shortcut:").value().as_deref(), Some("F6"));
}
type KbHarness<'a> = egui_kittest::Harness<'a, (WordApp, super::KeyboardForm)>;
/// The area of the Commands list that is on screen: 170 high, below the title, the item
@@ -288,6 +288,7 @@ fn edge_glyph(ui: &mut Ui, edges: &str) {
fn align_button(ui: &mut Ui, (v, h): (VAlign, Align), on: bool, tip: &str) -> egui::Response {
let t = Tokens::get(ui.ctx());
let (r, resp) = ui.allocate_exact_size(vec2(22.0, 22.0), Sense::click());
resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, ui.is_enabled(), on, tip));
let resp = resp.on_hover_text(tip);
let p = ui.painter_at(r);
let bg = if on {
@@ -523,9 +524,9 @@ pub fn body(app: &mut WordApp, ui: &mut Ui, f: Form) -> bool {
}
let size = ui.add(egui::TextEdit::singleline(&mut r.size).desired_width(36.0));
size.on_hover_text(tl!("Size:")).accessible_name(tl!("Size:"));
ui.toggle_value(&mut r.bold, egui::RichText::new("B").strong()).on_hover_text(tl!("Bold"));
ui.toggle_value(&mut r.italic, egui::RichText::new("I").italics()).on_hover_text(tl!("Italic"));
ui.toggle_value(&mut r.underline, egui::RichText::new("U").underline()).on_hover_text(tl!("Underline"));
ui.toggle_value(&mut r.bold, egui::RichText::new("B").strong()).on_hover_text(tl!("Bold")).accessible_name(tl!("Bold"));
ui.toggle_value(&mut r.italic, egui::RichText::new("I").italics()).on_hover_text(tl!("Italic")).accessible_name(tl!("Italic"));
ui.toggle_value(&mut r.underline, egui::RichText::new("U").underline()).on_hover_text(tl!("Underline")).accessible_name(tl!("Underline"));
ui.push_id("tstyle_color", |ui| {
ui.label(tl!("Font color:"));
color_menu(ui, &theme, &mut r.color);
@@ -661,6 +662,42 @@ mod tests {
use egui_kittest::kittest::Queryable;
use wordcraft_engine::Session;
/// Alignment choices expose their names and current selection, and can be toggled.
#[test]
fn alignment_buttons_expose_names_selection_and_clicks() {
use egui::accesskit::{Role, Toggled};
use egui_kittest::kittest::NodeT;
let mut h = egui_kittest::Harness::builder().with_size(vec2(200.0, 120.0)).build_ui_state(
|ui, selected: &mut Option<usize>| {
for (i, align, label) in
[(0, (VAlign::Top, Align::Left), "Align Top Left"), (1, (VAlign::Bottom, Align::Right), "Align Bottom Right")]
{
let on = *selected == Some(i);
if align_button(ui, align, on, label).clicked() {
*selected = if on { None } else { Some(i) };
}
}
ui.add_enabled_ui(false, |ui| {
align_button(ui, (VAlign::Center, Align::Center), false, "Align Center");
});
},
Some(0usize),
);
h.run_steps(2);
assert_eq!(h.get_by_role_and_label(Role::Button, "Align Top Left").accesskit_node().toggled(), Some(Toggled::True));
assert_eq!(h.get_by_role_and_label(Role::Button, "Align Bottom Right").accesskit_node().toggled(), Some(Toggled::False));
assert!(h.get_by_role_and_label(Role::Button, "Align Center").accesskit_node().is_disabled());
h.get_by_role_and_label(Role::Button, "Align Bottom Right").click();
h.run_steps(2);
assert_eq!(*h.state(), Some(1));
assert_eq!(h.get_by_role_and_label(Role::Button, "Align Top Left").accesskit_node().toggled(), Some(Toggled::False));
assert_eq!(h.get_by_role_and_label(Role::Button, "Align Bottom Right").accesskit_node().toggled(), Some(Toggled::True));
h.get_by_role_and_label(Role::Button, "Align Bottom Right").click();
h.run_steps(2);
assert_eq!(*h.state(), None);
assert_eq!(h.get_by_role_and_label(Role::Button, "Align Bottom Right").accesskit_node().toggled(), Some(Toggled::False));
}
fn steps(h: &mut egui_kittest::Harness<'_, WordApp>) {
for _ in 0..4 {
h.step();
@@ -671,11 +708,15 @@ mod tests {
/// even banded rows) and no other.
#[test]
fn the_part_picker_edits_the_part_it_shows() {
use egui::accesskit::Toggled;
use egui_kittest::kittest::NodeT;
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
app.run("insert.table", json!({"rows": 4, "cols": 3})).unwrap();
app.run("table.newStyle", json!({"name": "Parts"})).unwrap();
app.dialog = Dialog::open("modifyTableStyle", &mut app);
assert!(matches!(app.dialog, Some(Dialog::TableStyle { .. })));
// Keep the background ribbon's character controls out of the dialog's label queries.
app.ui.tab = "Insert".into();
let mut h = egui_kittest::Harness::builder().with_size(vec2(1440.0, 900.0)).build_ui_state(
|ui, app: &mut WordApp| {
let ctx = ui.ctx().clone();
@@ -691,15 +732,25 @@ mod tests {
h.get_by_label("Even Banded Rows").click();
steps(&mut h);
assert!(matches!(&h.state().dialog, Some(Dialog::TableStyle { region, .. }) if *region == part_index(TablePart::Band2Horz)));
h.get_by_label("B").click();
steps(&mut h);
for label in ["Bold", "Italic", "Underline"] {
assert_eq!(h.get_by_label(label).accesskit_node().toggled(), Some(Toggled::False));
h.get_by_label(label).click();
steps(&mut h);
assert_eq!(h.get_by_label(label).accesskit_node().toggled(), Some(Toggled::True));
}
h.get_by_label("OK").click();
steps(&mut h);
assert!(h.state().dialog.is_none(), "OK closes the dialog");
let st = h.state().session.doc.styles.get("Parts").cloned().unwrap();
assert_eq!(st.table_part(TablePart::Band2Horz).chr.bold, Some(true));
let chr = st.table_part(TablePart::Band2Horz).chr;
assert_eq!(chr.bold, Some(true));
assert_eq!(chr.italic, Some(true));
assert!(chr.underline.is_some_and(|u| u != Underline::None));
for other in [TablePart::WholeTable, TablePart::Band1Horz, TablePart::FirstRow, TablePart::Band2Vert] {
assert_ne!(st.table_part(other).chr.bold, Some(true), "{}", other.ooxml());
let chr = st.table_part(other).chr;
assert_ne!(chr.bold, Some(true), "{}", other.ooxml());
assert_ne!(chr.italic, Some(true), "{}", other.ooxml());
assert!(!chr.underline.is_some_and(|u| u != Underline::None), "{}", other.ooxml());
}
}
+51
View File
@@ -419,6 +419,9 @@ fn body(ui: &mut Ui, b: &mut FileBrowser, t: &Tokens) -> Option<Option<PathBuf>>
}
for e in entries.get(range).unwrap_or(&[]) {
let (r, resp) = ui.allocate_exact_size(vec2(ui.available_width(), ROW), Sense::click());
resp.widget_info(|| {
egui::WidgetInfo::selected(egui::Role::Button, ui.is_enabled(), b.selected.as_ref() == Some(&e.path), &e.name)
});
if b.selected.as_ref() == Some(&e.path) {
ui.painter().rect_filled(r, 2.0, t.checked);
} else if resp.hovered() {
@@ -765,6 +768,54 @@ mod tests {
assert!(crate::keytips::suppressed(&a, &ctx));
}
/// Drawn entries have names and selection state, and choosing one still picks its path.
#[test]
fn entries_expose_names_selection_and_picking() {
use egui::accesskit::{Role, Toggled};
use egui_kittest::kittest::{NodeT, Queryable};
let dir = scratch("entry_accessibility");
let folder = dir.join("Drafts");
let file = dir.join("chapter.docx");
std::fs::create_dir(&folder).unwrap();
std::fs::write(&file, b"x").unwrap();
let browser =
FileBrowser::new(FileDialogRequest::Open { purpose: "document".into() }, AfterPick::OpenDocument { document: 0 }, dir.clone(), false);
// Font changes take effect next frame; the buttons need the named semibold family.
let mut fonts = false;
let mut h = egui_kittest::Harness::builder().with_size(vec2(760.0, 520.0)).build_ui_state(
move |ui, state: &mut (FileBrowser, Option<Option<PathBuf>>)| {
if !fonts {
crate::theme::install_fonts(ui.ctx());
fonts = true;
return;
}
let t = Tokens::get(ui.ctx());
if let Some(picked) = body(ui, &mut state.0, &t) {
state.1 = Some(picked);
}
},
(browser, None),
);
h.run_steps(4);
for name in ["Drafts", "chapter.docx"] {
assert_eq!(h.get_by_role_and_label(Role::Button, name).accesskit_node().toggled(), Some(Toggled::False));
}
h.get_by_role_and_label(Role::Button, "Drafts").click();
h.run_steps(2);
assert_eq!(h.state().0.selected.as_ref(), Some(&folder));
assert_eq!(h.get_by_role_and_label(Role::Button, "Drafts").accesskit_node().toggled(), Some(Toggled::True));
h.get_by_role_and_label(Role::Button, "chapter.docx").click();
h.run_steps(2);
assert_eq!(h.state().0.selected.as_ref(), Some(&file));
assert_eq!(h.state().0.name, "chapter.docx");
assert_eq!(h.get_by_role_and_label(Role::Button, "Drafts").accesskit_node().toggled(), Some(Toggled::False));
assert_eq!(h.get_by_role_and_label(Role::Button, "chapter.docx").accesskit_node().toggled(), Some(Toggled::True));
h.get_by_role_and_label(Role::Button, "Open").click();
h.run_steps(2);
assert_eq!(h.state().1, Some(Some(file)));
let _ = std::fs::remove_dir_all(&dir);
}
/// #3535: exporting offers File › Export's formats as the types; the chosen one is the format,
/// the name's extension follows it, and the export writes that format.
#[test]
+64
View File
@@ -465,6 +465,70 @@ fn export_pdf_without_a_path_asks_where_to_save() {
let _ = std::fs::remove_dir_all(&dir);
}
/// A synchronous web save failure must not stamp a save that never reached its destination.
#[test]
fn failed_web_saves_restore_the_save_stamps() {
for id in ["file.save", "file.saveAs"] {
for (name, hosted, dirty, expected_calls) in [
("draft.unsupported", false, true, vec![]),
("draft.docx", false, true, vec!["download"]),
("draft.docx", true, true, vec!["host"]),
("draft.docx", false, false, vec!["download"]),
] {
let calls = Rc::new(RefCell::new(Vec::new()));
let downloaded = calls.clone();
let host_calls = calls.clone();
let services = Services {
download: Some(Box::new(move |_, _| {
downloaded.borrow_mut().push("download");
Err("download refused".into())
})),
host_save: hosted.then(|| {
Box::new(move |_: &str, _: &[u8], _: bool| {
host_calls.borrow_mut().push("host");
Err("host refused".into())
}) as crate::HostSaveFn
}),
..Default::default()
};
let mut a = WordApp::new(Session::new(wordcraft_doc::Document::from_text(UNSAVED)), services);
a.session.dirty = dirty;
a.session.path = Some("original.docx".into());
a.session.view.zoom = 1.37;
a.session.doc.core.created.clear();
a.session.doc.core.modified = "2020-01-02T03:04:05Z".into();
a.session.doc.core.last_modified_by = "Previous author".into();
a.session.doc.core.revision = 7;
let path_before = a.session.path.clone();
let core_before = a.session.doc.core.clone();
let zoom_before = a.session.doc.settings.zoom;
let undo_before = a.session.undo_depth();
assert!(a.run(id, json!({"path": name})).is_err(), "{id}: {name}");
assert_eq!(*calls.borrow(), expected_calls, "{id}: {name}");
assert_eq!(a.session.doc.core, core_before, "{id}: {name}");
assert_eq!(a.session.doc.settings.zoom, zoom_before, "{id}: {name}");
assert_eq!(a.session.undo_depth(), undo_before, "{id}: {name}");
assert_eq!(a.session.dirty, dirty, "{id}: {name}");
assert_eq!(a.session.path, path_before, "{id}: {name}");
}
let services = Services {
download: Some(Box::new(|_, bytes| {
assert!(bytes.starts_with(b"PK"));
Ok(())
})),
..Default::default()
};
let mut a = WordApp::new(Session::new(wordcraft_doc::Document::from_text(UNSAVED)), services);
a.session.dirty = true;
let revision_before = a.session.doc.core.revision;
assert_eq!(a.run(id, json!({"path": "draft.docx"})).unwrap()["downloaded"], "draft.docx");
assert_eq!(a.session.doc.core.revision, revision_before.saturating_add(1));
assert_eq!(a.session.doc.core.last_modified_by, a.session.author);
assert!(!a.session.doc.core.created.is_empty() && !a.session.doc.core.modified.is_empty());
assert!(!a.session.dirty);
}
}
/// An explicit web PDF export keeps an existing PDF suffix regardless of ASCII case.
#[test]
fn web_pdf_export_keeps_an_existing_suffix_in_any_case() {
+38 -2
View File
@@ -1645,9 +1645,19 @@ fn shape(pen: &Pen, kind: &str) -> bool {
"triangle" => solid(&[(10.0, 3.5), (17.0, 16.5), (3.0, 16.5)]),
"diamond" => solid(&[(10.0, 3.0), (17.0, 10.0), (10.0, 17.0), (3.0, 10.0)]),
"line" => pen.line(&[(4.0, 16.0), (16.0, 4.0)]),
// The block arrow the tile inserts (#6768), from the outline the document draws it with.
"arrow" => {
pen.line(&[(4.0, 16.0), (14.5, 5.5)]);
head((16.5, 3.5), (4.0, 16.0));
let (x0, y0, w, h) = (3.0, 5.0, 14.0, 10.0);
let pts: Vec<(f32, f32)> = wordcraft_doc::wrap::arrow_outline(wordcraft_doc::para::ShapeKind::Arrow, w, h)
.iter()
.map(|&(u, v)| (x0 + u * w, y0 + v * h))
.collect();
// Concave: the shaft and the head are tinted apart, then the outline.
if let [tail_top, neck_top, barb_top, tip, barb_bottom, neck_bottom, tail_bottom] = pts[..] {
pen.fill(&[tail_top, neck_top, neck_bottom, tail_bottom], tint);
pen.fill(&[barb_top, tip, barb_bottom], tint);
}
pen.closed(&pts, c);
}
"star" => {
let pts: Vec<(f32, f32)> = (0..10)
@@ -1745,6 +1755,32 @@ mod tests {
assert!(!has_default_highlight_bar("shadingNoBar"));
}
/// #6768: the Insert › Shapes Arrow tile is the block arrow that tile inserts, outlined as the
/// document draws it, not a thin line with a head.
#[test]
fn the_arrow_tile_is_the_block_arrow_it_inserts() {
let ctx = egui::Context::default();
let output = ctx.run_ui(egui::RawInput::default(), |ui| {
paint(ui.painter(), Rect::from_min_size(Pos2::ZERO, egui::vec2(20.0, 20.0)), "shape.arrow", Color32::BLACK, Color32::BLUE);
});
let outline: Vec<Pos2> = output
.shapes
.iter()
.find_map(|s| match &s.shape {
// The outline, not the tinted fills (closed too, but without a stroke).
Shape::Path(path) if path.closed && path.stroke.width > 0.0 => Some(path.points.clone()),
_ => None,
})
.expect("the arrow is outlined");
output.drop_without_applying_deltas();
let want = wordcraft_doc::wrap::arrow_outline(wordcraft_doc::para::ShapeKind::Arrow, 14.0, 10.0);
assert_eq!(outline.len(), want.len(), "{outline:?}");
for (got, (u, v)) in outline.iter().zip(want) {
let expected = pos2(3.0 + u * 14.0, 5.0 + v * 10.0);
assert!(got.distance(expected) < 0.01, "{got:?} vs {expected:?}");
}
}
/// Verify that the fitOnePage vector icon renders without panics and emits shapes.
#[test]
fn fit_one_page_icon_paints_without_panic() {
+24 -22
View File
@@ -142,33 +142,35 @@ pub fn paint(app: &WordApp, painter: &egui::Painter, t: &Tokens, layout: &DocLay
let ink = Stroke::new(1.5, t.accent);
let hover = painter.ctx().input(|i| i.pointer.hover_pos());
match (tool, app.canvas.table_stroke) {
(TableTool::Draw, Some(st)) => match table_draw::stroke(layout, st.page, st.from.0, st.from.1, st.to.0, st.to.1) {
Some(Kind::Rect(r)) => {
if let (Some(a), Some(b)) = (to_screen(st.page, r.x, r.y), to_screen(st.page, r.right(), r.bottom())) {
painter.rect_stroke(Rect::from_two_pos(a, b), 0.0, ink, egui::StrokeKind::Middle);
(TableTool::Draw, Some(st)) => {
match table_draw::stroke_in(layout, st.page, crate::table_resize::reach(app, layout, st.page), st.from.0, st.from.1, st.to.0, st.to.1) {
Some(Kind::Rect(r)) => {
if let (Some(a), Some(b)) = (to_screen(st.page, r.x, r.y), to_screen(st.page, r.right(), r.bottom())) {
painter.rect_stroke(Rect::from_two_pos(a, b), 0.0, ink, egui::StrokeKind::Middle);
}
}
Some(Kind::Vertical { x, y0, y1 }) => {
if let (Some(a), Some(b)) = (to_screen(st.page, x, y0), to_screen(st.page, x, y1)) {
painter.line_segment([a, b], ink);
}
}
Some(Kind::Horizontal { y, x0, x1 }) => {
if let (Some(a), Some(b)) = (to_screen(st.page, x0, y), to_screen(st.page, x1, y)) {
painter.line_segment([a, b], ink);
}
}
// Not a table or a line yet: the drag's box, dashed and dim.
None => {
if let (Some(a), Some(b)) = (to_screen(st.page, st.from.0, st.from.1), to_screen(st.page, st.to.0, st.to.1)) {
dashed_rect(painter, Rect::from_two_pos(a, b), Stroke::new(1.0, t.text_dim));
}
}
}
Some(Kind::Vertical { x, y0, y1 }) => {
if let (Some(a), Some(b)) = (to_screen(st.page, x, y0), to_screen(st.page, x, y1)) {
painter.line_segment([a, b], ink);
}
}
Some(Kind::Horizontal { y, x0, x1 }) => {
if let (Some(a), Some(b)) = (to_screen(st.page, x0, y), to_screen(st.page, x1, y)) {
painter.line_segment([a, b], ink);
}
}
// Not a table or a line yet: the drag's box, dashed and dim.
None => {
if let (Some(a), Some(b)) = (to_screen(st.page, st.from.0, st.from.1), to_screen(st.page, st.to.0, st.to.1)) {
dashed_rect(painter, Rect::from_two_pos(a, b), Stroke::new(1.0, t.text_dim));
}
}
},
}
(TableTool::Erase, _) => {
if let Some(p) = hover
&& let Some((page, x, y)) = crate::canvas::page_at(pages, layout, scale, p)
&& let Some(e) = table_draw::erase_target(layout, page, x, y)
&& let Some(e) = table_draw::erase_target_in(layout, page, crate::table_resize::reach(app, layout, page), x, y)
&& let (Some(a), Some(b)) = (to_screen(page, e.from.0, e.from.1), to_screen(page, e.to.0, e.to.1))
{
painter.line_segment([a, b], Stroke::new(3.0, t.red));
+8 -3
View File
@@ -99,11 +99,16 @@ pub(crate) fn available(app: &WordApp) -> bool {
&& crate::ink::cursor(app).is_none()
}
/// Which tables the pointer reaches on `page`: a header's and footer's while one is edited (#5558).
pub(crate) fn reach(app: &WordApp, layout: &DocLayout, page: usize) -> table_resize::Reach {
table_resize::Reach::of(layout, &app.session.doc, app.session.sel.focus.story, page)
}
/// The border or handle under screen point `p`, if any.
fn target_at(app: &WordApp, layout: &DocLayout, rects: &[Rect], scale: f32, p: Pos2) -> Option<(usize, f32, f32, ResizeTarget)> {
let (page, x, y) = crate::canvas::page_at(rects, layout, scale, p)?;
let sc = page_scale(rects, layout, scale, page)?;
let t = table_resize::resize_target(layout, &app.session.doc, page, x, y, REACH_PX / sc)?;
let t = table_resize::resize_target_in(layout, &app.session.doc, page, x, y, REACH_PX / sc, reach(app, layout, page))?;
Some((page, x, y, t))
}
@@ -167,7 +172,7 @@ pub(crate) fn grab(app: &mut WordApp, layout: &DocLayout, page: usize, x: f32, y
if !available(app) {
return;
}
if let Some(mut target) = table_resize::resize_target(layout, &app.session.doc, page, x, y, 1.0) {
if let Some(mut target) = table_resize::resize_target_in(layout, &app.session.doc, page, x, y, 1.0, reach(app, layout, page)) {
target.limit_to_selection(&app.session, y);
app.canvas.table_resize = Some(ResizeDrag { page, from: (x, y), to: (x, y), target, ruler: true });
}
@@ -277,7 +282,7 @@ pub fn paint(app: &WordApp, painter: &egui::Painter, t: &Tokens, layout: &DocLay
let Some(p) = painter.ctx().input(|i| i.pointer.hover_pos()) else { return };
let Some((page, x, y)) = crate::canvas::page_at(rects, layout, scale, p) else { return };
let Some(sc) = page_scale(rects, layout, scale, page) else { return };
let Some(tg) = table_resize::table_under(layout, &app.session.doc, page, x, y, REACH_PX / sc) else { return };
let Some(tg) = table_resize::table_under_in(layout, &app.session.doc, page, x, y, REACH_PX / sc, reach(app, layout, page)) else { return };
let h = tg.handle();
if let (Some(a), Some(b)) = (s(page, h.x, h.y), s(page, h.right(), h.bottom())) {
let r = Rect::from_two_pos(a, b);
+105
View File
@@ -8430,6 +8430,111 @@ fn focus_hides_the_ribbon_and_escape_brings_it_back() {
assert!(h.state().session.view.read_mode && shown(&h, "Focus"), "Immersive Reader keeps the status bar");
}
/// #5558: while the header is edited, its table is edited like one in the body: a click puts
/// the caret in the cell under it, typing goes there, and a column border drags to a new width.
#[test]
fn a_table_in_the_header_is_clicked_typed_in_and_resized() {
let ctx = egui::Context::default();
let mut a = app();
a.run("text.insert", json!({"text": "Body text"})).unwrap();
a.run("insert.header", json!({"text": "Head"})).unwrap();
a.run("insert.table", json!({"rows": 2, "cols": 2})).unwrap();
a.run("insert.closeHeader", json!({})).unwrap();
a.run("caret.docStart", json!({})).unwrap();
let screen = egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1280.0, 900.0));
let mut t = 0.0;
let mut frame = |a: &mut WordApp, events: Vec<egui::Event>| {
t += 1.0 / 60.0;
let input = egui::RawInput { events, time: Some(t), screen_rect: Some(screen), ..Default::default() };
ctx.run_ui(input, |ui| {
a.logic(ui.ctx());
a.ui(ui);
})
.drop_without_applying_deltas();
};
let btn = |pos, pressed| egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() };
for _ in 0..20 {
frame(&mut a, Vec::new());
}
a.run("insert.editHeader", json!({"page": 0})).unwrap();
for _ in 0..20 {
frame(&mut a, Vec::new());
}
let hf = a.session.sel.focus.story;
assert_ne!(hf, wordcraft_doc::StoryRef::Body, "editing the header");
let cells = |a: &mut WordApp| {
let l = a.session.layout();
let mut v: Vec<(usize, usize, wordcraft_geom::Rect)> = l.pages[0]
.header
.iter()
.filter_map(|it| match it {
wordcraft_layout::Placed::Cell { rect, row, cell, story, .. } if *story == hf => Some((*row, *cell, *rect)),
_ => None,
})
.collect();
v.sort_by_key(|c| (c.0, c.1));
v
};
let cs = cells(&mut a);
assert_eq!(cs.len(), 4, "the header's table is laid out: {cs:?}");
// A click in the second row's second cell puts the caret there.
let r = cs[3].2;
let at = canvas::page_to_screen(&mut a, 0, r.x + r.w / 2.0, r.y + r.h / 2.0).expect("on screen");
frame(&mut a, vec![egui::Event::PointerMoved(at)]);
frame(&mut a, vec![btn(at, true)]);
frame(&mut a, vec![btn(at, false)]);
for _ in 0..10 {
frame(&mut a, Vec::new());
}
let focus = a.session.sel.focus.clone();
assert_eq!(focus.story, hf);
assert_eq!(focus.path.cell().map(|(_, r, c)| (r, c)), Some((1, 1)), "the caret is in the clicked cell: {focus:?}");
frame(&mut a, vec![egui::Event::Text("X".into())]);
frame(&mut a, Vec::new());
assert!(a.session.doc.plain_text(hf).contains('X'), "typing goes into the cell");
// Dragging the border between the columns moves it.
let width = |a: &WordApp| {
let blocks = a.session.doc.story(hf).expect("the header");
blocks.iter().find_map(|b| b.as_table().map(|t| t.grid.clone())).expect("its table")
};
let before = width(&a);
let border = cs[0].2.right();
let y = cs[0].2.y + cs[0].2.h / 2.0;
let from = canvas::page_to_screen(&mut a, 0, border, y).expect("on screen");
let to = from + egui::vec2(60.0, 0.0);
frame(&mut a, vec![egui::Event::PointerMoved(from)]);
frame(&mut a, vec![btn(from, true)]);
for i in 1..=6 {
frame(&mut a, vec![egui::Event::PointerMoved(from + egui::vec2(10.0 * i as f32, 0.0))]);
}
frame(&mut a, vec![btn(to, false)]);
for _ in 0..5 {
frame(&mut a, Vec::new());
}
let after = width(&a);
assert!(after[0] > before[0] + 10.0, "the first column widened: {before:?} → {after:?}");
assert_eq!(a.session.sel.focus.story, hf, "still editing the header");
// A table copied from the body, pasted with Ctrl+V at the end of the header's text, is a
// table there too.
a.run("insert.closeHeader", json!({})).unwrap();
a.run("caret.docEnd", json!({})).unwrap();
a.run("insert.table", json!({"rows": 1, "cols": 3})).unwrap();
a.run("text.insert", json!({"text": "Copied"})).unwrap();
a.run("table.selectTable", json!({})).unwrap();
let copied = a.run("edit.copy", json!({})).unwrap()["text"].as_str().unwrap_or_default().to_string();
a.run("insert.editHeader", json!({"page": 0})).unwrap();
let blocks = a.session.doc.story(hf).map_or(0, |b| b.len());
let head = wordcraft_doc::Pos { story: hf, path: wordcraft_doc::Path::top(blocks.saturating_sub(1)), off: 4 };
a.run("caret.set", json!({"pos": head})).unwrap();
frame(&mut a, vec![egui::Event::Paste(copied)]);
for _ in 0..5 {
frame(&mut a, Vec::new());
}
let tables: Vec<usize> = a.session.doc.story(hf).expect("the header").iter().filter_map(|b| b.as_table().map(|t| t.cols())).collect();
assert_eq!(tables, vec![2, 3], "the pasted table is a table in the header");
assert_eq!(cells(&mut a).len(), 4 + 3, "and is drawn there");
}
#[test]
fn format_painter_single_click_formats_the_target_word_and_finishes() {
let mut a = app();
+1 -1
View File
@@ -21,7 +21,7 @@ crate name links to its source tree.
| L0 | [`geom`](../crates/geom/src) | 1,271 | Units (points, twips, EMU, inches, cm), rectangles and measurement parsing |
| L1 | [`doc`](../crates/doc/src) | 23,719 | Document model: stories, paragraphs, runs, tables, sections, styles, numbering, fields, notes, comments, revisions and equations; edit primitives and bidi |
| L1 | [`fonts`](../crates/fonts/src) | 7,088 | Font database, metrics, outlines, HarfRust shaping, Word font substitution and OpenType MATH |
| L1 | [`metafile`](../crates/metafile/src) | 3,614 | Shared Windows Metafile parsing and drawing primitives used by format readers and renderers |
| L1 (external) | [`craft-metafile`](https://github.com/storytold/craft-libs/tree/main/crates/metafile) | — | WMF, EMF and EMF+ reader shared with the other Craft apps: paths, pattern fills, bitmaps and text with their clips, placed into a picture frame for the renderers |
| L1 (external) | [`craft-proof`](https://github.com/storytold/craft-libs/tree/main/crates/proof) (package alias `wordcraft-proof`) | — | Proofing moved to craft-libs (CP1, 2026-11): fifteen spelling dictionaries: English (US, GB, CA), Polish, Portuguese, Italian, Croatian, Turkish, Russian, Czech, Indonesian and Spanish (Spain, Mexico, Latin America, Uruguay); language modules provide spelling, suggestions and grammar, while Bulgarian and German have hyphenation only. Its word lists and patterns are craft-i18n's `language-data/`, embedded from `CRAFT_I18N_DIR` at the commit in `craft-i18n.rev` (CI and releases set `CRAFT_I18N_REQUIRED=1`); without them English spelling falls back to an installed Hunspell English or craft-proof's built-in Moby list, and pattern hyphenation is off (Bulgarian, Turkish and Russian hyphenate by rule) |
| L2 | [`docbin`](../crates/docbin/src) | 8,815 | Word 97–2003 `.doc` reader (FIB, piece table, FKPs, SPRMs, stylesheet, lists, tables, notes, pictures) over a CFB container |
| L2 | [`docx`](../crates/docx/src) | 37,376 | OOXML WordprocessingML reader/writer (Transitional and Strict), OMML, custom properties and preserved VBA parts |
+3 -3
View File
@@ -1,6 +1,6 @@
# Control protocol
> **Last updated:** 2026-11-09 · #6146: scroll speed preferences (`ui.scrollSpeed`, `ui.touchpadScrollSpeed`); #6159: refuse ui.screenshot on secondary document windows and support root window selection with view.switchWindows.
> **Last updated:** 2026-11-14 · Correct the force-close request envelope and document the optional command search parameter; command behavior unchanged. #6146: scroll speed preferences (`ui.scrollSpeed`, `ui.touchpadScrollSpeed`); #6159: refuse ui.screenshot on secondary document windows and support root window selection with view.switchWindows.
Start the app with a control port: `wordcraft --control 7981` (or `WORDCRAFT_CONTROL_PORT=7981`).
A missing or invalid port after `--control` (not 1–65535) prints an error and exits with status 2.
@@ -85,7 +85,7 @@ let apps move windows, so there Arrange All and Side by Side only resize.
| Method | Params | Result |
|---|---|---|
| `engine.execute` | `command`, `params`, `doc?` | the command's result (any id from `engine.commands`, including UI commands `ui.tab`, `ui.dialog` (`{"name": dialog, "part"?: table style part}`; `part` opens New / Modify Table Style (`newTableStyle` / `modifyTableStyle`) on that part: `wholeTable`, `headerRow`, `firstColumn`, `bandedRows`, `nwCell`… as `table.modifyStyle` names them), `ui.backstage`, `ui.zotero.*` (see `docs/zotero.md`), `ui.language` (`{"value": "auto"\|"en"\|"zh-hans"\|"zh-hant"\|"ja"\|"pt-br"\|"es"\|"uk"\|"sr"\|"sr-latn"\|"et"\|"tr"\|"ru"\|"pl"\|"de"\|"it"\|"cs"\|"hu"\|"fr"}`), `ui.theme` (`{"value": "system"\|"light"\|"dark"}`; `system` follows the OS appearance, light when it reports none), `ui.interfaceSize` (`{"value": "auto"}` or `{"percent": 50–300}`, clamped; no value reads it; `auto` keeps the system display scale, capped so a window of at least 900x460 points fits the screen (#4030), a percentage is absolute, so 100 is one screen pixel per point (#822); the result's `percent` is the size drawn at and `auto` whether it follows the system; document zoom stays `view.zoom`), `ui.animations` (`{"value": "system"\|"on"\|"off"}`; no value reads it; `system` follows the system's animation setting, which the desktop app reads on Windows, macOS, Linux and the BSDs and the web app from `prefers-reduced-motion`, and means on where the system doesn't say; the result's `enabled` is what the setting comes to and `system` what the system reports, `null` when it doesn't say), `ui.fileBrowser` (desktop: `{"purpose": "document"\|"picture"\|"recipients"\|"save"\|"export"}` opens WordCraft's own file browser, for when the system file dialog doesn't show up, #576; `export` offers File › Export's formats as its types, #3535), `ui.saveAsTemplate` (File › Save As › Save as Word Template: the Save dialog for a `.dotx`, starting in the user templates folder; the result's `dir` is that folder, `null` on the web, #2852), `ui.caretAnimation` (`{"value": true\|false}`; no value reads it; off, the caret jumps and blinks on and off instead of gliding and fading), `ui.startScreen` (`{"value": true\|false}`; no value reads it; on, the default, the desktop and web apps start on File › Home when launched with nothing to open, #766), `ui.alignmentGuides` (`{"value": true\|false}`; no value reads it; on, the default, moving a picture or shape snaps it to the page, the margins and other objects, with guide lines while dragging; Alt moves freely), `ui.quickAccessToolbar` (`{"value": true\|false}`; no value toggles it; false takes the Quick Access Toolbar out of the title bar, as its menu's Hide Quick Access Toolbar does, and true brings it back, #1945), `ui.displayServer` (`{"value": "auto"\|"wayland"\|"x11"}`; no value reads it; File › Options › Advanced › Linux display server, which the desktop app reads on Linux and the BSDs at its next launch; `WORDCRAFT_WAYLAND` overrides it, #2184), `ui.scrollSpeed` (`{"value": "slow"\|"normal"\|"fast"}`; no value reads it; mouse-wheel scroll speed, #6146), `ui.touchpadScrollSpeed` (`{"value": "slow"\|"normal"\|"fast"}`; no value reads it; scales touchpad scrolling on Wayland: slow 2×, normal 4×, fast 8×; on macOS: 0.5×, 1×, 2×; File › Options › Advanced › Scrolling › Touchpad scroll speed, #6146), `ui.statusCount` (`{"value": "words"\|"characters"\|"charactersNoSpaces"}`; no value reads it; what the status bar's count shows — words (the default), characters with spaces, or characters without spaces — kept between runs, #2797), `ui.recentRemove` (`{"path": entry}` takes that document off the recent list — `path` must be an entry on the list; on the desktop the new list is saved right away: the result's `saved` is true then, false with `saveError` when the write failed (the removal still holds for this run) and null where the host keeps no preferences (the web app, or preferences switched off), #2716), `ui.recentClear` (`{}` clears the whole list; the result reports `removed`, the new `recent` and `saved` as above), `ui.focusRibbon` (`{"value": true\|false}`; no value toggles it; in Focus, true drops the ribbon down over the page, as the bar's ⋯ does, and false puts it away, as a click on the page does; outside Focus it stays put away, #1678), `ui.contextMenu` (opens the page's context menu below the caret, as Shift+F10 does), `ui.paneDock` (`{"pane": "navigation"\|"clipboard"\|"styles"\|"styleInspector"\|"accessibility"\|"altText"\|"formatShape"\|"restrictEditing"\|"comments"\|"smartArtText", "dock"?: "left"\|"right"\|"float", "before"?: pane\|null}`; no `dock` reads it; docks or floats a task pane as its menu does, kept between runs; Styles is `view.stylesPaneDock`, #1756; `before` puts the pane directly before that pane in the order, outside it on their edge, as a drop over a docked pane's outer third does, and `null` after every pane; the order is kept between runs)…) |
| `engine.commands` | — | every command: id, label, location, shortcut, params, enabled |
| `engine.commands` | `search?` | every command: id, label, location, shortcut, params, enabled |
| `document.inspect` | `text?`, `doc?` | blocks (text, style, runs, lists, tables), parts, sections, selection, pages |
| `ui.inspect` | — | UI state, view, dialog, window size, page rects on screen, caret, comment balloons (`balloons`: id + screen rect; `balloon`: the selected one), perf; `windows`: the other windows as the drawn window sees them (`available`, `others`, `sideBySide`, `syncScroll`); `document`: the active document's id; `documents`: the open documents (`id`, `title`, `path`, `dirty`, `active`) |
| `ui.click` | `x`, `y`, `button?`, `count?`, `shift?`, `cmd?`, `alt?` | real pointer input at window coordinates |
@@ -187,7 +187,7 @@ discard unsaved work is **refused with an error** (the app keeps running and the
save first (`file.save`), or pass `{"force": true}` to discard the changes and go ahead.
`file.close` closes the shown document, so it is refused while that document has unsaved
changes; the bare form `{"method": "file.close", "force": true}` (a method name that is a
changes; the bare form `{"method": "file.close", "params": {"force": true}}` (a method name that is a
command id) is guarded the same way, and only a boolean `true` counts as `force`. A document
without unsaved changes closes at once (#1268). Closing closes the document and its window, and
the window focused before it becomes the active one. The last window stays open with no page,
+1 -1
View File
@@ -93,7 +93,7 @@ Weights are the share of a Word user's file traffic (estimate). Read/write: ✅
| Encrypted/password-protected `.doc` (XOR/RC4) | <1% | R | 🟡 | — | ~60% | 1–2 | `crates/docbin/src/tests/encrypted.rs` | XOR obfuscation, RC4 and RC4 CryptoAPI open with a password (`docbin` `crypt.rs`, #1079). An AES header (`fAES`) is refused with a clear message: [MS-OFFCRYPTO] defines AES only for encrypted packages, which open through the `.docx` reader (gap 9) |
| `.md` Markdown | — | (no) | ✅ | ✅ | — | — | `crates/formats/src/tests.rs` | Beyond Word |
| `.tex` LaTeX | — | — | ✅ | ✅ | — | — | `crates/formats/src/tests.rs` | Beyond Word (#11), incl. math |
| Pictures for Insert › Picture, drag-and-drop and paste | — | R | ✅ | — | — | — | `insert_picture_takes_a_windows_metafile` (engine), `paste_picture.rs` | PNG, JPEG, GIF, WebP, BMP, and Windows Metafile `.wmf` / Enhanced Metafile `.emf` at their own frame size (#802), drawn by `crates/metafile`. Not yet: SVG, TIFF, ICO, HEIC |
| Pictures for Insert › Picture, drag-and-drop and paste | — | R | ✅ | — | — | — | `insert_picture_takes_a_windows_metafile` (engine), `paste_picture.rs` | PNG, JPEG, GIF, WebP, BMP, and Windows Metafile `.wmf` / Enhanced Metafile `.emf`, EMF+ records included (#6636), at their own frame size (#802), drawn with craft-libs' `craft-metafile`. Not yet: SVG, TIFF, ICO, HEIC |
| `.png` page images | — | (Save as picture, Mac) | — | ✅ | — | — | `io_ext.rs` | |
| `.json` document model | — | — | ✅ | ✅ | — | — | engine tests | For agents. A table cell's span is any number in the file; Insert Column and Merge Cells count it as at most 63 columns, as the `.docx` reader does (#3637) |
+4 -2
View File
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+2 -5
View File
@@ -1,6 +1,6 @@
# MCP server
> **Last updated:** 2026-10-31 · Delivery review fixes for #2596: unknown outcomes are not replayed, including image exports to a path; invalid UTF-8 returns a parse error without stopping later requests.
> **Last updated:** 2026-11-14 · Keep the complete `type_text` description in one tool-table row; behavior wording unchanged. Delivery review fixes for #2596: unknown outcomes are not replayed, including image exports to a path; invalid UTF-8 returns a parse error without stopping later requests.
WordCraft speaks the [Model Context Protocol](https://modelcontextprotocol.io) over stdio, so
Claude and other agents can write and edit documents.
@@ -173,10 +173,7 @@ test source in File › Options › Language and on the bar's Install.
| `new_document` | blank, sample, letter, resume, report; opens beside the open documents |
| `open_document` / `save_document` | docx, doc (open only), odt, rtf, html, md, tex, txt, json; save also pdf, png |
| `list_documents` | the open documents: `id`, `title`, `path`, `dirty`, `active` |
| `type_text` | type at the caret (`paragraphs: true` splits lines into paragraphs: one undo
step; each break is the Enter it stands for, so AutoFormat and AutoCorrect run and a
one-line control refuses; at most 10,000 lines — the cap is `text.insert`'s own, so a
control-channel or CLI call is held to it too) |
| `type_text` | type at the caret (`paragraphs: true` splits lines into paragraphs: one undo step; each break is the Enter it stands for, so AutoFormat and AutoCorrect run and a one-line control refuses; at most 10,000 lines — the cap is `text.insert`'s own, so a control-channel or CLI call is held to it too) |
| `select_text` | select the n-th occurrence of some text |
| `get_text` / `inspect_document` | read the document back (verify without screenshots) |
| `render_page` | a page as PNG |
+8 -6
View File
@@ -1,6 +1,7 @@
# Releasing WordCraft
1. Bump the version on `main`: `cargo xtask version set 0.2.0` (the one source of truth is
1. On a branch, bump the version with `cargo xtask version set 0.2.0`, then open and
merge a pull request into `main` (the one source of truth is
`[workspace.package] version`; the app shows it in `--version` and About, with the commit from
`WORDCRAFT_BUILD_SHA`).
2. Merge `main` into `release` and push. `.github/workflows/release.yml` builds:
@@ -17,12 +18,13 @@
3. The run drafts a GitHub Release `WordCraft v<version>` with `SHA256SUMS.txt`; review and publish it.
Signing secrets live in the repository's `release` environment (deployment branch: `release` only),
synced from the release manager's machine. Missing secrets
produce unsigned builds with a warning, so forks still build.
synced from the release manager's machine. On the release branch, the shared workflow fails the
macOS and Windows jobs if their signing credentials are missing. Local packaging can still
produce unsigned builds with a warning.
Local packaging: `packaging/macos/package.sh --arch universal`, `packaging/windows/package.ps1`,
`packaging/linux/package.sh` (then `packaging/linux/flatpak-bundle.sh` for the Flatpak), `packaging/web/package.sh`.
Dry run: `gh workflow run release.yml --ref <branch>` builds the unsigned jobs (version, Linux,
Linux riscv64, Flatpak, FreeBSD, web) on any branch; the signing jobs are refused there by the `release`
environment's branch rule, so no draft release is made.
A scheduled dry run runs on `main` nightly at 03:00 UTC. It builds every release target except
macOS, without signing, entering the `release` environment, pushing Flatpak images or making a
draft release. Manual dispatch uses the normal release path (`dry-run` is false).
+2 -2
View File
@@ -1,8 +1,8 @@
# Shared PDF writer
WordCraft uses `craft-pdf` with default features disabled and `write` enabled. Both that dependency
and the required root Krilla patch use the immutable `storytold/craft-libs` revision
`b926b5c03e256c86ca10934f58d03f628810b5b7`. Rust 1.95 or newer is required. The revision must be
and the required root Krilla patch use the same immutable `storytold/craft-libs` revision,
pinned in [`Cargo.toml`](../Cargo.toml). Rust 1.95 or newer is required. The revision must be
available from the remote before a fresh checkout can resolve it. The shared writer checks a
backend marker at compile time so an unpatched Krilla cannot replace the required backend.
+1 -1
View File
@@ -12,7 +12,7 @@ WordCraft uses this arrangement and its shared pane host, icons, typography and
## Scope and behavior
Review › Spelling & Grammar, Home › Editor and F7 open the task pane. The pass begins at the next issue from the current selection and continues to the end of the current story (body, header, note or other active text), not all document stories or only a selection. Each correction uses the existing review command and remains undoable. Ignore Once advances without changing the document or dictionaries. Ignore All lasts for the session; Add to Dictionary uses the personal dictionary. Those two actions are offered only for spelling issues. Completion remains visible; Check Again starts a wrapping search. The pane host supplies Close and docking.
Review › Spelling & Grammar, Home › Editor and F7 open the task pane. The initial search begins at the next issue from the current selection and wraps to the start of the current story if needed; pane navigation then stops at that story's end (body, header, note or other active text), not all document stories or only a selection. Each correction uses the existing review command and remains undoable. Ignore Once advances without changing the document or dictionaries. Ignore All lasts for the session; Add to Dictionary uses the personal dictionary. Those two actions are offered only for spelling issues. Completion remains visible; Check Again starts a wrapping search. The pane host supplies Close and docking.
If another command changes the document body or selection, a cached suggestion is refused; Check Again obtains a fresh target. Read-only/protected document commands retain their checks. The pane is local to each window, clears on a document switch and does not alter the compact right-click menu. Programmatic review commands return structured results without opening UI.
+8 -6
View File
@@ -5,12 +5,14 @@ Source Serif 4, Inter and JetBrains Mono, with their bundled styles. Family list
legacy style names such as Inter Medium. They do not load installed fonts, user font preferences,
or the optional `CRAFT_FONTS_DIR` input. No download or extra font checkout is required.
Every layout unit test starts with `crate::test_fonts();`, before constructing its fixture or
resolving a font. This initializes the process-wide database once, including when a single test is
run by name. The `wordcraft-fonts/test-support` development feature exposes the initializer;
enabling the feature alone has no effect. Initialization fails if an application database already
exists, rather than replacing a database whose faces may be in the shaping or math caches.
Other test binaries and application builds keep their normal font discovery behavior.
Layout entry points (`layout`, `layout_para`, `layout_equation` and
`display::mark_text_width`) initialize the process-wide font database once in unit-test builds,
including when a single test is run by name. Tests that resolve fonts before calling a layout
entry point must first call `crate::test_fonts();`. The `wordcraft-fonts/test-support`
development feature exposes the initializer; enabling the feature alone has no effect.
Initialization fails if an application database already exists, rather than replacing a database
whose faces may be in the shaping or math caches. Other test binaries and application builds
keep their normal font discovery behavior.
Uninstalled requested families use the normal substitution lists, restricted to this fixed set.
In particular, the default Aptos request resolves to Source Sans 3. These fonts are not Calibri
+5 -2
View File
File diff suppressed because one or more lines are too long
+8 -5
View File
@@ -19,11 +19,14 @@ Citations (each runs one of the commands below).
| `ui.zotero.status` | `{busy, waitingForAnswer, last}` |
| `ui.zotero.answer` | `{"button": n}`: answer a question Zotero is asking (OK/Yes 1, No/Cancel 0; with Yes/No/Cancel: Yes 2, No 1, Cancel 0) |
They run in the app (and through the control channel and MCP bridged to the app). A command
returns at once with `{"started": …}`; Zotero then works in its own window and WordCraft answers
it in the background. All changes from one command are one undo step. If New or Open replaces
the document while a command is running, Zotero's remaining calls for it get an error and the
new document is left as it is.
They run in the app (and through the control channel and MCP bridged to the app). The six Zotero
actions return at once with `{"started": …}`; Zotero then works in its own window and WordCraft
answers it in the background. All changes from one action are one undo step. If New or Open
replaces the document while an action is running, Zotero's remaining calls for it get an error
and the new document is left as it is.
`ui.zotero.status` returns the current state. A successful `ui.zotero.answer` returns
`{"answered": n}` for the selected button.
From a terminal, against a file:
+7 -4
View File
@@ -19,7 +19,7 @@ pub fn png_size(png: &[u8]) -> Result<(u32, u32), String> {
/// An ICO file holding `pngs`, which must be square and at most 256 px.
pub fn pack(pngs: &[Vec<u8>]) -> Result<Vec<u8>, String> {
if pngs.is_empty() || pngs.len() > u16::MAX as usize {
return Err("need at least one PNG".into());
return Err("need between 1 and 65535 PNGs".into());
}
let mut out = Vec::new();
out.extend_from_slice(&0u16.to_le_bytes()); // reserved
@@ -29,7 +29,7 @@ pub fn pack(pngs: &[Vec<u8>]) -> Result<Vec<u8>, String> {
for png in pngs {
let (w, h) = png_size(png)?;
if w != h || w == 0 || w > 256 {
return Err(format!("icon images must be square and at most 256 px, got {w}x{h}"));
return Err(format!("icon images must be square and between 1 and 256 px, got {w}x{h}"));
}
let dim = if w == 256 { 0 } else { w as u8 };
out.extend_from_slice(&[dim, dim, 0, 0]); // width, height, palette size, reserved
@@ -87,10 +87,13 @@ mod tests {
#[test]
fn rejects_bad_input() {
assert!(pack(&[]).is_err());
assert!(pack(&[fake_png(512)]).is_err());
assert_eq!(pack(&[]).unwrap_err(), "need between 1 and 65535 PNGs");
assert_eq!(pack(&vec![Vec::new(); usize::from(u16::MAX) + 1]).unwrap_err(), "need between 1 and 65535 PNGs");
assert_eq!(pack(&[fake_png(0)]).unwrap_err(), "icon images must be square and between 1 and 256 px, got 0x0");
assert_eq!(pack(&[fake_png(512)]).unwrap_err(), "icon images must be square and between 1 and 256 px, got 512x512");
assert!(pack(&[b"GIF89a".to_vec()]).is_err());
assert_eq!(png_size(&fake_png(48)).unwrap(), (48, 48));
assert!(pack(&[fake_png(1)]).is_ok());
}
#[test]
-1
View File
@@ -37,7 +37,6 @@ pub const TABLE: &[(&str, Class)] = &[
("control-key", Class::Standalone),
("doc", Class::Layer(1)),
("fonts", Class::Layer(1)),
("metafile", Class::Layer(1)),
("layout", Class::Layer(2)),
("docx", Class::Layer(2)),
("docbin", Class::Layer(2)),
+4 -2
View File
@@ -19,7 +19,7 @@ usage: cargo xtask <command>
commands:
assets check that every icon/image/font/asset is attributed in ATTRIBUTION.md
layers enforce the crate dependency layering (plan/architecture.md §3)
layers enforce the crate dependency layering (docs/architecture.md, Layers)
wasm cargo check --target wasm32-unknown-unknown for the wasm-safe crates (one call)
test workspace tests (cargo nextest when installed, else cargo test), the interface
audit with its missing-translation report, then doctests
@@ -34,6 +34,8 @@ commands:
show where test corpora live; --download fetches PngSuite into corpus/pngsuite
stats [--exact] count tests and lines per crate (--exact: ask the test harness via `-- --list`)
parity recompute the Word feature-parity summary in docs/parity-checklist.md
version [set X.Y.Z[-pre]]
show the workspace version, or set it and update Cargo.lock
visual-diff <ref.pdf> <test.pdf> <outdir> [--private] [--dpi N]
compare two PDFs of a document page by page (SSIM, line breaks, offsets);
needs poppler (pdftoppm, pdftotext)
@@ -100,7 +102,7 @@ pub fn metadata() -> Result<serde_json::Value, String> {
fn cmd_layers() -> Result<(), String> {
let crates = layers::from_metadata(&metadata()?)?;
println!("Dependency layering (plan/architecture.md §3)\n");
println!("Dependency layering (docs/architecture.md, Layers)\n");
println!("{:<28} {:<14} workspace deps", "crate", "layer");
for c in &crates {
let ws: Vec<String> = c