Compare commits

...
Author SHA1 Message Date
autocraft-bot[bot] 7517f12ef8 Merge main (52655f7d) into the pull request
Resolved the single conflict in docs/layout-parity.md. The status line k

Resolved the single conflict in docs/layout-parity.md. The status line keeps the PR's #6457 list-number kerning entry first, with Last updated set to 2026-12-03. The default branch's #6591 entry and all older entries follow it. No conflict markers remain. I did not build or run tests, since the change is docs-only.
2026-12-03 22:06:00 +00:00
autocraft-bot[bot] 52655f7d8a Merge pull request #8690 2026-12-03 19:37:59 +00:00
autocraft-bot[bot] 8bb24371ae Merge pull request #8689 2026-12-03 19:37:59 +00:00
autocraft-bot[bot] f920c301d0 Merge pull request #8681 2026-12-03 19:37:59 +00:00
autocraft-bot[bot] 9c36a3fcfb Merge pull request #8675 2026-12-03 19:37:59 +00:00
autocraft-bot[bot] 2a36448f5d Merge pull request #8677 2026-12-03 19:37:59 +00:00
autocraft-bot[bot] 7a53b46b82 Merge pull request #8674 2026-12-03 19:37:59 +00:00
autocraft-bot[bot] b8cad0d438 Merge pull request #8666 2026-12-03 19:37:59 +00:00
autocraft-bot[bot] 7d9c05ad94 Merge pull request #8664 2026-12-03 19:37:59 +00:00
autocraft-bot[bot] 9556951c4a Merge pull request #8641 2026-12-03 19:37:59 +00:00
batistalucasv 48b211621d Tests: remove redundant Dictate icon shape check from stub ribbon test (#8615) 2026-12-03 16:37:59 -03:00
batistalucasv c39e70fc85 engine: remove duplicate German date-field integration tests (#8540) 2026-12-03 16:33:51 -03:00
batistalucasv 0a1d913690 engine: drop redundant turns_on branches and cover collapsed caret (#8658) 2026-12-03 16:32:01 -03:00
batistalucasv c55e7a83e6 Layout: test a long word in a short at-least turned row (#8487) 2026-12-03 16:22:14 -03:00
batistalucasv b682a1fd06 PDF export: tag header and footer link annotations with Link/OBJR (#8642) 2026-12-03 16:17:01 -03:00
batistalucasv 6a6dfd7f58 Docs: restore ui.drag in control protocol reference (#8559) 2026-12-03 16:09:16 -03:00
batistalucasv 9d5789162f Layout: mark begins_section run-over case as inferred (#8569) 2026-12-03 16:01:11 -03:00
batistalucasv cdef8012e9 Tests: merge whole-paragraph mark compare checks into existing test (#8470) 2026-12-03 16:01:05 -03:00
batistalucasv 4dd74c36d5 docs(layout): mention cell_frame in Joint::take_up doc comment
Fixes #8564
2026-12-03 15:59:36 -03:00
batistalucasv 4073aa4274 docs(layout-parity): record list-number kerning in status line (#8583) 2026-12-03 15:26:11 -03:00
17 changed files with 285 additions and 166 deletions
+6 -3
View File
@@ -352,11 +352,14 @@ fn resolved(s: &Session) -> Vec<ResolvedChar> {
out
}
/// Whether a toggle without a `value` turns its format on. A selection follows its first character
/// in document order, as Word does: one that starts formatted loses the format, all of it (#6516).
/// Whether a toggle without a `value` turns its format on. A selection (including a selected
/// text box or a non-empty column block, whose `sel` is non-collapsed) follows its first
/// character in document order, as Word does: one that starts formatted loses the format, all of
/// it (#6516). A collapsed caret (including an empty column block) requires the whole word to
/// carry the format before toggling it off.
fn turns_on(s: &Session, has: impl Fn(&ResolvedChar) -> bool) -> bool {
let chars = resolved(s);
if !s.sel.is_collapsed() || selected_text_box(s).is_some() || column_rows(s).is_some() {
if !s.sel.is_collapsed() {
return !chars.first().is_some_and(has);
}
!chars.iter().all(has)
+29 -67
View File
@@ -16,72 +16,6 @@ fn empty_paras(s: &Session) -> usize {
s.doc.body.iter().filter(|b| matches!(b.as_para(), Some(p) if p.is_empty())).count()
}
#[test]
fn compare_marks_a_whole_paragraph_and_its_mark() {
// A whole inserted paragraph carries the insertion on its mark, not just on its runs.
let mut s = Session::new(Document::from_text("A\nB"));
s.run("review.compare", &json!({"text": "A\nNEW\nB"})).unwrap();
assert_eq!(s.doc.body.len(), 3);
let mid = s.doc.body[1].as_para().unwrap();
assert_eq!(mid.plain_text(), "NEW");
assert!(mid.mark.ins.is_some(), "the inserted paragraph's mark is not marked inserted");
s.run("review.rejectAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
assert_eq!(s.doc.body.len(), 2);
assert_eq!(empty_paras(&s), 0, "rejecting an inserted paragraph left an empty paragraph behind");
let mut s = Session::new(Document::from_text("A\nB"));
s.run("review.compare", &json!({"text": "A\nNEW\nB"})).unwrap();
s.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nNEW\nB");
assert_eq!(s.doc.body.len(), 3);
assert_eq!(empty_paras(&s), 0, "accepting an inserted paragraph left an empty paragraph behind");
// A whole deleted paragraph carries the deletion on its mark.
let mut s = Session::new(Document::from_text("A\nOLD\nB"));
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
assert_eq!(s.doc.body.len(), 3);
let mid = s.doc.body[1].as_para().unwrap();
assert_eq!(mid.plain_text(), "OLD");
assert!(mid.mark.del.is_some(), "the deleted paragraph's mark is not marked deleted");
s.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
assert_eq!(s.doc.body.len(), 2);
assert_eq!(empty_paras(&s), 0, "accepting a deleted paragraph left an empty paragraph behind");
let mut s = Session::new(Document::from_text("A\nOLD\nB"));
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
s.run("review.rejectAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nOLD\nB");
assert_eq!(s.doc.body.len(), 3);
assert_eq!(empty_paras(&s), 0, "rejecting a deleted paragraph left an empty paragraph behind");
}
#[test]
fn compare_marks_an_empty_paragraphs_mark() {
// An empty inserted paragraph is stamped on its mark, though `format` skips its empty range.
let mut s = Session::new(Document::from_text("A\nB"));
s.run("review.compare", &json!({"text": "A\n\nB"})).unwrap();
assert_eq!(s.doc.body.len(), 3);
let empty = s.doc.body[1].as_para().unwrap();
assert!(empty.is_empty());
assert!(empty.mark.ins.is_some(), "the empty inserted paragraph's mark is not marked inserted");
s.run("review.rejectAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
assert_eq!(s.doc.body.len(), 2);
assert_eq!(empty_paras(&s), 0, "rejecting an empty inserted paragraph left it behind");
// An empty deleted paragraph is stamped on its mark too.
let mut s = Session::new(Document::from_text("A\n\nB"));
s.run("review.compare", &json!({"text": "A\nB"})).unwrap();
assert_eq!(s.doc.body.len(), 3);
let empty = s.doc.body[1].as_para().unwrap();
assert!(empty.is_empty());
assert!(empty.mark.del.is_some(), "the empty deleted paragraph's mark is not marked deleted");
s.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nB");
assert_eq!(s.doc.body.len(), 2);
assert_eq!(empty_paras(&s), 0, "accepting an empty deleted paragraph left it behind");
}
#[test]
fn compare_keeps_another_authors_deletion_stamp() {
// A paragraph the original already carries as a tracked deletion by another author: Compare
@@ -1744,7 +1678,8 @@ fn compare_lcs_window_move_past_cap_does_not_cascade_false_revisions() {
}
/// Verifies that `mark_block` records paragraph mark revisions on whole-block deletions,
/// whole-block insertions, empty paragraphs, and ensures clean resolution via `review.acceptAll`.
/// whole-block insertions, empty paragraphs, and ensures clean resolution via `review.acceptAll`
/// and `review.rejectAll`.
#[test]
fn compare_mark_block_records_paragraph_mark_revisions_on_whole_block_changes() {
// Whole block delete/insert: test with differing paragraph count so whole-block paths trigger
@@ -1762,17 +1697,34 @@ fn compare_mark_block_records_paragraph_mark_revisions_on_whole_block_changes()
assert!(del_para.mark.del.is_some(), "whole-block delete must record revision on paragraph mark");
assert_eq!(del_para.mark.bold, Some(true), "paragraph mark formatting must be preserved on deleted block");
let mut s2_rej = Session::new(s2.doc.clone());
s2_rej.run("review.rejectAll", &json!({})).unwrap();
assert_eq!(s2_rej.doc.plain_text(StoryRef::Body), orig_multi);
assert_eq!(s2_rej.doc.body.len(), 3);
assert_eq!(empty_paras(&s2_rej), 0, "rejecting a deleted paragraph left an empty paragraph behind");
// Accept all changes: deleted paragraph is removed
s2.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s2.doc.plain_text(StoryRef::Body), rev_multi);
assert_eq!(s2.doc.body.len(), 2);
assert_eq!(empty_paras(&s2), 0, "accepting a deleted paragraph left an empty paragraph behind");
// Test whole-block insertion
let mut s3 = Session::new(Document::from_text(rev_multi));
s3.run("review.compare", &json!({"text": orig_multi})).unwrap();
let ins_para = s3.doc.body[1].as_para().expect("block 1 must be paragraph");
assert!(ins_para.mark.ins.is_some(), "whole-block insert must record revision on paragraph mark");
let mut s3_rej = Session::new(s3.doc.clone());
s3_rej.run("review.rejectAll", &json!({})).unwrap();
assert_eq!(s3_rej.doc.plain_text(StoryRef::Body), rev_multi);
assert_eq!(s3_rej.doc.body.len(), 2);
assert_eq!(empty_paras(&s3_rej), 0, "rejecting an inserted paragraph left an empty paragraph behind");
s3.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s3.doc.plain_text(StoryRef::Body), orig_multi);
assert_eq!(s3.doc.body.len(), 3);
assert_eq!(empty_paras(&s3), 0, "accepting an inserted paragraph left an empty paragraph behind");
// Test empty paragraph deletion and insertion (len == 0, where only mark carries the revision)
let orig_empty = "Before.\n\nAfter.";
@@ -1784,14 +1736,24 @@ fn compare_mark_block_records_paragraph_mark_revisions_on_whole_block_changes()
assert!(empty_del.mark.del.is_some(), "empty paragraph deletion must set mark.del");
s4.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s4.doc.plain_text(StoryRef::Body), rev_empty);
assert_eq!(s4.doc.body.len(), 2);
assert_eq!(empty_paras(&s4), 0, "accepting an empty deleted paragraph left it behind");
let mut s5 = Session::new(Document::from_text(rev_empty));
s5.run("review.compare", &json!({"text": orig_empty})).unwrap();
let empty_ins = s5.doc.body[1].as_para().expect("empty paragraph block");
assert_eq!(empty_ins.len(), 0);
assert!(empty_ins.mark.ins.is_some(), "empty paragraph insertion must set mark.ins");
let mut s5_rej = Session::new(s5.doc.clone());
s5_rej.run("review.rejectAll", &json!({})).unwrap();
assert_eq!(s5_rej.doc.plain_text(StoryRef::Body), rev_empty);
assert_eq!(s5_rej.doc.body.len(), 2);
assert_eq!(empty_paras(&s5_rej), 0, "rejecting an empty inserted paragraph left it behind");
s5.run("review.acceptAll", &json!({})).unwrap();
assert_eq!(s5.doc.plain_text(StoryRef::Body), orig_empty);
assert_eq!(s5.doc.body.len(), 3);
}
#[test]
+21
View File
@@ -1170,6 +1170,27 @@ fn toggle_on_a_column_block_follows_first_character() {
assert_eq!(toggled(1, false), vec![true, true, true]);
}
/// A collapsed caret inside a partly formatted word (including when column mode just started with
/// an empty block) turns the format on unless the whole word already has it (#8658).
#[test]
fn toggle_at_collapsed_caret_in_partly_formatted_word_turns_on() {
let toggled = |column_mode: bool| -> String {
let mut s = s();
run(&mut s, "text.insert", json!({"text": "Abc"}));
run(&mut s, "select.range", json!({"anchor": {"block": 0, "off": 0}, "focus": {"block": 0, "off": 1}}));
run(&mut s, "format.bold", json!({"value": true}));
run(&mut s, "caret.set", json!({"pos": {"block": 0, "off": 1}}));
if column_mode {
run(&mut s, "select.column", json!({}));
}
run(&mut s, "format.bold", json!({}));
let p = s.doc.para_at(&Pos::body(0, 0)).unwrap();
(0..3).map(|i| if p.props_of_char(i).bold == Some(true) { 'B' } else { '.' }).collect()
};
assert_eq!(toggled(false), "BBB");
assert_eq!(toggled(true), "BBB");
}
#[test]
fn bold_at_a_caret_takes_a_word_with_a_typographic_apostrophe() {
// Word bolds `don’t` and `dogs’` whole: `’` is part of the word like `'` (#6517).
-33
View File
@@ -183,18 +183,6 @@ fn german_date_fields_inherit_the_document_default_language() {
}
}
/// `MMM` and `ddd` use Word's Windows NLS short forms for German: two-letter weekdays (`So`,
/// `Mo`…) and `Mrz` for March, with no trailing full stop (#7146).
#[test]
fn a_german_short_date_field_uses_windows_nls_abbreviations() {
const PICTURE: &str = "ddd, d. MMM yyyy";
let d = open_body_in_lang("de-DE", &format!("<w:p>{}</w:p>", field(&format!(r#"DATE \@ "{PICTURE}""#), "Wed, 1 Jan 2020", false)));
let got = fields(&d);
assert_eq!(got[0].1, wordcraft_engine::cmd::insert::format_date_in(PICTURE, Some("de-DE")));
// The abbreviations at a fixed date, independent of when the test runs.
assert_eq!(wordcraft_engine::cmd::insert::format_date_parts_in(PICTURE, Some("de-DE"), 2026, 3, 15, (12, 0, 0), 3), "So, 15. Mrz 2026");
}
/// A `TIME` field whose picture carries German name tokens inherits the language too, so the
/// English result cached in the fixture is replaced with German weekday and month names.
#[test]
@@ -207,27 +195,6 @@ fn a_german_time_field_uses_german_names() {
assert_eq!(got[0].1, wordcraft_engine::cmd::insert::format_date_in(PICTURE, Some("de-DE")));
}
/// Austrian Standard German writes January as `Jänner` (`Jän`), while Germany, Switzerland and
/// bare `de` keep `Januar` (`Jan`), as in Windows NLS (#7146). A `de-AT` document reads German
/// through `docDefaults`; the refresh always uses the real clock, so the January names are asked
/// of the same formatter at a fixed January instant.
#[test]
fn austrian_german_documents_use_jaenner() {
const PICTURE: &str = "dddd, d. MMMM yyyy";
let d = open_body_in_lang("de-AT", &format!("<w:p>{}</w:p>", field(&format!(r#"DATE \@ "{PICTURE}""#), "Wednesday, 1 January 2020", false)));
let got = fields(&d);
assert_eq!(got[0].1, wordcraft_engine::cmd::insert::format_date_in(PICTURE, Some("de-AT")), "an Austrian document reads German");
let january = |lang: &str, picture: &str| wordcraft_engine::cmd::insert::format_date_parts_in(picture, Some(lang), 2026, 1, 15, (12, 0, 0), 0);
assert_eq!(january("de-AT", "MMMM"), "Jänner");
assert_eq!(january("de-AT", "MMM"), "Jän");
assert_eq!(january("de-AT", PICTURE), "Donnerstag, 15. Jänner 2026");
for lang in ["de-DE", "de-CH", "de"] {
assert_eq!(january(lang, "MMMM"), "Januar", "{lang}");
assert_eq!(january(lang, "MMM"), "Jan", "{lang}");
}
}
/// A minimal Word 97-2003 file whose only paragraph holds a `DATE` field cached as " 2001":
/// FIB, one compressed text piece, and the Clx that points at it.
fn binary_doc_with_stale_date() -> Vec<u8> {
+3 -2
View File
@@ -827,8 +827,9 @@ impl Joint {
}
/// Paragraph `p` of a box `width` wide going on from here, unless a page break comes before
/// it, it runs right to left or it is a text frame (`frames`: placed apart, sharing no line):
/// without its space before, as [`Joint::fit`] lays it out.
/// it, it runs right to left, or it is a text frame placed apart (`frames` and `cell_frame`
/// both hold, sharing no line; in a table cell, only frames anchored to `"text"`): without
/// its space before, as [`Joint::fit`] lays it out.
fn take_up(
self,
ctx: &mut Ctx,
+3 -2
View File
@@ -40,8 +40,9 @@ pub(crate) fn section_side(start: SectionStart, restart: Option<u32>, last: u32,
/// header and footer go on: the page where the section begins. A page's section is the one at its
/// top, so a section that starts continuously part-way down `prev` has no first page of its own:
/// Word shows the earlier section's header there and the section's default one from the next page
/// on, also when its first paragraph begins on `prev` and runs over. `sections` as
/// [`Document::sections`] gives them (each with its last block).
/// on; the case where its first paragraph begins on `prev` and runs over is treated the same way
/// (inferred, not measured separately in Word). `sections` as [`Document::sections`] gives them
/// (each with its last block).
pub(crate) fn begins_section(sections: &[(usize, &SectionProps)], prev: Option<&Page>, page: &Page) -> bool {
if prev.is_some_and(|p| p.section == page.section) {
return false;
+42
View File
@@ -3871,6 +3871,48 @@ fn a_text_box_skips_the_min_height_probe_for_turned_text() {
assert!(b.h > 80.0, "and so it runs on past the minimum height: {b:?}");
}
/// A single word longer than an at-least row's minimum height (0.3 cm / ~8.5 pt) runs past
/// the row along its length instead of growing the row, as long as the wrapped pieces fit across
/// the column.
#[test]
fn a_word_longer_than_min_height_does_not_grow_an_at_least_row() {
use wordcraft_doc::props::HeightRule;
crate::test_fonts();
let min_h = 8.5;
for turn in [TextDirection::Up, TextDirection::Down] {
let mut d = Document::from_text("After");
let mut t = Table::new(1, 1, 160.0);
t.props.style = None;
t.rows[0].props.height = Some(min_h);
t.rows[0].props.height_rule = HeightRule::AtLeast;
t.rows[0].cells[0].props.text_direction = turn;
t.rows[0].cells[0].blocks = vec![wordcraft_doc::para_block(Paragraph::with_text("WWWW", Default::default()))];
d.insert_block(StoryRef::Body, &Path::top(0), wordcraft_doc::Block::Table(t)).unwrap();
let l = lay(&d);
let (rect, clip) = l.pages[0]
.items
.iter()
.find_map(|it| match it {
Placed::Cell { rect, clip, cell: 0, .. } => Some((*rect, *clip)),
_ => None,
})
.unwrap();
assert!((rect.h - min_h).abs() < 0.01, "{turn:?}: cell grew past min height {min_h}: {rect:?}");
assert!(!clip, "{turn:?}: an at-least row does not clip overflowing text");
let extent = l.pages[0]
.items
.iter()
.find_map(|it| match it {
Placed::Lines { para, l0, l1, path, .. } if path.0 == [0, 0, 0, 0] => {
Some(para.lines.get(*l0..*l1).unwrap_or(&[]).iter().filter_map(|line| line.xs.last().copied()).fold(0.0f32, f32::max))
}
_ => None,
})
.unwrap();
assert!(extent > min_h, "{turn:?}: word should run past the min height {min_h}, got {extent}");
}
}
#[test]
fn turned_text_wraps_to_merged_rows_height() {
use wordcraft_doc::props::{HeightRule, VMerge};
+3 -5
View File
@@ -137,12 +137,10 @@ fn write_attempt(doc: &Document, lay: &DocLayout, opts: &PdfOptions, pages: &[us
}
}
surface.finish();
for (annotation, tag_slot) in annotations {
if opts.tagged
&& let Some((para_idx, child_idx)) = tag_slot
{
for (annotation, tag) in annotations {
if opts.tagged {
let annot_id = kp.add_tagged_annotation(annotation);
ex.attach_link_annotation(para_idx, child_idx, annot_id);
ex.attach_link_annotation(tag, annot_id);
} else {
kp.add_annotation(annotation);
}
+38 -5
View File
@@ -18,6 +18,17 @@ mod objects;
pub(crate) use objects::ObjectLookup;
mod text;
/// Where a link annotation's `OBJR` attaches in the structure tree.
#[derive(Clone, Copy)]
pub(crate) enum LinkTag {
/// Inside an existing `Tag::Link` group at `(para, child)` in `Exporter::tags`, with
/// reading-order position `at` as fallback.
Group { para: usize, child: usize, at: (usize, usize) },
/// Outside any paragraph (for example a header or footer artifact), as its own `Link`
/// structure element placed at reading-order position `at`.
Standalone((usize, usize)),
}
pub(crate) struct LinkRect {
pub(crate) x0: f32,
pub(crate) y0: f32,
@@ -26,6 +37,8 @@ pub(crate) struct LinkRect {
pub(crate) target: String,
/// `(para_idx, child_idx)` in `Exporter::tags` for this link's `Tag::Link` group.
pub(crate) tag: Option<(usize, usize)>,
/// Reading-order position ([`TagEntry::at`]) where this link was drawn.
pub(crate) at: (usize, usize),
}
pub(crate) struct Exporter<'a> {
@@ -230,11 +243,21 @@ impl Exporter<'_> {
}
}
/// Insert a link annotation's `OBJR` identifier as the first child of its `Tag::Link` group.
pub(crate) fn attach_link_annotation(&mut self, para_idx: usize, child_idx: usize, annot_id: Identifier) {
if let Some(Node::Group(g)) = self.tags.get_mut(para_idx).and_then(|e| e.children.get_mut(child_idx)) {
/// Attach a link annotation's `OBJR` identifier to its `Tag::Link` group, or add a standalone
/// `Div -> Link` entry holding just the `OBJR` when the link has no paragraph group (such as
/// a link drawn inside a header or footer artifact).
pub(crate) fn attach_link_annotation(&mut self, tag: LinkTag, annot_id: Identifier) {
if let LinkTag::Group { para, child, .. } = tag
&& let Some(Node::Group(g)) = self.tags.get_mut(para).and_then(|e| e.children.get_mut(child))
{
g.children.insert(0, Node::Leaf(annot_id));
return;
}
let at = match tag {
LinkTag::Group { at, .. } | LinkTag::Standalone(at) => at,
};
let g = TagGroup::with_children(Tag::Link, vec![Node::Leaf(annot_id)]);
self.tags.push(TagEntry { kind: Tag::Div.into(), children: vec![Node::Group(g)], source: None, at });
}
/// One draw of a paragraph's line, tagged for what it is: text as the paragraph's content
@@ -303,7 +326,17 @@ impl Exporter<'_> {
let dopts = self.opts.display_options();
// What the items share (the authors' colours, the clipped cells) is worked out once per page.
let shown = ItemDisplay::new(self.doc, page);
for it in page.header.iter().chain(page.footer.iter()) {
self.at.1 = 0;
for it in &page.header {
let draws = shown.draws(it, &dopts);
self.tagged(s, Role::Artifact(ArtifactType::Other), None, |me, s| {
for d in &draws {
me.draw(s, d);
}
});
}
self.at.1 = usize::MAX;
for it in &page.footer {
let draws = shown.draws(it, &dopts);
self.tagged(s, Role::Artifact(ArtifactType::Other), None, |me, s| {
for d in &draws {
@@ -312,7 +345,7 @@ impl Exporter<'_> {
});
}
for (i, it) in page.items.iter().enumerate() {
self.at.1 = page.reading.get(i).copied().unwrap_or(i);
self.at.1 = page.reading.get(i).copied().unwrap_or(i).saturating_add(1).min(usize::MAX - 1);
let draws = shown.draws(it, &dopts);
match it {
Placed::Lines { story, path, para, .. } => {
+7 -3
View File
@@ -1,5 +1,5 @@
use super::{
Annotation, ClKind, DocPath, Exporter, Fit, HashMap, LineEnd, LinkAnnotation, Outline, OutlineNode, Placed, Point, StoryRef, Target,
Annotation, ClKind, DocPath, Exporter, Fit, HashMap, LineEnd, LinkAnnotation, LinkTag, Outline, OutlineNode, Placed, Point, StoryRef, Target,
XyzDestination, krilla, write,
};
@@ -62,13 +62,17 @@ impl Exporter<'_> {
}
}
pub(crate) fn annotations(&self, fit: Fit) -> Vec<(Annotation, Option<(usize, usize)>)> {
pub(crate) fn annotations(&self, fit: Fit) -> Vec<(Annotation, LinkTag)> {
let mut v = Vec::new();
for link in &self.links {
let ((x0, y0), (x1, y1)) = (fit.point(link.x0, link.y0), fit.point(link.x1, link.y1));
let Some(rect) = krilla::geom::Rect::from_ltrb(x0, y0, x1, y1) else { continue };
let Some(t) = self.link_target(&link.target) else { continue };
v.push((Annotation::new_link(LinkAnnotation::new(rect, t), Some(link.target.clone())), link.tag));
let tag = match link.tag {
Some((para, child)) => LinkTag::Group { para, child, at: link.at },
None => LinkTag::Standalone(link.at),
};
v.push((Annotation::new_link(LinkAnnotation::new(rect, t), Some(link.target.clone())), tag));
}
v
}
+2 -2
View File
@@ -178,7 +178,7 @@ impl Exporter<'_> {
if self.link_target(link).is_none() {
return;
}
let continues = self.links.last().is_some_and(|prev| self.link_run_continues(prev.tag));
let continues = self.links.last().is_some_and(|prev| prev.at == self.at && self.link_run_continues(prev.tag));
if let Some(prev) = self.links.last_mut()
&& prev.target == link
&& (prev.y0 - y0).abs() < 0.5
@@ -191,7 +191,7 @@ impl Exporter<'_> {
return;
}
if self.links.len() < 10_000 {
self.links.push(super::LinkRect { x0, y0, x1, y1, target: link.to_string(), tag: None });
self.links.push(super::LinkRect { x0, y0, x1, y1, target: link.to_string(), tag: None, at: self.at });
self.last_link = Some(self.links.len() - 1);
}
}
+121
View File
@@ -3883,3 +3883,124 @@ fn separated_link_runs_are_separate_link_elements() {
}
assert_eq!(count(&tree), 2, "each separated link run needs its own Link element");
}
#[test]
fn header_and_footer_link_annotations_are_tagged_on_every_page() {
use hayro_syntax::object::{Array, Dict, Name, Object};
let header_props = CharProps { link: Some("https://header.example.com".into()), ..Default::default() };
let footer_props = CharProps { link: Some("https://footer.example.com".into()), ..Default::default() };
let body_props = CharProps { link: Some("https://body.example.com".into()), ..Default::default() };
let mut d = Document::new();
d.core.title = "Header and footer links".into();
let header_id = d.add_part(wordcraft_doc::PartKind::Header, vec![para_block(Paragraph::with_text("Header site", header_props))]);
let footer_id = d.add_part(wordcraft_doc::PartKind::Footer, vec![para_block(Paragraph::with_text("Footer site", footer_props))]);
d.last_section.headers.default = Some(header_id);
d.last_section.footers.default = Some(footer_id);
let mut p1 = Paragraph::with_text("Visit ", CharProps::default());
p1.insert_text(p1.len(), "Body", &body_props).unwrap();
let mut p2 = Paragraph::with_text("Second page", CharProps::default());
p2.props.page_break_before = Some(true);
d.body = vec![para_block(p1), para_block(p2)];
let bytes = export(&d, &PdfOptions { compress: false, tagged: true, ..Default::default() }).unwrap();
let pdf = hayro_syntax::Pdf::new(bytes).unwrap();
assert_eq!(pdf.pages().len(), 2, "expected two pages");
// Collect every link annotation across both pages and check /StructParent on each.
let mut expected_annots: Vec<(usize, String, i32)> = Vec::new();
for (page_idx, page) in pdf.pages().iter().enumerate() {
let annots = page.raw().get::<Array>(b"Annots").expect("page Annots");
for annot in annots.iter::<Dict>() {
let sp = annot.get::<i32>(b"StructParent").expect("link annotation missing /StructParent");
let id = format!("{:?}", annot.obj_id().expect("indirect annotation"));
expected_annots.push((page_idx, id, sp));
}
}
assert_eq!(expected_annots.len(), 5, "page 1 has header+body+footer links, page 2 has header+footer links");
let root = pdf.xref().get::<Dict>(pdf.xref().root_id()).unwrap();
let struct_tree = root.get::<Dict>(b"StructTreeRoot").expect("StructTreeRoot");
fn find_links(dict: &Dict, out: &mut Vec<(bool, Option<String>)>) {
if dict.get::<Name>(b"S").is_some_and(|s| s.as_ref() == b"Link") {
let mut has_mcid = false;
let mut objr = None;
if let Some(k) = dict.get::<Array>(b"K") {
for item in k.iter::<Object>() {
match item {
Object::Number(_) => has_mcid = true,
Object::Dict(d) if d.get::<Name>(b"Type").is_some_and(|t| t.as_ref() == b"OBJR") => {
objr = d.get::<Dict>(b"Obj").and_then(|o| o.obj_id()).map(|id| format!("{id:?}"));
}
_ => {}
}
}
}
out.push((has_mcid, objr));
}
if let Some(k) = dict.get::<Array>(b"K") {
for item in k.iter::<Object>() {
if let Object::Dict(child) = item {
find_links(&child, out);
}
}
} else if let Some(child) = dict.get::<Dict>(b"K") {
find_links(&child, out);
}
}
let mut links = Vec::new();
find_links(&struct_tree, &mut links);
assert_eq!(links.len(), expected_annots.len(), "every link annotation needs a /Link structure element: {links:?}");
for (page_idx, annot_id, _) in &expected_annots {
assert!(
links.iter().any(|(_, objr)| objr.as_deref() == Some(annot_id.as_str())),
"page {page_idx} annotation {annot_id} has no /Link OBJR in StructTreeRoot: {links:?}"
);
}
// The 4 header/footer links stay outside artifact content (OBJR only); the body link also holds its MCID.
assert_eq!(links.iter().filter(|(mcid, _)| !*mcid).count(), 4, "header/footer links hold only OBJR: {links:?}");
assert_eq!(links.iter().filter(|(mcid, _)| *mcid).count(), 1, "body link holds MCID and OBJR: {links:?}");
// Verify /ParentTree maps every annotation's /StructParent to a /Link structure element.
let parent_tree = struct_tree.get::<Dict>(b"ParentTree").expect("ParentTree");
let nums = parent_tree.get::<Array>(b"Nums").expect("ParentTree Nums");
let num_items: Vec<Object> = nums.iter::<Object>().collect();
for (page_idx, annot_id, sp) in &expected_annots {
let mut parent_role = None;
for pair in num_items.as_chunks::<2>().0 {
if let [Object::Number(k), Object::Dict(elem)] = pair
&& k.as_i64() == i64::from(*sp)
{
parent_role = elem.get::<Name>(b"S").map(|s| s.as_str().to_string());
break;
}
}
assert_eq!(
parent_role.as_deref(),
Some("Link"),
"page {page_idx} annotation {annot_id} /StructParent {sp} must point to /Link in /ParentTree"
);
}
// Verify reading order under Document: page 1 header link -> body P -> page 1 footer link -> page 2 header link -> body P -> page 2 footer link.
let mut tops: Vec<Dict> = match struct_tree.get::<Object>(b"K") {
Some(Object::Array(a)) => a.iter::<Dict>().collect(),
Some(Object::Dict(d)) => vec![d],
_ => Vec::new(),
};
while let [only] = tops.as_slice()
&& only.get::<Name>(b"S").is_some_and(|s| s.as_str() == "Document")
{
tops = match only.get::<Object>(b"K") {
Some(Object::Array(a)) => a.iter::<Dict>().collect(),
Some(Object::Dict(d)) => vec![d],
_ => Vec::new(),
};
}
let top_roles: Vec<String> = tops.iter().map(|d| d.get::<Name>(b"S").map(|s| s.as_str().to_string()).unwrap_or_default()).collect();
assert_eq!(top_roles, vec!["Div", "P", "Div", "Div", "P", "Div"], "header link before body, footer link after body");
}
+1 -1
View File
@@ -4,7 +4,7 @@
//! - `engine.execute {command, params, doc?}`: run any command (engine or `ui.*`)
//! - `engine.commands {search?}`: engine and app print commands with enablement and parameters
//! - `document.inspect`: document structure; `ui.inspect`: UI state, canvas geometry, perf
//! - `ui.click`, `ui.move`, `ui.wheel`, `ui.key`, `ui.release`, `ui.type`, `ui.ime`, `ui.capsLock`:
//! - `ui.click`, `ui.move`, `ui.drag`, `ui.wheel`, `ui.key`, `ui.release`, `ui.type`, `ui.ime`, `ui.capsLock`:
//! real input in screen points (or document points with `coordinates`), delivered by the
//! control library
//! - `ui.clickText {page, x, y}`: click at a page position (points from the page's top-left)
+4 -1
View File
@@ -368,7 +368,7 @@ fn a_script_opens_the_dialog_a_launcher_command_asks_for() {
/// Every method the Methods table of `docs/control-protocol.md` lists is one the control channel answers: none falls
/// through to the commands as an unknown id. The input methods moved to the framework's names in #7101, and the table
/// kept `ui.press`, `ui.drag` and `ui.text`.
/// kept `ui.press` and `ui.text` (while `ui.drag` moved to `{from, to}`).
#[test]
fn every_method_the_protocol_doc_lists_is_answered() {
let doc = include_str!("../../../../docs/control-protocol.md");
@@ -383,10 +383,13 @@ fn every_method_the_protocol_doc_lists_is_answered() {
.map(|name| name.trim_matches('`'))
.collect();
assert!(methods.contains(&"engine.execute"), "the Methods table: {methods:?}");
assert!(methods.contains(&"ui.drag"), "the Methods table: {methods:?}");
let ctx = installed();
for method in methods {
let r = call(&mut app(), &ctx, method, json!({}));
let unknown = wordcraft_engine::CmdError::Unknown(method.to_string()).to_string();
assert_ne!(r["error"].as_str(), Some(unknown.as_str()), "the doc lists `{method}`, which the control channel doesn't answer");
}
let (req, _rx) = ControlRequest::new("ui.drag", json!({"from": {"x": 10.0, "y": 10.0}, "to": {"x": 20.0, "y": 20.0}}));
assert!(matches!(control::handle(&mut app(), &ctx, &req), Reply::AfterInput));
}
-38
View File
@@ -1150,44 +1150,6 @@ fn unimplemented_stub_ribbon_buttons_are_disabled() {
.find(|n| n.accesskit_node().label().is_some_and(|l| l.split_whitespace().collect::<Vec<_>>().join(" ") == expected_label))
.unwrap_or_else(|| panic!("{tab}: ribbon button '{expected_label}' should exist"));
assert!(button.accesskit_node().is_disabled(), "{tab}: stub button {:?} ({id}) must be disabled", button.accesskit_node().label());
if expected_label == "Dictate" {
fn push_icon_rects(shape: &egui::Shape, clip: egui::Rect, btn_rect: egui::Rect, out: &mut Vec<egui::Rect>) {
match shape {
egui::Shape::Vec(items) => {
for item in items {
push_icon_rects(item, clip, btn_rect, out);
}
}
egui::Shape::Text(_) | egui::Shape::Noop => {}
other => {
let r = other.visual_bounding_rect().intersect(clip);
if r.is_positive()
&& btn_rect.expand(1.0).contains_rect(r)
&& r.width() < btn_rect.width() * 0.9
&& r.height() < btn_rect.height() * 0.9
{
out.push(r);
}
}
}
}
let btn_rect = button.rect();
let mut icon_rects = Vec::new();
for c in &h.output().shapes {
push_icon_rects(&c.shape, c.clip_rect, btn_rect, &mut icon_rects);
}
let icon_rect = icon_rects
.into_iter()
.reduce(|a, b| a.union(b))
.unwrap_or_else(|| panic!("Dictate button ({btn_rect:?}) must paint a bounded icon shape"));
assert!(
icon_rect.width() >= 16.0 && icon_rect.height() >= 16.0,
"Dictate ribbon icon must render at >= 16 pt, got {}x{} ({icon_rect:?})",
icon_rect.width(),
icon_rect.height()
);
assert!((icon_rect.width() - icon_rect.height()).abs() <= 2.0, "Dictate icon should be square: {icon_rect:?}");
}
}
}
+4 -3
View File
@@ -99,7 +99,8 @@ let apps move windows, so there Arrange All and Side by Side only resize.
| `ui.click` | `x`, `y`, `button?` (`left`, `right`, `middle`), `count?`, `hold?`, modifiers; or the `id` or `label` of a `ui.accessTree` node | real pointer input at window coordinates; `hold: true` keeps the button down until `ui.release` |
| `ui.clickText` | `page` (0-based), `x`, `y` (points from the page's top-left), `count?` | click inside a page; replies at once with `screen`, the window point it clicks (`[x, y]`), before the click is processed |
| `ui.move` | `x`, `y`, modifiers | pointer move; with a button held (`ui.click` with `hold`), a drag you can screenshot halfway |
| `ui.release` | `button?` or `key?`, `x?`, `y?` | lets go of what `hold` keeps down (with neither `button` nor `key`, everything, modifiers too). A drag is `ui.click` with `"hold": true`, then `ui.move`, then `ui.release` |
| `ui.drag` | `from`, `to` (each `{x?, y?, coordinates?, page?, control?}`), `button?` (`left`, `right`, `middle`), `steps?` (1–200, default 12), modifiers | one-request drag: presses at `from`, moves in even `steps` to `to`, and releases |
| `ui.release` | `button?` or `key?`, `x?`, `y?` | lets go of what `hold` keeps down (with neither `button` nor `key`, everything, modifiers too). A drag you can pause or screenshot halfway is `ui.click` with `"hold": true`, then `ui.move`, then `ui.release` |
| `ui.wheel` | `x`, `y`, `dy`, `dx?`, `unit?` (`points`, the default, or `lines`), modifiers | mouse-wheel or trackpad scroll at window coordinates (`dy` < 0 scrolls down) |
| `ui.key` | `key` (`B`, `Enter`, `Left`…), `hold?`, modifiers | key press through egui (shortcuts apply); `hold: true` keeps the key down until `ui.release` |
| `ui.type` | `text` | typed text through egui |
@@ -197,8 +198,8 @@ Positions are `{"story": "body" | {"part": n}, "path": [block, row, cell, block,
owns keyboard focus. Shortcuts, dialogs and document protection still apply. These methods do
not activate the native window.
`ui.click`, `ui.move`, `ui.release`, `ui.wheel`, `ui.key`, `ui.type`, `ui.ime`, `ui.capsLock`,
`ui.drop` and `ui.focus` defer their successful replies (`"result": null`). The current app
`ui.click`, `ui.move`, `ui.drag`, `ui.release`, `ui.wheel`, `ui.key`, `ui.type`, `ui.ime`,
`ui.capsLock`, `ui.drop` and `ui.focus` defer their successful replies (`"result": null`). The current app
can send a deferred reply during the final input pass, before the UI has applied that pass.
`ui.clickText` replies at once with the window point it clicks (`"screen": [x, y]`), before
the click is processed. `ui.type` sent after it is queued behind the click, but other requests,
File diff suppressed because one or more lines are too long