Compare commits

..
Author SHA1 Message Date
Martin BallandClaude Opus 5.5 d1bd8474b6 mcp: --connect=… gets the --connect refusal, not unknown option
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-21 10:14:26 +00:00
23 changed files with 316 additions and 1957 deletions
+13 -14
View File
@@ -1,4 +1,4 @@
# Exercise the native print host and all UI tests on Windows and macOS on PRs; the broad FreeBSD/ARM64 gates
# Exercise the native print host and all UI tests on PRs; the broad FreeBSD/ARM64 gates
# stay on their existing nightly/release schedule.
name: Printing
@@ -30,32 +30,31 @@ concurrency:
cancel-in-progress: true
jobs:
# The print host and UI tests on Windows and macOS, through the suite's shared gate: it checks out
# craft-i18n (craft-i18n.rev) and craft-fonts. Linux is not repeated here: ci.yml's gate runs
# `cargo xtask ci` there, which already covers fmt, workspace clippy, every test and the wasm build.
# The print host and UI tests on Linux, Windows and macOS, through the suite's shared gate: it
# checks out craft-i18n (craft-i18n.rev) and craft-fonts, and installs the Ubuntu packages through
# install-apt-packages, which falls back to mirrors outside ubuntu.com (as on 11 Nov 2026).
native:
name: Print
# Tracks @main so suite-wide CI fixes reach every app without a PR in each repository.
uses: storytold/craft-common-actions/.github/workflows/gate.yml@main
with:
os: '["windows-latest","macos-latest"]'
os: '["ubuntu-24.04","windows-latest","macos-latest"]'
timeout-minutes: 90
# The catalogs include CJK interface languages, so the UI tests need the suite's fonts, as in
# the gate (same commit as ci.yml and release.yml).
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
packages: >-
pkg-config libxkbcommon-dev libwayland-dev libx11-dev libxcursor-dev libxrandr-dev
libxi-dev libgtk-3-dev libfontconfig1-dev libfreetype-dev libvulkan1 mesa-vulkan-drivers
# No nextest: the tests run with cargo test, as before.
tools: ""
# Its own cache, apart from ci.yml's gate, which builds the whole workspace.
cache-version: v1-printing
# Test binaries without debug info: they link faster and shrink to about a third, and panics
# keep their file:line.
dev-strip: true
# Clippy on its own leg beside the tests, off their critical path. fmt is platform-independent
# and runs in ci.yml. The web app's wasm build, once: ci.yml's `cargo xtask wasm` checks the
# library crates and ui-egui, not apps/wordcraft-web.
lint-command: |
command: |
cargo fmt --all -- --check
cargo clippy -p wordcraft -p wordcraft-ui-egui --all-targets --locked -- -D warnings
if [ "$RUNNER_OS" = macOS ]; then
cargo test -p wordcraft -p wordcraft-ui-egui --locked
# Browser compatibility, once.
if [ "$RUNNER_OS" = Linux ]; then
cargo check -p wordcraft-web --target wasm32-unknown-unknown --locked
fi
command: cargo test -p wordcraft -p wordcraft-ui-egui --locked
+2 -12
View File
File diff suppressed because one or more lines are too long
+2 -42
View File
@@ -188,30 +188,6 @@ fn layout_table_block(input: TableBlockContext<'_, '_, '_>) -> bool {
true
}
/// Whether `story` is a header in a document of Word 2010's layout or older (compatibility mode
/// below 15), whose text keeps its place beside the header's own floating objects (#6805).
fn is_legacy_header(ctx: &Ctx, story: StoryRef) -> bool {
ctx.doc.settings.compat_mode < wordcraft_doc::COMPAT_MODE_CURRENT
&& matches!(story, StoryRef::Part(id) if ctx.doc.parts.get(&id).is_some_and(|p| p.kind == wordcraft_doc::PartKind::Header))
}
/// Where a top and bottom object at `r` starts and ends for such a header.
/// The distance below it counts (Word: 14.4 pt more for 14.4 pt); the one above neither moves it
/// nor makes the header taller.
fn legacy_reach_of(float: &wordcraft_doc::para::Float, r: Rect) -> Option<(f32, f32)> {
let below = if float.dist_bottom.is_finite() { float.dist_bottom.clamp(0.0, 1584.0) } else { 0.0 };
let bounds = float.spin().bounds(r);
(float.wrap == Wrap::TopAndBottom).then_some((bounds.y, bounds.bottom() + below))
}
/// The bottom of the lowest top and bottom object (`reach`) that starts above `text_bottom`, the
/// end of the header's text with the space after its last paragraph (Word counts an object
/// starting in it). Word also counts one starting a little further down (about 25 pt below one
/// line of text), not modelled here. Zero when there is none.
fn legacy_header_reach(text_bottom: f32, reach: &[(f32, f32)]) -> f32 {
reach.iter().filter(|(top, _)| *top < text_bottom).map(|(_, bottom)| *bottom).fold(0.0, f32::max)
}
/// Lay out a block list into a free-standing box of `width` (no page breaks): table cells,
/// headers, footers, notes, text boxes. Returns items relative to (0, 0) and the height. `frame`
/// says where the box sits on its page, for floating objects positioned relative to the page or
@@ -241,14 +217,6 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
// bottom edge (#3108). Behind-text and in-front-of-text objects don't: a page-anchored logo or
// watermark behind a cell's text must not stretch its row (see `align_h` in table.rs).
let mut float_objects_bottom = 0.0f32;
// A header in a document of Word 2010's layout or older (compatibility mode below 15): its
// text keeps its place beside its own objects, which wrap nothing, and only a top and bottom
// object reaching down from the text makes the header taller (#6805). Not in a table cell.
let legacy_header = !in_cell && is_legacy_header(ctx, story);
// Contour wraps were measured in mode 14; earlier modes keep using their existing rule.
let legacy_header_contours = legacy_header && ctx.doc.settings.compat_mode == 14;
// Top and bottom objects of such a header: where each starts and ends.
let mut legacy_reach: Vec<(f32, f32)> = Vec::new();
let mut table_areas = Vec::new();
let mut page_table_wraps = Vec::new();
let mut y = 0.0f32;
@@ -339,15 +307,8 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
{
r.x = keep_in_cell(r.x, r.w, left, right);
}
if (legacy_header && matches!(float.wrap, Wrap::TopAndBottom | Wrap::Square))
|| (legacy_header_contours && matches!(float.wrap, Wrap::Tight | Wrap::Through))
{
// These objects do not reflow the legacy header's own text in Word.
legacy_reach.extend(legacy_reach_of(float, r));
} else {
let outline = ctx.wrap_outline(o);
excl.extend(wrap_area(r, float, outline.as_deref().map(Vec::as_slice)));
}
let outline = ctx.wrap_outline(o);
excl.extend(wrap_area(r, float, outline.as_deref().map(Vec::as_slice)));
floats.insert(oi, r);
}
let rel = rel_exclusions(&excl, 0.0, y);
@@ -442,7 +403,6 @@ pub(crate) fn layout_box(ctx: &mut Ctx, input: BoxInput<'_>) -> BoxLayout {
}
}
}
y = y.max(legacy_header_reach(y, &legacy_reach));
let floats_bottom = float_tables.iter().map(|r| r.bottom()).fold(float_objects_bottom, f32::max);
ctx.hide_deleted = outer_hide;
BoxLayout { items, height: y.max(0.0), floats_bottom, last_top: last_top.max(0.0), table_areas, page_table_wraps }
+25 -178
View File
@@ -346,19 +346,10 @@ impl<'a> Flow<'a> {
if !(rp.keep_lines || (rp.keep_next && pb.y + height <= pb.bottom + 0.01)) {
return before;
}
// A paragraph closing a section that the next one starts on a new page keeps with
// nothing: what follows is not on this page (Word ignores Keep with next there; measured for a next-page break, odd and even by analogy).
let closes_page = pb.next_starts_page && self.p.section.is_some();
let need = height
+ if rp.keep_next && !closes_page {
next_first_line(ctx, self.block, self.laid_width, 0, pb.next_starts_page, &mut ctx.counters.clone())
} else {
0.0
};
let need = height + if rp.keep_next { next_first_line(ctx, self.block, self.width, 0, &mut ctx.counters.clone()) } else { 0.0 };
// (Against the whole column: balanced columns grow to hold it.)
// With the 0.01 pt of slack the other fit checks take. Balancing from Word 2013's layout
// keeps the lines and the next paragraph together at the top of a column too (#6821).
if pb.y + need > pb.bottom + 0.01 && (!pb.fresh() || Self::strict_widow_control(ctx, pb)) && need <= pb.next_room(self.body_top) {
// With the 0.01 pt of slack the other fit checks take.
if pb.y + need > pb.bottom + 0.01 && !pb.fresh() && need <= pb.next_room(self.body_top) {
pb.advance(self.block, self.body_top);
pb.y += rp.space_before.min(0.0);
return rp.space_before.min(0.0);
@@ -366,25 +357,6 @@ impl<'a> Flow<'a> {
before
}
/// Balancing from Word 2013's layout, a paragraph that was moved to the top of a column by
/// the lines before it (not by `keep_together`) keeps its lines, or itself with the next
/// paragraph, together there too: asks again, and places the paragraph's floats again where it
/// ends up (#6821).
fn keep_again(&mut self, ctx: &mut Ctx, pb: &mut PageBuilder, rooms: Rooms) {
while self.l0 == 0 && (self.pl.rp.keep_lines || self.pl.rp.keep_next) && pb.fresh() && Self::strict_widow_control(ctx, pb) {
let (col, pages) = (pb.col, pb.pages.len());
let before = self.keep_together(ctx, pb, rooms, 0.0);
if (pb.col, pb.pages.len()) == (col, pages) {
break;
}
// Reflow before testing the new column: wraps can change the paragraph's height.
let y0 = pb.y;
self.reanchor(ctx, pb, (y0, before), &[]);
self.anchor_y = y0 - before;
(self.rechecked, self.forced) = (false, Vec::new());
}
}
/// The lines going into a new column (or page) were broken around the wrap areas where the
/// paragraph started: break them again around this column's (the lines before stay as they
/// were, and so do the paragraph's own floating objects), when they differ (#1374).
@@ -475,19 +447,14 @@ impl<'a> Flow<'a> {
fit
}
/// Whether the line (the paragraph's line `l0`) may overflow the page: one holding nothing but
/// a page or column break, with text after it in the paragraph, stays at the bottom of the
/// page even when it doesn't fit (it only ends the page, and moving it would leave a blank
/// page behind it, as in Word), and so does an empty paragraph closing a section before a new
/// page (measured in Word: it stays on a full page instead of starting one of its own).
/// Measured in Word: a paragraph of only a page break is an ordinary line, and when its mark's
/// text doesn't fit it goes to the next page, blank page and all.
/// Whether the line may overflow the page: one holding nothing but a page or column break stays
/// at the bottom of the page even when it doesn't fit (it only ends the page, and moving it
/// would leave a blank page behind it, as in Word), and so does an empty paragraph closing a
/// section before a new page (measured in Word: it stays on a full page instead of starting
/// one of its own).
fn stays_at_bottom(&self, pb: &PageBuilder, l: &para::Line) -> bool {
let p = self.p;
let mark_only_after =
l.end == LineEnd::PageBreak && self.pl.lines.get(self.l0 + 1..).is_some_and(|rest| rest.iter().all(|m| only_markers(p, m.start..m.stop)));
let only_break = matches!(l.end, LineEnd::PageBreak | LineEnd::ColumnBreak)
&& !mark_only_after
&& p.text
.get(l.start..l.stop)
.is_some_and(|t| t.chars().all(|c| matches!(c, wordcraft_doc::para::PAGE_BREAK | wordcraft_doc::para::COLUMN_BREAK)));
@@ -510,46 +477,25 @@ impl<'a> Flow<'a> {
/// The end of the lines on this page after widow/orphan control, and keeping the rows beside
/// floating objects together.
/// Also says whether, balancing from Word 2013's layout, widow/orphan control alone moved every
/// line back (the next column has them, #6821).
fn settled_end(&self, ctx: &Ctx, pb: &PageBuilder, fit: &Fit) -> (usize, bool) {
fn settled_end(&self, pb: &PageBuilder, fit: &Fit) -> usize {
let (n, l0, mut l1) = (self.n(), self.l0, fit.l1);
// Widow/orphan control (2-line minimum at either end). Balancing the columns of a
// section's last page from Word 2013's layout (compatibility mode 15) applies it at the
// top of a column too, where moving on is no loss, and never leaves one line of a
// paragraph that goes on in the next column, even when the paragraph began in an earlier
// one (#6821).
let strict = Self::strict_widow_control(ctx, pb);
// Widow/orphan control (2-line minimum at either end).
if fit.forced.is_none() && l1 < n && self.pl.rp.widow_control && n >= 2 {
if l1 - l0 == 1 && l0 == 0 && (!pb.fresh() || strict) {
if l1 - l0 == 1 && l0 == 0 && !pb.fresh() {
l1 = l0; // orphan: move the first line to the next page
} else if n - l1 == 1 && (l1 - l0 >= 3 || (l0 > 0 && l1 - l0 >= 2)) {
l1 -= 1; // widow: take one more line along
} else if n - l1 == 1 && l0 == 0 && l1 - l0 == 2 && (!pb.fresh() || strict) {
} else if n - l1 == 1 && l0 == 0 && l1 - l0 == 2 && !pb.fresh() {
// Neither split of a three-line paragraph is allowed (two and a widow, or an
// orphan and two): it moves whole, as in Word.
l1 = l0;
}
// One line of a continued paragraph, with more after it (what was left of two lines
// after the widow line went along included): the rest moves with it.
if strict && l0 > 0 && l1 - l0 == 1 && l1 < n {
l1 = l0;
}
}
let moved_on = strict && fit.l1 > l0 && l1 == l0;
// A row (text both sides of a floating object) stays together.
while l1 > l0 && l1 < n && self.pl.lines.get(l1).is_some_and(|l| l.beside) {
l1 -= 1;
}
(l1, moved_on)
}
/// Whether the columns of this page are being balanced (`balance_columns`) and the document
/// has Word 2013's layout: Word then keeps the lines of a paragraph together that widow or
/// orphan control would split, at the top of a column as anywhere (#6821). Before compatibility
/// mode 15 it splits them.
fn strict_widow_control(ctx: &Ctx, pb: &PageBuilder) -> bool {
ctx.doc.settings.compat_mode >= 15 && !pb.relaxed && pb.balance.is_some_and(|(page, _)| page + 1 == pb.pages.len())
l1
}
/// Nothing fits on this page: move to the next column or page, and place the floats again
@@ -710,16 +656,16 @@ impl<'a> Flow<'a> {
}
}
/// Late floats placed for lines past `l1` wait for the next piece. An overflow line keeps
/// its floats because it is still emitted here. Whether the lines from `l0` are to be broken
/// again without the released floats. Does nothing once the wrap relays are used up
/// Late floats placed for lines that went on after all (past `l1`) wait for the next piece;
/// one whose own wrap pushed its line on stays, as before. Whether the lines from `l0` are to
/// be broken again without them. Does nothing once the wrap relays are used up
/// ([`MAX_WRAP_RELAYS`]).
fn settle_late(&mut self, pb: &mut PageBuilder, l1: usize, overflow: bool) -> bool {
fn settle_late(&mut self, pb: &mut PageBuilder, l1: usize) -> bool {
let l0 = self.l0;
if l0 == 0 || pb.web || self.late.placed.is_empty() || self.wrap_relays >= MAX_WRAP_RELAYS {
return false;
}
let end = l1 + usize::from(overflow);
let end = if l1 == l0 && pb.fresh() { l0 + 1 } else { l1 }; // what the overflow keeps
let moved = self.late.release(self.p, &self.pl, end, &mut pb.excl) || self.late.keep_back(self.p, &self.pl, l0..end);
moved && l1 > l0
}
@@ -904,7 +850,6 @@ fn place_para_in_flow(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block:
f.anchor_y = y0 - applied_before;
}
while f.l0 < f.n() {
f.keep_again(ctx, pb, rooms);
f.place_due_late(ctx, pb);
f.relay_wrap(ctx, pb);
f.relay_pages(ctx, pb);
@@ -915,20 +860,12 @@ fn place_para_in_flow(ctx: &mut Ctx, pb: &mut PageBuilder, p: &Paragraph, block:
let lead = if f.l0 == 0 { first.top.max(0.0) + rooms.top } else { 0.0 };
let notes = para_notes(ctx.doc, p, &f.pl);
let mut fit = f.fit_lines(ctx, pb, &notes, lead);
let (end, widowed) = f.settled_end(ctx, pb, &fit);
fit.l1 = end;
// On a fresh column an unfitting line can overflow. Strict widow control instead moves
// the lines on without emitting anything and must release their late floats as well.
let overflow = end == f.l0 && pb.fresh() && !widowed;
if f.settle_late(pb, end, overflow) {
fit.l1 = f.settled_end(pb, &fit);
if f.settle_late(pb, fit.l1) {
continue;
}
if fit.l1 == f.l0 {
// Balancing: widow/orphan control moved all the lines that fit on to the next column
// (or, short of room, the page after, which fails the try), where the lines of a
// column's first paragraph would otherwise overflow it. Lines pushed back for a row
// beside a floating object keep the overflow as before.
if !overflow {
if !pb.fresh() {
f.move_on(ctx, pb);
continue;
}
@@ -1068,9 +1005,8 @@ fn space_after_kept(ctx: &Ctx, block: usize, rp: &wordcraft_doc::resolve::Resolv
/// of a three-line one under that control (two would leave a widow), or all
/// of it under keep lines together — or all of it and what it keeps with in turn when it is
/// kept with the next too (a chain moves together in Word). Word carries a kept heading over
/// when the paragraph after it cannot start on the page (#966). `new_page`: the next section starts
/// on a new page, so the chain ends at the paragraph closing this one.
fn next_first_line(ctx: &mut Ctx, block: usize, width: f32, depth: usize, new_page: bool, counters: &mut Counters) -> f32 {
/// when the paragraph after it cannot start on the page (#966).
fn next_first_line(ctx: &mut Ctx, block: usize, width: f32, depth: usize, counters: &mut Counters) -> f32 {
match ctx.doc.body.get(block + 1).map(|b| &**b) {
Some(Block::Para(p)) => {
// Keep list indents and label metrics without consuming the document counters.
@@ -1105,16 +1041,9 @@ fn next_first_line(ctx: &mut Ctx, block: usize, width: f32, depth: usize, new_pa
// Its border room, unless it joins the paragraph before (or after) in one box.
let own = Edges::own(&pl, 0, pl.lines.len());
let top = if joined(ctx.doc, &ctx.doc.body, block + 1, Some(block), None) { 0.0 } else { own.top };
// The paragraph closing the section, when the next section starts a new page, keeps
// with nothing on this page (Word ignores its Keep with next).
if pl.rp.keep_next && depth < 8 && !(new_page && p.section.is_some()) {
if pl.rp.keep_next && depth < 8 {
let bottom = if joined(ctx.doc, &ctx.doc.body, block + 1, Some(block + 2), None) { 0.0 } else { own.bottom };
pl.rp.space_before
+ top
+ pl.height
+ bottom
+ pl.rp.space_after
+ next_first_line(ctx, block + 1, width, depth + 1, new_page, counters)
pl.rp.space_before + top + pl.height + bottom + pl.rp.space_after + next_first_line(ctx, block + 1, width, depth + 1, counters)
} else {
// The room this one needs to start on the page with the kept paragraph before
// it (#966).
@@ -1138,85 +1067,3 @@ fn next_first_line(ctx: &mut Ctx, block: usize, width: f32, depth: usize, new_pa
None => 0.0,
}
}
#[cfg(test)]
mod tests {
use super::*;
use wordcraft_doc::Pos;
use wordcraft_doc::para::{Anchor, Float, LINE_BREAK, Wrap, WrapText};
use wordcraft_doc::props::LineSpacing;
#[test]
fn strict_balancing_remeasures_kept_lines_in_the_next_column() {
crate::test_fonts();
let mut doc = Document::new();
doc.settings.compat_mode = 15;
doc.last_section.columns.count = 2;
let mut p = Paragraph::with_text("One two three four five six", Default::default());
p.props.line_spacing = Some(LineSpacing::Exactly(14.0));
p.props.keep_lines = Some(true);
doc.body = vec![wordcraft_doc::para_block(p)];
let p = doc.body[0].as_para().unwrap();
crate::pass::with_flow_page(&doc, |ctx, pb| {
let top = pb.top;
pb.balance = Some((0, 28.1));
pb.cap_columns();
// A preceding floating object leaves a narrow strip of the first column, but does
// not occupy the second column. The same kept paragraph fits there in one line.
pb.excl.push((Rect::new(pb.col_x(), top, pb.col_w() - 26.0, 100.0), false, None, WrapText::BothSides, false));
place_para_in_flow(ctx, pb, p, 0, top);
assert_eq!(pb.pages.len(), 1, "a fitting candidate kept the balance attempt on its page");
assert_eq!(pb.col, 1);
assert!(
pb.pages[0]
.items
.iter()
.any(|item| { matches!(item, Placed::Lines { x, l0: 0, l1: 1, story: StoryRef::Body, .. } if (*x - pb.col_x()).abs() < 0.01) })
);
});
}
#[test]
fn strict_widow_control_releases_a_late_float_when_no_line_is_emitted() {
crate::test_fonts();
let mut doc = Document::new();
doc.settings.compat_mode = 15;
doc.last_section.columns.count = 2;
let mut p = Paragraph::with_text(&format!("First{LINE_BREAK}Second{LINE_BREAK}Third"), Default::default());
p.props.line_spacing = Some(LineSpacing::Exactly(14.0));
p.props.widow_control = Some(true);
doc.body = vec![wordcraft_doc::para_block(p)];
let anchor = Pos::body(0, "First".len() + LINE_BREAK.len_utf8());
let float = Float { wrap: Wrap::Square, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, ..Default::default() };
doc.insert_object(&anchor, crate::tests::rect_shape(20.0, 20.0, float), &Default::default()).unwrap();
let p = doc.body[0].as_para().unwrap();
crate::pass::with_flow_page(&doc, |ctx, pb| {
let top = pb.top;
let height = 14.1;
pb.advance(0, top); // start in the last column of the previous page
pb.bottom = top + height;
pb.balance = Some((1, height));
let mut flow = Flow::new(ctx, pb, p, (0, top));
assert!(pb.excl.is_empty(), "the float waits for its anchor line");
// Continue after the first line. The balance attempt can fit only one of the two lines left.
flow.l0 = 1;
pb.advance(0, top);
assert!(pb.fresh());
assert!((pb.bottom - pb.top - height).abs() < 0.01);
flow.place_due_late(ctx, pb);
assert_eq!(pb.excl.len(), 1, "the anchor line fits before widow control");
let fit = flow.fit_lines(ctx, pb, &[], 0.0);
assert_eq!(fit.l1, 2);
let (end, widowed) = flow.settled_end(ctx, pb, &fit);
assert_eq!((end, widowed), (1, true));
let overflow = end == flow.l0 && pb.fresh() && !widowed;
assert!(!flow.settle_late(pb, end, overflow));
assert!(pb.excl.is_empty(), "no text is emitted here, so no wrap area may remain here");
});
}
}
-3
View File
@@ -71,9 +71,6 @@ pub(crate) struct PageBuilder<'a> {
/// Balancing columns: (page index, column height) — that page's columns end `height` below
/// the top of the section on it.
pub(crate) balance: Option<(usize, f32)>,
/// Balancing without the strict widow/orphan and keep rules of Word 2013's layout (#6821): the
/// last try when even the full column height does not hold the text with them.
pub(crate) relaxed: bool,
/// The page with the last explicit column break.
pub(crate) col_break_page: Option<usize>,
/// The section's footnotes go right below its text, not at the page bottom ...
+2 -6
View File
@@ -856,11 +856,8 @@ fn break_positions(text: &str, rp: &wordcraft_doc::resolve::ResolvedPara) -> Vec
// keeps a hyphen and a number together (LB25), and when a slash and a letter follow
// ("Dataprotection-" / "/Secrecyviolation", #3408), where LB13 forbids a break before the
// slash: add those positions back. Word keeps "fitness-/1589" whole, so a slash before a digit
// gains no break. Word also breaks between two hyphens in a row ("--------" is a ruled line
// that wraps at any hyphen), where UAX #14 keeps them together (LB21): without it a row of
// hyphens after a gap moves to the next line whole instead of filling the line first. Only
// U+002D is added here; a non-breaking hyphen (U+2011) and a minus sign (U+2212) stay
// unbreakable, and the other dashes keep their ordinary UAX #14 breaks.
// gains no break. Only U+002D is added here; a non-breaking hyphen (U+2011) and a minus sign
// (U+2212) stay unbreakable, and the other dashes keep their ordinary UAX #14 breaks.
let hyphen_breaks: Vec<usize> = text
.match_indices('-')
.filter_map(|(pos, _)| {
@@ -869,7 +866,6 @@ fn break_positions(text: &str, rp: &wordcraft_doc::resolve::ResolvedPara) -> Vec
match next.next() {
Some(n) if n.is_ascii_digit() => Some(i),
Some('/') => next.next().is_some_and(char::is_alphabetic).then_some(i),
Some('-') => Some(i),
_ => None,
}
})
+2 -30
View File
@@ -225,7 +225,6 @@ fn new_page_builder<'p>(
max_y: 0.0,
content_bottom: 0.0,
balance: None,
relaxed: false,
col_break_page: None,
sect_beneath: false,
beneath: false,
@@ -237,18 +236,6 @@ fn new_page_builder<'p>(
}
}
#[cfg(test)]
pub(super) fn with_flow_page(doc: &Document, test: impl FnOnce(&mut Ctx<'_>, &mut PageBuilder<'_>)) {
let mut cache = LayoutCache::new();
let opts = LayoutOptions::default();
let mut ctx = new_ctx(doc, &mut cache, &opts, (&HashMap::new(), None, &Totals::first_guess(1)));
let sect = &doc.last_section;
let early = EarlyFloats::new();
let mut page = new_page_builder(sect, sect.page_num_format, &early, false, false);
page.new_page(0, sect.margin_top);
test(&mut ctx, &mut page);
}
/// Endnotes in document order, with the section of their reference; placed at the end of a
/// section that keeps them there, else at the end of the document.
fn endnote_queue(ctx: &Ctx) -> VecDeque<(u32, usize)> {
@@ -707,9 +694,7 @@ fn balance_pass<'a>(
(page, top, h): (usize, f32, f32),
body_top: f32,
) -> bool {
let relaxed = pb.relaxed;
snap.restore(pb, ctx);
pb.relaxed = relaxed;
pb.balance = Some((page, h));
pb.cap_columns();
for block in first..end {
@@ -788,26 +773,13 @@ fn balance_columns<'a>(ctx: &mut Ctx, pb: &mut PageBuilder<'a>, blocks: (usize,
last = Some((mid, ok));
}
// End on the best height (the full column, as laid out first, when none was shorter).
let mut fits = true;
if last != Some((hi, true)) {
thrown = discard(ctx);
fits = pass(ctx, pb, hi);
if !fits && hi < full {
if !pass(ctx, pb, hi) && hi < full {
thrown = discard(ctx);
fits = pass(ctx, pb, full);
pass(ctx, pb, full);
}
}
// From Word 2013's layout the strict widow/orphan and keep rules (`Flow::strict_widow_control`)
// can push text past even the full column (on a page whose columns are only a couple of lines
// high, where moving a line on to the next column never helps). The layout first made, without
// them, always fit it, so lay the page out as it was then rather than leave the pass that
// spilled to a new page.
if !fits {
thrown = discard(ctx);
pb.relaxed = true;
pass(ctx, pb, full);
pb.relaxed = false;
}
thrown
}
+5 -35
View File
@@ -926,18 +926,6 @@ fn split_row_with(row: &RowLayout, cut: f32, whole_cells: bool) -> Option<(RowLa
let own_depth = row.items.iter().filter_map(|it| if let Placed::Cell { table, .. } = it { Some(table.0.len()) } else { None }).min();
// The first line of each paragraph that moves on (`l1` when all of them stay), by cell and
// item.
// The top of a cell's text on this page decides which paragraph starts the cell's part of the
// page. Only text in the flow counts: a floating picture or shape anchored in the cell can sit
// above it without the text being any less the first.
let content_top = |it: &Placed| -> Option<f32> {
if background(it) {
return None;
}
if let Some((_, _, _, y)) = text_lines(it) {
return Some(y);
}
it.turned_bounds().map(|r| r.y)
};
let splits: Vec<Vec<usize>> = cells
.iter()
.zip(&ends)
@@ -945,18 +933,13 @@ fn split_row_with(row: &RowLayout, cut: f32, whole_cells: bool) -> Option<(RowLa
// Where the cell's text ends: the paragraph ending lowest is the cell's last.
let lowest =
items.iter().filter_map(|it| text_lines(it).and_then(|(p, l0, l1, y)| crate::item_bottom(y, p, l0, l1))).fold(f32::MIN, f32::max);
// The top of what the cell holds on this page: a paragraph there starts the cell's
// part of the page, so a row that doesn't start below other content has nowhere to
// move it to (see `line_split`).
let cell_top = items.iter().filter_map(&content_top).fold(f32::MAX, f32::min);
items
.iter()
.map(|it| {
let Some((para, l0, l1, y)) = text_lines(it) else { return 0 };
// The cell's last paragraph ends with the cell's content (its space after).
let last = l1 == para.lines.len() && crate::item_bottom(y, para, l0, l1).is_some_and(|b| b >= lowest - 0.01);
let first = !whole_cells && y <= cell_top + 0.01;
line_split(para, (l0, l1), y, limit, end.filter(|_| last), first)
line_split(para, (l0, l1), y, limit, end.filter(|_| last))
})
.collect()
})
@@ -1279,16 +1262,7 @@ fn text_lines(it: &Placed) -> Option<(&ParaLayout, usize, usize, f32)> {
/// above `limit`: the last line of a cell's last paragraph needs room down to the cell's content
/// `end`, its space after. Widow control keeps two lines on either side of the break, or moves
/// the paragraph on whole.
///
/// `first`: the paragraph is the topmost content of its cell on a page the row doesn't start
/// below other content on (the row continues from the page before, or starts the page). Moving
/// it whole would gain nothing, and Word then splits it where the lines fall (measured with
/// synthetic documents, Word for Windows 16.0, compatibility mode 15): a lone first line stays,
/// and a three-line paragraph with room for two splits two and one, not leaving the first line
/// alone (a continuation's lone line stays too). A paragraph of four lines or more still takes
/// one more line along with its widow.
/// Without this, nothing was kept and the row ran off the bottom of the page (#6823).
fn line_split(para: &ParaLayout, (l0, l1): (usize, usize), y: f32, limit: f32, end: Option<f32>, first: bool) -> usize {
fn line_split(para: &ParaLayout, (l0, l1): (usize, usize), y: f32, limit: f32, end: Option<f32>) -> usize {
let n = para.lines.len();
let mut k = l0;
while k < l1 {
@@ -1302,16 +1276,12 @@ fn line_split(para: &ParaLayout, (l0, l1): (usize, usize), y: f32, limit: f32, e
// The body's rule differs: there a widow takes a line along only when three or more lines are
// on the page (`place_para_in_flow`).
if para.rp.widow_control && k > l0 && k < l1 {
// A widow: take one more line along, unless that leaves nothing of a paragraph that
// starts the page on it, or its first line alone.
// A widow: take one more line along.
if n - k == 1 {
let taken = k - 1;
if !(first && (taken <= l0 || (l0 == 0 && taken == 1))) {
k = taken;
}
k -= 1;
}
// An orphan (the first line alone): the paragraph moves on whole.
if l0 == 0 && k == 1 && !first {
if l0 == 0 && k == 1 {
k = 0;
}
}
+1 -10
View File
@@ -255,13 +255,6 @@ pub(crate) fn place_table(ctx: &mut Ctx, pb: &mut PageBuilder, t: &wordcraft_doc
.rows
.get(ri)
.is_some_and(|r| r.props.cant_split || (r.props.height_rule == HeightRule::Exact && r.props.height.is_some_and(|h| h > 0.0)));
// A Can't Split row (not an exact one) that is taller than a page splits where the page
// ends, as in Word (measured with synthetic documents): it moves to a new page first
// when it fits there, and only on a page it still doesn't fit does it break.
let splits_when_too_tall = ri >= header_rows.len()
&& t.rows
.get(ri)
.is_some_and(|r| r.props.cant_split && !(r.props.height_rule == HeightRule::Exact && r.props.height.is_some_and(|h| h > 0.0)));
let mut rest: Option<table::RowLayout> = None;
// On a new page holding only the repeated header rows.
let mut fresh = false;
@@ -297,9 +290,7 @@ pub(crate) fn place_table(ctx: &mut Ctx, pb: &mut PageBuilder, t: &wordcraft_doc
// (#4272): moving on can give the cell room there.
let first_part = rest.is_none() && !pb.at_top() && !fresh && !under_top_headers;
let moves_on = first_part && short_of_min(ri, room);
// A row that fits the room but for the border below it is still placed whole.
let too_tall_to_keep = splits_when_too_tall && !first_part && cur.height > room + 0.01;
let split = match ((splittable || too_tall_to_keep) && !moves_on && !defer_kept, first_part) {
let split = match (splittable && !moves_on && !defer_kept, first_part) {
(false, _) => None,
(true, true) => split_keeping_nested(ctx.doc, cur, room),
// On a fresh page, a nested row taller than the room splits rather than overflowing.
+1 -100
View File
@@ -5,15 +5,12 @@ use wordcraft_doc::props::{Align, Border, BorderStyle, Borders, ParaProps, TextD
use wordcraft_doc::{Pos, Table};
mod autospace;
mod balanced_tail;
mod bidi;
mod budget;
mod cell_floats;
mod complex;
mod float_top;
mod grid;
mod header_legacy_float;
mod keep_next_section;
mod ligature;
pub(crate) mod linear;
mod missing_glyphs;
@@ -23,7 +20,6 @@ mod numeral;
mod pages;
mod styleref;
mod table_contact;
mod table_first_line;
mod textbox;
mod vertical;
@@ -4668,8 +4664,7 @@ fn tall_rows_split_across_pages() {
.find_map(|i| if let Placed::Lines { path, para, .. } = i { (path.0 == vec![1, 0, 0, 0]).then_some(para.lines.len()) } else { None })
.unwrap_or(0);
assert_eq!(total, n);
// A "can't split" row taller than a page splits too, from the top of a page, as in Word (#6823);
// a shorter one moves on whole (`table_first_line`).
// "Can't split" rows move whole instead.
let mut d2 = Document::from_text("before\nafter");
t.rows[0].props.cant_split = true;
d2.insert_block(StoryRef::Body, &Path::top(1), wordcraft_doc::Block::Table(t)).unwrap();
@@ -8028,46 +8023,6 @@ fn a_page_break_at_the_bottom_of_a_full_page_leaves_no_blank_page() {
assert!(last_on_2, "the text after the break is on page 2");
}
/// Measured in Word for Mac: a paragraph holding only a page break is an ordinary line. When it
/// doesn't fit at the bottom of a full page it goes to the next one, and its break leaves that
/// page blank. Only a break with text after it in its paragraph stays on the full page (#534).
/// WordCraft kept both on the page, so a paper's references started a page early.
#[test]
fn a_paragraph_of_only_a_page_break_moves_when_it_does_not_fit() {
use wordcraft_doc::props::LineSpacing;
let chr = wordcraft_doc::CharProps { font: Some("Source Sans 3".into()), size: Some(12.0), ..Default::default() };
let doc = |spacing: LineSpacing, room: f32, tail: &[&str]| {
let para = |text: &str| {
let mut p = wordcraft_doc::Paragraph::with_text(text, chr.clone());
p.mark = chr.clone();
p.props = ParaProps { line_spacing: Some(spacing), space_before: Some(0.0), space_after: Some(0.0), ..Default::default() };
wordcraft_doc::para_block(p)
};
let mut d = Document::new();
d.body = (0..20).map(|i| para(&format!("Line {i}"))).chain(tail.iter().map(|t| para(t))).collect();
let l = lay(&d);
let pitch = l.caret(&Pos::body(1, 0)).unwrap().top - l.caret(&Pos::body(0, 0)).unwrap().top;
d.last_section.margin_bottom = d.last_section.page_h - d.last_section.margin_top - 20.0 * pitch - room;
d
};
let pages = |d: &Document| lay(d).pages.len();
let single = {
let l = lay(&doc(LineSpacing::Multiple(1.0), 600.0, &[]));
l.caret(&Pos::body(1, 0)).unwrap().top - l.caret(&Pos::body(0, 0)).unwrap().top
};
let only = ["\u{000C}", "After"];
let start = ["\u{000C}After"];
// Exactly 24 pt lines, 10 pt left: the break's own paragraph moves, a blank page follows.
assert_eq!(pages(&doc(LineSpacing::Exactly(24.0), 10.0, &only)), 3, "exact, break only");
assert_eq!(pages(&doc(LineSpacing::Exactly(24.0), 10.0, &start)), 2, "exact, break before text");
// Double spacing: the paragraph moves when its text cannot fit. Its leading can hang into
// the bottom margin once the paragraph mark fits.
assert_eq!(pages(&doc(LineSpacing::Multiple(2.0), single - 0.2, &only)), 3, "double, text doesn't fit");
assert_eq!(pages(&doc(LineSpacing::Multiple(2.0), single + 0.2, &only)), 2, "double, leading hangs");
assert_eq!(pages(&doc(LineSpacing::Multiple(2.0), 2.0 * single + 0.2, &only)), 2, "double, line fits");
assert_eq!(pages(&doc(LineSpacing::Multiple(2.0), single - 0.2, &start)), 2, "double, break before text");
}
/// #534: indents in characters (`w:firstLineChars`) are measured in the paragraph mark's font
/// size and win over the indent in points.
#[test]
@@ -15250,60 +15205,6 @@ fn a_hyphen_before_a_slash_is_a_break_opportunity_like_word() {
panic!("no width in the sweep wrapped the paragraph");
}
/// A row of hyphens wraps at any hyphen in Word: after a gap, the row first fills the line and
/// its rest goes on the next, where UAX #14 (LB21) keeps the hyphens together and the whole row
/// moved to the next line. The first width that wraps must leave `Deed ` and part of the row on
/// the first line. A row of non-breaking hyphens (U+2011) stays whole, so the first wrap moves it
/// whole, breaking at the space.
#[test]
fn a_row_of_hyphens_wraps_at_any_hyphen_like_word() {
let lines_of = |text: &str, margin_right: f32| -> Vec<String> {
let mut d = Document::from_text(text);
d.last_section.margin_right = margin_right;
let l = lay(&d);
l.pages[0]
.items
.iter()
.filter_map(|it| {
if let Placed::Lines { para, l0, l1, .. } = it {
Some(para.lines[*l0..*l1].iter().map(|line| text[line.start..line.stop].to_string()).collect::<Vec<_>>())
} else {
None
}
})
.flatten()
.collect()
};
let text = format!("Deed {}", "-".repeat(16));
let mut wrapped = false;
for m in 100..=540 {
let lines = lines_of(&text, m as f32);
if lines.len() < 2 {
continue; // still fits on one line at this width
}
assert!(lines[0].starts_with("Deed -"), "the first line takes part of the row: {lines:?}");
assert!(lines[1].starts_with('-'), "the rest of the row follows: {lines:?}");
assert_eq!(lines.concat(), text, "no hyphen is lost or added: {lines:?}");
wrapped = true;
break;
}
assert!(wrapped, "no width in the sweep wrapped the row of hyphens");
let row = "\u{2011}".repeat(16);
let text = format!("Deed {row}");
for m in 100..=540 {
let lines = lines_of(&text, m as f32);
if lines.len() < 2 {
continue; // still fits on one line at this width
}
assert_eq!(lines[0], "Deed ", "the only break is at the space: {lines:?}");
assert_eq!(lines[1], row, "the row of non-breaking hyphens stays whole: {lines:?}");
return;
}
panic!("no width in the sweep wrapped the non-breaking row");
}
/// docxide-pdf `dot-open-token*`: UAX #14 allows a break between a full stop and an opening
/// parenthesis, Word doesn't. The first width that wraps `Deed 2023.(Example` breaks at the space.
#[test]
-376
View File
@@ -1,376 +0,0 @@
//! The last page of a section whose columns are balanced before a continuous break, when it holds
//! only the end of a paragraph that began on the page before, or a whole paragraph of two or three
//! lines (#6821). Measured in Word for Windows with exact 14 pt lines and no spacing, in three and
//! in two columns, one case per document, saved as compatibility mode 15 and as 14: from mode 15
//! Word keeps such lines together in the first column that can hold them (the later columns may be
//! left short or empty), keeps a paragraph with "keep lines together" or "keep with next" whole
//! there when those rules fit, including in a section that starts and ends on one page. In mode
//! 14 Word splits two lines one per column. Synthetic tests also cover a footnote and a floating
//! picture. Mode 14's other layouts (a three-line tail, two and one; the text after the section)
//! and keep with next on the last lines of a paragraph that began on the page before remain open.
use crate::*;
use wordcraft_doc::para::{Anchor, Float, InlineObject, NoteKind, ShapeKind, Wrap};
use wordcraft_doc::props::{LineSpacing, ParaProps};
use wordcraft_doc::section::{SectionProps, SectionStart};
use wordcraft_doc::{PartKind, Pos, para_block};
const LINE: f32 = 14.0;
fn lay(doc: &Document) -> DocLayout {
let mut c = LayoutCache::new();
layout(doc, &mut c, &LayoutOptions::default())
}
fn para_with(text: &str, keep_lines: bool, keep_next: bool) -> Arc<Block> {
let chr = wordcraft_doc::CharProps { font: Some("Source Sans 3".into()), size: Some(12.0), ..Default::default() };
let mut p = Paragraph::with_text(text, chr);
p.props = ParaProps {
space_before: Some(0.0),
space_after: Some(0.0),
line_spacing: Some(LineSpacing::Exactly(LINE)),
keep_lines: keep_lines.then_some(true),
keep_next: keep_next.then_some(true),
..Default::default()
};
para_block(p)
}
fn para(text: &str) -> Arc<Block> {
para_with(text, false, false)
}
/// A paragraph of `k` lines, each ended by a line break: "P1", "P2"…
fn lines_text(k: usize) -> String {
(1..=k).map(|i| format!("P{i}")).collect::<Vec<_>>().join(&wordcraft_doc::para::LINE_BREAK.to_string())
}
#[derive(Clone, Copy, PartialEq)]
enum Keep {
No,
Lines,
Next,
}
/// What follows the filler paragraphs: a paragraph of `k` lines ("P1"…), then optionally one more
/// line ("Q1"), all in `cols` columns, then "After" in one column.
#[derive(Clone, Copy)]
struct Case {
cols: u32,
/// How many one-line paragraphs come first, relative to the lines on a page: `-3` leaves room
/// for three lines of the paragraph, `0` starts the paragraph on the next page, `1` puts one
/// more line before it there. With `intro` it is the plain number of them.
from_page_end: i32,
k: usize,
q: bool,
compat: u32,
/// A footnote referenced at the end of the paragraph.
note: bool,
/// A floating 28 pt tall picture-sized shape anchored in "Q1" (needs `q`).
float: Option<Wrap>,
/// This many lines of text and a one-column section break before the columns: the section
/// starts mid-page and ends on the same page.
intro: usize,
/// Columns closed by a continuous break (balanced) or running to the end of the document.
balanced: bool,
keep: Keep,
/// A page of this many lines of text (for a page too short for the rules).
page_lines: Option<i32>,
}
impl Case {
fn new(cols: u32, from_page_end: i32, k: usize) -> Case {
Case { cols, from_page_end, k, q: false, compat: 15, note: false, float: None, intro: 0, balanced: true, keep: Keep::No, page_lines: None }
}
}
/// The document of a case, the index of the `k`-line paragraph and of "Q1", and the offsets of the
/// paragraph's lines.
fn build(c: &Case) -> (Document, usize, Option<usize>, Vec<usize>) {
crate::test_fonts();
let mut d = Document::new();
d.settings.compat_mode = c.compat;
let mut s = SectionProps { start: SectionStart::Continuous, ..Default::default() };
s.columns.count = c.cols;
if let Some(n) = c.page_lines {
s.page_h = s.margin_top + s.margin_bottom + n as f32 * LINE + 0.5;
d.last_section.page_h = s.page_h;
}
let per_col = ((s.page_h - s.margin_top - s.margin_bottom) / LINE).floor() as i32;
let fillers = if c.intro > 0 { c.from_page_end.max(0) } else { (per_col * c.cols as i32 + c.from_page_end).max(0) } as usize;
let mut body: Vec<Arc<Block>> = (0..c.intro).map(|i| para(&format!("i{i}"))).collect();
if c.intro > 0 {
let mut one = SectionProps { start: SectionStart::Continuous, ..Default::default() };
one.columns.count = 1;
let mut mark = para("");
if let Block::Para(p) = Arc::make_mut(&mut mark) {
p.section = Some(Box::new(one));
}
body.push(mark);
}
body.extend((0..fillers).map(|i| para(&format!("r{i}"))));
let first = body.len();
let text = lines_text(c.k);
body.push(para_with(&text, c.keep == Keep::Lines, c.keep == Keep::Next));
let q = c.q.then_some(body.len());
if c.q {
body.push(para("Q1"));
}
let mark = body.len();
if c.balanced {
body.push(para(""));
body.push(para("After"));
}
d.body = body;
if c.balanced {
if let Some(Block::Para(p)) = d.body.get_mut(mark).map(Arc::make_mut) {
p.section = Some(Box::new(s));
}
d.last_section.start = SectionStart::Continuous;
} else {
d.last_section.columns.count = c.cols;
}
if let (Some(w), Some(qi)) = (c.float, q) {
let float = Float { wrap: w, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, x: 0.0, y: 0.0, ..Default::default() };
let shape = InlineObject::Shape {
kind: ShapeKind::Rectangle,
w: if w == Wrap::TopAndBottom { 100.0 } else { 60.0 },
h: 28.0,
fill: None,
stroke: None,
stroke_width: 1.0,
float,
story: None,
freeform: None,
effects: Default::default(),
extra: Default::default(),
};
d.insert_object(&Pos::body(qi, 0), shape, &Default::default()).unwrap();
}
let breaks = text.char_indices().filter(|(_, ch)| *ch == wordcraft_doc::para::LINE_BREAK);
let starts: Vec<usize> = std::iter::once(0).chain(breaks.map(|(i, ch)| i + ch.len_utf8())).collect();
if c.note {
let id = d.add_part(PartKind::Footnote, vec![para("Note")]);
let end = text.len();
d.insert_object(&Pos::body(first, end), InlineObject::NoteRef { kind: NoteKind::Footnote, id, custom: String::new() }, &Default::default())
.unwrap();
}
(d, first, q, starts)
}
/// The columns of the lines of the `k`-line paragraph (counted from the left, 0 to `cols - 1`),
/// of "Q1" if there is one, and the number of pages.
fn columns(c: &Case) -> (Vec<usize>, Option<usize>, usize) {
let (d, first, q, starts) = build(c);
let l = lay(&d);
let carets: Vec<_> = starts.iter().map(|&o| l.caret(&Pos::body(first, o)).unwrap()).collect();
let q_caret = q.map(|qi| l.caret(&Pos::body(qi, 0)).unwrap());
// The columns' left edges, from the section's declared geometry so that an empty column keeps
// its place. A line beside a float starts right of its column's edge, so a position is in the
// last edge at or left of it.
let sp = SectionProps::default();
let n = c.cols.max(1);
let width = (sp.page_w - sp.margin_left - sp.margin_right - sp.gutter - sp.columns.space * (n - 1) as f32) / n as f32;
let xs: Vec<f32> = (0..n).map(|i| sp.margin_left + i as f32 * (width + sp.columns.space)).collect();
let col = |x: f32| xs.iter().rposition(|e| *e <= x + 1.0).unwrap_or(usize::MAX);
(carets.iter().map(|c| col(c.x)).collect(), q_caret.map(|c| col(c.x)), l.pages.len())
}
fn of(c: &Case) -> Vec<usize> {
columns(c).0
}
// A: the last two lines of a paragraph whose first three lines closed the page before.
#[test]
fn the_last_two_lines_of_a_continued_paragraph_stay_in_the_first_column() {
for cols in [3, 2] {
let (v, _, pages) = columns(&Case::new(cols, -3, 5));
assert_eq!(pages, 2, "{cols} columns");
assert_eq!(v[3..], [0, 0], "{cols} columns: lines 4 and 5 together");
}
}
// B: three lines stay together too: not two and one, nor one and two.
#[test]
fn the_last_three_lines_of_a_continued_paragraph_stay_in_the_first_column() {
for cols in [3, 2] {
assert_eq!(of(&Case::new(cols, -3, 6))[3..], [0, 0, 0], "{cols} columns");
}
}
// L: five lines are three and two (not two, one and two).
#[test]
fn the_last_five_lines_of_a_continued_paragraph_are_three_and_two() {
for cols in [3, 2] {
assert_eq!(of(&Case::new(cols, -3, 8))[3..], [0, 0, 0, 1, 1], "{cols} columns");
}
}
// N: a one-line paragraph after the two lines goes to the second column.
#[test]
fn a_line_after_the_continued_two_lines_goes_to_the_next_column() {
for cols in [3, 2] {
let (v, q, _) = columns(&Case { q: true, ..Case::new(cols, -3, 5) });
assert_eq!((v[3..].to_vec(), q), (vec![0, 0], Some(1)), "{cols} columns");
}
}
// K, E: a paragraph of three lines (or two) that begins the last page stays together.
#[test]
fn a_whole_paragraph_of_two_or_three_lines_at_the_top_of_the_last_page_stays_together() {
for cols in [3, 2] {
assert_eq!(of(&Case::new(cols, 0, 3)), [0, 0, 0], "{cols} columns, three lines");
assert_eq!(of(&Case::new(cols, 0, 2)), [0, 0], "{cols} columns, two lines");
}
}
// K2: the same after one line of another paragraph in the first column: it starts the second.
#[test]
fn a_three_line_paragraph_after_one_line_on_the_last_page_stays_together() {
for cols in [3, 2] {
let (v, _, pages) = columns(&Case::new(cols, 1, 3));
assert_eq!((v, pages), (vec![1, 1, 1], 2), "{cols} columns");
}
}
// F: with a footnote on the last page, referenced at the end of the paragraph.
#[test]
fn a_footnote_on_the_last_page_leaves_the_tail_together() {
for cols in [3, 2] {
let n = |off, k| of(&Case { note: true, ..Case::new(cols, off, k) });
assert_eq!(n(-3, 5)[3..], [0, 0], "{cols} columns, two lines");
assert_eq!(n(-3, 6)[3..], [0, 0, 0], "{cols} columns, three lines");
assert_eq!(n(0, 2), [0, 0], "{cols} columns, whole paragraph of two lines");
assert_eq!(n(0, 3), [0, 0, 0], "{cols} columns, whole paragraph of three lines");
}
}
// L2: beside a square-wrapped float in the next paragraph; a top-and-bottom one is the guard.
#[test]
fn a_square_wrapped_float_after_the_tail_leaves_it_together() {
for cols in [3, 2] {
let sq = |off, k| columns(&Case { q: true, float: Some(Wrap::Square), ..Case::new(cols, off, k) });
let (v, q, _) = sq(-3, 5);
assert_eq!((v[3..].to_vec(), q), (vec![0, 0], Some(1)), "{cols} columns, two lines");
let (v, q, _) = sq(0, 3);
assert_eq!((v, q), (vec![0, 0, 0], Some(1)), "{cols} columns, whole paragraph of three lines");
}
}
#[test]
fn a_top_and_bottom_float_after_the_tail_is_laid_out_as_before() {
for cols in [3, 2] {
let tb = |off, k| columns(&Case { q: true, float: Some(Wrap::TopAndBottom), ..Case::new(cols, off, k) });
let (v, q, _) = tb(-3, 5);
assert_eq!((v[3..].to_vec(), q), (vec![0, 0], Some(1)), "{cols} columns, two lines");
let (v, q, _) = tb(0, 3);
assert_eq!((v, q), (vec![0, 0, 0], Some(1)), "{cols} columns, whole paragraph of three lines");
}
}
// M: a section that starts and ends on one page (after two lines of text in one column).
#[test]
fn a_five_line_paragraph_balanced_mid_page_is_three_and_two() {
assert_eq!(of(&Case { intro: 2, ..Case::new(3, 0, 5) }), [0, 0, 0, 1, 1]);
}
#[test]
fn a_section_balanced_mid_page_is_laid_out_as_before() {
let mid = |cols, filler, k| of(&Case { intro: 2, ..Case::new(cols, filler, k) });
assert_eq!(mid(3, 0, 2), [0, 0]);
assert_eq!(mid(3, 0, 3), [0, 0, 0]);
assert_eq!(mid(3, 0, 4), [0, 0, 1, 1]);
assert_eq!(mid(3, 0, 6), [0, 0, 1, 1, 2, 2]);
assert_eq!(mid(2, 0, 3), [0, 0, 0]);
assert_eq!(mid(2, 0, 5), [0, 0, 0, 1, 1]);
assert_eq!(mid(2, 0, 6), [0, 0, 0, 1, 1, 1]);
// After one more line.
assert_eq!(mid(3, 1, 3), [1, 1, 1]);
assert_eq!(mid(3, 1, 4), [1, 1, 2, 2]);
assert_eq!(mid(3, 1, 5), [0, 0, 1, 1, 1]);
assert_eq!(mid(2, 1, 4), [0, 0, 1, 1]);
assert_eq!(mid(2, 1, 6), [0, 0, 0, 1, 1, 1]);
}
// X: keep lines together, and keep with next, hold the paragraph whole in the first column.
#[test]
fn a_paragraph_kept_together_stays_whole_in_the_first_balanced_column() {
for cols in [3, 2] {
let kept = |off, k| of(&Case { keep: Keep::Lines, ..Case::new(cols, off, k) });
assert_eq!(kept(0, 3), [0, 0, 0], "{cols} columns, three lines at the top");
// Keep lines together moved it whole onto the last page.
assert_eq!(kept(-3, 5), [0, 0, 0, 0, 0], "{cols} columns, five lines");
assert_eq!(kept(-3, 6), [0, 0, 0, 0, 0, 0], "{cols} columns, six lines");
}
}
#[test]
fn a_paragraph_kept_with_the_next_stays_with_it_in_the_first_balanced_column() {
for cols in [3, 2] {
let (v, q, _) = columns(&Case { keep: Keep::Next, q: true, ..Case::new(cols, 0, 3) });
assert_eq!((v, q), (vec![0, 0, 0], Some(0)), "{cols} columns");
}
}
// Guards, the same in Word and before the change.
// C, M: four lines are two and two, six are two, two and two.
#[test]
fn longer_tails_are_balanced_as_before() {
for cols in [3, 2] {
assert_eq!(of(&Case::new(cols, -3, 7))[3..], [0, 0, 1, 1], "{cols} columns, four lines");
}
assert_eq!(of(&Case::new(3, -3, 9))[3..], [0, 0, 1, 1, 2, 2], "three columns, six lines");
}
// O: a four-line paragraph that begins the last page is two and two.
#[test]
fn a_four_line_paragraph_at_the_top_of_the_last_page_is_two_and_two() {
for cols in [3, 2] {
assert_eq!(of(&Case::new(cols, 0, 4)), [0, 0, 1, 1], "{cols} columns");
}
}
// Columns not balanced (nothing follows them): the lines are not split without need.
#[test]
fn unbalanced_columns_keep_the_tail_in_the_first_column() {
for cols in [3, 2] {
let c = Case { balanced: false, ..Case::new(cols, -3, 5) };
assert_eq!(of(&c)[3..], [0, 0], "{cols} columns");
}
}
// Before Word 2013's layout (mode 14) the two lines are split one per column, as Word does.
#[test]
fn mode_14_still_splits_the_last_two_lines_of_a_continued_paragraph() {
for cols in [3, 2] {
let c = Case { compat: 14, ..Case::new(cols, -3, 5) };
assert_eq!(of(&c)[3..], [0, 1], "{cols} columns");
}
}
/// How many lines of body text are laid out, and on how many pages.
fn shape(c: &Case) -> (usize, usize) {
let (d, ..) = build(c);
let l = lay(&d);
let lines = l
.pages
.iter()
.flat_map(|p| p.items.iter())
.map(|it| match it {
Placed::Lines { story: StoryRef::Body, l0, l1, .. } => l1 - l0,
_ => 0,
})
.sum();
(l.pages.len(), lines)
}
// A page whose columns hold two lines is too short for the rules that keep three lines together:
// not even the full column holds the paragraph with them, so the columns are laid out as before
// (mode 14), with every line placed and no more pages.
#[test]
fn a_page_too_short_for_the_strict_rules_is_laid_out_as_in_mode_14() {
let tiny = |compat| Case { compat, page_lines: Some(2), ..Case::new(2, 0, 3) };
let (pages, lines) = shape(&tiny(14));
assert!(lines >= 4, "the paragraph's three lines and After: {lines}");
assert_eq!(shape(&tiny(15)), (pages, lines));
}
@@ -1,223 +0,0 @@
//! A header in a document of Word 2010's layout or older (compatibility mode below 15) keeps its
//! text where it is beside its own floating objects, which wrap nothing there: a top and bottom
//! object only makes the header taller when it starts above the end of the text (#6805). From
//! Word 2013's layout (mode 15) the header's text goes below such an object.
//!
//! Measured in Word for Windows 16.0 on synthetic files (A4, Arial 10 pt, a header 17.3 pt down,
//! 20 pt top margin or more, a text box 451.65 x 29.55 pt anchored to the header's paragraph and
//! set 7.2 pt below its top, top and bottom wrapping, one line of text): at mode 14 the line stays
//! at the header's top and the body's first line starts at 54.3 pt (the box's bottom, 54.05, and
//! the line's rounding); at mode 15 the line goes below the box and the body starts at 65.9.
//! A box set 78 pt below a 39 pt line changes nothing in either mode. A wrap distance below the
//! box counts at both modes (14.4 pt: the body 14.4 pt lower), the one above changes nothing. A
//! box starting in the space after the last paragraph makes the header end at its bottom. With
//! three paragraphs and a box set 26 pt down the page, anchored in the second, no paragraph moves
//! at mode 14 and the body starts at the box's bottom (55.9 pt). Square wrapping at mode 14 leaves
//! the text as it is. Mode 11 (Word 2003's layout, measured on .doc files) behaves like 14: the
//! single line stays at the top and the body starts at 54.0 pt (mode 12: 54.0, mode 14: 54.8), and
//! no paragraph of the three-paragraph header moves. A 60 pt logo with Square, Tight or Through
//! wrap leaves three short header paragraphs in place at mode 14. At mode 15 each line shifts
//! right of the logo. Footers (which differ) and header table cells are outside this test.
use super::{lay, rect_shape};
use crate::{DocLayout, Placed, StoryRef};
use wordcraft_doc::para::{Anchor, Float, Wrap};
use wordcraft_doc::props::LineSpacing;
use wordcraft_doc::{Document, ParaProps, Paragraph, PartKind, Path, para_block};
const HEADER_TOP: f32 = 17.3;
const BOX_H: f32 = 29.55;
/// A page whose header holds one line of text with a text-box-sized shape anchored to it, set
/// `offset` below the paragraph's top with `wrap` (`None`: no shape), laid out as `mode` says.
fn page(mode: u32, wrap: Option<Wrap>, offset: f32) -> DocLayout {
page_with(mode, wrap, offset, (0.0, 0.0))
}
/// [`page`] with a wrap distance below the object and a space after the header's paragraph.
fn page_with(mode: u32, wrap: Option<Wrap>, offset: f32, (dist_bottom, after): (f32, f32)) -> DocLayout {
crate::test_fonts();
let mut d = Document::from_text("Body text.");
d.settings.compat_mode = mode;
d.last_section.header = HEADER_TOP;
d.last_section.margin_top = 20.0;
let mut p = Paragraph::with_text("Header line", Default::default());
p.props = ParaProps { space_before: Some(0.0), space_after: Some(after), ..Default::default() };
if let Some(wrap) = wrap {
let float = Float { wrap, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, x: 31.6, y: offset, dist_bottom, ..Default::default() };
p.insert_object(0, rect_shape(451.65, BOX_H, float), &Default::default()).unwrap();
}
let id = d.add_part(PartKind::Header, vec![para_block(p)]);
d.last_section.headers.default = Some(id);
lay(&d)
}
fn body_top(l: &DocLayout) -> f32 {
l.pages[0].items.iter().find_map(|i| if let Placed::Lines { y, story: StoryRef::Body, .. } = i { Some(*y) } else { None }).unwrap()
}
fn header_line_top(l: &DocLayout) -> f32 {
l.pages[0].header.iter().find_map(|i| if let Placed::Lines { y, story: StoryRef::Part(_), .. } = i { Some(*y) } else { None }).unwrap()
}
#[test]
fn mode_14_header_text_stays_beside_its_own_top_and_bottom_object() {
let (old, new, none) = (page(14, Some(Wrap::TopAndBottom), 7.2), page(15, Some(Wrap::TopAndBottom), 7.2), page(14, None, 0.0));
// The line stays at the header's top at mode 14, below the box at mode 15.
assert!((header_line_top(&old) - header_line_top(&none)).abs() < 0.5, "line at {}", header_line_top(&old));
assert!(header_line_top(&new) > HEADER_TOP + 7.2 + BOX_H - 0.5, "line at {}", header_line_top(&new));
// The body starts below the box at mode 14 (it reaches past the text), a line lower at 15.
assert!((body_top(&old) - (HEADER_TOP + 7.2 + BOX_H)).abs() < 0.5, "body at {}", body_top(&old));
assert!(body_top(&new) > body_top(&old) + 5.0, "mode 15 body at {}, mode 14 at {}", body_top(&new), body_top(&old));
}
#[test]
fn mode_14_object_set_below_the_header_text_adds_no_height() {
// Starting 78 pt down, under the line: no room taken in either mode.
let none = body_top(&page(14, None, 0.0));
for mode in [14, 15] {
let t = body_top(&page(mode, Some(Wrap::TopAndBottom), 78.0));
assert!((t - none).abs() < 0.5, "mode {mode}: body at {t}, {none} without the object");
}
}
#[test]
fn mode_14_square_object_leaves_header_text_and_height() {
let (sq, none) = (page(14, Some(Wrap::Square), 7.2), page(14, None, 0.0));
assert!((header_line_top(&sq) - header_line_top(&none)).abs() < 0.5, "line at {}", header_line_top(&sq));
assert!((body_top(&sq) - body_top(&none)).abs() < 0.5, "body at {}, {} without", body_top(&sq), body_top(&none));
}
#[test]
fn mode_14_header_text_ignores_a_narrow_logo_with_square_tight_or_through_wrap() {
crate::test_fonts();
let layout = |mode, wrap| {
let mut d = Document::from_text("Body text.");
d.settings.compat_mode = mode;
d.last_section.header = 30.0;
d.last_section.margin_top = 72.0;
let mut blocks = Vec::new();
for (i, text) in ["First line", "Second line", "Third line"].into_iter().enumerate() {
let mut p = Paragraph::with_text(text, Default::default());
p.props =
ParaProps { space_before: Some(0.0), space_after: Some(0.0), line_spacing: Some(LineSpacing::Exactly(12.0)), ..Default::default() };
if i == 0
&& let Some(wrap) = wrap
{
let float = Float { wrap, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, dist: 8.0, ..Default::default() };
p.insert_object(0, rect_shape(60.0, 60.0, float), &Default::default()).unwrap();
}
blocks.push(para_block(p));
}
let id = d.add_part(PartKind::Header, blocks);
d.last_section.headers.default = Some(id);
lay(&d)
};
let header_positions = |layout: &DocLayout| {
layout.pages[0]
.header
.iter()
.filter_map(|item| match item {
Placed::Lines { x, y, para, l0, .. } => para.lines.get(*l0).map(|line| (x + line.left, *y)),
_ => None,
})
.collect::<Vec<_>>()
};
for mode in [11, 12, 13, 14, 15] {
let plain = layout(mode, None);
let control = header_positions(&plain);
assert_eq!(control.len(), 3);
for wrap in [Wrap::Square, Wrap::Tight, Wrap::Through] {
let with_logo = layout(mode, Some(wrap));
let positions = header_positions(&with_logo);
assert_eq!(positions.len(), control.len(), "mode {mode}, {wrap:?}: {positions:?}");
for (&(x, y), &(plain_x, plain_y)) in positions.iter().zip(&control) {
assert!((y - plain_y).abs() < 0.5, "mode {mode}, {wrap:?}: line moved vertically from {plain_y} to {y}");
if mode == 14 || (mode < 14 && wrap == Wrap::Square) {
assert!((x - plain_x).abs() < 0.5, "mode {mode}, {wrap:?}: line moved from {plain_x} to {x}");
} else {
assert!(x > plain_x + 59.5, "mode {mode}, {wrap:?}: line at {x} does not clear the logo");
}
}
assert!((body_top(&with_logo) - body_top(&plain)).abs() < 0.5, "mode {mode}, {wrap:?}: body moved vertically");
}
}
}
#[test]
fn mode_14_body_text_still_goes_below_its_own_top_and_bottom_object() {
crate::test_fonts();
let top = |mode| {
let mut d = Document::from_text("Body text.");
d.settings.compat_mode = mode;
d.last_section.margin_top = 20.0;
let float = Float { wrap: Wrap::TopAndBottom, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, x: 31.6, y: 7.2, ..Default::default() };
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
p.insert_object(0, rect_shape(451.65, BOX_H, float), &Default::default()).unwrap();
body_top(&lay(&d))
};
let (old, new) = (top(14), top(15));
assert!((old - new).abs() < 0.5 && old > 20.0 + 7.2 + BOX_H - 0.5, "mode 14 body line at {old}, mode 15 at {new}");
}
#[test]
fn mode_14_distance_below_the_object_counts_and_a_start_in_the_space_after_extends() {
// Word: 14.4 pt below the box make the body 14.4 pt lower.
let (plain, spaced) = (body_top(&page(14, Some(Wrap::TopAndBottom), 7.2)), body_top(&page_with(14, Some(Wrap::TopAndBottom), 7.2, (14.4, 0.0))));
assert!((spaced - plain - 14.4).abs() < 0.5, "body at {spaced}, {plain} without the distance");
// A box starting 15 pt down, past the 11.5 pt line but inside its 10 pt space after: the
// header ends at the box's bottom (Word: 62.1 from the page's top).
let inside = page_with(14, Some(Wrap::TopAndBottom), 15.0, (0.0, 10.0));
assert!((body_top(&inside) - (HEADER_TOP + 15.0 + BOX_H)).abs() < 0.5, "body at {}", body_top(&inside));
}
#[test]
fn mode_14_no_header_paragraph_moves_for_an_object_set_down_the_page_from_the_second() {
crate::test_fonts();
let lines = |mode: u32, object: bool| {
let mut d = Document::from_text("Body text.");
d.settings.compat_mode = mode;
d.last_section.header = HEADER_TOP;
d.last_section.margin_top = 20.0;
let tight = ParaProps { space_before: Some(0.0), space_after: Some(0.0), ..Default::default() };
let mut blocks = Vec::new();
for (i, t) in ["First line", "Second line", "Third line"].into_iter().enumerate() {
let mut p = Paragraph::with_text(t, Default::default());
p.props = tight.clone();
if object && i == 1 {
let float = Float { wrap: Wrap::TopAndBottom, h_rel: Anchor::Page, v_rel: Anchor::Page, x: 72.0, y: 60.0, ..Default::default() };
p.insert_object(0, rect_shape(451.65, BOX_H, float), &Default::default()).unwrap();
}
blocks.push(para_block(p));
}
let id = d.add_part(PartKind::Header, blocks);
d.last_section.headers.default = Some(id);
let l = lay(&d);
let tops: Vec<f32> = l.pages[0].header.iter().filter_map(|i| if let Placed::Lines { y, .. } = i { Some(*y) } else { None }).collect();
(tops, body_top(&l))
};
let ((plain, _), (with, body)) = (lines(14, false), lines(14, true));
assert_eq!(plain.len(), with.len());
for (a, b) in plain.iter().zip(&with) {
assert!((a - b).abs() < 0.5, "header lines at {with:?}, {plain:?} without the object");
}
// The box is 60 pt down the page, over the third line (the test font's lines are taller than
// Word's 11.5 pt, so the box is set lower than the 26 pt measured): the body starts at its bottom.
assert!((body - (60.0 + BOX_H)).abs() < 0.5, "body at {body}");
}
#[test]
fn mode_11_header_text_stays_beside_its_own_top_and_bottom_object_like_mode_14() {
// Word: modes 11, 12 and 14 keep the line at the header's top; mode 15 moves it below the box.
let (m11, m12, m14, m15) = (
page(11, Some(Wrap::TopAndBottom), 7.2),
page(12, Some(Wrap::TopAndBottom), 7.2),
page(14, Some(Wrap::TopAndBottom), 7.2),
page(15, Some(Wrap::TopAndBottom), 7.2),
);
for l in [&m11, &m12] {
assert!((header_line_top(l) - header_line_top(&m14)).abs() < 0.5, "line at {}, {} at mode 14", header_line_top(l), header_line_top(&m14));
assert!((body_top(l) - body_top(&m14)).abs() < 0.5, "body at {}, {} at mode 14", body_top(l), body_top(&m14));
}
assert!(header_line_top(&m15) > header_line_top(&m11) + 5.0, "mode 15 line at {}, mode 11 at {}", header_line_top(&m15), header_line_top(&m11));
}
@@ -1,118 +0,0 @@
//! Keep with next on the paragraph that closes a section (#6834). When the next section starts
//! on a new page, the paragraph after it is not on this page, so Keep with next has nothing to
//! keep it with: it stays at the bottom of its page. Moving it over for want of the next
//! section's first line left a page holding only that section's paragraph. Only a next-page
//! break was measured in Word; odd-page and even-page breaks follow by analogy (not measured).
//! Fixed page size and exact line heights, so no font metrics are assumed. Invented text only.
use crate::*;
use wordcraft_doc::props::LineSpacing;
use wordcraft_doc::section::{SectionProps, SectionStart};
use wordcraft_doc::{ParaProps, Paragraph};
fn lay(doc: &Document) -> DocLayout {
let mut c = LayoutCache::new();
layout(doc, &mut c, &LayoutOptions::default())
}
/// A 400 x 300 pt page with 50 pt margins: 200 pt of body, ten 20 pt lines.
fn small_page(start: SectionStart) -> SectionProps {
SectionProps {
start,
page_w: 400.0,
page_h: 300.0,
margin_top: 50.0,
margin_bottom: 50.0,
margin_left: 50.0,
margin_right: 50.0,
..Default::default()
}
}
fn exact(text: &str, height: f32, keep: bool) -> Paragraph {
let mut p = Paragraph::with_text(text, Default::default());
p.props = ParaProps {
line_spacing: Some(LineSpacing::Exactly(height)),
space_before: Some(0.0),
space_after: Some(0.0),
keep_next: keep.then_some(true),
..Default::default()
};
p
}
/// `filler` exact 20 pt paragraphs, then the closing paragraph (15 pt, block index `filler`,
/// kept with the next when `keep`), then one 20 pt paragraph. When `closes`, the closing
/// paragraph ends section one and the second section starts as `start`; otherwise the second
/// paragraph is in the same section.
fn build(filler: usize, keep: bool, start: SectionStart, closes: bool, empty: bool) -> Document {
let mut d = Document::new();
d.body.clear();
for i in 0..filler {
d.body.push(wordcraft_doc::para_block(exact(&format!("Filler line {i}"), 20.0, false)));
}
let mut last = exact(if empty { "" } else { "Closing paragraph of the first part" }, 15.0, keep);
if closes {
last.section = Some(Box::new(small_page(SectionStart::NextPage)));
}
d.body.push(wordcraft_doc::para_block(last));
d.body.push(wordcraft_doc::para_block(exact("First paragraph of the second part", 20.0, false)));
d.last_section = small_page(if closes { start } else { SectionStart::NextPage });
d
}
/// The page (0-based) that holds the body paragraph `block`.
fn page_of(l: &DocLayout, block: u32) -> Option<usize> {
l.pages.iter().position(|p| p.items.iter().any(|it| matches!(it, Placed::Lines { story: StoryRef::Body, path, .. } if path.0 == [block])))
}
const NEXT_BREAKS: [SectionStart; 3] = [SectionStart::NextPage, SectionStart::OddPage, SectionStart::EvenPage];
/// The issue's case: nine 20 pt lines, an empty 15 pt kept closing paragraph that fits at the
/// bottom (195 of 200 pt) while the next section's first line (20 pt) would not, then one
/// paragraph of the next section. Two pages, none empty.
#[test]
fn an_empty_kept_closing_paragraph_leaves_no_empty_page() {
crate::test_fonts();
let l = lay(&build(9, true, SectionStart::NextPage, true, true));
assert_eq!(l.pages.len(), 2);
assert_eq!(page_of(&l, 9), Some(0), "the closing paragraph moved to the next page");
assert_eq!(page_of(&l, 10), Some(1));
}
#[test]
fn a_kept_closing_paragraph_stays_on_its_page_and_adds_no_page() {
crate::test_fonts();
for start in NEXT_BREAKS {
for empty in [true, false] {
for n in 0..25 {
let kept = lay(&build(n, true, start, true, empty));
let plain = lay(&build(n, false, start, true, empty));
assert_eq!(kept.pages.len(), plain.pages.len(), "{start:?}, {n} filler paragraphs, empty {empty}: keep with next added a page");
assert_eq!(page_of(&kept, n as u32), page_of(&plain, n as u32), "{start:?}, {n} filler paragraphs, empty {empty}");
}
}
}
}
#[test]
fn keep_with_next_still_moves_an_ordinary_paragraph_with_its_next_line() {
crate::test_fonts();
// No section ends here: the 15 pt paragraph fits (195 of 200 pt) but the 20 pt one after it
// does not, so the pair goes to page 2 together.
let kept = lay(&build(9, true, SectionStart::NextPage, false, false));
let plain = lay(&build(9, false, SectionStart::NextPage, false, false));
assert_eq!(page_of(&plain, 9), Some(0));
assert_eq!(page_of(&kept, 9), Some(1));
}
#[test]
fn keep_with_next_before_a_continuous_section_still_keeps_with_its_next_line() {
crate::test_fonts();
// The next section continues on this page, so its first line is what the paragraph keeps
// with (not measured in Word; the earlier behaviour stays).
let kept = lay(&build(9, true, SectionStart::Continuous, true, false));
let plain = lay(&build(9, false, SectionStart::Continuous, true, false));
assert_eq!(page_of(&plain, 9), Some(0));
assert_eq!(page_of(&kept, 9), Some(1));
}
-294
View File
@@ -1,294 +0,0 @@
//! A paragraph that starts a cell's part of a page, in a row split across pages, is split where
//! its lines fall, as in Word (#6823): moving it on whole would gain nothing, and keeping
//! widow/orphan control left the cell with nothing on the page, so the row was placed whole and
//! ran off the bottom. A paragraph below other content of its cell keeps the rule, and so does a
//! row that starts below other content of the page. A "can't split" row taller than a page
//! splits too.
//!
//! The expectations were measured in Word for Windows 16.0 (compatibility mode 15, widow control
//! on, Letter with 1 inch margins) on synthetic documents laid out like these.
use crate::*;
use wordcraft_doc::para::{Anchor, Float, InlineObject, Wrap};
use wordcraft_doc::props::{LineSpacing, ParaProps};
use wordcraft_doc::{Table, para_block};
fn lay(doc: &Document) -> DocLayout {
let mut c = LayoutCache::new();
layout(doc, &mut c, &LayoutOptions::default())
}
fn exact(height: f32, widow: bool) -> ParaProps {
ParaProps {
line_spacing: Some(LineSpacing::Exactly(height)),
space_before: Some(0.0),
space_after: Some(0.0),
widow_control: Some(widow),
..Default::default()
}
}
fn lines_para(lines: usize, height: f32, widow: bool, name: &str) -> Arc<Block> {
para_block(lines_paragraph(lines, height, widow, name))
}
fn lines_paragraph(lines: usize, height: f32, widow: bool, name: &str) -> Paragraph {
let text: Vec<String> = (1..=lines).map(|i| format!("{name}{i}")).collect();
let mut p = Paragraph::with_text(&text.join(&wordcraft_doc::para::LINE_BREAK.to_string()), Default::default());
p.props = exact(height, widow);
p
}
/// What the table is made of: `pre` one-line paragraphs of 16 pt before it, an optional repeated
/// header row, a row (can't split or not) whose second cell holds `fill` lines of `fill_height`,
/// the paragraphs `before` (lines and line height) and last a paragraph `last` of lines of a
/// height. The last two are inside a nested table when `nested` is set.
struct Case {
pre: usize,
header: bool,
cant_split: bool,
nested: bool,
fill: usize,
fill_height: f32,
before: Vec<(usize, f32)>,
last: (usize, f32),
widow: bool,
/// A picture floating through the text, anchored in the last paragraph and placed above it.
float_above: bool,
}
impl Case {
fn new(last: (usize, f32)) -> Case {
Case {
pre: 0,
header: false,
cant_split: false,
nested: false,
fill: 45,
fill_height: 14.0,
before: Vec::new(),
last,
widow: true,
float_above: false,
}
}
/// The lines of the last paragraph on each page.
fn per_page(&self) -> Vec<usize> {
crate::test_fonts();
let w = self.widow;
let mut d = Document::from_text("After");
for i in 0..self.pre {
let mut p = Paragraph::with_text(&format!("F{i}"), Default::default());
p.props = exact(16.0, w);
d.insert_block(StoryRef::Body, &Path::top(i), Block::Para(p)).unwrap();
}
let mut t = Table::new(1 + usize::from(self.header), 2, 400.0);
t.props.cell_margins = Some([0.0, 5.4, 0.0, 5.4]);
let row = usize::from(self.header);
if self.header {
t.rows[0].props.header = true;
for c in &mut t.rows[0].cells {
c.blocks = vec![lines_para(1, 14.0, w, "H")];
}
}
t.rows[row].props.cant_split = self.cant_split;
let mut inner: Vec<Arc<Block>> = self.before.iter().map(|&(n, h)| lines_para(n, h, w, "P")).collect();
let mut last = lines_paragraph(self.last.0, self.last.1, w, "B");
if self.float_above {
let float = Float { wrap: Wrap::Through, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, x: 250.0, y: -6.0, ..Default::default() };
let picture = InlineObject::Image {
media: "float".into(),
w: 20.0,
h: 20.0,
alt: "float".into(),
float,
crop: [0.0; 4],
fx: Default::default(),
ole: None,
};
last.insert_object(0, picture, &Default::default()).unwrap();
}
inner.push(para_block(last));
// Without a fill paragraph the cell starts with `inner`.
let mut blocks = if self.fill > 0 { vec![lines_para(self.fill, self.fill_height, w, "A")] } else { Vec::new() };
let mut at = vec![self.pre as u32, row as u32, 1, (blocks.len() + inner.len()) as u32 - 1];
if self.nested {
let mut nested = Table::new(1, 1, 200.0);
nested.rows[0].cells[0].blocks = inner.clone();
at = vec![self.pre as u32, row as u32, 1, blocks.len() as u32, 0, 0, inner.len() as u32 - 1];
blocks.push(Arc::new(Block::Table(nested)));
blocks.push(lines_para(1, 1.0, w, "Z"));
} else {
blocks.extend(inner);
}
t.rows[row].cells[1].blocks = blocks;
d.insert_block(StoryRef::Body, &Path::top(self.pre), Block::Table(t)).unwrap();
lay(&d)
.pages
.iter()
.map(|p| {
p.items
.iter()
.filter_map(|it| match it {
Placed::Lines { path, l0, l1, .. } if path.0 == at => Some(l1 - l0),
_ => None,
})
.sum()
})
.collect()
}
}
/// A three-line paragraph at the top of a page with room for its first line only keeps that line
/// there (the next two go on, one to a page here).
#[test]
fn a_first_line_alone_at_the_top_of_a_page_stays_in_a_split_row() {
assert_eq!(Case::new((3, 400.0)).per_page(), vec![0, 1, 1, 1]);
}
/// Two lines, room for one: one and one.
#[test]
fn a_two_line_paragraph_at_the_top_of_a_page_splits_one_and_one() {
assert_eq!(Case::new((2, 400.0)).per_page(), vec![0, 1, 1]);
}
/// Three lines, room for two: two and one (not the whole paragraph on, which is no better at the
/// top of a page, and not one and two).
#[test]
fn a_three_line_paragraph_at_the_top_of_a_page_with_room_for_two_splits_two_and_one() {
assert_eq!(Case::new((3, 300.0)).per_page(), vec![0, 2, 1]);
}
/// Guard (passes without the fix): four lines with room for three still keep two for the widow.
#[test]
fn four_lines_at_the_top_of_a_page_with_room_for_three_still_keep_two_for_the_widow() {
assert_eq!(Case::new((4, 200.0)).per_page(), vec![0, 2, 2]);
}
/// Guard (passes without the fix): a paragraph below another one of its cell on the page keeps
/// the orphan rule, so its single line there moves on with the rest.
#[test]
fn a_paragraph_below_other_content_of_its_cell_still_moves_on_whole_instead_of_an_orphan() {
let mut c = Case::new((3, 200.0));
c.before = vec![(1, 300.0)];
assert_eq!(c.per_page(), vec![0, 0, 3]);
}
/// Where only the later paragraphs of a cell continue, the one that moved to the top of a page
/// splits at its lines (two and one), the paragraph before it having stayed.
#[test]
fn a_later_paragraph_moved_to_the_top_of_a_page_splits_where_its_lines_fall() {
let mut c = Case::new((3, 300.0));
c.before = vec![(1, 100.0)];
assert_eq!(c.per_page(), vec![0, 0, 2, 1]);
}
/// Guard (passes without the fix): four lines below a paragraph, room for three, keep two.
#[test]
fn four_lines_below_other_content_with_room_for_three_still_keep_two_for_the_widow() {
let mut c = Case::new((4, 200.0));
c.before = vec![(1, 40.0)];
assert_eq!(c.per_page(), vec![0, 2, 2]);
}
/// Guard (passes without the fix): without widow control the paragraph always split where it fell.
#[test]
fn without_widow_control_the_lines_split_where_they_fall() {
let mut c = Case::new((3, 400.0));
c.widow = false;
assert_eq!(c.per_page(), vec![0, 1, 1, 1]);
}
/// A paragraph of a nested table splits the same way.
#[test]
fn a_nested_paragraph_at_the_top_of_a_page_splits_where_its_lines_fall() {
let mut c = Case::new((3, 300.0));
c.nested = true;
assert_eq!(c.per_page(), vec![0, 2, 1]);
let mut c = Case::new((2, 400.0));
c.nested = true;
assert_eq!(c.per_page(), vec![0, 1, 1]);
}
/// A nested paragraph below another one of the nested cell moves on whole, then splits at the top
/// of the page.
#[test]
fn a_nested_paragraph_below_other_content_moves_on_then_splits() {
let mut c = Case::new((3, 300.0));
c.nested = true;
c.before = vec![(1, 100.0)];
assert_eq!(c.per_page(), vec![0, 0, 2, 1]);
}
/// Under a repeated header row the paragraph that starts the page splits at its lines too. The
/// lines per page are Word's; Word leaves the header off some of the pages, which is not covered.
#[test]
fn under_a_repeated_header_row_the_paragraph_starting_the_page_splits_where_its_lines_fall() {
let mut c = Case::new((3, 300.0));
c.header = true;
c.fill = 44;
assert_eq!(c.per_page(), vec![0, 2, 1]);
let mut c = Case::new((3, 300.0));
c.header = true;
c.fill = 44;
c.before = vec![(1, 100.0)];
assert_eq!(c.per_page(), vec![0, 0, 2, 1]);
}
/// Guard (passes without the fix): under a header row, four lines with room for three keep two.
#[test]
fn under_a_repeated_header_row_four_lines_still_keep_two_for_the_widow() {
let mut c = Case::new((4, 200.0));
c.header = true;
c.fill = 44;
assert_eq!(c.per_page(), vec![0, 2, 2]);
}
/// A can't split row taller than a page splits where the pages end.
#[test]
fn a_cant_split_row_taller_than_a_page_splits_where_the_page_ends() {
let mut c = Case::new((3, 400.0));
c.cant_split = true;
assert_eq!(c.per_page(), vec![0, 1, 1, 1]);
}
/// A can't split row taller than a page that starts below text goes to the next page first, then
/// splits there.
#[test]
fn a_tall_cant_split_row_below_text_starts_the_next_page_and_splits_there() {
let mut c = Case::new((3, 400.0));
c.cant_split = true;
c.pre = 20;
assert_eq!(c.per_page(), vec![0, 0, 1, 1, 1]);
}
/// Guard (passes without the fix): a can't split row that fits the next page moves there whole.
#[test]
fn a_cant_split_row_that_fits_the_next_page_moves_there_whole() {
let mut c = Case::new((3, 16.0));
c.cant_split = true;
c.pre = 38;
c.fill = 5;
c.fill_height = 16.0;
assert_eq!(c.per_page(), vec![0, 3]);
}
/// A picture floating above the paragraph that starts the cell doesn't make it any less the
/// first: only the text in the flow decides. (Floats are placed with the first piece of their
/// paragraph, so this is the table's first page.)
#[test]
fn a_floating_picture_above_the_first_paragraph_doesnt_keep_it_from_splitting() {
let mut c = Case::new((3, 400.0));
c.fill = 0;
c.float_above = true;
assert_eq!(c.per_page(), vec![1, 1, 1]);
}
/// Guard (passes without the fix): a can't split row that fits a page with room to spare stays
/// whole on it, whatever the border below it needs.
#[test]
fn a_cant_split_row_that_fits_a_page_is_left_whole() {
let mut c = Case::new((1, 10.0));
c.cant_split = true;
assert_eq!(c.per_page(), vec![1, 0], "the row stays on page 1 (the paragraph after it is on page 2)");
}
+2 -4
View File
@@ -302,10 +302,8 @@ fn inline_box_that_resizes_to_fit_takes_its_texts_height() {
}
/// Filler paragraphs before the box in [`inline_box_that_resizes_to_fit_takes_its_texts_height`]:
/// enough that a 10 cm box no longer leaves room for the page break on the first page, while the
/// box fitted to its three lines does (a paragraph of only a page break that doesn't fit goes to
/// the next page, as in Word).
const FILLER: usize = 20;
/// enough that a 10 cm box no longer leaves room for the page break on the first page.
const FILLER: usize = 22;
/// A floating box that resizes to fit its text takes its text's height too, both where it is
/// drawn and the room the text beside it wraps around (an OpenDocument frame without a height).
+1 -1
View File
@@ -1,3 +1,3 @@
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" width="20" height="20">
<path d="M3 6 L7 3.5 L13 3.5 L17 6 L17.5 14 L13.5 16.5 L6.5 16.5 L2.5 14 Z M6 10.5 A1.5 1.5 0 1 0 9 10.5 A1.5 1.5 0 1 0 6 10.5 Z M11 10.5 A1.5 1.5 0 1 0 14 10.5 A1.5 1.5 0 1 0 11 10.5 Z" fill="currentColor" fill-rule="evenodd"/>
<path d="M3 6 L7 3.5 L13 3.5 L17 6 L17.5 14 L13.5 16.5 L6.5 16.5 L2.5 14 Z M6 10.5 A1.5 1.5 0 1 0 9 10.5 A1.5 1.5 0 1 0 6 10.5 Z M11 10.5 A1.5 1.5 0 1 0 14 10.5 A1.5 1.5 0 1 0 11 10.5 Z" fill="#1E6FD9" class="accent" fill-rule="evenodd"/>
</svg>

Before

Width:  |  Height:  |  Size: 322 B

After

Width:  |  Height:  |  Size: 332 B

-114
View File
@@ -436,117 +436,3 @@ fn status_bar_texts_stop_before_the_controls_in_a_narrow_window() {
let focus = wide.get_by_role_and_label(egui::accesskit::Role::Button, "Focus").rect();
assert!(painted_on_row_of(&wide, focus).iter().any(|(t, _)| t == "Track Changes: On"), "a wide window shows everything");
}
/// #7311: the title bar's Discord community button keeps its solid accent fill and contrasting
/// `on_strong` icon/label in both wide (pill with label) and narrow (compact icon-only) windows,
/// across Light and Dark themes, and still dispatches `ui.discord` when clicked.
#[test]
fn title_bar_discord_button_keeps_accent_fill_and_icon_contrast_in_wide_and_narrow_windows() {
use egui::accesskit::Role;
fn to_color32(rgba: craft::theme::Rgba) -> egui::Color32 {
egui::Color32::from(craft::theme::Srgba::from(rgba))
}
fn collect_shapes<'a>(shapes: &'a [egui::epaint::ClippedShape], out: &mut Vec<&'a egui::Shape>) {
for clipped in shapes {
fn walk<'a>(shape: &'a egui::Shape, out: &mut Vec<&'a egui::Shape>) {
match shape {
egui::Shape::Vec(children) => {
for child in children {
walk(child, out);
}
}
other => out.push(other),
}
}
walk(&clipped.shape, out);
}
}
for theme in ["light", "dark"] {
for (width, expect_compact) in [(1440.0_f32, false), (520.0_f32, true)] {
let mut a = new_app();
a.ui.show_discord = true;
a.run("ui.theme", json!({"value": theme})).unwrap();
let mut h = crate::test_harness::builder().with_size(egui::vec2(width, 700.0)).build_ui_state(app_frame, a);
crate::test_harness::frames(&mut h, 10);
let node = h.get_by_role_and_label(Role::Button, "Discord");
let rect = node.rect();
assert!(rect.is_positive(), "{theme} {width}: Discord button must be laid out");
if expect_compact {
assert!(rect.width() <= rect.height() + 4.0, "{theme} {width}: expected compact icon-only Discord button, got {rect:?}");
} else {
assert!(rect.width() > rect.height() + 10.0, "{theme} {width}: expected full labelled Discord pill, got {rect:?}");
}
let env = craft::ui::runtime::env::Env::of_root(&h.ctx);
let accent_strong = to_color32(env.tokens.color.accent.strong);
let on_strong = to_color32(env.tokens.color.text.on_strong);
let mut shapes = Vec::new();
collect_shapes(&h.output().shapes, &mut shapes);
let bg = shapes.iter().find_map(|s| match s {
egui::Shape::Rect(r)
if (r.rect.min.x - rect.min.x).abs() <= 1.5
&& (r.rect.max.x - rect.max.x).abs() <= 1.5
&& (r.rect.min.y - rect.min.y).abs() <= 1.5
&& (r.rect.max.y - rect.max.y).abs() <= 1.5
&& r.fill != egui::Color32::TRANSPARENT =>
{
Some(r)
}
_ => None,
});
let bg = bg.unwrap_or_else(|| panic!("{theme} {width}: expected a filled background rect for Discord button {rect:?}"));
assert_eq!(bg.fill, accent_strong, "{theme} {width}: Discord button fill should be accent.strong");
if !expect_compact {
let min_pill_radius = (rect.height() / 2.0 - 1.5).floor().max(0.0) as u8;
assert!(
bg.corner_radius.nw >= min_pill_radius,
"{theme} {width}: wide Discord button should have pill corners (>= {min_pill_radius}), got {:?}",
bg.corner_radius
);
}
let icon_tinted_on_strong = shapes.iter().any(|s| match s {
egui::Shape::Mesh(mesh) => {
let bounds = mesh.calc_bounds();
rect.expand(1.5).contains_rect(bounds) && !mesh.vertices.is_empty() && mesh.vertices.iter().all(|v| v.color == on_strong)
}
_ => false,
});
assert!(
icon_tinted_on_strong,
"{theme} {width}: Discord icon inside {rect:?} must paint in text.on_strong ({on_strong:?}), not accent ink"
);
if !expect_compact {
let has_label = shapes.iter().any(|s| match s {
egui::Shape::Text(t) => rect.expand(1.5).contains_rect(s.visual_bounding_rect()) && t.galley.text() == "Discord",
_ => false,
});
assert!(has_label, "{theme} {width}: wide Discord pill must paint its \"Discord\" label");
}
// Clicking the button dispatches `ui.discord` and opens the community URL.
h.get_by_role_and_label(Role::Button, "Discord").click();
let mut opened = None;
for _ in 0..4 {
crate::test_harness::step(&mut h);
for cmd in &h.output().platform_output.commands {
if let egui::OutputCommand::OpenUrl(url) = cmd {
opened = Some(url.url.clone());
}
}
}
assert_eq!(
opened.as_deref(),
Some("https://discord.gg/artcraft"),
"{theme} {width}: clicking the Discord button should open the community URL"
);
}
}
}
+3 -25
View File
@@ -6,10 +6,7 @@ use craft::behavior::IconId;
use craft::keymap::CommandRef;
use craft::menu::RibbonMenuRequest;
use craft::review::ui::Avatar;
use craft::theme::variant::Tone;
use craft::theme::{ControlSize, CustomVariant, Emphasis, RadiusStep, Tokens, Variant, VariantLook};
use craft::ui::buttons::button::ButtonStyleKey;
use craft::ui::buttons::icon_button::IconButtonStyleKey;
use craft::theme::ControlSize;
use craft::ui::buttons::{Button, IconButton};
use craft::ui::choice::Switch;
use craft::ui::contract::{Bind, BodyCx, Props as _, Show as _, ShowCollection as _, ShowContainer as _, TooltipSpec, Trigger};
@@ -235,19 +232,6 @@ fn qat_menu(app: &mut WordApp, ui: &mut Ui) -> egui::Rect {
out.response.rect
}
/// Solid accent pill look for the full title bar Discord button (#656, #7311).
fn discord_pill_look(tokens: &Tokens) -> VariantLook {
VariantLook::of(Emphasis::Solid, Tone::Accent, tokens).radius(RadiusStep::Pill)
}
/// Solid accent look for the compact icon-only Discord button when the title bar narrows (#5886, #7311).
fn discord_icon_look(tokens: &Tokens) -> VariantLook {
VariantLook::of(Emphasis::Solid, Tone::Accent, tokens)
}
const DISCORD_PILL: CustomVariant = CustomVariant::new::<ButtonStyleKey>("wordcraft.discord-pill", discord_pill_look);
const DISCORD_ICON: CustomVariant = CustomVariant::new::<IconButtonStyleKey>("wordcraft.discord-icon", discord_icon_look);
/// Search, the community button and the account, at the end of the bar; returns the rect they took. In a narrow
/// window they give way by `step` (#5886, as the old bar's fit): at 1 the Discord button drops its label, at 2 the
/// search shows its magnifier alone as well.
@@ -256,17 +240,11 @@ fn trailing(app: &mut WordApp, ui: &mut Ui, step: usize) -> Option<egui::Rect> {
if app.ui.show_discord {
let tip = TooltipSpec::new(tl!("Join the ArtCraft community on Discord").to_string());
let clicked = if step >= 1 {
let out = IconButton::new(IconId::new("discord"))
.label(tl!("Discord").to_string())
.variant(Variant::Custom(DISCORD_ICON))
.glyphs(GlyphRole::Tool)
.tooltip(tip)
.show(ui);
let out = IconButton::new(IconId::new("discord")).label(tl!("Discord").to_string()).tooltip(tip).show(ui);
rects.push(out.response.rect);
out.response.clicked()
} else {
let out =
Button::new(tl!("Discord").to_string()).icon(IconId::new("discord")).variant(Variant::Custom(DISCORD_PILL)).tooltip(tip).show(ui);
let out = Button::new(tl!("Discord").to_string()).icon(IconId::new("discord")).tooltip(tip).show(ui);
rects.push(out.response.rect);
out.clicked()
};
+33 -73
View File
@@ -90,9 +90,32 @@ pub(crate) fn style_tile_image(doc: &Document, id: &str, ppp: f32, dark_page: bo
if dark && !dark_page {
dim(&mut img);
}
// The old ribbon drew the sample letters on the ribbon itself, with no page behind them.
if !dark_page {
clear_white_paper(&mut img);
}
img
}
/// Takes the white paper out of `img`: each pixel becomes the colour that, laid over white, gives
/// it, so the letters keep their edges over any background and the paper is transparent.
fn clear_white_paper(img: &mut ColorImage) {
for px in &mut img.pixels {
let [r, g, b, _] = px.to_array();
let alpha = 255 - r.min(g).min(b);
if alpha == 0 {
*px = egui::Color32::TRANSPARENT;
continue;
}
// c = a * x + (1 - a) * 255, solved for x.
let unlay = |c: u8| -> u8 {
let lifted = i32::from(c) - (255 - i32::from(alpha));
(lifted.max(0) * 255 / i32::from(alpha)).clamp(0, 255) as u8
};
*px = egui::Color32::from_rgba_unmultiplied(unlay(r), unlay(g), unlay(b), alpha);
}
}
/// A Style Sets tile: a title, a heading and a paragraph in the set `name`.
fn style_set_image(name: &str, ppp: f32, dark: bool) -> ColorImage {
let mut s = wordcraft_engine::Session::new(Document::new());
@@ -318,82 +341,19 @@ pub(crate) fn wordart(ui: &mut Ui, cx: &mut BodyCx<'_>, app: &mut WordApp, comma
#[cfg(test)]
mod tests {
/// White paper turns transparent and black letters stay black and opaque.
#[test]
fn white_paper_clears_and_ink_stays() {
let mut img = egui::ColorImage::new([3, 1], vec![egui::Color32::WHITE, egui::Color32::BLACK, egui::Color32::from_rgb(128, 128, 128)]);
super::clear_white_paper(&mut img);
assert_eq!(img.pixels[0], egui::Color32::TRANSPARENT);
assert_eq!(img.pixels[1], egui::Color32::BLACK);
assert_eq!(img.pixels[2].a(), 127);
}
use super::*;
use std::sync::Arc;
/// Relative luminance (WCAG) of an opaque sRGB colour, in `0.0..=1.0`.
fn rel_luma(c: Color32) -> f64 {
let [r, g, b, _] = c.to_srgba_unmultiplied();
let lin = |u: u8| {
let s = f64::from(u) / 255.0;
if s <= 0.04045 { s / 12.92 } else { ((s + 0.055) / 1.055).powf(2.4) }
};
0.2126 * lin(r) + 0.7152 * lin(g) + 0.0722 * lin(b)
}
/// WCAG contrast ratio between two opaque colours.
fn contrast_ratio(a: Color32, b: Color32) -> f64 {
let (la, lb) = (rel_luma(a), rel_luma(b));
let (hi, lo) = if la >= lb { (la, lb) } else { (lb, la) };
(hi + 0.05) / (lo + 0.05)
}
/// The background paper pixel: the most frequent colour in the tile.
fn paper_color(img: &ColorImage) -> Color32 {
let mut counts = std::collections::HashMap::<Color32, usize>::new();
for &px in &img.pixels {
*counts.entry(px).or_insert(0) += 1;
}
counts.into_iter().max_by_key(|&(_, n)| n).expect("non-empty tile").0
}
/// #7309: Styles gallery tiles keep opaque paper in light and dark modes (dimmed in dark mode,
/// matching #663 and sibling galleries) so dark style ink remains legible, and leave Switch
/// Modes' dark page untouched by interface dimming.
#[test]
fn style_tile_keeps_opaque_paper_and_legible_contrast_in_dark_mode() {
let doc = Document::new();
let light = style_tile_image(&doc, "Normal", 1.0, false, false);
let dark = style_tile_image(&doc, "Normal", 1.0, false, true);
let dark_page_light_ui = style_tile_image(&doc, "Normal", 1.0, true, false);
let dark_page_dark_ui = style_tile_image(&doc, "Normal", 1.0, true, true);
assert!(light.pixels.iter().all(|p| p.a() == 255), "light-mode style tile keeps opaque paper");
assert!(dark.pixels.iter().all(|p| p.a() == 255), "dark-mode style tile keeps opaque paper (not a translucent veil)");
assert!(dark_page_dark_ui.pixels.iter().all(|p| p.a() == 255), "dark-page style tile stays opaque");
let lightest = |img: &ColorImage| img.pixels.iter().copied().max_by(|a, b| rel_luma(*a).total_cmp(&rel_luma(*b))).expect("non-empty tile");
let darkest = |img: &ColorImage| img.pixels.iter().copied().min_by(|a, b| rel_luma(*a).total_cmp(&rel_luma(*b))).expect("non-empty tile");
let light_paper = paper_color(&light);
let light_ink = darkest(&light);
let dark_paper = paper_color(&dark);
let dark_ink = darkest(&dark);
let dark_page_paper = paper_color(&dark_page_dark_ui);
let dark_page_ink = lightest(&dark_page_dark_ui);
assert!(rel_luma(light_paper) > rel_luma(dark_paper), "dark mode dims white paper below light mode");
assert!(rel_luma(dark_paper) > rel_luma(dark_ink), "dark-mode tile ink stays darker than its dimmed paper");
assert!(
contrast_ratio(light_paper, light_ink) >= 4.5,
"light-mode Normal tile needs >= 4.5:1 contrast (got {:.2}:1)",
contrast_ratio(light_paper, light_ink)
);
assert!(
contrast_ratio(dark_paper, dark_ink) >= 4.5,
"dark-mode Normal tile needs >= 4.5:1 contrast (got {:.2}:1)",
contrast_ratio(dark_paper, dark_ink)
);
assert_eq!(dark_page_light_ui.pixels, dark_page_dark_ui.pixels, "Switch Modes' dark page is not dimmed again by dark mode");
assert!(rel_luma(dark_page_paper) < rel_luma(dark_paper), "Switch Modes renders onto a dark page rather than dimmed white paper");
assert!(rel_luma(dark_page_ink) > rel_luma(dark_page_paper), "Switch Modes renders light ink onto the dark page");
assert!(
contrast_ratio(dark_page_paper, dark_page_ink) >= 4.5,
"dark-page Normal tile needs >= 4.5:1 contrast (got {:.2}:1)",
contrast_ratio(dark_page_paper, dark_page_ink)
);
}
/// #2: a style whose hanging indent is larger than its left indent previewed with its first line
/// starting off the tile's left edge; the first line now starts at the edge.
// PLAN: the sheet puts this test in previews/tests.rs; `ribbon::galleries` is private to `ribbon`, so
+217 -228
View File
@@ -14,7 +14,7 @@ use craft::ui::primitives::{HAlign, TextRun};
use craft::ui::tile_grid::{CaptionPlace, Tile, TileGrid};
use wordcraft_doc::props::Align;
use super::common::{icon_only, menu_button};
use super::common::menu_button;
use super::underline::underline_menu;
use egui::vec2;
use serde_json::Value;
@@ -174,96 +174,89 @@ pub(super) fn home(row: &mut RibbonRow<'_>, app: &mut WordApp) {
});
});
row.group(ribbon_group("font", "Font", "font", Some("format.fontDialog")), |ui| {
// The Font and Paragraph groups' small buttons sit side by side with no gap, as the old ribbon's (1 pt apart),
// and show their icons alone so they never expand with text labels (#7308).
icon_only(ui, |ui| {
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
Row::new().gap(Gap::None).show(ui, |ui, _| {
let mut family = st.get("font").and_then(Value::as_str).unwrap_or("").to_string();
let out = crate::widgets::font_box(ui, app, tl!("Font").to_string(), &mut family);
if let Some(f) = out.picked {
let _ = app.run("format.font", json!({"name": f}));
}
let fmt = |s: f64| if s.fract() == 0.0 { format!("{s:.0}") } else { format!("{s}") };
let mut size = st.get("size").and_then(Value::as_f64).map(fmt).unwrap_or_default();
let sizes: Vec<Entry<String>> =
wordcraft_engine::cmd::format::SIZES.iter().map(|s| Entry::new(fmt(f64::from(*s)), fmt(f64::from(*s)))).collect();
let out = craft::ui::pickers::ComboBox::new(tl!("Font Size").to_string(), Bind::bound(&mut size), &sizes).show(ui);
if let Some(v) = out.edit.events.committed()
&& let Ok(x) = v.trim().parse::<f64>()
{
let _ = app.run("format.size", json!({"size": x}));
}
for (icon, tip, id) in [("grow", "Increase Font Size", "format.growFont"), ("shrink", "Decrease Font Size", "format.shrinkFont")]
{
IconButton::command(crate::icons::id(icon), CommandRef::new(id))
.label(tl!(tip).to_string())
.tooltip(tl!(tip).to_string())
.show(ui);
}
let face = Button::new(tl!("Change Case").to_string()).icon(IconId::new("case")).tooltip(tl!("Change Case").to_string());
menu_button(ui, face, tl!("Change Case").to_string(), Some("format.changeCase"), |ui, _| {
for (label, mode) in [
("Sentence case.", "sentence"),
("lowercase", "lower"),
("UPPERCASE", "upper"),
("Capitalize Each Word", "title"),
("tOGGLE cASE", "toggle"),
] {
MenuItem::command(CommandRef::with_params("format.changeCase", json!({"mode": mode})))
.label(tl!(label).to_string())
.show(ui);
}
});
for (icon, tip, id) in [("clear", "Clear All Formatting", "format.clear"), ("phonetic", "Phonetic Guide", "format.phonetic")] {
IconButton::command(crate::icons::id(icon), CommandRef::new(id))
.label(tl!(tip).to_string())
.tooltip(tl!(tip).to_string())
.show(ui);
}
});
Row::new().gap(Gap::None).show(ui, |ui, _| {
for (icon, tip, id, on) in [("bold", "Bold", "format.bold", flag("bold")), ("italic", "Italic", "format.italic", flag("italic"))]
{
ToggleButton::command(CommandRef::new(id))
.icon(crate::icons::id(icon))
.icon_only()
.selected(on)
.tooltip(tl!(tip).to_string())
.show(ui);
}
SplitButton::<String>::command(
CommandRef::with_params("format.underline", json!({})),
SplitMenu::Body(Box::new(|ui, _| underline_menu(ui, app))),
)
.icon(IconId::new("underline"))
.selected(flag("underline"))
.tooltip(tl!("Underline").to_string())
.show(ui);
for (icon, tip, id, on) in [
("strike", "Strikethrough", "format.strikethrough", flag("strike")),
("subscript", "Subscript", "format.subscript", flag("subscript")),
("superscript", "Superscript", "format.superscript", flag("superscript")),
("charborder", "Character Border", "format.border", flag("border")),
] {
ToggleButton::command(CommandRef::new(id))
.icon(crate::icons::id(icon))
.icon_only()
.selected(on)
.tooltip(tl!(tip).to_string())
.show(ui);
}
IconButton::command(IconId::new("enclose"), CommandRef::new("format.enclose"))
.label(tl!("Enclose Characters").to_string())
.tooltip(tl!("Enclose Characters").to_string())
// The Font and Paragraph groups' small buttons sit side by side with no gap, as the old ribbon's (1 pt apart).
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
Row::new().gap(Gap::None).show(ui, |ui, _| {
let mut family = st.get("font").and_then(Value::as_str).unwrap_or("").to_string();
let out = crate::widgets::font_box(ui, app, tl!("Font").to_string(), &mut family);
if let Some(f) = out.picked {
let _ = app.run("format.font", json!({"name": f}));
}
let fmt = |s: f64| if s.fract() == 0.0 { format!("{s:.0}") } else { format!("{s}") };
let mut size = st.get("size").and_then(Value::as_f64).map(fmt).unwrap_or_default();
let sizes: Vec<Entry<String>> =
wordcraft_engine::cmd::format::SIZES.iter().map(|s| Entry::new(fmt(f64::from(*s)), fmt(f64::from(*s)))).collect();
let out = craft::ui::pickers::ComboBox::new(tl!("Font Size").to_string(), Bind::bound(&mut size), &sizes).show(ui);
if let Some(v) = out.edit.events.committed()
&& let Ok(x) = v.trim().parse::<f64>()
{
let _ = app.run("format.size", json!({"size": x}));
}
for (icon, tip, id) in [("grow", "Increase Font Size", "format.growFont"), ("shrink", "Decrease Font Size", "format.shrinkFont")] {
IconButton::command(crate::icons::id(icon), CommandRef::new(id))
.label(tl!(tip).to_string())
.tooltip(tl!(tip).to_string())
.show(ui);
let face = Button::new(tl!("Text Effects and Typography").to_string())
.icon(IconId::new("effects"))
.tooltip(tl!("Text Effects and Typography").to_string());
menu_button(ui, face, tl!("Text Effects and Typography").to_string(), None, |ui, cx| text_effects_menu(ui, cx, app));
crate::colors::highlight_split(ui, app, tl!("Text Highlight Color"));
crate::colors::font_color_split(ui, app, tl!("Font Color"), Target::cmd("format.color").remember(Remember::FontColor));
}
let face = Button::new(tl!("Change Case").to_string()).icon(IconId::new("case")).tooltip(tl!("Change Case").to_string());
menu_button(ui, face, tl!("Change Case").to_string(), Some("format.changeCase"), |ui, _| {
for (label, mode) in [
("Sentence case.", "sentence"),
("lowercase", "lower"),
("UPPERCASE", "upper"),
("Capitalize Each Word", "title"),
("tOGGLE cASE", "toggle"),
] {
MenuItem::command(CommandRef::with_params("format.changeCase", json!({"mode": mode}))).label(tl!(label).to_string()).show(ui);
}
});
for (icon, tip, id) in [("clear", "Clear All Formatting", "format.clear"), ("phonetic", "Phonetic Guide", "format.phonetic")] {
IconButton::command(crate::icons::id(icon), CommandRef::new(id))
.label(tl!(tip).to_string())
.tooltip(tl!(tip).to_string())
.show(ui);
}
});
Row::new().gap(Gap::None).show(ui, |ui, _| {
for (icon, tip, id, on) in [("bold", "Bold", "format.bold", flag("bold")), ("italic", "Italic", "format.italic", flag("italic"))] {
ToggleButton::command(CommandRef::new(id))
.icon(crate::icons::id(icon))
.icon_only()
.selected(on)
.tooltip(tl!(tip).to_string())
.show(ui);
}
SplitButton::<String>::command(
CommandRef::with_params("format.underline", json!({})),
SplitMenu::Body(Box::new(|ui, _| underline_menu(ui, app))),
)
.icon(IconId::new("underline"))
.selected(flag("underline"))
.tooltip(tl!("Underline").to_string())
.show(ui);
for (icon, tip, id, on) in [
("strike", "Strikethrough", "format.strikethrough", flag("strike")),
("subscript", "Subscript", "format.subscript", flag("subscript")),
("superscript", "Superscript", "format.superscript", flag("superscript")),
("charborder", "Character Border", "format.border", flag("border")),
] {
ToggleButton::command(CommandRef::new(id))
.icon(crate::icons::id(icon))
.icon_only()
.selected(on)
.tooltip(tl!(tip).to_string())
.show(ui);
}
IconButton::command(IconId::new("enclose"), CommandRef::new("format.enclose"))
.label(tl!("Enclose Characters").to_string())
.tooltip(tl!("Enclose Characters").to_string())
.show(ui);
let face = Button::new(tl!("Text Effects and Typography").to_string())
.icon(IconId::new("effects"))
.tooltip(tl!("Text Effects and Typography").to_string());
menu_button(ui, face, tl!("Text Effects and Typography").to_string(), None, |ui, cx| text_effects_menu(ui, cx, app));
crate::colors::highlight_split(ui, app, tl!("Text Highlight Color"));
crate::colors::font_color_split(ui, app, tl!("Font Color"), Target::cmd("format.color").remember(Remember::FontColor));
});
});
});
@@ -273,150 +266,146 @@ pub(super) fn home(row: &mut RibbonRow<'_>, app: &mut WordApp) {
// Alignment is shown as it reads on the page, so Left and Right swap in a right-to-left paragraph.
let (align, rtl) = rp.as_ref().map_or((Align::Left, false), |r| (r.align.visual(r.bidi), r.bidi));
let marks = app.session.view.marks;
icon_only(ui, |ui| {
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
Row::new().gap(Gap::None).show(ui, |ui, _| {
SplitButton::<String>::command(
CommandRef::with_params("para.bullets", json!({})),
SplitMenu::Body(Box::new(|ui, cx| bullets_menu(ui, cx, app))),
)
.icon(IconId::new("bullets"))
.selected(lists.bullets)
.tooltip(tl!("Bullets").to_string())
.show(ui);
SplitButton::<String>::command(
CommandRef::with_params("para.numbering", json!({})),
SplitMenu::Body(Box::new(|ui, _| {
for (l, k) in [
("1. 2. 3.", "numbered"),
("1) 2) 3)", "numberedParen"),
("I. II. III.", "outline"),
("A. B. C.", "upperLetter"),
("a) b) c)", "lowerLetter"),
("i. ii. iii.", "lowerRoman"),
] {
MenuItem::command(CommandRef::with_params("para.numbering", json!({"kind": k}))).label(tl!(l).to_string()).show(ui);
}
Divider::horizontal().show(ui);
MenuItem::command(CommandRef::new("para.restartNumbering")).label(tl!("Restart at 1").to_string()).show(ui);
MenuItem::command(CommandRef::with_params("para.numbering", json!({"off": true})))
.label(tl!("None").to_string())
.show(ui);
})),
)
.icon(IconId::new("numbering"))
.selected(lists.numbering)
.tooltip(tl!("Numbering").to_string())
.show(ui);
SplitButton::<String>::command(
CommandRef::with_params("para.multilevel", json!({})),
SplitMenu::Body(Box::new(|ui, _| {
for (l, k) in [("1. 1.1. 1.1.1.", "legal"), ("I. A. 1. a.", "outline")] {
MenuItem::command(CommandRef::with_params("para.multilevel", json!({"kind": k}))).label(tl!(l).to_string()).show(ui);
}
Divider::horizontal().show(ui);
// Lists linked to the heading styles: the headings carry the numbers. Each item
// reads as its first three levels, number then (translated) style name.
for (numbers, k) in [
(["1", "1.1", "1.1.1"], "headings"),
(["Article I.", "Section 1.01", "(a)"], "article"),
(["I.", "A.", "1."], "outlineHeadings"),
(["Chapter 1", "", ""], "chapter"),
] {
let text = numbers
.iter()
.zip(["Heading 1", "Heading 2", "Heading 3"])
.map(|(n, h)| if n.is_empty() { tl!(h).to_string() } else { format!("{} {}", tl!(n), tl!(h)) })
.collect::<Vec<_>>()
.join(" / ");
MenuItem::command(CommandRef::with_params("list.multilevelPreset", json!({"preset": k}))).label(text).show(ui);
}
Divider::horizontal().show(ui);
MenuItem::command(CommandRef::new("list.define")).label(tl!("Define New Multilevel List…").to_string()).show(ui);
Divider::horizontal().show(ui);
for lv in 0..5u64 {
MenuItem::command(CommandRef::with_params("para.listLevel", json!({"level": lv})))
.label(format!("Change to Level {}", lv + 1))
.show(ui);
}
})),
)
.icon(IconId::new("multilevel"))
.selected(lists.multilevel)
.tooltip(tl!("Multilevel List").to_string())
.show(ui);
for (icon, tip, id) in
[("outdent", "Decrease Indent", "para.outdent"), ("indent", "Increase Indent", "para.indent"), ("sort", "Sort", "para.sort")]
{
IconButton::command(crate::icons::id(icon), CommandRef::new(id))
.label(tl!(tip).to_string())
.tooltip(tl!(tip).to_string())
.show(ui);
}
ToggleButton::command(CommandRef::new("view.marks"))
.icon(IconId::new("wordcraft.pilcrow"))
.icon_only()
.selected(marks)
.tooltip(tl!("Show/Hide ¶").to_string())
.show(ui);
});
Row::new().gap(Gap::None).show(ui, |ui, _| {
for (icon, tip, id, on) in [
("alignLeft", "Align Left", "para.alignLeft", align == Align::Left),
("alignCenter", "Center", "para.alignCenter", align == Align::Center),
("alignRight", "Align Right", "para.alignRight", align == Align::Right),
("justify", "Justify", "para.justify", align == Align::Justify),
("textLtr", "Left-to-Right Text Direction", "para.ltr", !rtl),
("textRtl", "Right-to-Left Text Direction", "para.rtl", rtl),
] {
ToggleButton::command(CommandRef::new(id))
.icon(crate::icons::id(icon))
.icon_only()
.selected(on)
.tooltip(tl!(tip).to_string())
.show(ui);
}
let face = Button::new(tl!("Line and Paragraph Spacing").to_string())
.icon(IconId::new("lineSpacing"))
.tooltip(tl!("Line and Paragraph Spacing").to_string());
menu_button(ui, face, tl!("Line and Paragraph Spacing").to_string(), Some("para.lineSpacing"), |ui, _| {
for v in [1.0, 1.15, 1.5, 2.0, 2.5, 3.0] {
MenuItem::command(CommandRef::with_params("para.lineSpacing", json!({"value": v}))).label(format!("{v}")).show(ui);
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
Row::new().gap(Gap::None).show(ui, |ui, _| {
SplitButton::<String>::command(
CommandRef::with_params("para.bullets", json!({})),
SplitMenu::Body(Box::new(|ui, cx| bullets_menu(ui, cx, app))),
)
.icon(IconId::new("bullets"))
.selected(lists.bullets)
.tooltip(tl!("Bullets").to_string())
.show(ui);
SplitButton::<String>::command(
CommandRef::with_params("para.numbering", json!({})),
SplitMenu::Body(Box::new(|ui, _| {
for (l, k) in [
("1. 2. 3.", "numbered"),
("1) 2) 3)", "numberedParen"),
("I. II. III.", "outline"),
("A. B. C.", "upperLetter"),
("a) b) c)", "lowerLetter"),
("i. ii. iii.", "lowerRoman"),
] {
MenuItem::command(CommandRef::with_params("para.numbering", json!({"kind": k}))).label(tl!(l).to_string()).show(ui);
}
Divider::horizontal().show(ui);
for (label, id) in [
("Add Space Before Paragraph", "para.addSpaceBefore"),
("Remove Space After Paragraph", "para.removeSpaceAfter"),
("Line Spacing Options…", "para.dialog"),
] {
MenuItem::command(CommandRef::new(id)).label(tl!(label).to_string()).show(ui);
MenuItem::command(CommandRef::new("para.restartNumbering")).label(tl!("Restart at 1").to_string()).show(ui);
MenuItem::command(CommandRef::with_params("para.numbering", json!({"off": true}))).label(tl!("None").to_string()).show(ui);
})),
)
.icon(IconId::new("numbering"))
.selected(lists.numbering)
.tooltip(tl!("Numbering").to_string())
.show(ui);
SplitButton::<String>::command(
CommandRef::with_params("para.multilevel", json!({})),
SplitMenu::Body(Box::new(|ui, _| {
for (l, k) in [("1. 1.1. 1.1.1.", "legal"), ("I. A. 1. a.", "outline")] {
MenuItem::command(CommandRef::with_params("para.multilevel", json!({"kind": k}))).label(tl!(l).to_string()).show(ui);
}
});
crate::colors::shading_split(ui, app, tl!("Shading"), Target::cmd("para.shading").remember(Remember::Shading));
SplitButton::<String>::command(
CommandRef::with_params("para.borders", json!({"kind": "bottom"})),
SplitMenu::Body(Box::new(|ui, _| {
for (l, k) in [
("Bottom Border", "bottom"),
("Top Border", "top"),
("Left Border", "left"),
("Right Border", "right"),
("No Border", "none"),
("All Borders", "all"),
("Outside Borders", "outside"),
("Inside Borders", "inside"),
] {
MenuItem::command(CommandRef::with_params("para.borders", json!({"kind": k}))).label(tl!(l).to_string()).show(ui);
}
Divider::horizontal().show(ui);
MenuItem::command(CommandRef::new("insert.horizontalLine")).label(tl!("Horizontal Line").to_string()).show(ui);
MenuItem::command(CommandRef::new("para.borders")).label(tl!("Borders and Shading…").to_string()).show(ui);
})),
)
.icon(IconId::new("borders"))
.tooltip(tl!("Borders").to_string())
Divider::horizontal().show(ui);
// Lists linked to the heading styles: the headings carry the numbers. Each item
// reads as its first three levels, number then (translated) style name.
for (numbers, k) in [
(["1", "1.1", "1.1.1"], "headings"),
(["Article I.", "Section 1.01", "(a)"], "article"),
(["I.", "A.", "1."], "outlineHeadings"),
(["Chapter 1", "", ""], "chapter"),
] {
let text = numbers
.iter()
.zip(["Heading 1", "Heading 2", "Heading 3"])
.map(|(n, h)| if n.is_empty() { tl!(h).to_string() } else { format!("{} {}", tl!(n), tl!(h)) })
.collect::<Vec<_>>()
.join(" / ");
MenuItem::command(CommandRef::with_params("list.multilevelPreset", json!({"preset": k}))).label(text).show(ui);
}
Divider::horizontal().show(ui);
MenuItem::command(CommandRef::new("list.define")).label(tl!("Define New Multilevel List…").to_string()).show(ui);
Divider::horizontal().show(ui);
for lv in 0..5u64 {
MenuItem::command(CommandRef::with_params("para.listLevel", json!({"level": lv})))
.label(format!("Change to Level {}", lv + 1))
.show(ui);
}
})),
)
.icon(IconId::new("multilevel"))
.selected(lists.multilevel)
.tooltip(tl!("Multilevel List").to_string())
.show(ui);
for (icon, tip, id) in
[("outdent", "Decrease Indent", "para.outdent"), ("indent", "Increase Indent", "para.indent"), ("sort", "Sort", "para.sort")]
{
IconButton::command(crate::icons::id(icon), CommandRef::new(id))
.label(tl!(tip).to_string())
.tooltip(tl!(tip).to_string())
.show(ui);
}
ToggleButton::command(CommandRef::new("view.marks"))
.icon(IconId::new("wordcraft.pilcrow"))
.icon_only()
.selected(marks)
.tooltip(tl!("Show/Hide ¶").to_string())
.show(ui);
});
Row::new().gap(Gap::None).show(ui, |ui, _| {
for (icon, tip, id, on) in [
("alignLeft", "Align Left", "para.alignLeft", align == Align::Left),
("alignCenter", "Center", "para.alignCenter", align == Align::Center),
("alignRight", "Align Right", "para.alignRight", align == Align::Right),
("justify", "Justify", "para.justify", align == Align::Justify),
("textLtr", "Left-to-Right Text Direction", "para.ltr", !rtl),
("textRtl", "Right-to-Left Text Direction", "para.rtl", rtl),
] {
ToggleButton::command(CommandRef::new(id))
.icon(crate::icons::id(icon))
.icon_only()
.selected(on)
.tooltip(tl!(tip).to_string())
.show(ui);
}
let face = Button::new(tl!("Line and Paragraph Spacing").to_string())
.icon(IconId::new("lineSpacing"))
.tooltip(tl!("Line and Paragraph Spacing").to_string());
menu_button(ui, face, tl!("Line and Paragraph Spacing").to_string(), Some("para.lineSpacing"), |ui, _| {
for v in [1.0, 1.15, 1.5, 2.0, 2.5, 3.0] {
MenuItem::command(CommandRef::with_params("para.lineSpacing", json!({"value": v}))).label(format!("{v}")).show(ui);
}
Divider::horizontal().show(ui);
for (label, id) in [
("Add Space Before Paragraph", "para.addSpaceBefore"),
("Remove Space After Paragraph", "para.removeSpaceAfter"),
("Line Spacing Options…", "para.dialog"),
] {
MenuItem::command(CommandRef::new(id)).label(tl!(label).to_string()).show(ui);
}
});
crate::colors::shading_split(ui, app, tl!("Shading"), Target::cmd("para.shading").remember(Remember::Shading));
SplitButton::<String>::command(
CommandRef::with_params("para.borders", json!({"kind": "bottom"})),
SplitMenu::Body(Box::new(|ui, _| {
for (l, k) in [
("Bottom Border", "bottom"),
("Top Border", "top"),
("Left Border", "left"),
("Right Border", "right"),
("No Border", "none"),
("All Borders", "all"),
("Outside Borders", "outside"),
("Inside Borders", "inside"),
] {
MenuItem::command(CommandRef::with_params("para.borders", json!({"kind": k}))).label(tl!(l).to_string()).show(ui);
}
Divider::horizontal().show(ui);
MenuItem::command(CommandRef::new("insert.horizontalLine")).label(tl!("Horizontal Line").to_string()).show(ui);
MenuItem::command(CommandRef::new("para.borders")).label(tl!("Borders and Shading…").to_string()).show(ui);
})),
)
.icon(IconId::new("borders"))
.tooltip(tl!("Borders").to_string())
.show(ui);
});
});
});
-43
View File
@@ -728,46 +728,3 @@ fn table_shading_split_keeps_palette_and_apply_separate() {
h.state_mut().run("edit.undo", json!({})).unwrap();
assert_eq!(first_cell_shading(h.state()), Some(red), "No Color is undone in one step");
}
/// #7308: the compact menu and split buttons of Home › Font and Home › Paragraph show their icons
/// alone (keeping their names for access and tooltips) even in a wide window, leaving room for all
/// six tiles of the Styles gallery at 1920 pt.
#[test]
fn home_font_and_paragraph_buttons_stay_icon_only_and_styles_shows_six_tiles() {
use egui::accesskit::Role;
let button_width = |h: &Harness, name: &str| {
h.query_all(By::new().role(Role::Button).label(name)).next().unwrap_or_else(|| panic!("a button named {name}")).rect().width()
};
// Wide enough that the ribbon keeps every group at GroupLevel::Full: without `icon_only`, both
// Font and Paragraph render their full text labels, making longer names much wider than shorter
// ones and wider than text-labelled buttons like Replace.
let app = WordApp::new(Session::new(wordcraft_doc::Document::from_text("Text")), crate::Services::default());
let wide = tab_harness(app, "Home");
let replace_w = button_width(&wide, "Replace");
let menu_buttons = ["Change Case", "Text Effects and Typography", "Line and Paragraph Spacing"];
let menu_widths: Vec<(&str, f32)> = menu_buttons.iter().map(|&n| (n, button_width(&wide, n))).collect();
let base_menu_w = menu_widths[0].1;
for &(name, w) in &menu_widths {
assert!((w - base_menu_w).abs() < 1.0, "{name} ({w:.1} pt) differs from icon-only menu width ({base_menu_w:.1} pt): {menu_widths:?}");
assert!(w < replace_w, "{name} ({w:.1} pt) should be narrower than a labelled button like Replace ({replace_w:.1} pt)");
}
let split_buttons = ["Underline", "Text Highlight Color", "Font Color", "Bullets", "Numbering", "Multilevel List", "Shading", "Borders"];
let split_widths: Vec<(&str, f32)> = split_buttons.iter().map(|&n| (n, button_width(&wide, n))).collect();
let base_split_w = split_widths[0].1;
for &(name, w) in &split_widths {
assert!((w - base_split_w).abs() < 1.0, "{name} ({w:.1} pt) differs from icon-only split width ({base_split_w:.1} pt): {split_widths:?}");
assert!(w < replace_w, "{name} ({w:.1} pt) should be narrower than a labelled button like Replace ({replace_w:.1} pt)");
}
// At 1920 pt, Font no longer starves the Styles gallery: all six default quick styles show.
let app = WordApp::new(Session::new(wordcraft_engine::sample::sample_document()), crate::Services::default());
let full_hd = app_harness(app, vec2(1920.0, 900.0));
let shown = |name: &str| full_hd.query_all(By::new().label(name)).next().is_some();
for style in ["Normal", "No Spacing", "Heading 1", "Title", "Heading 2", "Subtitle"] {
assert!(shown(style), "Home › Styles should show {style} at 1920 pt");
}
}
+2 -6
View File
File diff suppressed because one or more lines are too long
+5 -22
View File
File diff suppressed because one or more lines are too long