Merge main (c658b7a3) into the pull request

I resolved the one conflict, in crates/fonts/src/word.rs. SERIF and MONO

I resolved the one conflict, in crates/fonts/src/word.rs. SERIF and MONO stay at module level, as the pull request has them. Main's Cousine entry is added to MONO, and main's Arimo and Tinos ordering is kept in the Arial, Arial Unicode and Times lists. No conflict markers remain. cargo fmt --check passes, clippy passes for wordcraft-fonts and wordcraft-layout, and the wordcraft-fonts tests pass. The four wordcraft-layout tests that match missing_font pass, including the pull request's a_missing_font_is_drawn_in_its_font_table_alternate. I did not run the full wordcraft-layout suite this time.
This commit is contained in:
autocraft-bot[bot]
2026-12-05 21:57:55 +00:00
79 changed files with 3891 additions and 445 deletions
+5
View File
@@ -156,6 +156,11 @@ Ranked, to beta (detail and remaining milestones in [docs/roadmap.md](docs/roadm
## Progress log
- 2026-12-04: Windows: a document window can be maximized again, by its maximize button, Win+Up or a drag to the top of the screen, and View › Window › Full Screen fills the screen again (#8838, #8861). Since v0.20.0, where each document is a window of its own, the window was sent back to its normal place a few passes after the system maximized it, so it shook and stayed its normal size, and full screen slid it to the side. The fix is in craft-libs (storytold/craft-libs#5339): a window's own state, read with its place, keeps the normal place from being sent while it is maximized, full screen or minimized. Readiness estimates unchanged.
- 2026-11-21: Page text on the shared page view is sharp again. After the port, pages were rasterised at the view's own scale and rounded up to whole pixels, which left a picture a pixel or two larger than its place on screen (2017 × 2852 for 2016 × 2851); the shared painter fits a picture into its place, so it was squeezed by a twentieth of a percent and the text slid off the pixel grid and back down the page: a reporter's screenshot showed baselines spread over three pixel rows. Pictures are now made exactly as many pixels each way as the place the view last rested at, which the painter draws one pixel for one. A headless test through the real page view and picture store holds this at three zooms and two screen densities. Not yet seen in the running app. Readiness estimates unchanged.
- 2026-11-20: The sharper page text, subpixel (LCD) text and the Screen text smoothing option are ported onto the shared page view and Options that the UI port (#7101) brought. Two things changed on the way. The page view asks for page pictures rounded up to a multiple of 16 pixels and scales them into place, which resamples every glyph (A4 at 100 % on a 2x screen: 2256 pixels for 2245), so pages are now rasterised at the view's own scale wherever it accounts for the side asked for, and subpixel text is drawn only on such pictures. And the app no longer reads the system's text settings itself: system access moved to craft-libs' `platform::appearance`, which has none, so pages are drawn each platform's fixed way plus the user's own Screen text smoothing choice until craft-libs reports them (the 2026-11-19 entry on following the system no longer holds). Two shared-API gaps are recorded in `docs/ui-parity.md`: the text settings reader, and drawing a screen-scale page picture at its own pixel size. Run on macOS only; not seen in the running app since the port. Readiness estimates unchanged.
- 2026-11-19: Page text can be drawn with subpixel (LCD) antialiasing: File › Options › General › Screen text smoothing offers Use system setting, Grayscale and Subpixel (LCD); `view.textSmoothing` reaches the same setting headlessly. A page is rasterised three times with only its text a third of a pixel apart and each colour channel is taken from the pass that matches its stripe, so drawing order, coloured text, dark pages and rotated text need no special cases and nothing but text gets coloured edges. Once the system settings are read (nothing reads them yet), "Use system setting" will turn it on where the system asks for it (ClearType, or `rgba` antialiasing on a Linux desktop) on screens below 2x; macOS never asks, so there it is the user's choice. Exports are unchanged. Run on macOS only, on headless rasters: not yet seen on a 1x LCD, on Windows or on Linux, and not timed. Readiness estimates unchanged.
- 2026-11-19: Page drawing can take the system's text settings (darkening strength, hinting, subpixel order), but nothing reads them from the system yet, so pages are drawn each platform's fixed way and "Use system setting" is greyscale. Readiness estimates unchanged.
- 2026-11-19: Page text on macOS and Windows is no longer soft. Baselines sit on whole device pixels, so the feet of the letters fill one pixel row instead of greying two; and the macOS font smoothing we imitate thickens letters sideways only, by widening each outline and filling it once, where a stroke all round added a third of a pixel of grey above and below every letter. Found by comparing 144 dpi screenshots of the same paragraph in WordCraft, Preview and OpenOffice: none of the three used subpixel antialiasing; WordCraft alone had its serifs spread over two rows. Linux and BSD text was already hinted onto the grid; exports are unchanged. Readiness estimates unchanged.
- 2026-12-01: Hindi interface language (`hi`): File › Options › Interface language offers हिन्दी, and `hi`, `hi-IN` and `hi_IN.UTF-8` system locales pick it. The catalog is craft-i18n's `locales/hi/wordcraft.tsv` (`craft-i18n.rev` at 217f413); interface text is drawn by the embedded Noto Sans Devanagari face. No Hindi proofing, so the Hindi interface doesn't set the language of new documents. Readiness estimates unchanged.
- 2026-11-28: Layout indexes numbering definitions for each list and STYLEREF walk. List labels still follow the document's literal labels, start overrides and nested restart rules (#3615).
+1
View File
@@ -16,6 +16,7 @@ workspace = true
[dependencies]
wordcraft-doc = { workspace = true }
wordcraft-engine = { workspace = true }
wordcraft-fonts = { workspace = true }
wordcraft-render = { workspace = true }
wordcraft-mcp = { workspace = true }
wordcraft-zotero = { workspace = true }
+17
View File
@@ -616,6 +616,10 @@ fn run_convert(rest: &[String], open: impl Fn(&str, Option<&str>) -> Result<Sess
}
let password = password_from(rest)?;
let mut s = open(&i, password.as_deref())?;
// A refused strict export prints only its report, so its note waits for the export to succeed.
if !strict {
report_missing_metric_fonts();
}
if rest.iter().any(|a| a == "--update-fields") {
update_fields(&mut s)?;
}
@@ -631,6 +635,9 @@ fn run_convert(rest: &[String], open: impl Fn(&str, Option<&str>) -> Result<Sess
if let Err(e) = r {
return Err(if strict { refusal(&mut s, e, markup, to_png.then_some(1)) } else { engine_error(e) });
}
if strict {
report_missing_metric_fonts();
}
// The confirmation is a result, so it goes to stdout with the others (#7070).
write_stdout(|w| writeln!(w, "wrote {o}"))
}
@@ -656,6 +663,16 @@ fn run_source_paths(rest: &[String], script: Option<&script::Script>) -> (Option
(from_file, from_template)
}
fn report_missing_metric_fonts() {
for (word, used) in wordcraft_fonts::word::missing_metric_fonts() {
use std::io::Write as _;
let _ = writeln!(
std::io::stderr().lock(),
"note: {word} and its metric-compatible twins aren't installed; the primary family is {used}, so lines and pages may not match Word's; uncovered characters may use glyph fallback"
);
}
}
/// Show a successful command's result, or its warning when results aren't printed.
fn report_run_result(id: &str, result: &Value, print: bool) -> Result<(), Failure> {
if print {
@@ -68,14 +68,3 @@ fn run_keeps_saving_after_stdout_closes() {
}
let _ = std::fs::remove_dir_all(&d);
}
/// The helper starts from a clean directory, so a file left by an earlier failed run cannot
/// satisfy a later run's existence checks.
#[test]
fn dir_resets_leftover_state() {
let d = dir("leftover");
std::fs::write(d.join("second.png"), b"stale").unwrap();
let d = dir("leftover");
assert!(!d.join("second.png").exists(), "a stale second.png survived dir()");
let _ = std::fs::remove_dir_all(&d);
}
+8 -2
View File
@@ -813,8 +813,14 @@ impl Document {
/// Repair every paragraph's runs (see [`Paragraph::normalize`]); for models from untrusted
/// JSON, whose run lengths may overflow, fall short or split a character.
pub fn normalize_runs(&mut self) {
let mut stories: Vec<&mut Blocks> = vec![&mut self.body];
stories.extend(self.parts.values_mut().map(|p| &mut p.blocks));
let separators = [&mut self.footnote_separators, &mut self.endnote_separators]
.into_iter()
.flat_map(|s| [&mut s.separator, &mut s.continuation_separator, &mut s.continuation_notice])
.flatten();
let stories = std::iter::once(&mut self.body)
.chain(self.parts.values_mut().map(|part| &mut part.blocks))
.chain(separators)
.chain(self.glossary.iter_mut().map(|entry| &mut entry.blocks));
for blocks in stories {
for b in blocks.iter_mut() {
edit::each_para_mut(Arc::make_mut(b), 0, &mut |p: &mut Paragraph| {
+19
View File
@@ -959,6 +959,25 @@ fn normalize_runs_reconciles_objects_with_markers() {
// Deleting the first marker keeps B on the second.
p.delete(1, 4).unwrap();
assert_eq!(p.objects, vec![fs("B")]);
let mut d = build();
let p = d.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
p.objects.push(fs("Surplus"));
p.runs[0].len = 1;
d.footnote_separators.continuation_notice = Some(d.body.clone());
d.endnote_separators.separator = Some(d.body.clone());
d.glossary.push(BuildingBlock { name: "Quick Parts example".into(), blocks: d.body.clone(), ..Default::default() });
d.normalize_runs();
for (name, blocks) in [
("footnote continuation notice", d.footnote_separators.continuation_notice.as_ref().unwrap()),
("endnote separator", d.endnote_separators.separator.as_ref().unwrap()),
("Quick Parts entry", &d.glossary[0].blocks),
] {
edit::each_para(&blocks[0], 0, &mut |p| {
assert_eq!(p.objects, vec![fs("A"), fs("B")], "{name} drops the surplus object");
assert_eq!(p.runs.iter().map(|r| r.len).sum::<usize>(), p.text.len(), "{name} repairs its runs");
});
}
// The cost is linear: the markers and runs `reconcile_objects` walks (`crate::work`), not a
// timing. 8x the unmatched markers cost about 8x the steps, far more if each removal rescans.
let reconcile = |extra: usize| {
+10 -5
View File
@@ -861,14 +861,19 @@ fn replace_all(s: &mut Session, v: &Value) -> CmdResult {
}
let n: usize = found.iter().map(Vec::len).sum();
let saved_sel = s.sel.clone();
let orig_story_matched = found.iter().any(|r| r[0].a.story == saved_sel.focus.story);
// The main text comes last, so under Track Changes the caret ends where it did before;
// when the original story had no match, restore the selection so it stays there.
let orig_story = saved_sel.focus.story;
let mut orig_story_sel = None;
// The main text comes last, so under Track Changes keep the selection from the caret's own
// story (or restore the saved selection if that story had no match, #9063 / #9186).
for results in found.into_iter().rev() {
let is_orig = results[0].a.story == orig_story;
replace_found(s, results)?;
if s.doc.settings.track_changes && is_orig {
orig_story_sel = Some(s.sel.clone());
}
}
if s.doc.settings.track_changes && !orig_story_matched {
s.sel = saved_sel;
if s.doc.settings.track_changes {
s.sel = orig_story_sel.unwrap_or(saved_sel);
}
s.status = format!("All done. We made {n} replacements.");
Ok(json!({"replaced": n}))
+8 -6
View File
@@ -956,14 +956,16 @@ pub fn state(s: &Session) -> Value {
(*cached_state(s)).clone()
}
/// The common East Asian family shown by the font controls. If a slot has no face, keep
/// showing the named font. Resolve each theme slot once even for a selection with many runs.
/// The common East Asian family shown by the font controls. A theme slot without a face uses
/// the run's ordinary font, as layout does. Resolve each theme slot once per selection.
fn selection_east_asian_font<'a>(doc: &'a Document, runs: &'a [ResolvedChar]) -> Option<&'a str> {
let mut themes = HashMap::new();
let mut fonts = runs.iter().map(|run| {
run.font_ea_theme
.and_then(|slot| *themes.entry(slot).or_insert_with(|| wordcraft_layout::para::east_asian_font(doc, run)))
.or(run.font_ea.as_deref())
let mut fonts = runs.iter().map(|run| match run.font_ea_theme {
Some(slot) => {
let face = *themes.entry(slot).or_insert_with(|| wordcraft_layout::para::east_asian_font(doc, run));
Some(face.unwrap_or(&run.font))
}
None => run.font_ea.as_deref(),
});
let first = fonts.next().flatten()?;
fonts.all(|font| font == Some(first)).then_some(first)
+3 -1
View File
@@ -33,7 +33,9 @@ pub(crate) use select::select_object;
pub(crate) use select::{edit_obj, has_shape_or_canvas};
#[cfg(test)]
use select::{has_group, holds_ink, obj_size, with_obj};
pub use select::{min_size, object_selection, picked_objects, selected, selected_all, selected_or_text_box, target_objects};
pub use select::{
has_picture_format_target, min_size, object_selection, picked_objects, selected, selected_all, selected_or_text_box, target_objects,
};
#[cfg(test)]
use shape::can_link;
pub(crate) use shape::set_text_body;
+2 -2
View File
@@ -1,4 +1,4 @@
use super::select::{edit_obj, is_shape_or_canvas, obj_size, select_object, selected, target_objects, with_obj};
use super::select::{edit_obj, has_picture, is_shape_or_canvas, obj_size, select_object, selected, target_objects, with_obj};
use super::{CmdError, CmdResult, InlineObject, Pos, Rgb, Session, Value, Wrap, json, p};
use wordcraft_doc::picfx::PicFx;
@@ -190,7 +190,7 @@ pub fn fit_size(w: f32, h: f32, keep: bool) -> (f32, f32) {
/// Ctrl+click, #8832), one undo step. The selection is as it was afterwards.
pub(super) fn each_picture(s: &mut Session, run: impl Fn(&mut Session) -> CmdResult) -> CmdResult {
let picks = target_objects(s, |o| matches!(o, InlineObject::Image { .. }));
if picks.len() < 2 {
if picks.is_empty() || (picks.len() == 1 && has_picture(s).is_none()) {
return run(s);
}
let (sel, also) = (s.sel.clone(), s.also_selected.clone());
+10
View File
@@ -7,6 +7,16 @@ pub(super) fn has_picture(s: &Session) -> Option<&'static str> {
}
}
/// Whether commands that already format multiple pictures have a target. A secondary
/// picture counts when objects were explicitly picked, even if the primary object is a shape.
pub fn has_picture_format_target(s: &Session) -> bool {
has_picture(s).is_none() || (!s.also_selected.is_empty() && !target_objects(s, |o| matches!(o, InlineObject::Image { .. })).is_empty())
}
pub(super) fn has_any_picture(s: &Session) -> Option<&'static str> {
(!has_picture_format_target(s)).then_some("select a picture first")
}
/// Guard returning `None` when a picture, shape, or active text box is selected.
pub(super) fn has_object(s: &Session) -> Option<&'static str> {
if selected_or_text_box(s).is_some() { None } else { Some("select a picture or shape first") }
+13 -13
View File
@@ -4,9 +4,9 @@ use super::picture::{
adjust, adjust_media, clear_lum, crop, each_picture, original_media, recolor, relook, remove_background, reset, shape_size, size,
};
use super::select::{
all_objects, alt_text, can_group, edit_obj, has_any_movable, has_any_shape, has_floating, has_group, has_movable, has_object, has_picture,
has_placeable, has_shape, has_shape_or_canvas, has_sizable, is_shape_or_canvas, obj_size, objects_list, selected_or_text_box, target_objects,
with_float, with_floats_matching, with_movable_floats, with_obj,
all_objects, alt_text, can_group, edit_obj, has_any_movable, has_any_picture, has_any_shape, has_floating, has_group, has_movable, has_object,
has_picture, has_placeable, has_shape, has_shape_or_canvas, has_sizable, is_shape_or_canvas, obj_size, objects_list, selected_or_text_box,
target_objects, with_float, with_floats_matching, with_movable_floats, with_obj,
};
use super::shape::{NO_TEXT_BOX, can_link, has_text_box, link_text_box, set_text_body, shape_effects, text_box_target};
use super::{CmdError, CommandSpec, InlineObject, Pos, Rgb, Selection, Spin, TextVert, VAlign, Wrap, WrapText, json, p, sel_result};
@@ -87,7 +87,7 @@ pub fn specs() -> Vec<CommandSpec> {
})
})
.params(r#"{"brightness"?: -100..100, "contrast"?: -100..100, "sharpen"?: -100..100}"#)
.when(has_picture),
.when(has_any_picture),
CommandSpec::new("picture.color", "Color", "Picture Format › Adjust", |s, v| {
each_picture(s, |s| {
let mode = p::str(v, "mode").unwrap_or("grayscale").to_string();
@@ -101,7 +101,7 @@ pub fn specs() -> Vec<CommandSpec> {
})
})
.params(r#"{"mode": "grayscale|sepia|washout|blackAndWhite|saturation|tint", "saturation"?: 0..400}"#)
.when(has_picture),
.when(has_any_picture),
CommandSpec::new("picture.iconColor", "Icon Color", "Picture Format › Adjust", |s, v| {
each_picture(s, |s| {
let c = p::str(v, "color").and_then(Rgb::parse).ok_or_else(|| CmdError::Params("`color` (RRGGBB) is required".into()))?;
@@ -117,7 +117,7 @@ pub fn specs() -> Vec<CommandSpec> {
})
})
.params(r#"{"color": "RRGGBB"}"#)
.when(has_picture),
.when(has_any_picture),
CommandSpec::new("picture.effects", "Artistic Effects", "Picture Format › Adjust", |s, v| {
each_picture(s, |s| {
// One effect at a time, as in Word: a second one replaces the first (#2052).
@@ -126,7 +126,7 @@ pub fn specs() -> Vec<CommandSpec> {
})
})
.params(r#"{"effect": "blur|sharpen|invert|posterize|pixelate|none"} (replaces the picture's effect)"#)
.when(has_picture),
.when(has_any_picture),
CommandSpec::new("picture.transparency", "Transparency", "Picture Format › Adjust", |s, v| {
each_picture(s, |s| {
let t = p::f32(v, "percent").unwrap_or(50.0).clamp(0.0, 100.0);
@@ -148,7 +148,7 @@ pub fn specs() -> Vec<CommandSpec> {
})
})
.params(r#"{"percent": 0..100}"#)
.when(has_picture),
.when(has_any_picture),
CommandSpec::new("picture.removeBackground", "Remove Background", "Picture Format › Adjust", |s, v| {
each_picture(s, |s| {
let tol = p::f32(v, "tolerance").unwrap_or(30.0).clamp(0.0, 255.0);
@@ -156,7 +156,7 @@ pub fn specs() -> Vec<CommandSpec> {
})
})
.params(r#"{"tolerance"?: 0..255}"#)
.when(has_picture),
.when(has_any_picture),
CommandSpec::new("picture.compress", "Compress Pictures", "Picture Format › Adjust", |s, v| {
each_picture(s, |s| {
let max = p::u64(v, "maxPixels").unwrap_or(1600).clamp(32, 20000) as u32;
@@ -164,8 +164,8 @@ pub fn specs() -> Vec<CommandSpec> {
})
})
.params(r#"{"maxPixels"?: n}"#)
.when(has_picture),
CommandSpec::new("picture.reset", "Reset Picture", "Picture Format › Adjust", |s, v| each_picture(s, |s| reset(s, v))).when(has_picture),
.when(has_any_picture),
CommandSpec::new("picture.reset", "Reset Picture", "Picture Format › Adjust", |s, v| each_picture(s, |s| reset(s, v))).when(has_any_picture),
CommandSpec::new("picture.change", "Change Picture", "Picture Format › Adjust", |s, v| {
let bytes = if let Some(d) = p::str(v, "data") {
crate::cmd::insert::base64_decode(d).ok_or_else(|| CmdError::Params("bad base64".into()))?
@@ -210,7 +210,7 @@ pub fn specs() -> Vec<CommandSpec> {
})
})
.params(r#"{"style": "simpleFrame|thickFrame|rounded|softEdge|shadow"} (replaces the picture's style and border)"#)
.when(has_picture),
.when(has_any_picture),
CommandSpec::new("picture.border", "Picture Border", "Picture Format › Picture Styles", |s, v| {
each_picture(s, |s| {
let c = p::str(v, "color").and_then(Rgb::parse).unwrap_or(Rgb::BLACK);
@@ -220,7 +220,7 @@ pub fn specs() -> Vec<CommandSpec> {
})
})
.params(r#"{"color"?: "RRGGBB", "width"?: px} (replaces the picture's border)"#)
.when(has_picture),
.when(has_any_picture),
CommandSpec::new("arrange.rotate", "Rotate", "Layout › Arrange", |s, v| {
// Turns and flips are the object's angle and mirroring (DrawingML `a:xfrm`): the
// picture's pixels are never rewritten. A flip mirrors what is on the page, so a
+105
View File
@@ -432,6 +432,59 @@ fn two_inserted_pictures_in_a_row_are_both_kept() {
assert_eq!(s.run("arrange.selectionPane", &json!({})).unwrap().as_array().map(Vec::len), Some(2));
}
#[test]
fn picture_border_uses_picked_pictures_even_when_a_shape_is_primary() {
for (picked, expected) in
[(&[2, 0][..], [true, false]), (&[2, 0, 1][..], [true, true]), (&[0, 2, 1][..], [true, true]), (&[2][..], [false, false])]
{
let mut s = Session::new(wordcraft_doc::Document::new());
for w in [20, 24] {
let data = super::super::insert::base64_encode(&png(w, 10));
s.run("insert.picture", &json!({"data": data})).unwrap();
}
s.run("caret.docEnd", &json!({})).unwrap();
s.run("insert.shape", &json!({"kind": "rectangle"})).unwrap();
s.run("caret.docStart", &json!({})).unwrap();
for index in picked {
s.run("select.addObject", &json!({"index": index})).unwrap();
}
let selection = s.sel.clone();
let extras = s.also_selected.clone();
let undo = s.undo_depth();
let shape = |s: &Session| {
let (_, object) = all_objects(s).into_iter().find(|(_, o)| matches!(o, InlineObject::Shape { .. })).unwrap();
serde_json::to_value(object).unwrap()
};
let shape_before = shape(&s);
let borders = |s: &Session| {
all_objects(s)
.into_iter()
.filter_map(|(_, o)| match o {
InlineObject::Image { media, .. } => Some(s.picture_looks.get(&media).is_some_and(|l| l.border.is_some())),
_ => None,
})
.collect::<Vec<_>>()
};
let result = s.run("picture.border", &json!({"width": 3}));
if expected == [false, false] {
assert!(result.is_err(), "a shape alone cannot take a picture border");
assert_eq!(s.undo_depth(), undo);
} else {
result.unwrap();
assert_eq!(s.undo_depth(), undo + 1);
}
assert_eq!(s.sel, selection);
assert_eq!(s.also_selected, extras);
assert_eq!(shape(&s), shape_before);
assert_eq!(borders(&s), expected);
if expected != [false, false] {
s.run("edit.undo", &json!({})).unwrap();
assert_eq!(borders(&s), [false, false]);
assert_eq!(shape(&s), shape_before);
}
}
}
/// #8832: a picture command on several selected pictures changes each, in one undo step.
#[test]
fn picture_border_applies_to_every_selected_picture() {
@@ -2267,3 +2320,55 @@ fn shape_size_and_rotation_only_affect_shapes_in_mixed_selection() {
assert_eq!(objs2[1].1.frame().unwrap().0, 180.0);
assert_eq!(objs2[2].1.frame().unwrap().0, 180.0);
}
#[test]
fn picture_format_commands_stay_enabled_when_shape_is_selected_first() {
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("insert.shape", &json!({"kind": "rectangle", "width": 100.0, "height": 60.0})).unwrap();
let data = super::super::insert::base64_encode(&png(12, 12));
s.sel = Selection::caret(s.doc.end_of(StoryRef::Body));
s.run("insert.picture", &json!({"data": data})).unwrap();
s.sel = Selection::caret(s.doc.end_of(StoryRef::Body));
s.run("insert.picture", &json!({"data": data})).unwrap();
// Shape clicked first, then one picture added.
s.run("select.objects", &json!({"index": 0})).unwrap();
s.run("select.addObject", &json!({"index": 1})).unwrap();
s.run("picture.border", &json!({"color": "FF0000", "width": 3})).unwrap();
assert!(matches!(
&all_objects(&s)[1].1,
InlineObject::Image { media, .. } if s.picture_looks.get(media).is_some_and(|l| l.border.is_some())
));
// Shape clicked first, then two pictures added.
s.run("select.addObject", &json!({"index": 2})).unwrap();
s.run("picture.style", &json!({"style": "rounded"})).unwrap();
let objs = all_objects(&s);
for idx in [1, 2] {
assert!(
matches!(&objs[idx].1, InlineObject::Image { media, .. } if s.picture_looks.get(media).is_some_and(|l| l.style.as_deref() == Some("rounded"))),
"picture {idx} should get rounded style"
);
}
}
#[test]
fn single_object_picture_commands_need_the_picture_selected_first() {
let mut s = Session::new(wordcraft_doc::Document::new());
s.run("insert.shape", &json!({"kind": "rectangle", "width": 100.0, "height": 60.0})).unwrap();
let data = super::super::insert::base64_encode(&png(12, 12));
s.sel = Selection::caret(s.doc.end_of(StoryRef::Body));
s.run("insert.picture", &json!({"data": data})).unwrap();
// Shape clicked first, then the picture added: Crop, Change Picture and Alt Text would act on the shape.
s.run("select.objects", &json!({"index": 0})).unwrap();
s.run("select.addObject", &json!({"index": 1})).unwrap();
for (cmd, args) in [("picture.crop", json!({"left": 0.1})), ("picture.altText", json!({"text": "x"})), ("picture.change", json!({"data": data}))]
{
assert!(matches!(s.run(cmd, &args), Err(CmdError::Disabled(_))), "{cmd}");
}
// Picture first: enabled.
s.run("select.objects", &json!({"index": 1})).unwrap();
s.run("picture.crop", &json!({"left": 0.1})).unwrap();
}
+1 -1
View File
@@ -113,7 +113,7 @@ pub(super) fn outline_step(s: &mut Session, promote: bool) -> CmdResult {
// Outline view: the headings hidden under a collapsed heading move a level with it.
let carried = crate::cmd::outline::hidden_subheadings(s);
let (a, b) = s.sel.ordered();
let paths = s.doc.paths_between(&a, &b);
let paths = if s.cell_range().is_some_and(|range| !range.stream) { crate::cmd::selected_paths(s) } else { s.doc.paths_between(&a, &b) };
// The heading before the selection, for promoted body text.
let before = s
.doc
+153 -28
View File
@@ -187,38 +187,163 @@ pub(super) fn create_style(s: &mut Session, v: &Value) -> CmdResult {
Ok(json!({"id": id}))
}
/// Capture `T`'s serde struct field list so unknown keys in `v` are rejected instead of silently ignored (#9203).
/// Deserialize `T` from `v`, rejecting unknown fields on `T` and any nested structs (#9203, #9291).
fn deserialize_strict<T: serde::de::DeserializeOwned>(section: &str, v: &Value) -> Result<T, CmdError> {
struct ProbeDe<'a>(&'a mut Option<&'static [&'static str]>);
impl<'de> serde::Deserializer<'de> for ProbeDe<'_> {
type Error = serde::de::value::Error;
fn deserialize_struct<V: serde::de::Visitor<'de>>(
self,
_name: &'static str,
fields: &'static [&'static str],
_visitor: V,
) -> Result<V::Value, Self::Error> {
*self.0 = Some(fields);
Err(serde::de::Error::custom(""))
}
serde::forward_to_deserialize_any! {
bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes byte_buf
option unit unit_struct newtype_struct seq tuple tuple_struct map enum identifier ignored_any
}
fn deserialize_any<V: serde::de::Visitor<'de>>(self, _visitor: V) -> Result<V::Value, Self::Error> {
Err(serde::de::Error::custom(""))
}
}
let mut fields = None;
let _ = T::deserialize(ProbeDe(&mut fields));
if let (Some(fields), Some(map)) = (fields, v.as_object()) {
for key in map.keys() {
if !fields.contains(&key.as_str()) {
return Err(CmdError::Params(format!("unknown field `{key}` in `{section}`")));
use serde::de::{DeserializeSeed, EnumAccess, IntoDeserializer, MapAccess, SeqAccess, VariantAccess, Visitor};
struct StrictDe<'a>(&'a Value);
struct StrictSeq<'a>(std::slice::Iter<'a, Value>);
struct StrictMap<'a>(serde_json::map::Iter<'a>, Option<&'a Value>);
struct StrictEnum<'a>(&'a str, &'a Value);
// Internally tagged enums buffer their fields before decoding them, bypassing StrictMap.
fn validate_text_fill(fill: &Value) -> Result<(), serde_json::Error> {
let tag = fill.get("type").or_else(|| fill.get(0));
// Serde's numeric variant indices follow the TextFill declaration order.
let fields: &[_] = match (tag.and_then(Value::as_str), tag.and_then(Value::as_u64)) {
(Some("none"), _) | (_, Some(0)) => &["type"],
(Some("solid"), _) | (_, Some(1)) => &["type", "color", "transparency"],
(Some("gradient"), _) | (_, Some(2)) => &["type", "stops", "angle"],
_ => return Ok(()), // The regular decoder reports missing or unknown tags.
};
let stops = if let Some(map) = fill.as_object() {
if let Some(key) = map.keys().find(|key| !fields.contains(&key.as_str())) {
return Err(serde::de::Error::custom(format!("`textEffects.fill`: unknown field `{key}`")));
}
map.get("stops")
} else if fields.contains(&"stops") {
fill.get(1)
} else {
None
};
if let Some(stops) = stops.and_then(Value::as_array) {
for stop in stops {
<wordcraft_doc::wordart::GradStop as serde::Deserialize>::deserialize(StrictDe(stop))
.map_err(|e| serde::de::Error::custom(format!("`textEffects.fill.stops`: {e}")))?;
}
}
Ok(())
}
serde_json::from_value(v.clone()).map_err(|e| CmdError::Params(e.to_string()))
impl<'de> SeqAccess<'de> for StrictSeq<'_> {
type Error = serde_json::Error;
fn next_element_seed<S: DeserializeSeed<'de>>(&mut self, seed: S) -> Result<Option<S::Value>, Self::Error> {
self.0.next().map(|v| seed.deserialize(StrictDe(v))).transpose()
}
}
impl<'de> MapAccess<'de> for StrictMap<'_> {
type Error = serde_json::Error;
fn next_key_seed<K: DeserializeSeed<'de>>(&mut self, seed: K) -> Result<Option<K::Value>, Self::Error> {
let Some((k, v)) = self.0.next() else { return Ok(None) };
self.1 = Some(v);
seed.deserialize(k.as_str().into_deserializer()).map(Some)
}
fn next_value_seed<V: DeserializeSeed<'de>>(&mut self, seed: V) -> Result<V::Value, Self::Error> {
let v = self.1.take().ok_or_else(|| serde::de::Error::custom("missing map value"))?;
seed.deserialize(StrictDe(v))
}
}
impl<'de> VariantAccess<'de> for StrictEnum<'_> {
type Error = serde_json::Error;
fn unit_variant(self) -> Result<(), Self::Error> {
serde::Deserialize::deserialize(self.1)
}
fn newtype_variant_seed<T: DeserializeSeed<'de>>(self, seed: T) -> Result<T::Value, Self::Error> {
seed.deserialize(StrictDe(self.1))
}
fn tuple_variant<V: Visitor<'de>>(self, len: usize, visitor: V) -> Result<V::Value, Self::Error> {
serde::Deserializer::deserialize_tuple(StrictDe(self.1), len, visitor)
}
fn struct_variant<V: Visitor<'de>>(self, fields: &'static [&'static str], visitor: V) -> Result<V::Value, Self::Error> {
serde::Deserializer::deserialize_struct(StrictDe(self.1), "", fields, visitor)
}
}
impl<'de> EnumAccess<'de> for StrictEnum<'_> {
type Error = serde_json::Error;
type Variant = Self;
fn variant_seed<V: DeserializeSeed<'de>>(self, seed: V) -> Result<(V::Value, Self::Variant), Self::Error> {
let val = seed.deserialize(self.0.into_deserializer())?;
Ok((val, self))
}
}
impl<'de> serde::Deserializer<'de> for StrictDe<'_> {
type Error = serde_json::Error;
fn deserialize_any<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
match self.0 {
Value::Null => visitor.visit_unit(),
Value::Bool(b) => visitor.visit_bool(*b),
Value::Number(n) => n.deserialize_any(visitor),
Value::String(s) => visitor.visit_str(s),
Value::Array(arr) => visitor.visit_seq(StrictSeq(arr.iter())),
Value::Object(map) => visitor.visit_map(StrictMap(map.iter(), None)),
}
}
fn deserialize_option<V: Visitor<'de>>(self, visitor: V) -> Result<V::Value, Self::Error> {
if self.0.is_null() { visitor.visit_none() } else { visitor.visit_some(self) }
}
fn deserialize_newtype_struct<V: Visitor<'de>>(self, _name: &'static str, visitor: V) -> Result<V::Value, Self::Error> {
visitor.visit_newtype_struct(self)
}
fn deserialize_enum<V: Visitor<'de>>(
self,
_name: &'static str,
_variants: &'static [&'static str],
visitor: V,
) -> Result<V::Value, Self::Error> {
match self.0 {
Value::String(s) => visitor.visit_enum(s.as_str().into_deserializer()),
Value::Object(map) if map.len() == 1 => {
if let Some((k, v)) = map.iter().next() {
visitor.visit_enum(StrictEnum(k, v))
} else {
self.deserialize_any(visitor)
}
}
_ => self.deserialize_any(visitor),
}
}
fn deserialize_struct<V: Visitor<'de>>(
self,
name: &'static str,
fields: &'static [&'static str],
visitor: V,
) -> Result<V::Value, Self::Error> {
if name == "TextEffects" {
let fill = match self.0 {
Value::Array(values) => fields.iter().position(|&field| field == "fill").and_then(|index| values.get(index)),
_ => self.0.get("fill"),
};
if let Some(fill) = fill {
validate_text_fill(fill)?;
}
}
if let Value::Object(map) = self.0 {
for key in map.keys() {
if !fields.contains(&key.as_str()) {
return Err(serde::de::Error::custom(format!("unknown field `{key}`")));
}
}
return visitor.visit_map(StrictMap(map.iter(), None));
}
self.deserialize_any(visitor)
}
serde::forward_to_deserialize_any! {
bool i8 i16 i32 i64 i128 u8 u16 u32 u64 u128 f32 f64 char str string bytes byte_buf
unit unit_struct seq tuple tuple_struct map identifier ignored_any
}
}
T::deserialize(StrictDe(v)).map_err(|e| CmdError::Params(format!("`{section}`: {e}")))
}
/// Modify a style's character and paragraph formatting, display name or next-paragraph style.
+3 -2
View File
@@ -320,10 +320,11 @@ fn resolve_all(s: &mut Session, accept: bool) -> CmdResult {
let prefix_len = resolve_para(s, st, &path, (0, len), (true, true), accept)?;
if trailing && remove_trailing_para(s, st, &path)? {
// Selection ends in the removed paragraph go to the end of the one before it;
// clamping later would keep their offsets in that paragraph's text (#8500).
for end in [&mut s.sel.anchor, &mut s.sel.focus] {
// keep that offset through any later remapping when earlier edits resolve.
for (end, offset) in [&mut s.sel.anchor, &mut s.sel.focus].into_iter().zip(&mut offsets) {
if end.story == st && end.path == path {
*end = s.doc.clamp(&Pos { off: usize::MAX, ..end.clone() });
*offset = end.off;
}
}
}
+3 -3
View File
@@ -123,12 +123,12 @@ pub(super) fn insert(s: &mut Session, v: &Value) -> CmdResult {
s.push_undo("AutoFormat", doc, sel);
// Undo right after it makes the capitalised word an exception.
let depth = s.undo_steps_so_far();
if let Some(c) = s.autocap.as_mut().filter(|c| c.depth == u64::MAX) {
c.depth = depth;
if let Some(c) = s.autocap.as_mut() {
c.commit_depth(depth);
}
}
}
s.autocap.take_if(|c| c.depth == u64::MAX);
crate::cmd::tools::AutoCap::clear_uncommitted(&mut s.autocap);
s.set_ime_edit_outcome(outcome);
sel_result(s)
}
+2 -2
View File
@@ -145,7 +145,7 @@ fn enter(s: &mut Session, undo_step: bool) -> Result<(), CmdError> {
if let Some((doc, sel)) = plain {
// Removes the marks, then AutoCorrects the word as without them.
crate::cmd::tools::autocorrect_word(s, true)?;
s.autocap.take_if(|c| c.depth == u64::MAX);
crate::cmd::tools::AutoCap::clear_uncommitted(&mut s.autocap);
let (done_doc, done_sel) = (std::mem::replace(&mut s.doc, doc), std::mem::replace(&mut s.sel, sel));
let new = split_para(s, &at)?;
let c = s.doc.para_at(&new).map(|p| p.mark.clone()).unwrap_or_default();
@@ -165,7 +165,7 @@ fn enter(s: &mut Session, undo_step: bool) -> Result<(), CmdError> {
return Ok(());
}
crate::cmd::tools::autocorrect_word(s, true)?;
s.autocap.take_if(|c| c.depth == u64::MAX);
crate::cmd::tools::AutoCap::clear_uncommitted(&mut s.autocap);
at = s.sel.focus.clone();
}
let new = split_para(s, &at)?;
+66 -9
View File
@@ -268,6 +268,15 @@ fn plain_word(w: &str) -> bool {
!w.trim().is_empty() && w.chars().count() <= MAX_FROM && !w.contains(|c: char| c.is_whitespace() || c == '\u{FFFC}')
}
#[derive(Clone, Debug)]
pub(super) struct PronounCap {
depth: u64,
story: wordcraft_doc::StoryRef,
path: wordcraft_doc::Path,
start: usize,
backspaced: bool,
}
/// The newest automatic capitalisation (a sentence capital, a TWo INitial CApitals fix), kept so
/// that undoing it, or backspacing it and typing the word again, makes an exception (#1857).
#[derive(Clone, Debug)]
@@ -283,22 +292,62 @@ pub struct AutoCap {
pub(super) prev: String,
/// The TWo INitial CApitals word as typed ("TWo").
pub(super) two_caps: Option<String>,
/// The English replacement of lowercase i with uppercase I.
pub(super) pronoun_i: bool,
/// The English replacement of lowercase i with uppercase I, kept alongside an earlier sentence
/// capital so an automatic `I` does not wipe the pending first-letter exception.
pub(super) pronoun: Option<PronounCap>,
/// The user backspaced into the word after the change.
pub(super) backspaced: bool,
}
impl AutoCap {
pub(crate) fn commit_depth(&mut self, depth: u64) {
if self.depth == u64::MAX {
self.depth = depth;
}
if let Some(p) = self.pronoun.as_mut().filter(|p| p.depth == u64::MAX) {
p.depth = depth;
}
}
pub(crate) fn clear_uncommitted(slot: &mut Option<Self>) {
if let Some(c) = slot.as_mut() {
if c.pronoun.as_ref().is_some_and(|p| p.depth == u64::MAX) {
c.pronoun = None;
}
if c.depth == u64::MAX {
*slot = None;
}
}
}
pub(super) fn record_pronoun(slot: &mut Option<Self>, story: wordcraft_doc::StoryRef, path: wordcraft_doc::Path, start: usize) {
let pronoun = PronounCap { depth: u64::MAX, story, path: path.clone(), start, backspaced: false };
if let Some(c) = slot.as_mut().filter(|c| !c.prev.is_empty() || c.two_caps.is_some()) {
c.pronoun = Some(pronoun);
} else {
*slot =
Some(Self { depth: u64::MAX, story, path, start, prev: String::new(), two_caps: None, pronoun: Some(pronoun), backspaced: false });
}
}
pub(super) fn take_backspaced_pronoun(slot: &mut Option<Self>, english: bool, word: &str, f: &Pos, start: usize) -> bool {
let Some(c) = slot.as_mut() else { return false };
let Some(p) = c.pronoun.take() else { return false };
if c.prev.is_empty() && c.two_caps.is_none() {
*slot = None;
}
english && word == "i" && p.backspaced && p.story == f.story && p.path == f.path && p.start == start
}
/// The start of a just-corrected I when Backspace removes the separator after it.
pub(crate) fn pronoun_before_separator(&self, a: &Pos, f: &Pos, undo_steps: u64) -> Option<Pos> {
(self.pronoun_i
&& !self.backspaced
&& self.story == f.story
&& self.path == f.path
&& self.start.checked_add(1) == Some(a.off)
&& self.depth.checked_add(1) == Some(undo_steps))
.then(|| Pos { off: self.start, ..f.clone() })
let p = self.pronoun.as_ref()?;
(!p.backspaced
&& p.story == f.story
&& p.path == f.path
&& p.start.checked_add(1) == Some(a.off)
&& p.depth.checked_add(1) == Some(undo_steps))
.then(|| Pos { off: p.start, ..f.clone() })
}
pub(crate) fn add_exceptions(self, ac: &mut AutoCorrectPrefs) {
@@ -317,6 +366,14 @@ impl AutoCap {
if f.story == self.story && f.path == self.path && a.off <= self.start && f.off > self.start {
self.backspaced = true;
}
if let Some(p) = &mut self.pronoun
&& f.story == p.story
&& f.path == p.path
&& a.off <= p.start
&& f.off > p.start
{
p.backspaced = true;
}
}
}
+14 -13
View File
@@ -198,19 +198,20 @@ fn compare_terminal_deleted_paragraph_resolves_fully() {
#[test]
fn resolving_a_selected_terminal_paragraph_puts_the_caret_before_it() {
// A selection inside the terminal paragraph that Reject All (insertion) or Accept All
// (deletion) removes ends as a caret at the end of the paragraph before it, not over the
// same offsets of that paragraph's text (#8500).
let cases = [("A\nKeep this", "A\nKeep this\nNEW", "review.rejectAll"), ("A\nKeep this\nOLD", "A\nKeep this", "review.acceptAll")];
for (orig, revised, cmd) in cases {
let mut s = Session::new(Document::from_text(orig));
s.run("review.compare", &json!({"text": revised})).unwrap();
s.sel = Selection { anchor: Pos::body(2, 0), focus: Pos::body(2, 3) };
s.run(cmd, &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nKeep this", "{cmd}");
assert_eq!(s.sel, Selection::caret(Pos::body(1, "Keep this".len())), "{cmd}");
s.run("text.insert", &json!({"text": "Z"})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nKeep thisZ", "{cmd}");
let keep = "A\nKeep this";
// Both endpoints of the removed paragraph go to the preceding paragraph's end (#8500),
// even if removing another paragraph subsequently shifts that paragraph up (#8913).
for (changed, last) in [("A\nKeep this\nNEW", 2), ("A\nEarlier\nKeep this\nNEW", 3)] {
for (orig, revised, cmd) in [(keep, changed, "review.rejectAll"), (changed, keep, "review.acceptAll")] {
let mut s = Session::new(Document::from_text(orig));
s.run("review.compare", &json!({"text": revised})).unwrap();
s.run("select.range", &json!({"anchor": Pos::body(last, 0), "focus": Pos::body(last, 3)})).unwrap();
s.run(cmd, &json!({})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), keep, "{cmd}, last block {last}");
assert_eq!(s.sel, Selection::caret(Pos::body(1, "Keep this".len())), "{cmd}, last block {last}");
s.run("text.insert", &json!({"text": "Z"})).unwrap();
assert_eq!(s.doc.plain_text(StoryRef::Body), "A\nKeep thisZ", "{cmd}, last block {last}");
}
}
}
+4 -16
View File
@@ -74,7 +74,7 @@ pub fn autocorrect_word(s: &mut Session, on_enter: bool) -> Result<(), CmdError>
&& letters.chars().nth(1).is_some_and(char::is_uppercase)
&& letters.chars().next().is_some_and(char::is_uppercase))
.then(|| letters.clone()),
pronoun_i: false,
pronoun: None,
backspaced: false,
});
let fixed: String = reps.concat();
@@ -86,10 +86,7 @@ pub fn autocorrect_word(s: &mut Session, on_enter: bool) -> Result<(), CmdError>
// same way (#835); every English (en-GB, en-CA…) counts (#1281).
let english = s.doc.para_at(&f).is_none_or(|_| wordcraft_proof::ProofLang::from_tag(lang.as_deref()).is_english());
// A rejected pronoun is kept at this occurrence only, including at the start of a sentence.
let keep_i = s
.autocap
.take_if(|c| c.pronoun_i)
.is_some_and(|c| english && word == "i" && c.backspaced && c.story == f.story && c.path == f.path && c.start == start);
let keep_i = AutoCap::take_backspaced_pronoun(&mut s.autocap, english, &word, &f, start);
let found = if ac.replace_text && !keep_i { ac.replacement_in(&word, english) } else { None };
let (from, rep) = match found {
Some(r) => (start, Some(r)),
@@ -113,16 +110,7 @@ pub fn autocorrect_word(s: &mut Session, on_enter: bool) -> Result<(), CmdError>
caret = (f.off + rep.len()).saturating_sub(end - from);
s.sel = Selection::caret(Pos { off: caret, ..f.clone() });
if english && word == "i" && rep == "I" {
s.autocap = Some(AutoCap {
depth: u64::MAX,
story: f.story,
path: f.path.clone(),
start,
prev: String::new(),
two_caps: None,
pronoun_i: true,
backspaced: false,
});
AutoCap::record_pronoun(&mut s.autocap, f.story, f.path.clone(), start);
}
}
let end = caret.saturating_sub(trigger);
@@ -198,7 +186,7 @@ pub fn autocorrect_word(s: &mut Session, on_enter: bool) -> Result<(), CmdError>
start,
prev,
two_caps: None,
pronoun_i: false,
pronoun: None,
backspaced: false,
});
}
+38
View File
@@ -52,6 +52,15 @@ pub fn specs() -> Vec<CommandSpec> {
}
Ok(json!({"paperColor": color}))
}).params(r#"{"value": "document" | "green" | "cream" | "gray"}"#).pure(),
// How the edges of page text are smoothed on screen. Screen only; never in the document.
CommandSpec::new("view.textSmoothing", "Screen Text Smoothing", "View › Display", |s, v| {
let smoothing: TextSmoothing = serde_json::from_value(v.get("value").cloned().unwrap_or(Value::Null))
.map_err(|_| CmdError::Params("screen text smoothing must be system, grayscale, or subpixel".into()))?;
s.prefs.text_smoothing = smoothing;
Ok(json!({"textSmoothing": smoothing}))
})
.params(r#"{"value": "system" | "grayscale" | "subpixel"}"#)
.pure(),
// Print Layout: hide the white space (margins, headers, footers) between pages. Screen only.
CommandSpec::new("view.hideWhiteSpace", "Hide White Space", "View › Show", |s, v| toggle(s, v, |x| &mut x.hide_white_space))
.params(r#"{"value"?: bool}"#)
@@ -349,6 +358,35 @@ fn read_line_spacing(s: &mut Session, v: &Value) -> CmdResult {
Ok(json!({"spacing": spacing}))
}
/// How the edges of page text are smoothed on screen, saved with user preferences, never in the
/// document. Exports, prints and PDFs are not affected.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
pub enum TextSmoothing {
/// As the system is set: subpixel where it asks for it (ClearType on Windows, `rgba`
/// antialiasing on a Linux desktop) and the screen is not a high-density one, else
/// greyscale. macOS never asks for it.
#[default]
System,
/// Greyscale antialiasing: grey edges, no colour.
Grayscale,
/// Subpixel (LCD) antialiasing, whatever the system says: edges three times as fine
/// sideways, with faint colour in them. In the system's stripe order, RGB when it gives none.
Subpixel,
}
impl TextSmoothing {
pub const ALL: [Self; 3] = [Self::System, Self::Grayscale, Self::Subpixel];
pub fn label(self) -> &'static str {
match self {
Self::System => "Use system setting",
Self::Grayscale => "Grayscale",
Self::Subpixel => "Subpixel (LCD)",
}
}
}
/// Screen-only paper presets, saved with user preferences, never in the document.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "camelCase")]
+22 -5
View File
@@ -229,11 +229,16 @@ fn resolve_entry(path: &str) -> Result<PathBuf, String> {
let (Some(folder), Some(name)) = (absolute.parent(), absolute.file_name()) else {
return Err(format!("automation path rejected: not a file name: {path}"));
};
let mut entry = resolve_absolute(path, folder)?;
entry.push(name);
if std::fs::symlink_metadata(&entry).is_ok_and(|m| !m.file_type().is_symlink()) {
// Without its real path the name stays as given, which can only leave a root, not reach one.
return Ok(std::fs::canonicalize(&entry).unwrap_or(entry));
let resolved_folder = resolve_absolute(path, folder)?;
let entry = resolved_folder.join(name);
// Only accept `canonicalize` (for on-disk case) when it stays in `resolved_folder` under the
// same name, so a symlink swapped in after `symlink_metadata` cannot redirect outside -> inside (#9292).
if std::fs::symlink_metadata(&entry).is_ok_and(|m| !m.file_type().is_symlink())
&& let Ok(canon) = std::fs::canonicalize(&entry)
&& canon.parent() == Some(resolved_folder.as_path())
&& canon.file_name().is_some_and(|c| c.to_string_lossy().eq_ignore_ascii_case(&name.to_string_lossy()))
{
return Ok(canon);
}
Ok(entry)
}
@@ -488,6 +493,18 @@ mod tests {
let _ = std::fs::remove_dir_all(base);
}
/// A symlink beside the write root that leads into it is not inside the root: writing would replace the link.
#[cfg(unix)]
#[test]
fn a_sibling_symlink_into_the_write_root_is_rejected() {
let (base, roots) = folders("sibling-link");
let link = base.join("evil");
std::os::unix::fs::symlink(base.join("out"), &link).unwrap();
let e = roots.check(&s(link), Access::Write).unwrap_err();
assert!(e.contains("outside the write root"), "{e}");
let _ = std::fs::remove_dir_all(base);
}
/// Scopes nest, and a scope applies only on the thread that set it.
#[test]
fn scopes_nest_and_stay_on_their_thread() {
+11
View File
@@ -10,6 +10,10 @@ pub struct Prefs {
/// On-screen paper for pages without a document background; excluded from saved documents.
#[serde(deserialize_with = "lenient_paper_color")]
pub paper_color: crate::cmd::view::PaperColor,
/// How the edges of page text are smoothed on screen (`view.textSmoothing`); excluded from
/// saved documents.
#[serde(deserialize_with = "lenient_text_smoothing")]
pub text_smoothing: crate::cmd::view::TextSmoothing,
/// Track Changes Options: what markup shows and how revisions are drawn (per user, as in
/// Word).
pub markup: wordcraft_layout::display::MarkupOptions,
@@ -72,6 +76,7 @@ impl Default for Prefs {
fn default() -> Self {
Prefs {
paper_color: Default::default(),
text_smoothing: Default::default(),
count_notes: true,
markup: Default::default(),
print_markup: false,
@@ -119,6 +124,12 @@ fn lenient_paper_color<'de, D: serde::Deserializer<'de>>(d: D) -> Result<crate::
Ok(serde_json::from_value(value).unwrap_or_default())
}
/// Ignore an invalid saved text smoothing without discarding other preferences.
fn lenient_text_smoothing<'de, D: serde::Deserializer<'de>>(d: D) -> Result<crate::cmd::view::TextSmoothing, D::Error> {
let value = serde_json::Value::deserialize(d)?;
Ok(serde_json::from_value(value).unwrap_or_default())
}
/// Ignore an invalid saved Page Color without discarding other preferences.
fn lenient_read_page_color<'de, D: serde::Deserializer<'de>>(d: D) -> Result<crate::cmd::view::ReadPageColor, D::Error> {
let value = serde_json::Value::deserialize(d)?;
+4 -1
View File
@@ -63,7 +63,10 @@ impl Session {
/// A navigated style change is for the Accept or Reject that follows: a command that edits
/// or moves the selection forgets it.
fn forget_review_style(&mut self, id: &str, mutates: bool) {
if (mutates && !matches!(id, "review.accept" | "review.reject")) || id.starts_with("caret.") || id.starts_with("select.") {
if (mutates && !matches!(id, "review.accept" | "review.reject" | "review.acceptAndNext" | "review.rejectAndNext"))
|| id.starts_with("caret.")
|| id.starts_with("select.")
{
self.review_style = None;
}
}
+191 -3
View File
@@ -4508,6 +4508,14 @@ fn tracked_style_definition_changes_are_recorded_and_resolved() {
run(&mut s, "review.acceptAll", json!({}));
assert_eq!(s.doc.styles.get("Heading1").unwrap().chr.bold, Some(true), "accepting keeps the change");
assert!(s.doc.revisions.is_empty());
for (command, italic) in [("review.rejectAndNext", None), ("review.acceptAndNext", Some(true))] {
run(&mut s, "styles.modify", json!({"style": "Heading1", "chr": {"italic": true}}));
run(&mut s, "review.nextChange", json!({}));
run(&mut s, command, json!({}));
assert_eq!(s.doc.styles.get("Heading1").unwrap().chr.italic, italic, "{command} resolves the navigated style definition");
assert_eq!(run(&mut s, "review.changes", json!({})), json!([]), "{command} leaves no style change behind");
}
}
/// #2697 review: Update Style to Match Selection also rewrites the selected paragraph. Its body
@@ -8446,10 +8454,139 @@ fn styles_modify_rejects_unknown_para_and_chr_fields() {
let err = s.run("styles.modify", &json!({"style": "Heading1", "chr": {"unknownKey": true}})).unwrap_err();
assert!(matches!(err, crate::CmdError::Params(_)), "expected Params error, got {err:?}");
s.run("styles.modify", &json!({"style": "Heading1", "para": {"spaceBefore": 123.0, "pageBreakBefore": true}})).unwrap();
// #9291: unknown keys inside nested structs (such as Borders / Border) are rejected too.
let err = s.run("styles.modify", &json!({"style": "Heading1", "para": {"borders": {"Top": {"width": 1.0}}}})).unwrap_err();
assert!(matches!(err, crate::CmdError::Params(_)), "expected Params error for nested Borders key, got {err:?}");
let err = s.run("styles.modify", &json!({"style": "Heading1", "para": {"borders": {"top": {"bogus": 1.0}}}})).unwrap_err();
assert!(matches!(err, crate::CmdError::Params(_)), "expected Params error for nested Border key, got {err:?}");
s.run(
"styles.modify",
&json!({"style": "Heading1", "para": {"spaceBefore": 123.0, "pageBreakBefore": true, "borders": {"top": {"width": 1.5, "style": "single"}}}}),
)
.unwrap();
let h1 = s.doc.styles.get("Heading1").unwrap();
assert_eq!(h1.para.space_before, Some(123.0));
assert_eq!(h1.para.page_break_before, Some(true));
assert!(h1.para.borders.as_ref().and_then(|b| b.top).is_some_and(|t| (t.width - 1.5).abs() < 0.01));
}
#[test]
fn styles_modify_checks_tagged_text_fill_fields_before_changing_the_style() {
use wordcraft_doc::wordart::TextFill;
let mut s = s();
let before = s.doc.styles.get("Heading1").unwrap().clone();
let gradient_stops = json!([{"pos": 0, "color": "112233"}, {"pos": 100, "color": "445566", "transparency": 25}]);
for (fill, field) in [
(json!({"type": "solid", "color": "FF0000", "bogus": 1}), "bogus"),
(json!({"type": "none", "color": "FF0000"}), "color"),
(json!({"type": "gradient", "stops": gradient_stops, "color": "FF0000"}), "color"),
(json!({"type": "gradient", "stops": [{"pos": 0, "color": "112233", "bogus": 1}]}), "bogus"),
] {
let err = s
.run(
"styles.modify",
&json!({"style": "Heading1", "name": "Renamed", "para": {"spaceBefore": 123}, "chr": {"textEffects": {"fill": fill}}}),
)
.unwrap_err();
assert!(matches!(err, crate::CmdError::Params(ref detail) if detail.contains(field)), "{err:?}");
assert_eq!(s.doc.styles.get("Heading1"), Some(&before), "rejected fill must leave the style unchanged");
}
let fill = |s: &Session| s.doc.styles.get("Heading1").unwrap().chr.text_effects.as_ref().unwrap().fill.clone().unwrap();
s.run("styles.modify", &json!({"style": "Heading1", "chr": {"textEffects": {"fill": {"type": "solid", "color": "FF0000"}}}})).unwrap();
assert_eq!(fill(&s), TextFill::Solid { color: wordcraft_doc::Rgb(255, 0, 0), transparency: 0.0 });
s.run(
"styles.modify",
&json!({"style": "Heading1", "chr": {"textEffects": {"fill": {"type": "gradient", "angle": 45, "stops": gradient_stops}}}}),
)
.unwrap();
assert!(matches!(fill(&s), TextFill::Gradient { stops, angle } if angle == 45.0 && stops.len() == 2 && stops[1].transparency == 25.0));
s.run("styles.modify", &json!({"style": "Heading1", "chr": {"textEffects": {"fill": {"type": "none"}}}})).unwrap();
assert_eq!(fill(&s), TextFill::None);
}
#[test]
fn styles_modify_checks_text_fills_in_positional_arguments() {
use serde_json::Value;
use wordcraft_doc::wordart::TextFill;
let chr_with = |text_effects: Value, positional: bool| {
if positional {
// CharProps puts textEffects after the first 30 optional fields.
let mut fields = vec![Value::Null; 30];
fields.push(text_effects);
Value::Array(fields)
} else {
json!({"textEffects": text_effects})
}
};
let mut s = s();
let stops = json!([{"pos": 0, "color": "112233"}, [100, "445566", 25]]);
for (positional_chr, positional_effects) in [(false, false), (false, true), (true, false), (true, true)] {
let effects = |fill: Value| if positional_effects { json!([fill]) } else { json!({"fill": fill}) };
let before = s.doc.styles.get("Heading1").unwrap().clone();
for fill in [
json!({"type": "solid", "color": "FF0000", "bogus": 1}),
json!({"type": "gradient", "stops": [{"pos": 0, "color": "112233", "bogus": 1}]}),
json!(["gradient", [{"pos": 0, "color": "112233", "bogus": 1}], 45]),
] {
let chr = chr_with(effects(fill), positional_chr);
let params = json!({"style": "Heading1", "name": "Renamed", "para": {"spaceBefore": 123}, "chr": chr});
let err = s.run("styles.modify", &params).unwrap_err();
assert!(matches!(err, crate::CmdError::Params(ref detail) if detail.contains("unknown field") && detail.contains("bogus")), "{err:?}");
assert_eq!(s.doc.styles.get("Heading1"), Some(&before));
}
for fill in [json!({"type": "gradient", "stops": stops, "angle": 45}), json!(["gradient", stops, 45])] {
let chr = chr_with(effects(fill), positional_chr);
s.run("styles.modify", &json!({"style": "Heading1", "chr": chr})).unwrap();
let fill = s.doc.styles.get("Heading1").unwrap().chr.text_effects.as_ref().unwrap().fill.as_ref().unwrap();
assert!(matches!(fill, TextFill::Gradient { stops, angle } if *angle == 45.0 && stops.len() == 2 && stops[1].transparency == 25.0));
}
}
let before = s.doc.styles.get("Heading1").unwrap().clone();
let old = chr_with(json!([{"type": "solid", "color": "FF0000", "bogus": 1}]), true);
let err = s.run("styles.modify", &json!({"style": "Heading1", "chr": {"fmtChange": {"rev": 0, "old": old}}})).unwrap_err();
assert!(matches!(err, crate::CmdError::Params(ref detail) if detail.contains("unknown field") && detail.contains("bogus")), "{err:?}");
assert_eq!(s.doc.styles.get("Heading1"), Some(&before));
}
#[test]
fn styles_modify_checks_numeric_text_fill_tags() {
let mut refused = s();
let before = refused.doc.styles.get("Heading1").unwrap().clone();
for fill in [
json!({"type": 0, "bogus": 1}),
json!({"type": 1, "color": "FF0000", "bogus": 1}),
json!({"type": 2, "stops": [{"pos": 0, "color": "112233"}], "bogus": 1}),
json!({"type": 2, "stops": [{"pos": 0, "color": "112233", "bogus": 1}]}),
json!([2, [{"pos": 0, "color": "112233", "bogus": 1}], 45]),
] {
let err = refused
.run("styles.modify", &json!({"style": "Heading1", "name": "Renamed", "para": {"spaceBefore": 123}, "chr": {"textEffects": [fill]}}))
.unwrap_err();
assert!(matches!(err, crate::CmdError::Params(ref detail) if detail.contains("unknown field") && detail.contains("bogus")), "{err:?}");
assert_eq!(refused.doc.styles.get("Heading1"), Some(&before));
}
let stops = json!([{"pos": 0, "color": "112233"}, [100, "445566", 25]]);
for (fill, named) in [
(json!({"type": 0}), json!({"type": "none"})),
(json!([0]), json!({"type": "none"})),
(json!({"type": 1, "color": "FF0000"}), json!({"type": "solid", "color": "FF0000", "transparency": 0.0})),
(json!([1, "FF0000", 0]), json!({"type": "solid", "color": "FF0000", "transparency": 0.0})),
(json!({"type": 2, "stops": stops, "angle": 45}), json!({"type": "gradient", "stops": stops, "angle": 45})),
(json!([2, stops, 45]), json!({"type": "gradient", "stops": stops, "angle": 45})),
] {
let set_fill = |fill| {
let mut s = s();
s.run("styles.modify", &json!({"style": "Heading1", "chr": {"textEffects": {"fill": fill}}})).unwrap();
s.doc.styles.get("Heading1").unwrap().chr.text_effects.as_ref().unwrap().fill.clone().unwrap()
};
assert_eq!(set_fill(fill), set_fill(named));
}
}
/// #865: `styles.modify` takes a colour the way `format.color` does (`RRGGBB`, `#RRGGBB`, `auto`),
@@ -15057,7 +15194,7 @@ fn export_png_refuses_a_path_that_is_not_png() {
#[test]
fn ime_body_epoch_marks_body_replacements_not_edits() {
let mut s = s();
let id = s.document_id();
let document_id = s.document_id();
run(&mut s, "text.insert", json!({"text": "one"}));
let first = s.ime_body_epoch();
run(&mut s, "text.insert", json!({"text": " two"}));
@@ -15066,7 +15203,7 @@ fn ime_body_epoch_marks_body_replacements_not_edits() {
run(&mut s, "document.setText", json!({"text": "same text"}));
let replaced = s.ime_body_epoch();
assert!(replaced > first, "setText replaces the body under the same document id");
assert_eq!(s.document_id(), id, "the document id itself is unchanged");
assert_eq!(s.document_id(), document_id, "the document id itself is unchanged");
// The same text again still replaces the body: a composition must not survive on content
// equality.
@@ -15458,6 +15595,37 @@ fn export_png_rejects_a_page_number_that_does_not_fit() {
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn screen_text_smoothing_is_a_persistent_preference_not_document_formatting() {
use crate::cmd::view::TextSmoothing;
let mut s = s();
run(&mut s, "text.insert", json!({"text": "Screen text test", "raw": true}));
let before = serde_json::to_value(&s.doc).unwrap();
let docx_before = wordcraft_docx::write(&s.doc).unwrap();
s.dirty = false;
assert_eq!(s.prefs.text_smoothing, TextSmoothing::System, "follows the system until the user chooses");
for (value, expected) in [("subpixel", TextSmoothing::Subpixel), ("grayscale", TextSmoothing::Grayscale), ("system", TextSmoothing::System)] {
let r = run(&mut s, "view.textSmoothing", json!({"value": value}));
assert_eq!(r["textSmoothing"], value);
assert_eq!(s.prefs.text_smoothing, expected);
assert_eq!(serde_json::to_value(&s.doc).unwrap(), before);
assert!(!s.dirty);
assert_eq!(wordcraft_docx::write(&s.doc).unwrap(), docx_before);
let restored: crate::Prefs = serde_json::from_value(serde_json::to_value(&s.prefs).unwrap()).unwrap();
assert_eq!(restored.text_smoothing, expected);
}
run(&mut s, "view.textSmoothing", json!({"value": "subpixel"}));
for v in [json!({}), json!({"value": "lcd"}), json!({"value": 42}), json!({"value": null}), json!({"value": ["subpixel"]})] {
assert!(s.run("view.textSmoothing", &v).is_err(), "{v}");
assert_eq!(s.prefs.text_smoothing, TextSmoothing::Subpixel, "a refused value changes nothing");
}
let legacy: crate::Prefs = serde_json::from_value(json!({})).unwrap();
assert_eq!(legacy.text_smoothing, TextSmoothing::System);
let future: crate::Prefs = serde_json::from_value(json!({"textSmoothing":"future", "countNotes":false})).unwrap();
assert_eq!(future.text_smoothing, TextSmoothing::System);
assert!(!future.count_notes);
}
#[test]
fn screen_paper_color_is_a_persistent_preference_not_document_formatting() {
use crate::cmd::view::PaperColor;
@@ -16002,6 +16170,26 @@ fn replace_all_with_track_changes_keeps_caret_when_original_story_has_no_match()
);
}
/// #9186: With Track Changes on, Replace All must keep the caret in its original story even when
/// both that story and the main text have matches.
#[test]
fn replace_all_with_track_changes_keeps_caret_in_original_story_when_both_match() {
use wordcraft_doc::StoryRef;
let mut t = s();
run(&mut t, "document.setText", json!({"text": "Body: [NAME]."}));
let header_id = run(&mut t, "insert.header", json!({"text": "Header: [NAME]"}))["story"].as_u64().unwrap() as u32;
let header_story = StoryRef::Part(header_id);
t.sel = crate::session::Selection::caret(Pos::new(header_story, wordcraft_doc::Path::top(0), 0));
run(&mut t, "review.trackChanges", json!({"enabled": true}));
let r = run(&mut t, "edit.replaceAll", json!({"text": "[NAME]", "with": "Jane"}));
assert_eq!(r["replaced"], 2, "{r}");
assert_eq!(t.sel.focus.story, header_story, "caret must stay in the header story");
assert!(t.in_header_footer());
assert!(t.doc.plain_text(StoryRef::Body).contains("Jane"));
assert!(t.doc.plain_text(header_story).contains("Jane"));
}
/// #9064: Replace All skips stories nothing shows any more (a removed header, a footnote whose
/// reference was deleted without tracking) and does not count them.
#[test]
+17 -10
View File
@@ -7,24 +7,31 @@ use crate::Session;
use crate::cmd::insert::base64_encode;
#[test]
fn format_state_reports_the_east_asian_theme_face_and_keeps_unresolved_and_mixed_controls() {
fn format_state_reports_the_east_asian_theme_face_and_per_run_fallbacks() {
use std::sync::Arc;
use wordcraft_doc::props::ThemeFont;
use wordcraft_doc::{Document, Path, StoryRef};
let mut doc = Document::from_text("漢字");
Arc::make_mut(&mut doc.styles).default_chr.font_ea = Some("Times New Roman".into());
doc.para_mut(StoryRef::Body, &Path::top(0))
.unwrap()
.format(0, "漢".len(), &|props| props.font_ea_theme = Some(ThemeFont::MinorEastAsia))
.unwrap();
let first = "漢".len();
let second = "漢字".len();
let mut doc = Document::from_text("漢字文");
let defaults = &mut Arc::make_mut(&mut doc.styles).default_chr;
defaults.font = Some("Example Latin".into());
defaults.font_ea = Some("Times New Roman".into());
let para = doc.para_mut(StoryRef::Body, &Path::top(0)).unwrap();
para.format(0, second, &|props| props.font_ea_theme = Some(ThemeFont::MinorEastAsia)).unwrap();
para.format(first, second, &|props| props.font = Some("Other Latin".into())).unwrap();
let mut fallback = Session::new(doc.clone());
fallback.run("select.all", &json!({})).unwrap();
assert_eq!(fallback.run("format.state", &json!({})).unwrap()["fontEastAsia"], "Times New Roman");
for (start, end, family) in [(0, first, "Example Latin"), (first, second, "Other Latin")] {
fallback.run("select.range", &json!({"anchor": Pos::body(0, start), "focus": Pos::body(0, end)})).unwrap();
assert_eq!(fallback.run("format.state", &json!({})).unwrap()["fontEastAsia"], family);
}
fallback.run("select.range", &json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, second)})).unwrap();
assert!(fallback.run("format.state", &json!({})).unwrap()["fontEastAsia"].is_null(), "the unresolved slot uses each run's own font");
doc.passthrough.insert("wordcraft:theme.fonts".into(), Arc::new(b"minor\tface\tea\tExample CJK Face\n".to_vec()));
let mut s = Session::new(doc);
s.run("select.range", &json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, "漢".len())})).unwrap();
s.run("select.range", &json!({"anchor": Pos::body(0, 0), "focus": Pos::body(0, second)})).unwrap();
assert_eq!(s.run("format.state", &json!({})).unwrap()["fontEastAsia"], "Example CJK Face");
s.run("select.all", &json!({})).unwrap();
assert!(s.run("format.state", &json!({})).unwrap()["fontEastAsia"].is_null(), "the theme face and named face differ");
+65
View File
@@ -3191,6 +3191,24 @@ fn backspacing_an_automatic_i_keeps_the_retyped_word_lowercase() {
assert_eq!(s.doc.plain_text(StoryRef::Body), "So I");
}
#[test]
fn automatic_i_keeps_pending_first_letter_exception_from_earlier_sentence_capital() {
let mut s = typed("hello there. so i ");
assert_eq!(s.doc.plain_text(StoryRef::Body), "Hello there. So I ");
// Backspacing back to "hello there. " and retyping "so " still learns "there.".
typ(&mut s, "\u{8}\u{8}\u{8}\u{8}\u{8}so ");
assert_eq!(s.doc.plain_text(StoryRef::Body), "Hello there. so ");
assert_eq!(first_letter_list(&s), ["there."]);
// Restoring lowercase "i" first still leaves the earlier sentence-capital record intact.
let mut s = typed("hello there. so i ");
typ(&mut s, "\u{8}");
assert_eq!(s.doc.plain_text(StoryRef::Body), "Hello there. So i");
typ(&mut s, " \u{8}\u{8}\u{8}\u{8}\u{8}so ");
assert_eq!(s.doc.plain_text(StoryRef::Body), "Hello there. so ");
assert_eq!(first_letter_list(&s), ["there."]);
}
#[test]
fn restoring_a_lowercase_i_preserves_the_deleted_separators_formatting_for_typing() {
let mut s = typed("so ");
@@ -3481,6 +3499,53 @@ fn backspace_deletes_selected_columns_and_delete_clears_them() {
assert_eq!(table_cells(&s), [["a1", "", "c1"], ["a2", "", "c2"], ["a3", "", "c3"]]);
}
#[test]
fn promote_and_demote_only_change_list_levels_in_selected_cells() {
for (command, changed_level) in [("para.promote", 0), ("para.demote", 2)] {
let mut s = table_between(0, 1);
let num = Arc::make_mut(&mut s.doc.numbering).try_add_list(wordcraft_doc::ListKind::Numbered).unwrap();
let story = StoryRef::Body;
for path in s.doc.para_paths(story) {
s.doc.para_mut(story, &path).unwrap().props.numbering = Some(wordcraft_doc::props::NumRef { num, level: 1 });
}
run(&mut s, "table.selectColumn", json!({}));
let range = s.cell_range().unwrap().clone();
assert_eq!((range.rows, range.cols), ((0, 2), (1, 1)));
let selected = s.sel.clone();
run(&mut s, command, json!({}));
assert_eq!(s.sel, selected);
for path in s.doc.para_paths(story) {
let expected = if path.cell().is_some_and(|(_, _, col)| col == 1) { changed_level } else { 1 };
let actual = s.doc.para(story, &path).unwrap().props.numbering;
assert_eq!(actual, Some(wordcraft_doc::props::NumRef { num, level: expected }), "{command}: {path:?}");
}
run(&mut s, "edit.undo", json!({}));
for path in s.doc.para_paths(story) {
assert_eq!(
s.doc.para(story, &path).unwrap().props.numbering,
Some(wordcraft_doc::props::NumRef { num, level: 1 }),
"undo {command}: {path:?}",
);
}
}
}
#[test]
fn promote_keeps_the_heading_at_the_end_of_a_text_selection_in_scope() {
let mut s = typed("First\nSecond\nThird");
for index in 0..3 {
run(&mut s, "caret.set", json!({"pos": Pos::body(index, 0)}));
run(&mut s, "para.style", json!({"style": "Heading2"}));
}
assert_eq!(wordcraft_layout::outline::levels(&s.doc), [2, 2, 2]);
run(&mut s, "select.range", json!({"anchor": Pos::body(0, 1), "focus": Pos::body(1, 0)}));
assert!(s.cell_range().is_none());
run(&mut s, "para.promote", json!({}));
assert_eq!(wordcraft_layout::outline::levels(&s.doc), [1, 1, 2]);
}
/// The first top-level table's cells, row by row, one entry per block: a paragraph's text, or
/// `<table>` for a nested table.
fn cell_blocks(s: &Session) -> Vec<Vec<Vec<String>>> {
+14
View File
@@ -483,3 +483,17 @@ fn named_instances_and_collection_members_are_capped() {
// (under 0.1 s on a loaded machine) only backs up "read once", with room for a busy CI.
assert!(started.elapsed() < std::time::Duration::from_secs(10), "{:?}", started.elapsed());
}
#[test]
fn missing_calibri_without_carlito_reports_the_drawn_fallback() {
let db = FontDb::with_font_dirs(Vec::new());
db.set_system_fallback(false);
db.faces.write().unwrap().retain(|face| !face.family.eq_ignore_ascii_case("Carlito"));
assert!(!db.has_family("Carlito"));
let missing = crate::word::missing_metric_fonts_in(&db);
let used = missing.iter().find(|(family, _)| *family == "Calibri").map_or("", |(_, used)| used.as_str());
assert!(!used.is_empty(), "Calibri should be reported without Carlito");
assert_ne!(used, "Carlito");
assert!(db.has_family(used), "the notice names the face actually drawn");
}
+84 -7
View File
@@ -46,7 +46,7 @@ pub fn uses_generic_serif_or_monospace_fallback(family: &str) -> bool {
const SANS: &[&str] = &["Carlito", "Helvetica Neue", "Arial", "Liberation Sans", "Noto Sans", "DejaVu Sans", "Source Sans 3"];
const SERIF: &[&str] = &["Caladea", "Times New Roman", "Liberation Serif", "Georgia", "Noto Serif", "DejaVu Serif", "Source Serif 4"];
const MONO: &[&str] = &["Courier New", "Liberation Mono", "Menlo", "Consolas", "DejaVu Sans Mono", "JetBrains Mono"];
const MONO: &[&str] = &["Courier New", "Liberation Mono", "Cousine", "Menlo", "Consolas", "DejaVu Sans Mono", "JetBrains Mono"];
/// Word's symbol fonts (Symbol, Wingdings…) are proprietary: their characters are drawn as their
/// Unicode equivalents (`wordcraft_doc::symbol_fonts`) from these faces or any face that has them.
@@ -83,9 +83,9 @@ fn substitutes_by_name(family: &str) -> (&'static [&'static str], bool) {
return substitutes_by_name(first);
}
}
const ARIAL: &[&str] = &["Liberation Sans", "Helvetica", "Helvetica Neue", "Arimo", "Source Sans 3"];
const ARIAL_UNICODE: &[&str] = &["Arial", "Liberation Sans", "Helvetica", "Helvetica Neue", "Arimo", "Source Sans 3"];
const TIMES: &[&str] = &["Liberation Serif", "Times", "Tinos", "Source Serif 4"];
const ARIAL: &[&str] = &["Liberation Sans", "Arimo", "Helvetica", "Helvetica Neue", "Source Sans 3"];
const ARIAL_UNICODE: &[&str] = &["Arial", "Liberation Sans", "Arimo", "Helvetica", "Helvetica Neue", "Source Sans 3"];
const TIMES: &[&str] = &["Liberation Serif", "Tinos", "Times", "Source Serif 4"];
// Persian / Arabic document fonts. Naskh (book) faces such as B Nazanin, B Lotus, B Zar and
// Traditional Arabic, then the sans faces (B Yekan, B Titr, IRANSans) people use for
// headings and screens. Open fonts with full Persian coverage first.
@@ -500,6 +500,37 @@ fn substitute(db: &FontDb, family: &str) -> Option<&'static str> {
.or_else(|| installed.first().copied())
}
/// Word's core families, each with the open fonts that share its metrics. Without the family or
/// a twin, text set in it wraps and paginates differently from Word (Times New Roman drawn in a
/// wider serif fits fewer lines to a page).
const CORE_METRIC_FONTS: &[(&str, &[&str])] = &[
("Times New Roman", &["Liberation Serif", "Tinos"]),
("Arial", &["Liberation Sans", "Arimo"]),
("Courier New", &["Liberation Mono", "Cousine"]),
("Calibri", &["Carlito"]),
("Cambria", &["Caladea"]),
];
/// Word's core families not drawn with themselves or a metric twin, paired with the primary
/// resolved family. Glyphs the primary family cannot draw may still use glyph fallback.
pub fn missing_metric_fonts() -> Vec<(&'static str, String)> {
missing_metric_fonts_in(FontDb::global())
}
pub(crate) fn missing_metric_fonts_in(db: &FontDb) -> Vec<(&'static str, String)> {
CORE_METRIC_FONTS
.iter()
.filter_map(|(word, twins)| {
let resolved = resolve_with_db(db, word, false, false);
if has_metric_resolution(db.has_family(word), twins, &resolved.face.family) { None } else { Some((*word, resolved.face.family.clone())) }
})
.collect()
}
fn has_metric_resolution(installed_word_font: bool, twins: &[&str], resolved_family: &str) -> bool {
installed_word_font || twins.iter().any(|twin| resolved_family.eq_ignore_ascii_case(twin))
}
fn style_name(bold: bool, italic: bool) -> &'static str {
match (bold, italic) {
(false, false) => "Regular",
@@ -711,9 +742,7 @@ pub fn resolve(family: &str, bold: bool, italic: bool) -> Resolved {
return *r;
}
}
let (fam, substituted) = resolve_family(db, family);
let face = db.face(&fam, style_name(bold, italic));
let r = Resolved { synth_bold: bold && face.weight < 600.0, synth_italic: italic && !face.italic, substituted, face: FaceRef::of(&face) };
let r = resolve_with_db(db, family, bold, italic);
if cacheable {
let mut c = cache.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if c.0 == generation {
@@ -734,6 +763,12 @@ pub fn resolve(family: &str, bold: bool, italic: bool) -> Resolved {
r
}
fn resolve_with_db(db: &FontDb, family: &str, bold: bool, italic: bool) -> Resolved {
let (fam, substituted) = resolve_family(db, family);
let face = db.face(&fam, style_name(bold, italic));
Resolved { synth_bold: bold && face.weight < 600.0, synth_italic: italic && !face.italic, substituted, face: FaceRef::of(&face) }
}
/// A line's (ascent, descent) from hhea values, both positive: the line gap goes above the ascent.
fn hhea_line(ascender: i16, descender: i16, line_gap: i16) -> (f64, f64) {
(f64::from(ascender) + f64::from(line_gap.max(0)), f64::from(descender).abs())
@@ -1100,6 +1135,48 @@ mod tests {
}
}
#[test]
fn core_font_notice_uses_the_actual_installed_face() {
const SERIF: &[u8] = include_bytes!("../../../assets/fonts/SourceSerif4-Regular.ttf");
let database = |name: Option<&str>| {
let db = FontDb::with_font_dirs(Vec::new());
db.set_system_fallback(false);
if let Some(name) = name {
assert_eq!(db.add_document_fonts(vec![(SERIF.to_vec(), name.to_owned())]), 1);
}
db
};
let original = database(Some("Times New Roman"));
assert!(missing_metric_fonts_in(&original).iter().all(|(family, _)| *family != "Times New Roman"));
assert_eq!(resolve_with_db(&original, "Times New Roman", false, false).face.family, "Times New Roman");
let twin = database(Some("Liberation Serif"));
assert!(missing_metric_fonts_in(&twin).iter().all(|(family, _)| *family != "Times New Roman"));
assert_eq!(resolve_with_db(&twin, "Times New Roman", false, false).face.family, "Liberation Serif");
let fallback = database(None);
assert_eq!(
missing_metric_fonts_in(&fallback).iter().find(|(family, _)| *family == "Times New Roman"),
Some(&("Times New Roman", "Source Serif 4".to_owned()))
);
assert_eq!(resolve_with_db(&fallback, "Times New Roman", false, false).face.family, "Source Serif 4");
let no_carlito = database(Some("DejaVu Sans"));
assert!(!no_carlito.has_family("Carlito"));
assert_eq!(resolve_with_db(&no_carlito, "Calibri", false, false).face.family, "DejaVu Sans");
assert_eq!(
missing_metric_fonts_in(&no_carlito).iter().find(|(family, _)| *family == "Calibri"),
Some(&("Calibri", "DejaVu Sans".to_owned()))
);
}
#[test]
fn a_listed_but_uninstalled_carlito_does_not_hide_the_chosen_fallback() {
assert!(!has_metric_resolution(false, &["Carlito"], "DejaVu Sans"));
assert!(has_metric_resolution(false, &["Carlito"], "Carlito"));
}
/// Semicolon-separated fallback lists resolve to the first installed family, or to a
/// candidate's substitute when no listed family is installed.
#[test]
+34 -1
View File
@@ -665,7 +665,8 @@ impl<'a> Flow<'a> {
// Not in the full-height fallback pass, which must keep the original layout.
let column = pb.uncapped_bottom() - pb.top;
let balancing = pb.balance.is_some_and(|(page, h)| page + 1 == pb.pages.len() && h + 0.01 < column);
if l0 == 0 || fit.l1 < n || fit.forced.is_some() || !rp.keep_next || !balancing || pb.web {
// A paragraph closing a section never shares its column with the next section's first block (#9206).
if l0 == 0 || fit.l1 < n || fit.forced.is_some() || !rp.keep_next || self.p.section.is_some() || !balancing || pb.web {
return fit.l1;
}
let (Some(first), Some(last)) = (self.pl.lines.get(l0), self.pl.lines.last()) else { return fit.l1 };
@@ -1373,6 +1374,38 @@ mod tests {
use wordcraft_doc::props::LineSpacing;
use wordcraft_geom::Rect;
#[test]
fn kept_paragraphs_reserve_no_room_for_suppressed_spacing() {
crate::test_fonts();
let room = |doc: &Document| {
let mut reserved = None;
crate::pass::with_flow_page(doc, |ctx, pb| {
reserved = Some(next_first_line(ctx, 0, pb.col_w(), 0, false, &mut ctx.counters.clone()));
});
reserved.expect("the flow page was measured")
};
for automatic_list in [false, true] {
let mut base = Document::from_text("Kept paragraph\nFollowing paragraph");
if automatic_list {
let num = Arc::make_mut(&mut base.numbering).add_list(wordcraft_doc::ListKind::Numbered);
for block in 0..2 {
base.para_mut(StoryRef::Body, &Path::top(block)).unwrap().props.numbering = Some(wordcraft_doc::props::NumRef { num, level: 0 });
}
}
let q = base.para_mut(StoryRef::Body, &Path::top(1)).unwrap();
q.props.space_before = Some(0.0);
let mut spaced = base.clone();
let q = spaced.para_mut(StoryRef::Body, &Path::top(1)).unwrap();
q.props.space_before = Some(48.0);
if automatic_list {
q.props.space_before_auto = Some(true);
} else {
q.props.contextual_spacing = Some(true);
}
assert_eq!(room(&spaced), room(&base), "suppressed spacing takes no room (list: {automatic_list})");
}
}
#[test]
fn strict_balancing_remeasures_kept_lines_in_the_next_column() {
crate::test_fonts();
+46 -20
View File
@@ -189,6 +189,34 @@ pub(crate) fn placed_cost_by(it: &Placed, limit: usize, cost: impl Fn(&Placed) -
}
}
/// Whether a header laid out with the rendered body area grows past `body_top` and retrying
/// with the declared margins (`margin_area: None`) produces a shorter layout. Both
/// [`header_table_areas`] and [`headers_footers`] use this so body table avoidance matches the
/// header actually drawn.
fn lay_header_box<T>(
ctx: &mut Ctx,
frame: PageFrame<'_>,
header_y: f32,
body_top: f32,
measured: bool,
mut lay: impl FnMut(&mut Ctx, PageFrame<'_>) -> (f32, T),
) -> T {
// List counters and equation numbers before the header, so a second layout counts from the
// same place and only the layout kept advances them.
let before = (ctx.counters.clone(), ctx.eq_count);
let (laid_h, laid) = lay(ctx, frame);
if measured && header_y + laid_h > body_top + 0.01 {
let rendered = (std::mem::replace(&mut ctx.counters, before.0), ctx.eq_count);
ctx.eq_count = before.1;
let (measured_h, measured) = lay(ctx, PageFrame { margin_area: None, ..frame });
if measured_h < laid_h - 0.01 {
return measured;
}
(ctx.counters, ctx.eq_count) = rendered;
}
laid
}
/// Header tables can displace a non-overlapping body table. Page-positioned drawings keep
/// their own wrapping rules, so only table areas are retained from the header layout.
pub(crate) fn header_table_areas(ctx: &mut Ctx, pb: &PageBuilder) -> Vec<Rect> {
@@ -207,9 +235,10 @@ pub(crate) fn header_table_areas(ctx: &mut Ctx, pb: &PageBuilder) -> Vec<Rect> {
return Vec::new();
}
let set = hf.heads.set(page.section);
let even_page = !(sect.title_page && first) && ctx.doc.settings.even_odd_headers && page.number.is_multiple_of(2);
let id = if sect.title_page && first {
set.first
} else if ctx.doc.settings.even_odd_headers && page.number.is_multiple_of(2) {
} else if even_page {
set.even.or(set.default)
} else {
set.default
@@ -217,6 +246,8 @@ pub(crate) fn header_table_areas(ctx: &mut Ctx, pb: &PageBuilder) -> Vec<Rect> {
let Some(id) = id else { return Vec::new() };
let Some(part) = ctx.doc.parts.get(&id) else { return Vec::new() };
let blocks = part.blocks.clone();
// As in `headers_footers`: an even-page header with its own part was never measured for the body top.
let header_measured = !even_page || set.even.is_none();
let x = sect.margin_left + sect.gutter;
let frame =
PageFrame { sect, margin_area: Some((page.body.y, page.body.bottom())), origin: (x, sect.header), number: page.number, mirror: ctx.mirror };
@@ -229,8 +260,11 @@ pub(crate) fn header_table_areas(ctx: &mut Ctx, pb: &PageBuilder) -> Vec<Rect> {
let track = std::mem::replace(&mut ctx.track_totals, false);
ctx.fields.page_format = sect.page_num_format;
ctx.fields.page = page.number;
let mut areas = again(ctx, 0, |ctx| {
with_pct_base(ctx, base, |ctx| layout_box(ctx, BoxInput::other(StoryRef::Part(id), &blocks, sect.text_width(), 0, Some(frame)))).table_areas
let mut areas = lay_header_box(ctx, frame, sect.header, page.body.y, header_measured, |ctx, frame| {
let res = again(ctx, 0, |ctx| {
with_pct_base(ctx, base, |ctx| layout_box(ctx, BoxInput::other(StoryRef::Part(id), &blocks, sect.text_width(), 0, Some(frame))))
});
(res.height, res.table_areas)
});
ctx.counters = counters;
ctx.boxes = boxes;
@@ -485,23 +519,15 @@ pub(crate) fn headers_footers(ctx: &mut Ctx, pages: &mut [Page], sections: &[(us
with_pct_base(ctx, base, |c| layout_box(c, BoxInput::other(StoryRef::Part(id), &blocks, w, 0, Some(frame))))
})
};
// List counters and equation numbers before the header, so a second layout counts
// from the same place and only the layout kept advances them.
let before = (ctx.counters.clone(), ctx.eq_count);
let (mut laid, mut behind, mut front) = lay_header(ctx, frame);
// The body top was measured with the declared margins (`body_top_for`). If the rendered
// area moves a wrapping Margin-anchored object into the header's text and the header
// grows past that body top, keep the measured layout: its text can't run into the body.
if sect.header + laid.height > page.body.y + 0.01 {
let rendered = (std::mem::replace(&mut ctx.counters, before.0), ctx.eq_count);
ctx.eq_count = before.1;
let measured = lay_header(ctx, PageFrame { margin_area: None, ..frame });
if measured.0.height < laid.height - 0.01 {
(laid, behind, front) = measured;
} else {
(ctx.counters, ctx.eq_count) = rendered;
}
}
// The body top was measured with the declared margins (`body_top_for`), only for the
// default and first-page headers of non-turned sections (`section_tops`). Even-page
// headers and fixed-margin sections were never measured for `page.body.y`, so skip
// the retry (#9226).
let header_measured = !sect.text_direction.is_turned() && (page.hf_slot != HfSlot::Even || hf.heads.set(page.section).even.is_none());
let (laid, behind, front) = lay_header_box(ctx, frame, sect.header, page.body.y, header_measured, |ctx, frame| {
let res = lay_header(ctx, frame);
(res.0.height, res)
});
let mut items = laid.items;
for it in &mut items {
it.translate(x, sect.header);
+35 -14
View File
@@ -798,23 +798,44 @@ impl DocLayout {
/// In turned text, the position on the next (`next`) or previous line in reading order, at
/// `goal` along the line (its own frame; `None` keeps the caret's). Returns it with that
/// along-line coordinate. Only lines of the same flow count (the paragraphs of one story
/// level or of one table cell, not another cell's), so `None` at the first/last line of the
/// caret's flow on the page.
/// level or of one table cell, not another cell's). In the body the step crosses page
/// boundaries, so `None` only at the first/last line of the flow; in any other story (laid
/// out again on every page) it stops at the first/last line on the page.
pub fn turned_line(&self, pos: &Pos, goal: Option<f32>, next: bool, page_hint: usize) -> Option<(Pos, f32)> {
// Only the body flows from page to page: a header, a footer or a text box in one is laid
// out again on every page, so the adjacent page holds the caret's own lines again.
let crosses_pages = pos.story == StoryRef::Body;
let page_lines = |page_idx: usize| -> Vec<(&Path, &std::sync::Arc<ParaLayout>, usize)> {
let Some(page) = self.pages.get(page_idx) else { return Vec::new() };
items_of(page, pos.story)
.filter_map(|it| match it {
Placed::Lines { story, path, para, l0, l1, turn, .. }
if *story == pos.story && turn.is_turned() && path.parent() == pos.path.parent() =>
{
Some((path, para, *l0, *l1))
}
_ => None,
})
.flat_map(|(path, para, l0, l1)| (l0..l1).map(move |li| (path, para, li)))
.collect()
};
let c = self.caret_on(pos, page_hint)?;
let lines: Vec<(&Path, &std::sync::Arc<ParaLayout>, usize)> = items_of(self.pages.get(c.page)?, pos.story)
.filter_map(|it| match it {
Placed::Lines { story, path, para, l0, l1, turn, .. }
if *story == pos.story && turn.is_turned() && path.parent() == pos.path.parent() =>
{
Some((path, para, *l0, *l1))
}
_ => None,
})
.flat_map(|(path, para, l0, l1)| (l0..l1).map(move |li| (path, para, li)))
.collect();
let lines = page_lines(c.page);
let here = lines.iter().position(|(path, para, li)| *path == &pos.path && *li == para.line_of(pos.off))?;
let (path, para, li) = lines.get(if next { here + 1 } else { here.checked_sub(1)? })?;
let adjacent;
let (path, para, li) = if next {
if let Some(t) = lines.get(here + 1) {
t
} else {
adjacent = if crosses_pages { page_lines(c.page + 1) } else { Vec::new() };
adjacent.first()?
}
} else if let Some(prev) = here.checked_sub(1).and_then(|i| lines.get(i)) {
prev
} else {
adjacent = if crosses_pages { page_lines(c.page.checked_sub(1)?) } else { Vec::new() };
adjacent.last()?
};
let gx = match goal {
Some(g) => g,
None => lines[here].1.x_of(lines[here].2, pos.off)?,
+2 -1
View File
@@ -600,6 +600,7 @@ impl<'e> Breaker<'e> {
// mixing fonts is as much taller as its runs' extents make it, once (Word for Mac and
// Windows: 10 pt Times New Roman with 10 pt Courier New at 1.5 and double spacing).
let run_leading = if single > 0.0 && !pictures_alone { single.min(text_natural) } else { text_natural };
let picture_leading = if pictures_alone { font_natural } else { run_leading };
// Keep the picture floor independent of list-label metrics.
let natural = asc + desc;
let pictures = if obj_asc > asc { obj_asc + desc } else { 0.0 };
@@ -609,7 +610,7 @@ impl<'e> Breaker<'e> {
(LineSpacing::Multiple(m), Some(g)) => ((g.snap_height(natural) * m).max(g.snap_height(pictures)), true),
(LineSpacing::AtLeast(v), Some(g)) => (g.snap_height(natural.max(pictures)).max(v), true),
(LineSpacing::Multiple(m), None) => {
((text_natural + (m - 1.0) * run_leading + label_extra).max(text_pictures + (m - 1.0).max(0.0) * font_natural), false)
((text_natural + (m - 1.0) * run_leading + label_extra).max(text_pictures + (m - 1.0).max(0.0) * picture_leading), false)
}
(LineSpacing::AtLeast(v), None) => (natural.max(text_pictures).max(v), false),
(LineSpacing::Exactly(v), _) => (v, false),
+147 -36
View File
@@ -40,6 +40,11 @@ pub struct MergeEdges {
pub top: Vec<Placed>,
/// When the row is the last on a page: the closing bottom border of a merge running on.
pub end: Vec<Placed>,
/// `(x, w)` of each vertical merge in this row that continues onto the following row.
pub spans: Vec<(f32, f32)>,
/// `(x, w)` of each vertical merge that ends in this row: it too continues past the first part
/// of the row when the row is split.
pub ends: Vec<(f32, f32)>,
}
/// A cell of a [`RowLayout`].
@@ -915,13 +920,33 @@ fn grow_vertical_merges(rows: &[Vec<CellBox>], heights: &mut [f32]) {
}
}
/// Remember the fill (or none) each restart cell gives its merge's continuation.
fn note_restart_fills(merge_fill: &mut std::collections::HashMap<usize, Rgb>, cells: &[CellBox]) {
for c in cells.iter().filter(|c| c.vmerge == VMerge::Restart) {
/// Remember the fill and background picture (or none) each restart cell gives its merge's continuation.
fn note_restarts<'a>(
merge_fill: &mut std::collections::HashMap<usize, Rgb>,
merge_picture: &mut std::collections::HashMap<usize, &'a wordcraft_doc::props::CellPicture>,
table: &'a Table,
ri: usize,
cells: &[CellBox],
) {
for (ci, c) in cells.iter().enumerate().filter(|(_, c)| c.vmerge == VMerge::Restart) {
match c.fill {
Some(f) => merge_fill.insert(c.g, f),
None => merge_fill.remove(&c.g),
};
match table.rows.get(ri).and_then(|r| r.cells.get(ci)).and_then(|cell| cell.props.picture.as_deref()) {
Some(pic) => merge_picture.insert(c.g, pic),
None => merge_picture.remove(&c.g),
};
}
}
/// Append a cell's clipped background picture to `items` if it produces any placed images.
fn push_cell_picture(items: &mut Vec<Placed>, pic: Option<&wordcraft_doc::props::CellPicture>, rect: Rect, story: StoryRef, path: &[u32]) {
if let Some(pic) = pic {
let images = cell_picture(pic, rect, story, path);
if !images.is_empty() {
items.push(Placed::Clip { rect, spin: wordcraft_geom::Spin::default(), items: images });
}
}
}
@@ -941,6 +966,17 @@ struct TableRows<'a> {
only: Option<(usize, f32)>,
}
/// Total height of a vertical merge from row `ri` (starting at `rh`) through its continuing rows.
fn cont_height(cont: &[Vec<usize>], heights: &[f32], ri: usize, g: usize, rh: f32) -> f32 {
let mut total = rh;
let mut k = ri + 1;
while cont.get(k).is_some_and(|v| v.contains(&g)) {
total += heights.get(k).copied().unwrap_or(0.0);
k += 1;
}
total
}
/// Place the laid-out cells of every row: vertical alignment, turned text, borders and the cell
/// rectangles, clipped where the row's exact height or a fixed table's column is too small for
/// the cell's text.
@@ -965,10 +1001,11 @@ fn finish_table_rows(ctx: &mut Ctx, input: TableRows<'_>) -> TableLayout {
// Second pass: place cells with their row height, fills and borders.
let mut out = Vec::with_capacity(rows.len());
let mut merge_fill: std::collections::HashMap<usize, Rgb> = std::collections::HashMap::new();
let mut merge_picture: std::collections::HashMap<usize, &wordcraft_doc::props::CellPicture> = std::collections::HashMap::new();
for (ri, cells) in rows.into_iter().enumerate() {
if only.is_some_and(|(row, _)| row != ri) {
// The restart fills of earlier rows still shade the continuation of a merge.
note_restart_fills(&mut merge_fill, &cells);
// The restart fills and background pictures of earlier rows still apply to the continuation of a merge.
note_restarts(&mut merge_fill, &mut merge_picture, t, ri, &cells);
continue;
}
let rh = heights.get(ri).copied().unwrap_or(0.0);
@@ -979,14 +1016,7 @@ fn finish_table_rows(ctx: &mut Ctx, input: TableRows<'_>) -> TableLayout {
for (ci, c) in cells.into_iter().enumerate() {
let first = items.len();
// A restart cell spans several rows: its height is their sum.
let mut span_h = rh;
if c.vmerge == VMerge::Restart {
let mut k = ri + 1;
while cont.get(k).is_some_and(|v| v.contains(&c.g)) {
span_h += heights.get(k).copied().unwrap_or(0.0);
k += 1;
}
}
let span_h = if c.vmerge == VMerge::Restart { cont_height(&cont, &heights, ri, c.g, rh) } else { rh };
let rect = Rect::new(c.x, 0.0, c.w, span_h);
if c.vmerge != VMerge::Continue
&& let Some(f) = c.fill
@@ -994,13 +1024,14 @@ fn finish_table_rows(ctx: &mut Ctx, input: TableRows<'_>) -> TableLayout {
items.push(Placed::Fill { rect, color: f });
}
// Its background picture, over the shading and under the text, cut off at its edges.
if c.vmerge != VMerge::Continue
&& let Some(pic) = t.rows.get(ri).and_then(|r| r.cells.get(ci)).and_then(|cell| cell.props.picture.as_deref())
{
let images = cell_picture(pic, rect, story, path);
if !images.is_empty() {
items.push(Placed::Clip { rect, spin: wordcraft_geom::Spin::default(), items: images });
}
if c.vmerge != VMerge::Continue {
push_cell_picture(
&mut items,
t.rows.get(ri).and_then(|r| r.cells.get(ci)).and_then(|cell| cell.props.picture.as_deref()),
rect,
story,
path,
);
}
// Behind-text frames count towards vertical alignment even without inline content.
// They do not increase the row's flow height.
@@ -1076,28 +1107,36 @@ fn finish_table_rows(ctx: &mut Ctx, input: TableRows<'_>) -> TableLayout {
items.push(Placed::Rule { x0: hx0, y0, x1: hx1, y1: y0, border: e });
}
let last_of_merge = c.vmerge == VMerge::None || !cont.get(ri + 1).is_some_and(|v| v.contains(&c.g));
if last_of_merge && let Some(e) = b.bottom.filter(Border::is_visible) {
items.push(Placed::Rule { x0: hx0, y0: y1, x1: hx1, y1, border: e });
}
if c.vmerge == VMerge::Restart {
match c.fill {
Some(f) => merge_fill.insert(c.g, f),
None => merge_fill.remove(&c.g),
};
match t.rows.get(ri).and_then(|r| r.cells.get(ci)).and_then(|cell| cell.props.picture.as_deref()) {
Some(pic) => merge_picture.insert(c.g, pic),
None => merge_picture.remove(&c.g),
};
}
if !last_of_merge && let Some(e) = b.bottom.filter(Border::is_visible) {
merge.end.push(Placed::Rule { x0: hx0, y0: y1, x1: hx1, y1, border: e });
if !last_of_merge {
merge.spans.push((c.x, c.w));
if let Some(e) = b.bottom.filter(Border::is_visible) {
merge.end.push(Placed::Rule { x0: hx0, y0: y1, x1: hx1, y1, border: e });
}
} else {
if c.vmerge == VMerge::Continue {
merge.ends.push((c.x, c.w));
}
if let Some(e) = b.bottom.filter(Border::is_visible) {
items.push(Placed::Rule { x0: hx0, y0: y1, x1: hx1, y1, border: e });
}
}
if c.vmerge == VMerge::Continue {
let mut left = rh;
let mut k = ri + 1;
while cont.get(k).is_some_and(|v| v.contains(&c.g)) {
left += heights.get(k).copied().unwrap_or(0.0);
k += 1;
}
let left = cont_height(&cont, &heights, ri, c.g, rh);
let cont_rect = Rect::new(c.x, 0.0, c.w, left);
if let Some(color) = merge_fill.get(&c.g) {
merge.top.push(Placed::Fill { rect: Rect::new(c.x, 0.0, c.w, left), color: *color });
merge.top.push(Placed::Fill { rect: cont_rect, color: *color });
}
push_cell_picture(&mut merge.top, merge_picture.get(&c.g).copied(), cont_rect, story, path);
if let Some(e) = b.top.filter(Border::is_visible) {
merge.top.push(Placed::Rule { x0: hx0, y0, x1: hx1, y1: y0, border: e });
}
@@ -1434,7 +1473,13 @@ fn split_row_with(row: &RowLayout, cut: f32, whole_cells: bool) -> Option<(RowLa
bottom: row.bottom,
edge: 0.0,
cells: Vec::new(),
merge: MergeEdges { top: row.merge.top.clone(), end: at_y(&row.merge.end, cut) },
// Every merge in the row runs on from this part, those ending in the row too.
merge: MergeEdges {
top: row.merge.top.clone(),
end: at_y(&row.merge.end, cut),
spans: [row.merge.spans.as_slice(), &row.merge.ends].concat(),
ends: Vec::new(),
},
},
RowLayout {
height,
@@ -1442,7 +1487,12 @@ fn split_row_with(row: &RowLayout, cut: f32, whole_cells: bool) -> Option<(RowLa
bottom: row.bottom,
edge: row.edge,
cells: parts,
merge: MergeEdges { top: shorter(&row.merge.top, row.height - height), end: at_y(&row.merge.end, height) },
merge: MergeEdges {
top: shorter(&row.merge.top, row.height - height),
end: at_y(&row.merge.end, height),
spans: row.merge.spans.clone(),
ends: row.merge.ends.clone(),
},
},
))
}
@@ -1463,12 +1513,19 @@ fn at_y(items: &[Placed], y: f32) -> Vec<Placed> {
.collect()
}
/// The fills of a merge's top edge for a continuation `by` points shorter than its row.
/// Shorten a merge's continuation backgrounds by the height removed from its first row.
fn shorter(items: &[Placed], by: f32) -> Vec<Placed> {
let shorten = |rect: &Rect| Rect::new(rect.x, rect.y, rect.w, rect.h - by);
items
.iter()
.map(|it| match it {
Placed::Fill { rect, color } => Placed::Fill { rect: Rect::new(rect.x, rect.y, rect.w, (rect.h - by).max(0.0)), color: *color },
Placed::Fill { rect, color } => Placed::Fill { rect: shorten(rect), color: *color },
Placed::Clip { rect, spin, items } => {
let rect = shorten(rect);
// Keep the original picture geometry, including any tile that crosses the new bottom.
let items = items.iter().filter(|it| !matches!(it, Placed::Image { rect: image, .. } if !rect.intersects(image))).cloned().collect();
Placed::Clip { rect, spin: *spin, items }
}
other => other.clone(),
})
.collect()
@@ -2068,6 +2125,60 @@ fn autofit(grid: &mut [f32], content: &[(f32, f32)], t: &Table, avail: f32) {
}
}
#[cfg(test)]
mod merged_min_height_tests {
use super::*;
// The vertical merge used by turned-text layout in #6529, with three rows
// in the right-hand column and a fourth row outside the merge.
fn three_row_merge() -> Table {
let mut table = Table::new(4, 2, 100.0);
for (row, (merge, height)) in
table.rows.iter_mut().zip([(VMerge::Restart, 24.0), (VMerge::Continue, 32.0), (VMerge::Continue, 40.0), (VMerge::None, 64.0)])
{
row.cells[1].props.vmerge = merge;
row.props.height_rule = HeightRule::AtLeast;
row.props.height = Some(height);
}
table
}
#[test]
fn merged_min_height_sums_all_three_rows() {
assert_eq!(merged_min_height(&three_row_merge(), 0, 1), Some(96.0));
}
#[test]
fn merged_min_height_requires_a_restart_followed_by_a_continuation() {
let mut table = three_row_merge();
assert_eq!(merged_min_height(&table, 1, 1), None, "a continuation is not a restart");
table.rows[1].cells[1].props.vmerge = VMerge::None;
assert_eq!(merged_min_height(&table, 0, 1), None, "a continuation below a gap does not count");
}
#[test]
fn merged_min_height_requires_valid_at_least_heights_throughout() {
let mut table = three_row_merge();
for i in 0..3 {
let original = table.rows[i].props.clone();
for (rule, height) in [
(HeightRule::Auto, Some(32.0)),
(HeightRule::Exact, Some(32.0)),
(HeightRule::AtLeast, None),
(HeightRule::AtLeast, Some(0.0)),
(HeightRule::AtLeast, Some(-1.0)),
(HeightRule::AtLeast, Some(f32::INFINITY)),
(HeightRule::AtLeast, Some(f32::NAN)),
] {
table.rows[i].props.height_rule = rule;
table.rows[i].props.height = height;
assert_eq!(merged_min_height(&table, 0, 1), None, "row {i}: {rule:?}, {height:?}");
}
table.rows[i].props = original;
}
}
}
#[cfg(test)]
mod width_tests {
use super::*;
+19 -6
View File
@@ -253,6 +253,8 @@ pub(crate) fn place_table(ctx: &mut Ctx, pb: &mut PageBuilder, t: &wordcraft_doc
// Where the items of this table's rows on the page and column start; none before a row is placed.
let page_from = std::cell::Cell::new(None::<usize>);
let pending_end: std::cell::RefCell<Vec<Placed>> = std::cell::RefCell::new(Vec::new());
let pending_spans: std::cell::RefCell<Vec<(f32, f32)>> = std::cell::RefCell::new(Vec::new());
let in_spans = |spans: &[(f32, f32)], rect: &Rect| spans.iter().any(|&(sx, sw)| (rect.x - sx).abs() < 0.01 && (rect.w - sw).abs() < 0.01);
let place = |pb: &mut PageBuilder, row: &table::RowLayout, body: bool| {
let (x, y) = (pb.col_x() + tl.x, pb.y);
let limit = pb.bottom.max(y + row.height);
@@ -270,19 +272,28 @@ pub(crate) fn place_table(ctx: &mut Ctx, pb: &mut PageBuilder, t: &wordcraft_doc
it
})
.collect();
*pending_spans.borrow_mut() = row.merge.spans.iter().map(|&(mx, mw)| (x + mx, mw)).collect();
}
if let Some(pg) = pb.page() {
if starts_page {
page_from.set(Some(pg.items.len()));
}
// The continuing fill goes under the row's items (their borders), its top rules over them.
// Continuing shading and pictures go under the row's content and borders.
// The merge's opening border still goes above the row.
let top = if starts_page { row.merge.top.as_slice() } else { &[] };
let (fills, rules) = (top.iter().filter(|i| matches!(i, Placed::Fill { .. })), top.iter().filter(|i| !matches!(i, Placed::Fill { .. })));
for it in fills.chain(&row.items).chain(rules) {
let is_background = |it: &&Placed| matches!(it, Placed::Fill { .. } | Placed::Clip { .. });
let backgrounds = top.iter().filter(is_background);
let rules = top.iter().filter(|it| !is_background(it));
for it in backgrounds.chain(&row.items).chain(rules) {
let mut it = it.clone();
let is_merge = match &it {
Placed::Fill { rect, .. } | Placed::Clip { rect, .. } | Placed::Cell { rect, .. } => in_spans(&row.merge.spans, rect),
_ => false,
};
it.translate(x, y);
// The area ends at this page's bottom, #8872.
if let Placed::Fill { rect, .. } | Placed::Clip { rect, .. } | Placed::Cell { rect, .. } = &mut it
// The merged cell's area ends at this page's bottom, #8872 / #9191.
if is_merge
&& let Placed::Fill { rect, .. } | Placed::Clip { rect, .. } | Placed::Cell { rect, .. } = &mut it
&& rect.bottom() > limit
{
rect.h = (limit - rect.y).max(0.0);
@@ -296,11 +307,13 @@ pub(crate) fn place_table(ctx: &mut Ctx, pb: &mut PageBuilder, t: &wordcraft_doc
// The page ends here: close the merges running on to the next one.
let close_merges = |pb: &mut PageBuilder| {
let end = std::mem::take(&mut *pending_end.borrow_mut());
let spans = std::mem::take(&mut *pending_spans.borrow_mut());
let bottom = pb.y;
if let Some(pg) = pb.page() {
// The merged cells' areas end with the last row on the page.
// Only the merged cells' areas end with the last row on the page (#9191).
for it in pg.items.iter_mut().skip(page_from.get().unwrap_or(usize::MAX)) {
if let Placed::Fill { rect, .. } | Placed::Clip { rect, .. } | Placed::Cell { rect, .. } = it
&& in_spans(&spans, rect)
&& rect.y < bottom
&& rect.bottom() > bottom
{
+378 -6
View File
@@ -3469,6 +3469,39 @@ fn a_vertical_merge_across_a_page_break_stays_inside_the_page() {
assert!(spanning, "the merge still spans the rows left on the page");
}
/// The same when the merge's last row is the one split: on each page its area ends with the
/// part of that row there, whether the merge starts on that page or runs on from an earlier one.
#[test]
fn a_vertical_merge_whose_last_row_splits_ends_with_each_part() {
crate::test_fonts();
use wordcraft_doc::props::{Rgb, VMerge};
let mut d = Document::new();
let mut t = Table::new(20, 2, 468.0);
for (i, row) in t.rows.iter_mut().enumerate() {
row.cells[0].props.vmerge = match i {
10 => VMerge::Restart,
11..=13 => VMerge::Continue,
_ => VMerge::None,
};
}
t.rows[10].cells[0].props.shading = Some(Rgb(200, 0, 0));
t.rows[13].cells[1].blocks = (0..80).map(|_| wordcraft_doc::para_block(Paragraph::with_text("line", Default::default()))).collect();
d.insert_block(StoryRef::Body, &Path::top(0), wordcraft_doc::Block::Table(t)).unwrap();
let l = lay(&d);
let mut shaded_pages = 0;
for page in &l.pages {
// Where the rows on this page end, by the unmerged column.
let rows_end =
page.items.iter().filter_map(|i| if let Placed::Cell { rect, cell: 1, .. } = i { Some(rect.bottom()) } else { None }).fold(0.0, f32::max);
let fills: Vec<Rect> = page.items.iter().filter_map(|i| if let Placed::Fill { rect, .. } = i { Some(*rect) } else { None }).collect();
shaded_pages += usize::from(!fills.is_empty());
for rect in fills {
assert!(rect.bottom() <= rows_end + 0.01, "{rect:?} runs past the rows on its page, which end at {rows_end}");
}
}
assert!(shaded_pages >= 3, "the last row splits over more than one page break: {shaded_pages}");
}
#[test]
fn a_vertical_merge_aligns_its_text_with_the_first_page() {
crate::test_fonts();
@@ -10455,11 +10488,14 @@ fn multiple_spacing_adds_a_multiple_of_the_tallest_run_not_of_the_mixed_line() {
// run's own height to it, not (m - 1) x the line's (Word for Mac and Windows: 10pt Times New
// Roman with 10pt Courier New, 18.09pt at 1.5 spacing where 1.5 x the 12.34pt line gives 18.51).
let font = |(f, size): (&str, f32)| wordcraft_doc::CharProps { font: Some(f.into()), size: Some(size), ..Default::default() };
let height = |fonts: &[(&str, f32)], m: f32| {
let height = |fonts: &[(&str, f32)], m: f32, with_picture: bool| {
let mut p = wordcraft_doc::Paragraph::with_text("run ", font(fonts[0]));
for &f in &fonts[1..] {
p.append(wordcraft_doc::Paragraph::with_text("run ", font(f)));
}
if with_picture {
p.insert_object(p.len(), picture(30.0, 40.0, Default::default()), &font(fonts[0])).unwrap();
}
p.props = ParaProps { line_spacing: Some(wordcraft_doc::props::LineSpacing::Multiple(m)), ..Default::default() };
let mut d = Document::new();
d.body = vec![wordcraft_doc::para_block(p)];
@@ -10468,12 +10504,19 @@ fn multiple_spacing_adds_a_multiple_of_the_tallest_run_not_of_the_mixed_line() {
};
// The larger sans has the taller ascent, the serif the deeper descent.
let (sans, serif) = (("Inter", 12.0), ("Source Serif 4", 10.5));
let tallest = height(&[sans], 1.0).max(height(&[serif], 1.0));
let mixed = height(&[sans, serif], 1.0);
let tallest = height(&[sans], 1.0, false).max(height(&[serif], 1.0, false));
let mixed = height(&[sans, serif], 1.0, false);
assert!(mixed > tallest + 0.1, "the fonts don't make a taller line together: {mixed} vs {tallest}");
for m in [1.5, 2.0] {
let got = height(&[sans, serif], m);
assert!((got - (mixed + (m - 1.0) * tallest)).abs() < 0.01, "{m}: {got}, line {mixed}, tallest run {tallest}");
let with_picture = height(&[sans, serif], 1.0, true);
assert!(with_picture > mixed, "the tall picture raises the line height");
for (with_picture, single_height) in [(false, mixed), (true, with_picture)] {
for m in [1.5, 2.0] {
let got = height(&[sans, serif], m, with_picture);
assert!(
(got - (single_height + (m - 1.0) * tallest)).abs() < 0.01,
"{m}, picture {with_picture}: {got}, line {single_height}, tallest run {tallest}"
);
}
}
}
@@ -13338,6 +13381,44 @@ fn balanced_columns_keep_a_continued_tail_with_the_space_after_it() {
assert!((q.2 - (tail_top + 28.0 + 28.0)).abs() < 0.5, "Q under P5's space after: Q {q:?}, P {pieces:?}");
}
/// #9206: a paragraph that closes a balanced section with `keep_next` must not reserve column
/// room in `kept_tail_end` for the next section's first paragraph.
#[test]
fn balanced_columns_do_not_keep_a_section_closing_tail_with_the_next_section() {
crate::test_fonts();
use wordcraft_doc::props::LineSpacing;
use wordcraft_doc::section::{SectionProps, SectionStart};
let lb = wordcraft_doc::para::LINE_BREAK;
let filler = 135;
let make_doc = |keep_next: bool| {
let mut text: Vec<String> = (0..filler).map(|i| format!("F{i}")).collect();
text.push("P1".into());
text.push("Q".into());
let mut d = Document::from_text(&text.join("\n"));
for block in &mut d.body {
if let Block::Para(para) = Arc::make_mut(block) {
para.props.line_spacing = Some(LineSpacing::Exactly(14.0));
para.props.space_before = Some(0.0);
para.props.space_after = Some(0.0);
}
}
let mut s = SectionProps::default();
s.columns.count = 3;
let p = d.para_mut(StoryRef::Body, &Path::top(filler)).unwrap();
let rest: String = (2..=12).map(|i| format!("{lb}P{i}")).collect();
p.insert_text(2, &rest, &Default::default()).unwrap();
p.props.keep_next = Some(keep_next);
p.section = Some(Box::new(s));
d.last_section.start = SectionStart::Continuous;
d
};
let without = lay(&make_doc(false));
let with_keep = lay(&make_doc(true));
assert_eq!(pieces_of(&with_keep, filler), pieces_of(&without, filler), "keep_next on section-closing tail must not unbalance columns");
assert_eq!(para_boxes(&with_keep)[filler + 1], para_boxes(&without)[filler + 1], "Q below the balanced section must stay at the same y");
}
/// #9208: when the next paragraph's `space_before` is dropped by contextual spacing, `kept_tail_end`
/// must not count it on top of `gap_after`.
#[test]
@@ -19636,6 +19717,89 @@ fn header_margin_wrap_retry_counts_labels_once() {
assert_eq!(retried, labels(Wrap::BehindText), "the retried header counts like the one laid out once");
}
/// #9226: an even-page header is never measured for `page.body.y`, so it keeps its rendered
/// margin-area layout instead of retrying with the declared margins.
#[test]
fn even_page_header_does_not_retry_with_declared_margins() {
use wordcraft_doc::para::{Anchor, Float, FloatAlign, Wrap};
let even_shape_y = |wrap: Wrap| {
let mut doc = Document::from_text(&"Body\n".repeat(120));
doc.settings.even_odd_headers = true;
let s = &mut doc.last_section;
s.margin_top = 20.0;
s.margin_bottom = 20.0;
s.header = 36.0;
s.footer = 36.0;
let (pw, ph) = (s.page_w, s.page_h);
// Short default header/footer so `page.body.y == 36.0 + 10.0 = 46.0` (smaller than the even header).
let def_h = doc.add_part(
wordcraft_doc::PartKind::Header,
vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("Odd", Default::default()))],
);
let def_f = doc.add_part(wordcraft_doc::PartKind::Footer, vec![wordcraft_doc::para_block(boundary_header_para())]);
let mut hp = boundary_header_para();
let float = Float { wrap, h_rel: Anchor::Page, v_rel: Anchor::Margin, v_align: Some(FloatAlign::End), ..Default::default() };
hp.insert_object(0, rect_shape(pw, ph - 136.0, float), &Default::default()).unwrap();
let even_h = doc.add_part(wordcraft_doc::PartKind::Header, vec![wordcraft_doc::para_block(hp)]);
let s = &mut doc.last_section;
s.headers.default = Some(def_h);
s.headers.even = Some(even_h);
s.footers.default = Some(def_f);
let laid = lay(&doc);
assert!(laid.pages.len() >= 2);
shapes(&laid.pages[1].header)[0].y
};
assert!((even_shape_y(Wrap::Square) - even_shape_y(Wrap::BehindText)).abs() < 0.01);
}
#[test]
fn header_table_areas_match_retried_header_margin_fallback() {
use wordcraft_doc::para::{Anchor, Float, FloatAlign, Wrap};
use wordcraft_doc::props::{HeightRule, TableFloat};
let mut doc = Document::from_text("Body");
let s = &mut doc.last_section;
s.margin_top = 20.0;
s.margin_bottom = 20.0;
s.header = 36.0;
s.footer = 36.0;
let (pw, ph) = (s.page_w, s.page_h);
// Header has a wrapping Margin-bottom picture that triggers the retry with declared margins,
// plus a Margin-bottom floating table.
let mut hp = boundary_header_para();
let float = Float { wrap: Wrap::Square, h_rel: Anchor::Page, v_rel: Anchor::Margin, v_align: Some(FloatAlign::End), ..Default::default() };
hp.insert_object(0, rect_shape(pw, ph - 136.0, float), &Default::default()).unwrap();
let mut header_table = Table::new(1, 1, 80.0);
header_table.rows[0].props.height = Some(20.0);
header_table.rows[0].props.height_rule = HeightRule::Exact;
header_table.props.float =
Some(TableFloat { h_rel: Anchor::Page, v_rel: Anchor::Margin, v_align: Some(FloatAlign::End), x: 300.0, ..Default::default() });
let header = doc.add_part(wordcraft_doc::PartKind::Header, vec![wordcraft_doc::para_block(hp), Arc::new(Block::Table(header_table))]);
doc.last_section.headers.default = Some(header);
let footer = doc.add_part(wordcraft_doc::PartKind::Footer, vec![wordcraft_doc::para_block(boundary_header_para())]);
doc.last_section.footers.default = Some(footer);
// Place a body floating table at the rendered-area bottom position (ph - 86 - 20). Because the
// drawn header falls back to declared margins (ph - 20 - 20), the two tables do not overlap
// and the body table must stay at ph - 106.0.
let mut body_table = Table::new(1, 1, 80.0);
body_table.rows[0].props.height = Some(20.0);
body_table.rows[0].props.height_rule = HeightRule::Exact;
let rendered_y = ph - 86.0 - 20.0;
body_table.props.float = Some(TableFloat { h_rel: Anchor::Page, v_rel: Anchor::Page, x: 300.0, y: rendered_y, ..Default::default() });
doc.body.insert(0, Arc::new(Block::Table(body_table)));
let laid = lay(&doc);
let page = &laid.pages[0];
let cell_y = |items: &[Placed]| items.iter().find_map(|it| if let Placed::Cell { rect, .. } = it { Some(rect.y) } else { None }).unwrap();
let header_tbl_y = cell_y(&page.header);
let body_tbl_y = cell_y(&page.items);
assert!((header_tbl_y - (ph - 20.0 - 20.0)).abs() < 0.01, "header table at declared margin: {header_tbl_y}");
assert!((body_tbl_y - rendered_y).abs() < 0.01, "body table should not avoid ghost rendered-area header table: {body_tbl_y} vs {rendered_y}");
}
#[test]
fn header_boundary_obstacle() {
use wordcraft_doc::para::Anchor;
@@ -19813,6 +19977,89 @@ fn header_margin_table_area() {
}
}
/// #9383: the final part of a split continuation row keeps its own background extent.
#[test]
fn a_split_merge_continuation_picture_ends_at_the_following_row() {
use display::Draw;
use wordcraft_doc::props::{CellPicture, HeightRule, LineSpacing, PictureRepeat, Rgb, VMerge};
let paragraph = |text: &str| {
let mut p = Paragraph::with_text(text, Default::default());
p.props.line_spacing = Some(LineSpacing::Exactly(14.0));
p.props.space_before = Some(0.0);
p.props.space_after = Some(0.0);
wordcraft_doc::para_block(p)
};
let shade = Rgb(220, 185, 70);
let tile = [30.0, 7.0];
for split in [false, true] {
let mut d = pagination_fixture_document("");
d.last_section.page_h = 320.0;
d.last_section.margin_top = 40.0;
d.last_section.margin_bottom = 40.0;
let media = d.add_media(vec![0u8; 8], "png");
let mut table = Table::new(3, 2, 200.0);
let start = &mut table.rows[0].cells[0];
start.props.vmerge = VMerge::Restart;
start.props.shading = Some(shade);
start.props.picture = Some(Box::new(CellPicture { media: media.clone(), size: tile, repeat: PictureRepeat::Tile, align: [0.0, 0.0] }));
start.blocks = vec![paragraph("Merged")];
table.rows[0].cells[1].blocks = vec![paragraph("Start")];
table.rows[1].cells[0].props.vmerge = VMerge::Continue;
table.rows[1].cells[1].blocks = (0..if split { 26 } else { 3 }).map(|_| paragraph("Continued")).collect();
table.rows[2].cells[0].blocks = vec![paragraph("Following")];
if !split {
// The short continuation moves on whole, so it still opens its second page.
table.rows[0].props.height = Some(220.0);
table.rows[0].props.height_rule = HeightRule::Exact;
table.rows[1].props.cant_split = true;
}
d.body = vec![Arc::new(Block::Table(table)), paragraph("Aftertable")];
let layout = lay(&d);
let parts: Vec<_> = (0..layout.pages.len()).filter_map(|i| cell_rect(&layout, i, 1, 0).map(|rect| (i, rect))).collect();
assert_eq!(parts.len(), if split { 2 } else { 1 }, "split={split}: {parts:?}");
let &(last, continuation) = parts.last().unwrap();
assert!(last > 0, "the final fragment opens a later page");
let following = cell_rect(&layout, last, 2, 0).expect("the next row shares the final page");
let draws = display::page_display(&d, &layout.pages[last], &display::DisplayOptions::default());
let (clip, tiles) = draws
.iter()
.find_map(|draw| match draw {
Draw::Clip { rect, items } if items.iter().any(|item| matches!(item, Draw::Image { media: key, .. } if *key == media)) => {
Some((rect, items))
}
_ => None,
})
.expect("continued background picture");
assert!((clip.y - continuation.y).abs() < 0.01 && (clip.h - continuation.h).abs() < 0.01, "split={split}: {clip:?} vs {continuation:?}");
assert!(clip.bottom() <= following.y + 0.01, "the picture ends before the following row");
assert!(
draws.iter().any(|draw| matches!(draw, Draw::Fill { rect, color, .. }
if *color == shade && *rect == *clip)),
"solid shading has the same extent"
);
let images: Vec<_> = tiles
.iter()
.filter_map(|item| match item {
Draw::Image { rect, media: key, .. } if *key == media => Some(rect),
_ => None,
})
.collect();
assert!(images.iter().all(|image| clip.intersects(image) && image.w == tile[0] && image.h == tile[1]));
assert!(images.iter().any(|image| (image.y - clip.y).abs() < 0.01), "the first tile stays at the top");
assert!(images.iter().any(|image| image.bottom() >= clip.bottom() - 0.01), "the last tile reaches the clipped edge");
for following_text in ["Following", "Aftertable"] {
assert!(
draws.iter().any(|draw| matches!(draw, Draw::Glyphs { text, glyphs, .. }
if text == following_text && !glyphs.is_empty() && glyphs.iter().all(|g| g.2 > clip.bottom()))),
"{following_text} is drawn below the background"
);
}
}
}
mod shape_alpha;
/// A row with a background picture split over two pages: each part draws its own piece of the
@@ -19843,6 +20090,131 @@ fn a_split_cells_background_picture_is_drawn_on_both_parts() {
}
}
/// #9192 and #9362: a vertically merged cell draws its clipped background picture behind
/// the text and borders on the first page and on continuation pages.
#[test]
fn a_merged_cells_background_picture_is_drawn_on_both_pages() {
use display::Draw;
use wordcraft_doc::props::{Border, Borders, CellPicture, PictureRepeat, Rgb, VMerge};
let mut d = Document::new();
let mut t = wordcraft_doc::Table::new(50, 2, 100.0);
let media = d.add_media(vec![0u8; 8], "png");
let shade = Rgb(240, 230, 150);
let border_color = Rgb(20, 40, 150);
let border = Some(Border { color: Some(border_color), ..Border::single(6.0) });
t.props.borders = Some(Borders { left: border, inside_v: border, ..Default::default() });
let restart = &mut t.rows[0].cells[0];
restart.props.vmerge = VMerge::Restart;
restart.props.shading = Some(shade);
restart.props.picture = Some(Box::new(CellPicture { media, size: [30.0, 6.0], repeat: PictureRepeat::Tile, align: [0.0, 0.0] }));
restart.blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text("Cell", Default::default()))];
for (r, row) in t.rows.iter_mut().enumerate() {
if r > 0 {
row.cells[0].props.vmerge = VMerge::Continue;
}
row.cells[1].blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text(&format!("Row {r}"), Default::default()))];
}
d.body = vec![std::sync::Arc::new(wordcraft_doc::Block::Table(t)), wordcraft_doc::para_block(wordcraft_doc::Paragraph::new())];
let l = lay(&d);
assert!(l.pages.len() >= 2, "the merged table spans at least two pages");
for (n, page) in l.pages.iter().take(2).enumerate() {
let clips: Vec<Rect> = page.items.iter().filter_map(|it| if let Placed::Clip { rect, .. } = it { Some(*rect) } else { None }).collect();
assert_eq!(clips.len(), 1, "page {n}: expected continued merged-cell picture clip, got {clips:?}");
let picture_rect = clips[0];
assert!(picture_rect.h > 0.0 && picture_rect.bottom() <= page.h + 0.01, "page {n}: {picture_rect:?}");
let draws = display::page_display(&d, page, &display::DisplayOptions::default());
let fill = draws
.iter()
.position(|item| matches!(item, Draw::Fill { color, rect, .. } if *color == shade && *rect == picture_rect))
.expect("merged-cell shading");
let picture = draws
.iter()
.position(|item| {
matches!(item, Draw::Clip { rect, items }
if *rect == picture_rect && items.iter().any(|item| matches!(item, Draw::Image { .. })))
})
.expect("clipped background picture");
assert!(fill < picture, "page {n}: shading goes behind the picture");
for x in [picture_rect.x, picture_rect.right()] {
let side = draws
.iter()
.position(|item| {
matches!(item, Draw::Line { color, width, x0, y0, x1, y1, .. }
if *color == border_color && *width >= 6.0 && (*x0 - x).abs() < 0.01 && (*x1 - x).abs() < 0.01
&& (*y0 - picture_rect.y).abs() < 0.01 && *y1 > *y0)
})
.unwrap_or_else(|| panic!("page {n}: first-row border at x={x}"));
assert!(picture < side, "page {n}: the picture must be behind the first-row side border at x={x}");
}
let text = draws.iter().position(|item| matches!(item, Draw::Glyphs { text, .. } if !text.trim().is_empty())).expect("first row text");
assert!(picture < text, "page {n}: the picture goes behind the text");
}
}
/// #9191: page-end trimming in `table_flow` must cut only continuing merged-cell areas, not
/// unrelated `Clip` items (such as a floating drawing canvas anchored in a row).
#[test]
fn page_end_trimming_does_not_cut_a_floating_canvas_clip_in_a_table_row() {
use wordcraft_doc::para::{Anchor, CanvasStyle, Float, GroupChild, ShapeKind, Wrap};
use wordcraft_doc::props::{Rgb, VMerge};
let mut d = Document::new();
let mut t = wordcraft_doc::Table::new(50, 2, 200.0);
t.rows[0].cells[0].props.vmerge = VMerge::Restart;
t.rows[0].cells[0].props.shading = Some(Rgb(10, 20, 30));
for (r, row) in t.rows.iter_mut().enumerate() {
if r > 0 {
row.cells[0].props.vmerge = VMerge::Continue;
}
row.cells[1].blocks = vec![wordcraft_doc::para_block(wordcraft_doc::Paragraph::with_text(&format!("Row {r}"), Default::default()))];
}
d.body = vec![std::sync::Arc::new(wordcraft_doc::Block::Table(t)), wordcraft_doc::para_block(wordcraft_doc::Paragraph::new())];
let probe = lay(&d);
assert!(probe.pages.len() >= 2);
let last_row = probe.pages[0]
.items
.iter()
.filter_map(|it| match it {
Placed::Cell { row, .. } => Some(*row),
_ => None,
})
.max()
.expect("page 0 has table rows");
let member = InlineObject::Shape {
kind: ShapeKind::Rectangle,
w: 40.0,
h: 30.0,
fill: Some(Fill::solid(Rgb(40, 50, 60))),
stroke: None,
stroke_width: 0.0,
float: Float::default(),
story: None,
effects: Default::default(),
freeform: None,
extra: Default::default(),
};
let canvas = InlineObject::Group {
w: 80.0,
h: 120.0,
float: Float { wrap: Wrap::InFrontOfText, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, y: 40.0, ..Default::default() },
ch_w: 80.0,
ch_h: 120.0,
children: vec![GroupChild { x: 10.0, y: 10.0, obj: member }],
canvas: Some(CanvasStyle { fill: Some(Fill::solid(Rgb(0xF0, 0xF4, 0xFF))), stroke: None, stroke_width: 0.0 }),
};
let mut p = wordcraft_doc::Paragraph::with_text(&format!("Row {last_row}"), Default::default());
p.insert_object(0, canvas, &Default::default()).unwrap();
if let wordcraft_doc::Block::Table(tbl) = std::sync::Arc::make_mut(&mut d.body[0]) {
tbl.rows[last_row].cells[1].blocks = vec![wordcraft_doc::para_block(p)];
}
let l = lay(&d);
let clips: Vec<Rect> = l.pages[0].items.iter().filter_map(|it| if let Placed::Clip { rect, .. } = it { Some(*rect) } else { None }).collect();
assert!(clips.iter().any(|r| (r.h - 120.0).abs() < 0.01), "floating canvas clip must keep its full 120 pt height: {clips:?}");
}
/// A table moved to a new page by a page break before its first paragraph shows the number of
/// the page it lands on in that cell's PAGE field, not the page it was laid out for.
#[test]
+85
View File
@@ -214,3 +214,88 @@ fn turned_line_stays_in_its_table_cell() {
assert!(l.turned_line(&at(cell, 0, 1), None, false, 0).is_none());
}
}
/// #9151: in a multi-page vertical section, stepping past the last column of page 0 enters the
/// first column of page 1, and stepping back from page 1's first column returns to page 0.
#[test]
fn turned_line_crosses_page_boundary() {
crate::test_fonts();
let text = (0..60).map(|i| format!("col{i:02}")).collect::<Vec<_>>().join("\n");
let mut d = Document::from_text(&text);
d.last_section.text_direction = TextDirection::Down;
let l = lay(&d);
assert!(l.pages.len() >= 2, "expected multiple pages, got {}", l.pages.len());
let page0_last_para = l.pages[0]
.items
.iter()
.filter_map(|it| match it {
crate::Placed::Lines { path, .. } => Some(path.last()),
_ => None,
})
.next_back()
.expect("page 0 has turned lines");
let page1_first_para = l.pages[1]
.items
.iter()
.filter_map(|it| match it {
crate::Placed::Lines { path, .. } => Some(path.last()),
_ => None,
})
.next()
.expect("page 1 has turned lines");
assert_eq!(page1_first_para, page0_last_para + 1);
let last_on_p0 = Pos::body(page0_last_para, 2);
let (next, g) = l.turned_line(&last_on_p0, None, true, 0).expect("steps onto page 1");
assert_eq!((&next.path, next.off), (&Path::top(page1_first_para), 2));
let (back, _) = l.turned_line(&next, Some(g), false, 1).expect("steps back onto page 0");
assert_eq!((back.path, back.off), (Path::top(page0_last_para), 2));
}
/// #9151: a header is laid out again on every page, so a vertical text box in it holds the same
/// columns on each; stepping past its last or first column stays in the box instead of entering
/// the copy on the adjacent page.
#[test]
fn turned_line_does_not_cross_pages_in_a_header_text_box() {
use wordcraft_doc::props::TextVert;
use wordcraft_doc::{PartKind, TextBody, para_block};
crate::test_fonts();
let text = (0..200).map(|i| format!("line{i:03}")).collect::<Vec<_>>().join("\n");
let mut d = Document::from_text(&text);
let boxed = d.add_part(
PartKind::TextBox,
vec![para_block(Paragraph::with_text("ab", Default::default())), para_block(Paragraph::with_text("cd", Default::default()))],
);
if let Some(p) = d.parts.get_mut(&boxed) {
p.body = TextBody { vert: TextVert::Vert, ..Default::default() };
}
let shape = InlineObject::Shape {
kind: wordcraft_doc::para::ShapeKind::TextBox,
w: 100.0,
h: 100.0,
fill: None,
stroke: None,
stroke_width: 1.0,
float: Default::default(),
story: Some(boxed),
effects: Default::default(),
freeform: None,
extra: Default::default(),
};
let mut p = Paragraph::with_text("Header", Default::default());
p.insert_object(6, shape, &Default::default()).unwrap();
let header = d.add_part(PartKind::Header, vec![para_block(p)]);
d.last_section.headers.default = Some(header);
let l = lay(&d);
assert!(l.pages.len() >= 4, "expected several pages, got {}", l.pages.len());
let at = |para: usize, off: usize| Pos { story: StoryRef::Part(boxed), path: Path::top(para), off };
// Within the box, the columns still step.
assert_eq!(l.turned_line(&at(0, 1), None, true, 1).map(|(p, _)| p.path), Some(Path::top(1)));
// Past its edges, there is no further column, on any page.
for page in 1..3 {
assert!(l.turned_line(&at(1, 1), None, true, page).is_none(), "next from the last column on page {page}");
assert!(l.turned_line(&at(0, 1), None, false, page).is_none(), "previous from the first column on page {page}");
}
}
+25 -13
View File
@@ -351,8 +351,8 @@ impl Exporter<'_> {
self.at.1 = page.reading.get(i).copied().unwrap_or(i).saturating_add(1).min(usize::MAX - 1);
let draws = shown.draws(it, &dopts);
match it {
Placed::Lines { story, path, para, .. } => {
let idx = self.entry(*story, path, para);
Placed::Lines { story, path, para, l0, l1, .. } => {
let idx = self.entry(*story, path, para, *l0..*l1);
for d in &draws {
self.line_item(s, d, idx, *story, path);
}
@@ -412,21 +412,33 @@ impl Exporter<'_> {
p.text_without(&dropped)
}
/// The structure entry for a paragraph on this page (created on first sight, in reading order).
fn entry(&mut self, story: StoryRef, path: &DocPath, pl: &wordcraft_layout::para::ParaLayout) -> usize {
if let Some(i) = self.tag_index.get(&(story, path.clone())) {
return *i;
}
let kind: TagKind = match self.doc.para(story, path).map(|p| self.doc.styles.resolve_para(&p.props).outline_level) {
Some(Some(l)) if l < 6 => {
/// The structure entry for a paragraph on this page. A heading starts at its first visible line.
fn entry(&mut self, story: StoryRef, path: &DocPath, pl: &wordcraft_layout::para::ParaLayout, lines: std::ops::Range<usize>) -> usize {
let key = (story, path.clone());
let existing = self.tag_index.get(&key).copied();
let heading: Option<TagKind> = match self.doc.para(story, path).map(|p| self.doc.styles.resolve_para(&p.props).outline_level) {
Some(Some(l)) if l < 6 && lines.contains(&nav::first_heading_line(pl)) => {
let title = self.doc.para(story, path).map(|p| self.title_text(p, pl).trim().chars().take(200).collect::<String>());
Tag::Hn(NonZeroU16::new(u16::from(l) + 1).unwrap_or(NonZeroU16::MIN), title).into()
Some(Tag::Hn(NonZeroU16::new(u16::from(l) + 1).unwrap_or(NonZeroU16::MIN), title).into())
}
_ => Tag::P.into(),
_ => None,
};
self.tags.push(TagEntry { kind, children: Vec::new(), source: Some((story, path.clone())), at: self.at });
if let Some(i) = existing {
// A break-only piece in an earlier column can already have opened an entry: empty, or
// holding only the list number the layout still draws before a column break.
if let Some(kind) = heading
&& !matches!(self.tags[i].kind, TagKind::Hn(..))
{
self.tags[i].kind = kind;
if self.tags[i].children.is_empty() {
self.tags[i].at = self.at;
}
}
return i;
}
self.tags.push(TagEntry { kind: heading.unwrap_or_else(|| Tag::P.into()), children: Vec::new(), source: Some(key.clone()), at: self.at });
let i = self.tags.len() - 1;
self.tag_index.insert((story, path.clone()), i);
self.tag_index.insert(key, i);
i
}
+15 -12
View File
@@ -6,6 +6,20 @@ use super::{
XyzDestination, krilla, write,
};
/// A leading page or column break can be placed separately from the heading.
pub(super) fn first_heading_line(para: &wordcraft_layout::para::ParaLayout) -> usize {
para.lines
.iter()
.take_while(|line| {
matches!(line.end, LineEnd::PageBreak | LineEnd::ColumnBreak)
&& para
.clusters
.get(line.c0..line.c1)
.is_some_and(|cs| cs.iter().all(|c| matches!(c.kind, ClKind::PageBreak | ClKind::ColumnBreak | ClKind::Marker)))
})
.count()
}
impl Exporter<'_> {
/// Where a bookmark is: (output page, x, y) — the page and line its start lands on, which
/// in a paragraph split across pages need not be the paragraph's first page.
@@ -91,18 +105,7 @@ impl Exporter<'_> {
let Placed::Lines { story: StoryRef::Body, path, para, l0, l1, x, y, .. } = it else { continue };
let Some(p) = self.doc.para(StoryRef::Body, path) else { continue };
let Some(level) = self.doc.styles.resolve_para(&p.props).outline_level else { continue };
// A leading page break can be placed on the previous page without the heading.
let first = para
.lines
.iter()
.take_while(|line| {
line.end == LineEnd::PageBreak
&& para
.clusters
.get(line.c0..line.c1)
.is_some_and(|cs| cs.iter().all(|c| matches!(c.kind, ClKind::PageBreak | ClKind::Marker)))
})
.count();
let first = first_heading_line(para);
if !(*l0..*l1).contains(&first) {
continue;
}
+43 -8
View File
@@ -2105,8 +2105,9 @@ fn outline_after_leading_breaks() {
assert!(target > 0, "the heading follows a page break");
for pages in [None, Some(vec![target]), Some(vec![target, 0]), Some(vec![0])] {
let expected = pages.as_ref().map_or(Some(target), |p| p.iter().position(|i| *i == target));
let bytes = export(&d, &PdfOptions { pages, ..Default::default() }).unwrap();
let bytes = export(&d, &PdfOptions { pages, tagged: true, ..Default::default() }).unwrap();
let pdf = hayro_syntax::Pdf::new(bytes).unwrap();
assert_eq!(heading_one_tags(&pdf), usize::from(expected.is_some()), "heading tags follow the visible heading past leading breaks");
let catalog = pdf.xref().get::<Dict<'_>>(pdf.xref().root_id()).unwrap();
let outlines = catalog.get::<Dict<'_>>(b"Outlines");
let Some(expected) = expected else {
@@ -2121,6 +2122,37 @@ fn outline_after_leading_breaks() {
}
}
#[test]
fn numbered_heading_after_column_break_keeps_heading_tag() {
let mut d = Document::from_text("");
d.last_section.columns = wordcraft_doc::section::Columns { count: 2, space: 36.0, separator: false, widths: Vec::new() };
let list = Arc::make_mut(&mut d.numbering).add_list(ListKind::Numbered);
let mut heading = Paragraph::with_text("\u{e}Second column heading", CharProps::default()).styled("Heading1");
heading.props.numbering = Some(NumRef { num: list, level: 0 });
d.body = vec![para_block(Paragraph::with_text("First column", CharProps::default())), para_block(heading)];
let bytes = export(&d, &PdfOptions { tagged: true, ..Default::default() }).unwrap();
let pdf = hayro_syntax::Pdf::new(bytes).unwrap();
assert_eq!(heading_one_tags(&pdf), 1, "the heading is tagged where its text starts, though its number is drawn before the column break");
}
fn heading_one_tags(pdf: &hayro_syntax::Pdf) -> usize {
use hayro_syntax::object::{Dict, Name, Object};
fn count(node: Object<'_>) -> usize {
match node {
Object::Array(array) => array.iter::<Object>().map(count).sum(),
Object::Dict(dict) => {
let heading = dict.get::<Name>(b"S").is_some_and(|role| role.as_ref() == b"H1");
usize::from(heading) + dict.get::<Object>(b"K").map_or(0, count)
}
_ => 0,
}
}
let catalog = pdf.xref().get::<Dict>(pdf.xref().root_id()).unwrap();
catalog.get::<Dict>(b"StructTreeRoot").and_then(|tree| tree.get::<Object>(b"K")).map_or(0, count)
}
#[test]
fn outline_keeps_visible_objects() {
use hayro_syntax::object::{Array, Dict};
@@ -4141,9 +4173,9 @@ fn table_cell_links_with_same_target_stay_in_their_own_cells() {
}
}
/// A paragraph's continuation must follow the footer and header between its pages.
/// A split heading has one heading tag, with its continuation read after the intervening footer and header.
#[test]
fn spanning_paragraph_links_follow_page_reading_order() {
fn spanning_heading_has_one_heading_tag_and_keeps_link_order() {
use hayro_syntax::object::{Array, Dict, Name, Object};
let mut d = Document::new();
@@ -4154,7 +4186,9 @@ fn spanning_paragraph_links_follow_page_reading_order() {
let footer = d.add_part(wordcraft_doc::PartKind::Footer, vec![para_block(linked("Footer", "footer"))]);
d.last_section.headers.default = Some(header);
d.last_section.footers.default = Some(footer);
d.body = vec![para_block(linked("First page\u{c}Second page", "body"))];
let mut heading = linked("First page\u{c}Second page", "body");
heading.props.outline_level = Some(0);
d.body = vec![para_block(heading)];
let bytes = export(&d, &PdfOptions { compress: false, tagged: true, ..Default::default() }).unwrap();
let pdf = hayro_syntax::Pdf::new(bytes).unwrap();
@@ -4168,14 +4202,14 @@ fn spanning_paragraph_links_follow_page_reading_order() {
expected.push(format!("{:?}", annots[i].obj_id().unwrap()));
}
}
fn collect(o: Object<'_>, out: &mut Vec<String>) {
fn collect(o: Object<'_>, links: &mut Vec<String>) {
match o {
Object::Array(a) => a.iter::<Object>().for_each(|o| collect(o, out)),
Object::Array(a) => a.iter::<Object>().for_each(|o| collect(o, links)),
Object::Dict(d) => {
if d.get::<Name>(b"Type").is_some_and(|t| t.as_ref() == b"OBJR") {
out.push(format!("{:?}", d.get::<Dict>(b"Obj").unwrap().obj_id().unwrap()));
links.push(format!("{:?}", d.get::<Dict>(b"Obj").unwrap().obj_id().unwrap()));
} else if let Some(k) = d.get::<Object>(b"K") {
collect(k, out);
collect(k, links);
}
}
_ => {}
@@ -4185,5 +4219,6 @@ fn spanning_paragraph_links_follow_page_reading_order() {
let tree = root.get::<Dict>(b"StructTreeRoot").unwrap();
let mut actual = Vec::new();
collect(tree.get::<Object>(b"K").unwrap(), &mut actual);
assert_eq!(heading_one_tags(&pdf), 1, "the second page continues the heading text without a duplicate heading tag");
assert_eq!(actual, expected, "links must follow page reading order across a split paragraph");
}
+260 -54
View File
@@ -159,13 +159,29 @@ pub struct RenderOptions {
/// Colour for formatting marks.
pub mark_color: Rgb,
/// Thicken glyphs slightly the way macOS draws text on screen ("font smoothing"), so pages
/// look like they do in other Mac apps. For on-screen rasters only: exports stay exact.
pub text_darkening: bool,
/// look like they do in other Mac apps: 0 is none, 1 the system's default strength
/// ([`stem_darkening`]), and other values scale it, up to twice (the system's own setting
/// has a lighter and a stronger step). A value that isn't a number is none. For on-screen
/// rasters only: exports stay exact.
pub text_darkening: f32,
/// Put every glyph's baseline on a whole device pixel, for text that is neither rotated nor
/// mirrored. A baseline between two pixel rows spreads the feet of the letters (serifs, the
/// bottoms of stems) over both rows as two grey rows instead of one solid one, which reads as
/// blur. A glyph moves by half a pixel at most and never sideways, so lines break as without
/// it. Hinted text already sits like this. For on-screen rasters only: exports stay exact.
pub baseline_snap: bool,
/// Hint text for the screen the way FreeType's `hintslight` does on Linux desktops: glyph
/// baselines sit on whole pixels and their horizontal edges (x-height, cap height) are moved
/// onto the pixel grid, so text looks as crisp as in other apps there. Nothing moves
/// sideways, so lines break as without it. For on-screen rasters only: exports stay exact.
pub hinting: bool,
/// Subpixel (LCD) antialiasing for text, for a screen whose colour stripes run in this order
/// (see [`LcdOrder`]); `None` is greyscale antialiasing. Text gets three times the detail
/// sideways, where slanted and round strokes need it most, at the price of faint colour at
/// its edges, and the page is rasterised three times. Everything but text is drawn as
/// without it. For on-screen rasters only, and only where the raster's pixels are the
/// screen's own: exports stay exact.
pub lcd: Option<LcdOrder>,
/// Dark page (View › Switch Modes): every colour but pictures has its lightness inverted, so
/// white paper turns black and black text white while hues stay the same. Screen only.
pub dark: bool,
@@ -176,6 +192,20 @@ pub struct RenderOptions {
pub read_paper: Option<Rgb>,
}
/// The order of a screen's red, green and blue stripes, left to right, within each pixel.
///
/// With [`RenderOptions::lcd`] set, each colour channel of a pixel takes the text's coverage
/// around its own stripe, a third of a pixel to one side of the pixel's middle or the other,
/// instead of all three taking the coverage of the whole pixel. A pixel's stripes are a pixel
/// wide in all, so each channel still averages over one pixel's width: this is the result of
/// rasterising text at three times the width and averaging three neighbours (the box filter
/// FreeType calls its light LCD filter), with no sharper filter and no fringe reduction.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum LcdOrder {
Rgb,
Bgr,
}
/// Default grey for a dark page's paper.
pub const DARK_PAPER: u8 = 0x33;
@@ -267,8 +297,10 @@ impl Default for RenderOptions {
display: DisplayOptions::default(),
paper: Rgb::WHITE,
mark_color: Rgb(0x2B, 0x57, 0x9A),
text_darkening: false,
text_darkening: 0.0,
baseline_snap: false,
hinting: false,
lcd: None,
dark: false,
dark_paper: DARK_PAPER,
read_paper: None,
@@ -296,6 +328,52 @@ fn render_region_capped(doc: &Document, page: &Page, w: u32, h: u32, view: Affin
// Over the cap the whole picture is drawn smaller, not cropped.
let view = if (cw, ch) == (w, h) { view } else { Affine::scale_non_uniform(cw as f64 / w as f64, ch as f64 / h as f64) * view };
let (w16, h16) = (cw as u16, ch as u16);
let drew_text = std::cell::Cell::new(false);
let mut pixels = raster_page(doc, page, (w16, h16), view, opts, Pass { shift: 0.0, drew_text: &drew_text });
// Subpixel text: the page twice more, its text a third of a pixel to each side, for the
// channels whose stripes sit there. A page without text is the same all three times.
if let Some(order) = opts.lcd
&& drew_text.get()
{
let side = |shift: f64| raster_page(doc, page, (w16, h16), view, opts, Pass { shift, drew_text: &drew_text });
let (text_right, text_left) = (side(LCD_SHIFT), side(-LCD_SHIFT));
let (red, blue) = match order {
LcdOrder::Rgb => (&text_right, &text_left),
LcdOrder::Bgr => (&text_left, &text_right),
};
take_lcd_channels(&mut pixels, red, blue);
}
Rendered { width: w16 as u32, height: h16 as u32, pixels }
}
/// How far, in device pixels, the middle of a pixel's first or last colour stripe is from the
/// middle of the pixel.
const LCD_SHIFT: f64 = 1.0 / 3.0;
/// One rasterisation of a page among the one or three that make its raster.
#[derive(Clone, Copy)]
struct Pass<'a> {
/// How far to the right text is drawn from its place, in device pixels (see
/// [`RenderOptions::lcd`]). Nothing else moves.
shift: f64,
/// Set once the pass has drawn text that `shift` moves.
drew_text: &'a std::cell::Cell<bool>,
}
/// The red of `pixels` from `red` and its blue from `blue`, two rasters of the same size
/// (premultiplied RGBA8). Text shifted right puts under each pixel's middle what lay a third of a
/// pixel to its left, where an RGB screen's red stripe is, and so on. The alpha stays, and
/// no channel is left above it.
fn take_lcd_channels(pixels: &mut [u8], red: &[u8], blue: &[u8]) {
for ((px, r), b) in pixels.as_chunks_mut::<4>().0.iter_mut().zip(red.as_chunks::<4>().0).zip(blue.as_chunks::<4>().0) {
px[0] = r[0].min(px[3]);
px[2] = b[2].min(px[3]);
}
}
/// Rasterise a page into `size` pixels (premultiplied RGBA8) with `view` (page points → pixels).
fn raster_page(doc: &Document, page: &Page, size: (u16, u16), view: Affine, opts: &RenderOptions, pass: Pass) -> Vec<u8> {
let (w16, h16) = size;
let mut ctx = context_pool::CONTEXTS.take(w16, h16);
ctx.set_transform(Affine::IDENTITY);
ctx.set_paint(color(opts.paper_of(doc), 1.0));
@@ -314,7 +392,7 @@ fn render_region_capped(doc: &Document, page: &Page, w: u32, h: u32, view: Affin
ctx.push_opacity_layer(alpha);
}
for it in &items {
draw(&mut ctx, doc, it, view, &visible, opts);
draw(&mut ctx, doc, it, view, &visible, opts, pass);
}
if faded {
ctx.pop_layer();
@@ -327,7 +405,7 @@ fn render_region_capped(doc: &Document, page: &Page, w: u32, h: u32, view: Affin
ctx.render(pm, &mut res);
}
context_pool::CONTEXTS.give_back(ctx);
Rendered { width: w16 as u32, height: h16 as u32, pixels }
pixels
}
/// The on-screen colour behind page point (`x`, `y`): the paper (page colour), then any
@@ -495,24 +573,30 @@ fn draw_watermark(ctx: &mut RenderContext, view: Affine, page: &Page, wm: &wordc
/// Does `view` map page points to device pixels without rotation, skew or mirroring, scaling both
/// axes alike? Only then do hinted outlines (made on the pixel grid) line up with the screen.
/// "Alike" allows the two axes a fifth of a percent apart: a page raster made to fill a whole
/// number of pixels each way ([`render_area_to`]) is scaled that little differently across and
/// down (a pixel in some two thousand), and is as upright as any.
fn is_upright(view: Affine) -> bool {
let [a, b, c, d, e, f] = view.as_coeffs();
[a, b, c, d, e, f].iter().all(|v| v.is_finite()) && b == 0.0 && c == 0.0 && a > 0.0 && (a - d).abs() <= a * 1e-6
[a, b, c, d, e, f].iter().all(|v| v.is_finite()) && b == 0.0 && c == 0.0 && a > 0.0 && (a - d).abs() <= a * 2e-3
}
/// How far, in device pixels, macOS-style font smoothing pushes each side of a glyph outline out
/// at `ppem` device pixels per em. Values from Pathfinder (MIT/Apache-2.0), which measured them
/// against macOS: 1.21% of the pixel size horizontally and 1.25 times that vertically, each
/// capped at 0.3 px, and no darkening past 72 px per em. We stroke the outline, which grows it
/// evenly, so this is the mean of the two.
/// sideways at `ppem` device pixels per em. The value is Pathfinder's (MIT/Apache-2.0), which
/// measured it against macOS: 1.21% of the pixel size, capped at 0.3 px, and no darkening past
/// 72 px per em. Pathfinder also grows glyphs up and down (1.25 times as far). We don't: a third
/// of a pixel of grey above and below every letter is what made page text look out of focus
/// beside other Mac apps, whose letters end on a clean pixel row. Stems get thicker, which is
/// the weight the smoothing is for; the tops and feet of the letters stay where the font puts
/// them.
pub fn stem_darkening(ppem: f64) -> f64 {
const FACTOR: [f64; 2] = [0.0121, 0.0121 * 1.25];
const FACTOR: f64 = 0.0121;
const MAX_PX: f64 = 0.3;
const MAX_PPEM: f64 = 72.0;
if !ppem.is_finite() || ppem <= 0.0 || ppem > MAX_PPEM {
return 0.0;
}
FACTOR.iter().map(|f| (ppem * f).min(MAX_PX)).sum::<f64>() / 2.0
(ppem * FACTOR).min(MAX_PX)
}
/// A wavy line from `(x0, y0)` to `(x1, y1)`; at most 20 000 units long, so a huge extent can't make it endless.
@@ -596,6 +680,7 @@ struct Frame<'a> {
opts: &'a RenderOptions,
view: Affine,
visible: &'a kurbo::Rect,
pass: Pass<'a>,
}
/// The rectangle in kurbo's terms.
@@ -607,12 +692,12 @@ fn kurbo_rect(rect: &wordcraft_geom::Rect) -> kurbo::Rect {
/// `visible` is a culling area in those point coordinates; nested clips intersect it and turns
/// transform it into the child's coordinates. Shape and path strokes apply their stored caps,
/// while ink uses its tool's round ends and joins.
fn draw(ctx: &mut RenderContext, doc: &Document, it: &Draw, view: Affine, visible: &kurbo::Rect, opts: &RenderOptions) {
let fr = Frame { doc, opts, view, visible };
fn draw(ctx: &mut RenderContext, doc: &Document, it: &Draw, view: Affine, visible: &kurbo::Rect, opts: &RenderOptions, pass: Pass) {
let fr = Frame { doc, opts, view, visible, pass };
match it {
Draw::Figure { draws, .. } => {
for d in draws {
draw(ctx, doc, d, view, visible, opts);
draw(ctx, doc, d, view, visible, opts, pass);
}
}
Draw::Fill { .. } => draw_fill(ctx, &fr, it),
@@ -634,7 +719,7 @@ fn draw(ctx: &mut RenderContext, doc: &Document, it: &Draw, view: Affine, visibl
ctx.push_clip_layer(&r.to_path(0.1));
let local = r.intersect(*visible);
for it in items {
draw(ctx, doc, it, view, &local, opts);
draw(ctx, doc, it, view, &local, opts, pass);
}
ctx.pop_layer();
}
@@ -642,14 +727,14 @@ fn draw(ctx: &mut RenderContext, doc: &Document, it: &Draw, view: Affine, visibl
let m = Affine::new(Draw::turn_matrix(*turn, *x, *y).map(f64::from));
let local = m.inverse().transform_rect_bbox(*visible);
for it in items {
draw(ctx, doc, it, view * m, &local, opts);
draw(ctx, doc, it, view * m, &local, opts, pass);
}
}
Draw::Rotated { cx, cy, spin, items } => {
let m = Affine::new(spin.matrix(*cx, *cy).map(f64::from));
let local = m.inverse().transform_rect_bbox(*visible);
for it in items {
draw(ctx, doc, it, view * m, &local, opts);
draw(ctx, doc, it, view * m, &local, opts, pass);
}
}
}
@@ -704,7 +789,8 @@ fn draw_line(ctx: &mut RenderContext, fr: &Frame, it: &Draw) {
}
_ => {
let (st, off) = match snap_rule(fr.view, (x0, y0, x1, y1), w) {
Some((w_px, off)) => (kurbo::Stroke { width: w_px / fr.view.as_coeffs()[0], ..st }, off),
// The width is across the rule: in points by the scale that way.
Some((w_px, off)) => (kurbo::Stroke { width: w_px / rule_scale(fr.view, y0 == y1), ..st }, off),
None => (st, (0.0, 0.0)),
};
ctx.set_stroke(st);
@@ -721,11 +807,13 @@ fn snap_rule(view: Affine, (x0, y0, x1, y1): (f64, f64, f64, f64), width: f64) -
if !is_upright(view) {
return None;
}
let [k, _, _, _, tx, ty] = view.as_coeffs();
let [_, _, _, _, tx, ty] = view.as_coeffs();
if y0 == y1 && x0 != x1 {
let k = rule_scale(view, true);
let (w_px, c) = snap_hairline(y0 * k + ty, width * k);
Some((w_px, (0.0, (c - ty) / k - y0)))
} else if x0 == x1 && y0 != y1 {
let k = rule_scale(view, false);
let (w_px, c) = snap_hairline(x0 * k + tx, width * k);
Some((w_px, ((c - tx) / k - x0, 0.0)))
} else {
@@ -733,6 +821,16 @@ fn snap_rule(view: Affine, (x0, y0, x1, y1): (f64, f64, f64, f64), width: f64) -
}
}
/// Device pixels per point across a rule: down the page for a level rule, across it for an
/// upright one. An upright view ([`is_upright`]) may scale the two a little differently (a page
/// raster made to fill a whole number of pixels each way), and a rule's place and width are
/// measured across it: with the other scale, a level rule low on such a page was snapped up to
/// a pixel from where it lies, its edges between pixel rows.
fn rule_scale(view: Affine, level: bool) -> f64 {
let [across, _, _, down, ..] = view.as_coeffs();
if level { down } else { across }
}
/// A line `width_px` wide centred at device coordinate `centre`, moved so both edges fall on whole
/// pixels. Returns the width, made a whole number of pixels (at least one), and the new centre.
fn snap_hairline(centre: f64, width_px: f64) -> (f64, f64) {
@@ -762,23 +860,25 @@ fn draw_glyphs(ctx: &mut RenderContext, fr: &Frame, it: &Draw) {
// Scaled letters (`w:w`): each glyph stretched across from its pen position.
let sx = if x_scale.is_finite() && *x_scale > 0.0 { f64::from(*x_scale) } else { 1.0 };
let skew = Affine::scale_non_uniform(sx, 1.0) * skew;
// Outline strokes, in font units: synthetic bold, then on-screen stem darkening (a
// stroke grows the outline by half its width on each side). Darkening is skipped for
// translucent text, where the stroke overlapping the fill would show as a darker rim.
// Synthetic bold strokes the outline, in font units.
let px_per_pt = view.determinant().abs().sqrt();
let darken_px = if opts.text_darkening && *alpha >= 1.0 { stem_darkening(*size as f64 * px_per_pt) } else { 0.0 };
let darken = if darken_px > 0.0 && k * px_per_pt > 0.0 { 2.0 * darken_px / (k * px_per_pt) } else { 0.0 };
let outline_stroke = if *synth_bold { face.upem * 0.03 } else { 0.0 } + darken;
let join = if darken > 0.0 { kurbo::Join::Round } else { kurbo::Join::Miter };
let outline_stroke = if *synth_bold { face.upem * 0.03 } else { 0.0 };
if outline_stroke > 0.0 {
ctx.set_stroke(kurbo::Stroke::new(outline_stroke).with_join(join));
ctx.set_stroke(kurbo::Stroke::new(outline_stroke).with_join(kurbo::Join::Miter));
}
// Emoji and other colour glyphs (#1269) are drawn from the font's colour data.
let colour = face.has_color_glyphs();
let ppem = *size as f64 * px_per_pt;
// Hinted outlines are in device pixels: only for an upright, unmirrored, evenly scaled
// view (not rotated text boxes), where the pixel grid lines up with the glyphs.
let hint_ppem = (opts.hinting && !colour && is_upright(view)).then_some(ppem as f32);
// On-screen stem darkening: each outline is widened along its own x axis, in one piece (see
// [`stem_darkening`] and [`widened`]). Skipped for translucent text, as it always was.
let strength = if opts.text_darkening.is_finite() { f64::from(opts.text_darkening).clamp(0.0, 2.0) } else { 0.0 };
let darken_px = if *alpha >= 1.0 { stem_darkening(ppem) * strength } else { 0.0 };
// Hinted outlines are in device pixels, and a snapped baseline is a row of them: only for an
// upright, unmirrored, evenly scaled view (not rotated text boxes), where the pixel grid
// lines up with the glyphs.
let upright = is_upright(view);
let hint_ppem = (opts.hinting && !colour && upright).then_some(ppem as f32);
let snap = opts.baseline_snap && upright;
// The outline strokes in device pixels, for the hinted outlines.
let stroke_px = outline_stroke * k * px_per_pt;
let mut hinted_stroke = false;
@@ -795,39 +895,130 @@ fn draw_glyphs(ctx: &mut RenderContext, fr: &Frame, it: &Draw) {
ctx.set_paint(color(opts.ink(*c), *alpha));
continue;
}
if let Some(o) = hint_ppem.and_then(|p| db.hinted_outline(face, *gid, p)) {
if o.elements().is_empty() {
continue;
let pen = view * kurbo::Point::new(gx, gy);
let hinted = hint_ppem.and_then(|p| db.hinted_outline(face, *gid, p));
let hinted_now = hinted.is_some();
let (o, at) = if let Some(o) = hinted {
if outline_stroke > 0.0 && !hinted_stroke {
ctx.set_stroke(kurbo::Stroke::new(stroke_px).with_join(kurbo::Join::Miter));
hinted_stroke = true;
}
// The baseline on a whole pixel, as the hinting assumes.
let at = view * kurbo::Point::new(gx, gy);
ctx.set_transform(Affine::translate((at.x, at.y.round())) * skew);
ctx.fill_path(&o);
if outline_stroke > 0.0 {
if !hinted_stroke {
ctx.set_stroke(kurbo::Stroke::new(stroke_px).with_join(join));
hinted_stroke = true;
}
ctx.stroke_path(&o);
(o, Affine::translate((pen.x, pen.y.round())) * skew)
} else {
if outline_stroke > 0.0 && hinted_stroke {
ctx.set_stroke(kurbo::Stroke::new(outline_stroke).with_join(kurbo::Join::Miter));
hinted_stroke = false;
}
continue;
}
let o = db.outline(face, *gid);
let at = view * Affine::translate((gx, gy)) * skew * Affine::scale(k);
// The same baseline for text drawn from the font's own outlines.
let lift = if snap && pen.y.is_finite() { pen.y.round() - pen.y } else { 0.0 };
(db.outline(face, *gid), Affine::translate((0.0, lift)) * at)
};
if o.elements().is_empty() {
continue;
}
ctx.set_transform(view * Affine::translate((gx, gy)) * skew * Affine::scale(k));
ctx.fill_path(&o);
// This pass's sideways shift, across the screen whichever way the text is turned.
fr.pass.drew_text.set(true);
ctx.set_transform(Affine::translate((fr.pass.shift, 0.0)) * at);
// The darkened outline is the glyph: synthetic bold strokes it too. Stroking the font's own
// outline there would cover the widening (the stroke reaches further than it does) and
// leave such text as light as without darkening.
let wide = (darken_px > 0.0).then(|| widened(&o, darken_px / widen_unit(hinted_now, k * px_per_pt, sx)));
let shape = wide.as_ref().unwrap_or(&o);
ctx.fill_path(shape);
if outline_stroke > 0.0 {
if hinted_stroke {
ctx.set_stroke(kurbo::Stroke::new(outline_stroke).with_join(join));
hinted_stroke = false;
}
ctx.stroke_path(&o);
ctx.stroke_path(shape);
}
}
}
/// How many device pixels one unit of a glyph outline is across the screen, for turning a
/// widening in device pixels into the outline's own units: a hinted outline is in device pixels
/// already and the font's own in font units (`font_px` device pixels each), and both are then
/// stretched `stretch` times across by scaled letters (`w:w`). Without the stretch for hinted
/// outlines, text scaled to 400 % was widened four times too far.
fn widen_unit(hinted: bool, font_px: f64, stretch: f64) -> f64 {
if hinted { stretch } else { font_px * stretch }
}
/// `path` with every edge moved `d` sideways, away from the ink: the shape a glyph makes when it
/// is smeared `d` to the left and `d` to the right, so stems get `2 d` thicker while nothing
/// grows up or down. One outline, filled once, so partly covered pixels are counted once (the
/// outline drawn again beside itself counted them two and three times, which read as bold).
///
/// Each point moves with the edges it joins: by `d` where both face the same side, or one of
/// them is level; not at all at the top or the foot of a curve, where one faces left and the
/// other right. Curve control points move by the same rule along the control polygon. Which side
/// of an edge is ink follows from the direction the outline runs in, read off its signed area,
/// so the holes of letters narrow as their stems widen. An outline with no area, or with
/// numbers that aren't finite, is returned as it is.
fn widened(path: &BezPath, d: f64) -> BezPath {
use kurbo::PathEl;
let els = path.elements();
// The control polygon of each contour, as (first point index, point count).
let mut pts: Vec<kurbo::Point> = Vec::with_capacity(els.len() * 2);
let mut contours: Vec<(usize, usize)> = Vec::new();
let mut start = 0;
for el in els {
match el {
PathEl::MoveTo(p) => {
if pts.len() > start {
contours.push((start, pts.len() - start));
}
start = pts.len();
pts.push(*p);
}
PathEl::LineTo(p) => pts.push(*p),
PathEl::QuadTo(c, p) => pts.extend([*c, *p]),
PathEl::CurveTo(c1, c2, p) => pts.extend([*c1, *c2, *p]),
PathEl::ClosePath => {}
}
}
if pts.len() > start {
contours.push((start, pts.len() - start));
}
let ring = |first: usize, n: usize, i: usize| pts.get(first + i % n.max(1)).copied().unwrap_or_default();
let area: f64 =
contours.iter().map(|&(first, n)| (0..n).map(|i| ring(first, n, i).to_vec2().cross(ring(first, n, i + 1).to_vec2())).sum::<f64>()).sum();
if !(d.is_finite() && d > 0.0 && area.is_finite() && area != 0.0) {
return path.clone();
}
// Which way the edge from `a` to `b` faces: 1 right, -1 left, 0 for a level edge.
let faces = |a: kurbo::Point, b: kurbo::Point| {
let (run, rise) = ((b.x - a.x).abs(), b.y - a.y);
if rise.abs() <= 1e-6 * (run + rise.abs()) { 0.0 } else { (rise * area).signum() }
};
let mut moved = pts.clone();
for &(first, n) in &contours {
for i in 0..n {
let at = ring(first, n, i);
// The nearest different points before and after: a contour may repeat a point (a
// run of more than a few is left where it is).
let before = (1..n.min(8)).map(|step| ring(first, n, i + n - step)).find(|p| *p != at);
let after = (1..n.min(8)).map(|step| ring(first, n, i + step)).find(|p| *p != at);
let (Some(before), Some(after)) = (before, after) else { continue };
let push = (faces(before, at) + faces(at, after)).clamp(-1.0, 1.0);
if let Some(p) = moved.get_mut(first + i) {
p.x += push * d;
}
}
}
let mut next = moved.into_iter();
let mut take = || next.next().unwrap_or_default();
let mut out = BezPath::with_capacity(els.len());
for el in els {
out.push(match el {
PathEl::MoveTo(_) => PathEl::MoveTo(take()),
PathEl::LineTo(_) => PathEl::LineTo(take()),
PathEl::QuadTo(..) => PathEl::QuadTo(take(), take()),
PathEl::CurveTo(..) => PathEl::CurveTo(take(), take(), take()),
PathEl::ClosePath => PathEl::ClosePath,
});
}
out
}
fn draw_mark(ctx: &mut RenderContext, fr: &Frame, it: &Draw) {
let Draw::Mark { x, baseline, size, ch, color: mark } = it else { return };
let face = wordcraft_fonts::word::resolve("Source Sans 3", false, false).face;
@@ -1280,6 +1471,19 @@ pub fn render_area(doc: &Document, page: &Page, area: wordcraft_geom::Rect, scal
render_region(doc, page, pw, ph, view, opts)
}
/// Render the page `area` (points) into exactly `w`×`h` pixels: the area fills the raster, scaled
/// across and down by whatever that takes. For a raster that must be a given number of device
/// pixels each way, where [`render_area`]'s single scale gives the next whole pixel up: a picture
/// one pixel larger than its place on screen is scaled into it, and every glyph resampled.
pub fn render_area_to(doc: &Document, page: &Page, area: wordcraft_geom::Rect, w: u32, h: u32, opts: &RenderOptions) -> Rendered {
let (w, h) = (w.clamp(1, MAX_SIDE), h.clamp(1, MAX_SIDE));
let (sx, sy) = (f64::from(w) / f64::from(area.w), f64::from(h) / f64::from(area.h));
let fine = |v: f64| v.is_finite() && v > 0.0;
let (sx, sy) = if fine(sx) && fine(sy) && area.x.is_finite() && area.y.is_finite() { (sx, sy) } else { (1.0, 1.0) };
let (x, y) = if area.x.is_finite() && area.y.is_finite() { (f64::from(area.x), f64::from(area.y)) } else { (0.0, 0.0) };
render_region(doc, page, w, h, Affine::scale_non_uniform(sx, sy) * Affine::translate((-x, -y)), opts)
}
/// Draw `items` (page points) alone, on nothing, over the page `area` (points) at `scale` px/pt:
/// no paper, no watermark. A dragged object's preview.
pub fn render_items(doc: &Document, items: &[Draw], area: wordcraft_geom::Rect, scale: f32, opts: &RenderOptions) -> Rendered {
@@ -1293,8 +1497,10 @@ pub fn render_items(doc: &Document, items: &[Draw], area: wordcraft_geom::Rect,
* Affine::translate((-x as f64, -y as f64));
let mut ctx = RenderContext::new_with(w16, h16, vello_cpu::RenderSettings { num_threads: 0, ..Default::default() });
let visible = view.inverse().transform_rect_bbox(kurbo::Rect::new(0.0, 0.0, w16 as f64, h16 as f64)).inflate(40.0, 40.0);
// One pass, text in its place: an area raster (a preview, a dragged object) is greyscale.
let drew_text = std::cell::Cell::new(false);
for it in items {
draw(&mut ctx, doc, it, view, &visible, opts);
draw(&mut ctx, doc, it, view, &visible, opts, Pass { shift: 0.0, drew_text: &drew_text });
}
ctx.flush();
let mut pixels = vec![0u8; w16 as usize * h16 as usize * 4];
+358 -3
View File
@@ -265,7 +265,7 @@ fn stem_darkening_follows_the_macos_curve() {
assert_eq!(stem_darkening(f64::NAN), 0.0);
assert_eq!(stem_darkening(-5.0), 0.0);
// Small text grows in proportion to its pixel size...
assert!((stem_darkening(10.0) - 10.0 * 0.0121 * 2.25 / 2.0).abs() < 1e-9);
assert!((stem_darkening(10.0) - 10.0 * 0.0121).abs() < 1e-9);
// ...body text on a Retina screen hits the 0.3 px cap...
assert_eq!(stem_darkening(30.0), 0.3);
assert_eq!(stem_darkening(72.0), 0.3);
@@ -283,12 +283,29 @@ fn text_darkening_adds_ink_on_screen_only() {
let d = Document::from_text("Marketing analytics lead with twelve years of measurement work.");
let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default());
let plain = render_page(&d, &l.pages[0], 2.0, &RenderOptions::default());
let dark = render_page(&d, &l.pages[0], 2.0, &RenderOptions { text_darkening: true, ..Default::default() });
let dark = render_page(&d, &l.pages[0], 2.0, &RenderOptions { text_darkening: 1.0, ..Default::default() });
let (a, b) = (ink(&plain), ink(&dark));
// About 0.3 px more on every edge of an 11 pt line at 2x: clearly more ink, not bold.
assert!(b as f64 > a as f64 * 1.08 && (b as f64) < a as f64 * 1.6, "plain {a}, darkened {b}");
// Off by default: exports and thumbnails are untouched.
assert!(!RenderOptions::default().text_darkening);
assert_eq!(RenderOptions::default().text_darkening, 0.0);
}
#[test]
fn text_darkening_is_a_strength() {
let d = Document::from_text("Marketing analytics lead with twelve years of measurement work.");
let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default());
let at = |strength: f32| ink(&render_page(&d, &l.pages[0], 2.0, &RenderOptions { text_darkening: strength, ..Default::default() }));
// The system's lighter, default and stronger steps each add ink.
let (none, light, default, strong) = (at(0.0), at(0.5), at(1.0), at(1.5));
assert!(none < light && light < default && default < strong, "{none} {light} {default} {strong}");
assert_eq!(none, ink(&render_page(&d, &l.pages[0], 2.0, &RenderOptions::default())));
// No more than twice the default, and junk is no darkening at all.
assert_eq!(at(2.0), at(50.0));
assert_eq!(at(2.0), at(f32::INFINITY.min(f32::MAX)));
for junk in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -1.0] {
assert_eq!(at(junk), none, "{junk}");
}
}
/// Inked pixels that are only partly covered (grey): an edge between two pixel rows.
@@ -303,6 +320,315 @@ fn ink_columns(img: &Rendered) -> (usize, usize) {
(inked.iter().copied().min().unwrap_or(0), inked.iter().copied().max().unwrap_or(0))
}
/// The first and last pixel rows with any ink.
fn ink_row_span(img: &Rendered) -> (usize, usize) {
let w = img.width as usize;
let inked: Vec<usize> = img.pixels.as_chunks::<4>().0.iter().enumerate().filter(|(_, p)| p[0] < 250).map(|(i, _)| i / w.max(1)).collect();
(inked.iter().copied().min().unwrap_or(0), inked.iter().copied().max().unwrap_or(0))
}
/// One line of flat-footed capitals in a bundled face: no letter dips under the baseline.
fn flat_capitals() -> (Document, wordcraft_layout::DocLayout) {
let mut d = Document::from_text("THE FELT HILT FILE LIFT HEFT TILT");
let styles = std::sync::Arc::make_mut(&mut d.styles);
styles.default_chr.font = Some("Source Sans 3".into());
styles.default_chr.size = Some(12.0);
let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default());
(d, l)
}
#[test]
fn a_snapped_baseline_ends_the_letters_on_a_whole_pixel_row() {
let (d, l) = flat_capitals();
let snap = RenderOptions { baseline_snap: true, ..Default::default() };
// Scales that put the baseline at different places between two pixel rows.
let mut sharper = 0;
for scale in [1.0, 1.25, 1.45, 96.0 / 72.0 * 1.45, 2.0, 2.3] {
let plain = render_page(&d, &l.pages[0], scale, &RenderOptions::default());
let snapped = render_page(&d, &l.pages[0], scale, &snap);
// The row under the letters' feet: all of it white once the baseline is on a pixel
// boundary, where the unsnapped feet leave a grey row or end a row early.
let (_, foot) = ink_row_span(&snapped);
let w = snapped.width as usize;
let foot_row = &snapped.pixels[foot * w * 4..(foot + 1) * w * 4];
let darkest = foot_row.as_chunks::<4>().0.iter().map(|p| p[0]).min().unwrap_or(255);
assert!(darkest < 16, "scale {scale}: the feet fill their last row (darkest pixel {darkest})");
let (g0, g1) = (grey(&plain), grey(&snapped));
assert!(g1 <= g0, "scale {scale}: grey pixels: plain {g0}, snapped {g1}");
sharper += usize::from(g1 < g0);
// The same weight, and nothing moves sideways.
let (a, b) = (ink(&plain), ink(&snapped));
assert!((b as f64 - a as f64).abs() < a as f64 * 0.02, "scale {scale}: ink: plain {a}, snapped {b}");
assert_eq!(ink_columns(&plain), ink_columns(&snapped), "scale {scale}");
// No more than half a pixel up or down.
let ((t0, b0), (t1, b1)) = (ink_row_span(&plain), ink_row_span(&snapped));
assert!(t0.abs_diff(t1) <= 1 && b0.abs_diff(b1) <= 1, "scale {scale}: plain {t0}..{b0}, snapped {t1}..{b1}");
}
assert!(sharper >= 3, "snapping sharpened {sharper} of 6 scales");
// Off by default: exports and thumbnails are untouched.
assert!(!RenderOptions::default().baseline_snap);
}
#[test]
fn rotated_views_keep_their_baselines() {
let (d, l) = flat_capitals();
let snap = RenderOptions { baseline_snap: true, ..Default::default() };
let view = Affine::translate((300.0, -50.0)) * Affine::rotate(0.3) * Affine::scale(1.9);
let plain = render_region(&d, &l.pages[0], 600, 300, view, &RenderOptions::default());
assert!(ink(&plain) > 0);
assert_eq!(plain.pixels, render_region(&d, &l.pages[0], 600, 300, view, &snap).pixels);
}
#[test]
fn darkening_thickens_stems_and_leaves_the_tops_and_feet_of_letters_alone() {
let (d, l) = flat_capitals();
let snap = RenderOptions { baseline_snap: true, ..Default::default() };
let dark = RenderOptions { text_darkening: 1.0, ..snap.clone() };
for scale in [1.0, 1.45, 2.0] {
let plain = render_page(&d, &l.pages[0], scale, &snap);
let darkened = render_page(&d, &l.pages[0], scale, &dark);
// More ink, in the same pixel rows: nothing is added above the letters or under them
// (the stroke this replaces put a third of a pixel of grey on both).
assert!(ink(&darkened) as f64 > ink(&plain) as f64 * 1.05, "scale {scale}");
assert_eq!(ink_row_span(&plain), ink_row_span(&darkened), "scale {scale}");
// Sideways, less than a pixel each way.
let ((l0, r0), (l1, r1)) = (ink_columns(&plain), ink_columns(&darkened));
assert!(l1 <= l0 && l0 - l1 <= 1 && r1 >= r0 && r1 - r0 <= 1, "scale {scale}: plain {l0}..{r0}, darkened {l1}..{r1}");
}
}
#[test]
fn widening_moves_edges_sideways_away_from_the_ink() {
// A 10 x 10 square with a 4 x 4 hole, the hole running the other way round.
let mut ring = kurbo::Rect::new(0.0, 0.0, 10.0, 10.0).to_path(0.1);
ring.move_to((3.0, 3.0));
for p in [(3.0, 7.0), (7.0, 7.0), (7.0, 3.0)] {
ring.line_to(p);
}
ring.close_path();
for path in [ring.clone(), ring.reverse_subpaths()] {
let wide = widened(&path, 0.5);
// The square is 1 wider and the hole 1 narrower; neither is any taller.
let b = wide.bounding_box();
assert_eq!((b.x0, b.x1, b.y0, b.y1), (-0.5, 10.5, 0.0, 10.0));
assert!((wide.area().abs() - (11.0 * 10.0 - 3.0 * 4.0)).abs() < 1e-9, "{}", wide.area());
assert_eq!(wide.elements().len(), path.elements().len());
}
// A round shape: wider, no taller, and its top and bottom points stay put.
let disc = kurbo::Circle::new((0.0, 0.0), 5.0).to_path(1e-3);
let b = widened(&disc, 0.25).bounding_box();
assert!((b.width() - 10.5).abs() < 0.02 && (b.height() - 10.0).abs() < 0.02, "{b:?}");
// Nothing to widen, or nothing to widen by: the path comes back as it was.
let line = BezPath::from_vec(vec![kurbo::PathEl::MoveTo((0.0, 0.0).into()), kurbo::PathEl::LineTo((5.0, 5.0).into())]);
for (path, d) in [(&line, 0.5), (&ring, 0.0), (&ring, -1.0), (&ring, f64::NAN), (&ring, f64::INFINITY), (&BezPath::new(), 0.5)] {
assert_eq!(widened(path, d).elements(), path.elements(), "{d}");
}
// Hostile outlines don't panic: points that aren't numbers, and one point repeated.
let mut odd = BezPath::new();
odd.move_to((f64::NAN, 0.0));
odd.line_to((1.0, f64::INFINITY));
odd.quad_to((2.0, 2.0), (0.0, 0.0));
let _ = widened(&odd, 0.5);
let mut same = BezPath::new();
same.move_to((1.0, 1.0));
for _ in 0..50 {
same.line_to((1.0, 1.0));
}
same.line_to((4.0, 1.0));
same.line_to((4.0, 5.0));
same.close_path();
assert_eq!(widened(&same, 0.5).elements().len(), same.elements().len());
}
/// The sum of one colour channel's distance from white.
fn channel_ink(img: &Rendered, channel: usize) -> u64 {
img.pixels.as_chunks::<4>().0.iter().map(|p| 255 - p[channel] as u64).sum()
}
#[test]
fn lcd_text_takes_each_channel_from_around_its_own_stripe() {
let d = Document::from_text("Nobody has assembled this board yet. Italic and round strokes gain the most.");
let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default());
let (w, h) = (700, 200);
let view = Affine::scale(1.25);
let lcd = |order| RenderOptions { lcd: Some(order), ..Default::default() };
let grey = render_region(&d, &l.pages[0], w, h, view, &RenderOptions::default());
let rgb = render_region(&d, &l.pages[0], w, h, view, &lcd(LcdOrder::Rgb));
let bgr = render_region(&d, &l.pages[0], w, h, view, &lcd(LcdOrder::Bgr));
assert!(ink(&grey) > 0);
// The page a third of a pixel to the right and to the left, in greyscale.
let moved = |dx: f64| render_region(&d, &l.pages[0], w, h, Affine::translate((dx, 0.0)) * view, &RenderOptions::default());
let (right, left) = (moved(1.0 / 3.0), moved(-1.0 / 3.0));
let mut coloured = 0;
let rasters = [&grey, &rgb, &bgr, &right, &left].map(|r| r.pixels.as_chunks::<4>().0);
for i in 0..rasters[0].len() {
let [g, c, m, r, l] = rasters.map(|px| px[i]);
// Green sits in the middle of the pixel: it and the alpha are the greyscale raster's.
assert_eq!((c[1], c[3]), (g[1], g[3]));
// Red is what a pixel a third to the left would see, blue a third to the right.
assert_eq!((c[0], c[2]), (r[0], l[2]), "pixel {i}");
// BGR stripes are the mirror image.
assert_eq!((m[0], m[1], m[2], m[3]), (c[2], c[1], c[0], c[3]));
coloured += usize::from(c[0] != c[2]);
}
assert!(coloured > 200, "{coloured} pixels have red and blue apart");
// No colour cast: each channel carries the same ink, to within a hundredth.
let [r, g, b] = [0, 1, 2].map(|c| channel_ink(&rgb, c) as f64);
assert!((r - g).abs() < g * 0.01 && (b - g).abs() < g * 0.01, "{r} {g} {b}");
// Off by default: exports and thumbnails are untouched.
assert_eq!(RenderOptions::default().lcd, None);
}
#[test]
fn lcd_changes_nothing_but_text() {
let lcd = RenderOptions { lcd: Some(LcdOrder::Rgb), ..Default::default() };
// A page with no text: the same raster, from one pass.
let mut blank = Document::from_text("");
blank.settings.page_color = Some(Rgb(0x20, 0x60, 0xA0));
let l = layout(&blank, &mut LayoutCache::new(), &LayoutOptions::default());
assert_eq!(render_page(&blank, &l.pages[0], 0.5, &lcd).pixels, render_page(&blank, &l.pages[0], 0.5, &RenderOptions::default()).pixels);
// A page with text on a page colour: pixels differ only where the text is.
let mut d = Document::from_text("Coloured paper under one line of text.");
d.settings.page_color = Some(Rgb(0xFF, 0xF0, 0xC0));
let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default());
let (grey, sub) = (render_page(&d, &l.pages[0], 1.25, &RenderOptions::default()), render_page(&d, &l.pages[0], 1.25, &lcd));
let w = grey.width as usize;
let paper = grey.pixels[..4].to_vec();
let inked: Vec<usize> = grey.pixels.as_chunks::<4>().0.iter().enumerate().filter(|(_, p)| p[..] != paper[..]).map(|(i, _)| i).collect();
let (top, bottom) = (inked.iter().map(|i| i / w).min().unwrap(), inked.iter().map(|i| i / w).max().unwrap());
let (first, last) = (inked.iter().map(|i| i % w).min().unwrap(), inked.iter().map(|i| i % w).max().unwrap());
let mut changed = 0;
for (i, (a, b)) in grey.pixels.as_chunks::<4>().0.iter().zip(sub.pixels.as_chunks::<4>().0).enumerate() {
if a != b {
changed += 1;
let (x, y) = (i % w, i / w);
assert!((top..=bottom).contains(&y) && x + 1 >= first && x <= last + 1, "pixel {x},{y} is outside the text");
}
}
assert!(changed > 50, "{changed}");
}
#[test]
fn lcd_channels_never_exceed_the_alpha() {
// Premultiplied pixels: a colour above its alpha would be brighter than white.
let mut px = vec![10, 20, 30, 40, 200, 200, 200, 255];
take_lcd_channels(&mut px, &[90, 0, 0, 255, 7, 0, 0, 255], &[0, 0, 80, 255, 0, 0, 9, 255]);
assert_eq!(px, [40, 20, 40, 40, 7, 200, 9, 255]);
// Rasters of other sizes leave the rest alone and don't panic.
let mut px = vec![1, 2, 3, 255, 4, 5, 6, 255, 9];
take_lcd_channels(&mut px, &[50, 0, 0, 255], &[]);
assert_eq!(px, [1, 2, 3, 255, 4, 5, 6, 255, 9]);
}
/// The glyph runs of `text` in a bundled face at 12 pt, as the page draws them, each changed by
/// `change`; and the area they are in.
fn glyph_runs(text: &str, change: impl Fn(&mut Draw)) -> (Document, Vec<Draw>, wordcraft_geom::Rect) {
let mut d = Document::from_text(text);
let styles = std::sync::Arc::make_mut(&mut d.styles);
styles.default_chr.font = Some("Source Sans 3".into());
styles.default_chr.size = Some(12.0);
let l = layout(&d, &mut LayoutCache::new(), &LayoutOptions::default());
let page = &l.pages[0];
let mut runs: Vec<Draw> = page_layers(&d, page, &DisplayOptions::default())
.into_iter()
.flat_map(|(_, items)| items)
.filter(|it| matches!(it, Draw::Glyphs { .. }))
.collect();
assert!(!runs.is_empty());
runs.iter_mut().for_each(change);
(d, runs, wordcraft_geom::Rect::new(0.0, 0.0, page.w, 200.0))
}
/// How much is drawn on nothing: the sum of the pixels' opacity.
fn opacity(img: &Rendered) -> u64 {
img.pixels.as_chunks::<4>().0.iter().map(|p| p[3] as u64).sum()
}
#[test]
fn synthetic_bold_is_darkened_too() {
// A face with no bold of its own is made bold by stroking its outlines. The stroke reaches
// further than the darkening does, so it has to stroke the darkened outline: the darkening
// then moves the bold text's edges as far as the regular text's, and adds about as much ink.
let added = |bold: bool, scale: f32| {
let (d, runs, area) = glyph_runs("Bold made by stroking the outline", |run| {
if let Draw::Glyphs { synth_bold, .. } = run {
*synth_bold = bold;
}
});
let dark = RenderOptions { text_darkening: 1.0, ..Default::default() };
let (plain, darkened) =
(opacity(&render_items(&d, &runs, area, scale, &RenderOptions::default())), opacity(&render_items(&d, &runs, area, scale, &dark)));
assert!(plain > 0 && darkened > plain, "bold {bold}: plain {plain}, darkened {darkened}");
(darkened - plain) as f64
};
for scale in [1.0, 2.0] {
let (regular, bold) = (added(false, scale), added(true, scale));
assert!(bold > regular * 0.75, "scale {scale}: ink added: {regular} regular, {bold} bold");
}
}
#[test]
fn stretched_hinted_text_is_darkened_as_far_as_unstretched() {
// One letter, hinted, at its own width and scaled to 400 % (`w:w`): the darkening moves each
// edge the same distance on screen, so it adds about the same ink to both.
let added = |stretch: f32| {
let (d, runs, area) = glyph_runs("H", |run| {
if let Draw::Glyphs { x_scale, .. } = run {
*x_scale = stretch;
}
});
let hint = RenderOptions { hinting: true, ..Default::default() };
let dark = RenderOptions { text_darkening: 1.0, ..hint.clone() };
let (plain, darkened) = (opacity(&render_items(&d, &runs, area, 2.0, &hint)), opacity(&render_items(&d, &runs, area, 2.0, &dark)));
assert!(darkened > plain, "stretch {stretch}: plain {plain}, darkened {darkened}");
(darkened - plain) as f64
};
let (own, stretched) = (added(1.0), added(4.0));
assert!(stretched < own * 1.5 && stretched > own * 0.6, "ink added: {own} unstretched, {stretched} stretched");
// The conversion itself: a widening of `px` device pixels, in outline units, is `px` again
// once the outline is on screen.
for (hinted, font_px, stretch) in [(true, 0.02, 1.0), (true, 0.02, 4.0), (false, 0.02, 1.0), (false, 0.02, 4.0)] {
let on_screen = if hinted { stretch } else { font_px * stretch };
assert!((0.25 / widen_unit(hinted, font_px, stretch) * on_screen - 0.25).abs() < 1e-12, "{hinted} {stretch}");
}
}
#[test]
fn an_area_rendered_to_a_pixel_size_fills_it_and_keeps_its_text_on_the_grid() {
let (d, l) = flat_capitals();
let page = &l.pages[0];
let area = wordcraft_geom::Rect::new(0.0, 0.0, page.w, page.h);
let snap = RenderOptions { baseline_snap: true, ..Default::default() };
// A page 1746.155 × 2469.544 pixels at its scale, made 1746 × 2470: a pixel in two thousand off each way.
let scale = 1746.155 / page.w;
let (w, h) = (1746, (page.h * scale).round() as u32 + 1);
let exact = render_area_to(&d, page, area, w, h, &snap);
assert_eq!((exact.width, exact.height), (w, h));
// One scale gives the next whole pixel up each way: not the size asked for.
let up = render_area(&d, page, area, scale, &snap);
assert_eq!(up.width, 1747);
// The text is as it is at the page's own scale, feet on a whole pixel row: scaled that little differently
// across and down, the page is still upright.
let foot_is_dark = |img: &Rendered| {
let (_, foot) = ink_row_span(img);
let w = img.width as usize;
img.pixels[foot * w * 4..(foot + 1) * w * 4].as_chunks::<4>().0.iter().map(|p| p[0]).min().unwrap_or(255) < 16
};
assert!(foot_is_dark(&exact) && foot_is_dark(&up));
assert!(is_upright(Affine::scale_non_uniform(2.0, 2.002)) && is_upright(Affine::scale_non_uniform(2.933, 2.9334)));
assert!(!is_upright(Affine::scale_non_uniform(2.0, 2.01)));
// Hostile sizes and areas: clamped, never a panic.
for (area, w, h) in [
(wordcraft_geom::Rect::new(0.0, 0.0, 0.0, 0.0), 10, 10),
(wordcraft_geom::Rect::new(f32::NAN, f32::INFINITY, f32::NAN, -5.0), 10, 10),
(area, 0, 0),
(area, u32::MAX, 3),
] {
let img = render_area_to(&d, page, area, w, h, &snap);
assert!(img.width >= 1 && img.height >= 1 && img.pixels.len() == img.width as usize * img.height as usize * 4);
}
}
#[test]
fn hinting_sharpens_screen_text_without_making_it_bolder_or_moving_it() {
let mut d =
@@ -2053,6 +2379,35 @@ fn rules_of_one_width_cover_the_same_whole_pixels_at_every_zoom() {
assert!(snap_rule(Affine::scale(2.0), (0.0, 0.0, 9.0, 4.0), 0.5).is_none());
}
#[test]
fn rules_snap_by_the_scale_across_them_on_a_page_scaled_a_little_differently_each_way() {
// A page raster made to fill a whole number of pixels is scaled a pixel in a thousand or two
// differently across and down. A level rule lies where the scale down the page puts it, and
// an upright one where the scale across does.
for (kx, ky) in [(2.0, 2.002), (2.002, 2.0), (2.933, 2.9334), (1.3333, 1.3329)] {
let view = Affine::new([kx, 0.0, 0.0, ky, 37.3, 12.9]);
assert!(is_upright(view));
for i in 0..40 {
let pos = 10.0 + f64::from(i) * 17.37;
let (w_h, (_, oy)) = snap_rule(view, (5.0, pos, 400.0, pos), 0.5).unwrap();
let (w_v, (ox, _)) = snap_rule(view, (pos, 5.0, pos, 400.0), 0.5).unwrap();
for (w, centre, lies) in [(w_h, (pos + oy) * ky + 12.9, pos * ky + 12.9), (w_v, (pos + ox) * kx + 37.3, pos * kx + 37.3)] {
let edge = centre - w / 2.0;
assert!((edge - edge.round()).abs() < 1e-9, "scales {kx} {ky}: edge {edge} is off the pixel grid");
// Snapped onto the grid from where it lies: never further than its own width and half a pixel.
assert!((centre - lies).abs() <= w / 2.0 + 0.5 + 1e-9, "scales {kx} {ky}: moved {} px", centre - lies);
}
}
}
// The case from review: a level rule at 250 pt, half a point wide, at 2.0 across and 2.002 down, is a pixel
// wide and centred on 500.5 already. It stays there.
let view = Affine::scale_non_uniform(2.0, 2.002);
let (w, (_, oy)) = snap_rule(view, (5.0, 250.0, 400.0, 250.0), 0.5).unwrap();
assert_eq!(w, 1.0);
assert!(((250.0 + oy) * 2.002 - 500.5).abs() < 1e-9, "centre {}", (250.0 + oy) * 2.002);
assert_eq!((rule_scale(view, true), rule_scale(view, false)), (2.002, 2.0));
}
/// The same three pictures that don't draw as in the PDF test: each stays a grey box, and the page's
/// pixels are what they were before strict export existed (#6005).
#[test]
+11
View File
@@ -157,7 +157,17 @@ impl WordApp {
self.execute_command(id, params, false)
}
/// Resolving a comment saves the text typed in its open edit first. If that write is
/// refused, the comment stays unresolved and the draft is kept.
fn save_comment_edit_before(&mut self, id: &str) -> Result<(), String> {
if id == "review.resolveComment" {
panes::commit_open_comment_edit(self)?;
}
Ok(())
}
fn execute_command(&mut self, id: &str, params: Value, bitmap_if_empty: bool) -> Result<Value, String> {
self.save_comment_edit_before(id)?;
self.clear_command_targets(id);
if let Some(error) = self.document_required_error(id) {
return Err(error);
@@ -1323,6 +1333,7 @@ pub(crate) fn works_without_document(id: &str) -> bool {
| "tools.customizeRibbon"
| "view.darkMode"
| "view.paperColor"
| "view.textSmoothing"
| "view.marks"
| "view.ruler"
| "view.numeral"
+1 -1
View File
@@ -60,7 +60,7 @@ impl ThumbSource<ThumbKey> for TemplateThumbs {
let Some(page) = layout.pages.first() else { return ThumbRender::Blank };
// The longest side of the page is `request.side` pixels; the store never asks for zero.
let scale = request.side as f32 / page.w.max(page.h).max(1.0);
let image = wordcraft_render::render_page(&session.doc, page, scale, &crate::canvas::screen_render_options());
let image = wordcraft_render::render_page(&session.doc, page, scale, &crate::canvas::thumbnail_render_options());
let pixels = image.to_straight();
ThumbRender::Ready(egui::ColorImage::from_rgba_unmultiplied([image.width as usize, image.height as usize], &pixels))
}
+18 -3
View File
@@ -65,7 +65,7 @@ pub(crate) use links::follow_link;
use links::{field_link, is_followable_link, is_generated_bookmark_link};
pub use navigation::page_to_screen;
use navigation::viewed_page;
pub(crate) use pages::{PageKeys, dark_page, page_doc, page_screen_scale, preview_sel, screen_render_options};
pub(crate) use pages::{PageKeys, dark_page, page_doc, page_screen_scale, preview_sel, screen_render_options, thumbnail_render_options};
use pages::{page_render_options, shown_layout};
use reading::{reading_anchor_page, reading_page_start, web_layout_width};
use story::dims_body;
@@ -112,6 +112,11 @@ pub struct CanvasState {
/// The page asks for the keyboard between this pass and the next ([`CanvasState::focus_page_after_pass`]): always
/// (no ids), or only while focus is still on one of the ids.
focus_after_pass: Option<Vec<egui::Id>>,
/// Where the page view put its pages (page, place in screen points) the last time two passes running put
/// them in the same places: the view at rest. Page pictures are made to fill these places exactly
/// (`source::WordPages`); while the view moves they stay as they were, so a scroll or a zoom under way makes
/// no picture again for a place it is only passing through.
pub(crate) settled_pages: Vec<(usize, Rect)>,
/// How many page pictures the page view kept resident after the last pass (S-L352).
pub(crate) resident_pictures: usize,
/// The caret's glide and blink.
@@ -422,6 +427,7 @@ impl Default for CanvasState {
shown: ShownPages::default(),
focus_pending: true,
focus_after_pass: None,
settled_pages: Vec::new(),
resident_pictures: 0,
glide: crate::caret_glide::CaretGlide::default(),
comments: Default::default(),
@@ -766,7 +772,8 @@ fn show_reading(app: &mut WordApp, ui: &mut Ui, layout: &Arc<DocLayout>, full: R
let columns = Rect::from_min_max(full.min, pos2(full.max.x, (full.max.y - metrics.nav_bar).max(full.min.y)));
let footer = Rect::from_min_max(pos2(full.min.x, columns.max.y), full.max);
let mut state = std::mem::take(&mut app.canvas.reading);
let source = source::WordPages::new(app, layout, false, None);
// Read Mode sizes its columns itself: no view scale to rasterise at.
let source = source::WordPages::new(app, layout, false, None, None);
let out = ReadingView::new(tl!("Document"), &source, &mut state, paper).zoom(zoom).show_at(ui, columns);
// The page-turn row sits at the bottom right, as in v0.19.1 (the far end, so the bottom left in a right-to-left UI),
// the page view's side margin in from the edge.
@@ -855,7 +862,7 @@ fn show_pages(app: &mut WordApp, ui: &mut Ui, layout: &Arc<DocLayout>, full: Rec
let options =
LayoutOptions { markup: f64::from(markup_width(app)), min_columns: if app.session.view.multi_page { 2 } else { 1 }, ..LayoutOptions::WORD };
let paper = DataColor::new(paper_color(app));
let source = source::WordPages::new(app, layout, dim_body, hidden);
let source = source::WordPages::new(app, layout, dim_body, hidden, Some(scale as f32));
// The describer owns its snapshot, as the source does, so the page view can hold it while the body edits the app.
let described = preview_sel(app).unwrap_or(app.session.sel_ends()).clone();
let describer = crate::a11y::DocumentDescriber::new(source.doc(), layout.clone(), (described.anchor.clone(), described.focus.clone()));
@@ -1049,6 +1056,14 @@ fn show_pages(app: &mut WordApp, ui: &mut Ui, layout: &Arc<DocLayout>, full: Rec
// A window's page has the keyboard from its first pass (production's `want_focus` started on), so typing lands
// without a click; a modal dialog keeps the keyboard until it closes.
let view_rect = body_view.map_or(body_rect, |v| v.rect);
// The same places two passes running: the view is at rest, and these are the places pictures are made for.
let placed = |pages: &[PlacedPage]| pages.iter().map(|p| (p.page, p.rect)).collect::<Vec<_>>();
let now = placed(&out.pages);
if now == placed(&app.canvas.shown.pages) && now != app.canvas.settled_pages {
app.canvas.settled_pages = now;
// The pictures of the places just settled are made on the next pass.
ui.ctx().request_repaint();
}
app.canvas.shown =
ShownPages { rect: body_rect, pages: out.pages.clone(), laid: laid_rects(&out), view: view_rect, canvas: Some(out.canvas.response.id) };
if app.canvas.focus_pending && !app.modal_open() {
+6
View File
@@ -81,6 +81,9 @@ fn open_edit_on_double_click(app: &mut WordApp, ui: &Ui) {
return;
}
let Some(c) = app.session.doc.comments.get(&id) else { return };
if c.resolved {
return;
}
let text = app.session.doc.plain_text(StoryRef::Part(c.part));
app.canvas.comments.edit(thread_id(id), 0, text);
}
@@ -102,6 +105,9 @@ fn apply(app: &mut WordApp, cards: &[Card], edit: CommentEdit) {
}
CommentEdit::Edit { thread, index, text, .. } => {
let Some(id) = app_id(thread).and_then(|t| message_id(app, t, index)) else { return };
if app.session.doc.comments.get(&id).is_some_and(|c| c.resolved) {
return;
}
// An empty comment is deleted, as Word does.
let _ = if text.trim().is_empty() {
app.run("review.deleteComment", json!({"id": id}))
+1 -1
View File
@@ -123,7 +123,7 @@ impl Component for EquationFrameControl<'_> {
line: cx.color(t.color.overlay.line),
accent: cx.color(t.color.accent.solid),
soft: cx.color(t.color.accent.soft),
shade: cx.color(t.color.accent.solid.with_alpha(40)),
shade: cx.color(t.color.state.text_selection),
handle_fill: cx.color(t.color.overlay.handle_fill),
handle_stroke: cx.color(t.color.overlay.handle_stroke),
}
+110 -10
View File
@@ -1,5 +1,7 @@
use std::fmt::Write as _;
use craft::ui::primitives::textures::MAX_TEXTURE;
use super::{DocLayout, Hash, Hasher, Page, Placed, Pos, Rect, WordApp, json};
/// Streams `Debug` formatting directly into a [`Hasher`] without intermediate `String` allocations.
@@ -20,6 +22,9 @@ impl std::fmt::Write for HashFmt<'_> {
// revision that the pages' pictures key on directly.
pub(super) fn view_key(app: &WordApp, dim_body: bool, hidden: Option<&Pos>) -> u64 {
let mut h = std::collections::hash_map::DefaultHasher::new();
// A page drawn under the system's earlier text settings, or the user's earlier smoothing choice, must not pass
// for one drawn under these.
(crate::screen_text::current().key(), app.session.prefs.text_smoothing).hash(&mut h);
let v = &app.session.view;
(v.marks, app.session.prefs.marks, v.show_markup, v.dark_mode, wordcraft_render::DARK_PAPER, v.hide_ink, v.draw.replay).hash(&mut h);
(v.read_mode, v.read_page_color, app.session.prefs.paper_color).hash(&mut h);
@@ -180,6 +185,9 @@ pub(crate) fn dark_page(app: &WordApp) -> bool {
/// Render options for this view's page rasters: marks, markup, dark page, header/body dimming.
pub(super) fn page_render_options(app: &WordApp, dim_body: bool) -> wordcraft_render::RenderOptions {
let mut opts = screen_render_options();
// Pages, and only pages, follow the system's own text settings once they are known ([`crate::screen_text`]);
// `view_key` has them, so a change redraws the pages.
crate::screen_text::current().apply(&mut opts);
opts.display.marks = app.session.view.marks;
opts.display.always = app.session.prefs.marks;
opts.display.placeholders = true;
@@ -208,15 +216,107 @@ pub(super) fn page_render_options(app: &WordApp, dim_body: bool) -> wordcraft_re
opts
}
/// Render options for page rasters shown on screen, so a page looks as text does in the
/// platform's other apps (exports never change): on macOS, text is darkened the way the system
/// draws it; on Linux and the BSDs it is hinted lightly, as FreeType's `hintslight` draws it
/// there (not darkened: hinted text already has FreeType's weight, and darkening made it
/// look semi-bold).
pub(crate) fn screen_render_options() -> wordcraft_render::RenderOptions {
wordcraft_render::RenderOptions {
text_darkening: cfg!(target_os = "macos"),
hinting: cfg!(all(unix, not(target_os = "macos"))),
..Default::default()
/// Subpixel (LCD) text for the page rasters of a screen with `ppp` device pixels per point, as File › Options ›
/// General › Screen text smoothing says. "Use system setting" draws it where the system asks for it
/// ([`crate::screen_text`]) and the screen is below two device pixels per point: on a denser screen the stripes are
/// too fine to gain from, and a page has four times the pixels to rasterise three times. "Subpixel (LCD)" draws it
/// on any screen, in the system's stripe order, RGB when it names none (macOS never does).
pub(super) fn lcd_for(
choice: wordcraft_engine::cmd::view::TextSmoothing,
asked: Option<crate::screen_text::SubpixelOrder>,
stripes: Option<crate::screen_text::SubpixelOrder>,
ppp: f32,
) -> Option<wordcraft_render::LcdOrder> {
use crate::screen_text::SubpixelOrder;
use wordcraft_engine::cmd::view::TextSmoothing;
use wordcraft_render::LcdOrder;
let order = |stripes: SubpixelOrder| match stripes {
SubpixelOrder::Rgb => LcdOrder::Rgb,
SubpixelOrder::Bgr => LcdOrder::Bgr,
};
match choice {
TextSmoothing::Grayscale => None,
// The user's own choice, in the order of their screen even where the system has smoothing off (a BGR panel
// with ClearType off must not get RGB edges).
TextSmoothing::Subpixel => Some(asked.or(stripes).map(order).unwrap_or(LcdOrder::Rgb)),
// Written so a density that isn't a number is greyscale too.
TextSmoothing::System => asked.map(order).filter(|_| ppp < 2.0),
}
}
/// The scale (pixels per document point) to rasterise a page picture at, and whether that is the screen's own.
///
/// The page view asks for a picture by its longest side in pixels, `side`, rounded up to a multiple of `step`, and
/// scales what it gets to the page's place on screen. Rasterised at `side`, a page is up to `step` pixels larger
/// than it shows and every glyph is resampled on the way to the screen, which undoes baselines put on whole pixels
/// and makes subpixel text wrong (each colour's edge off its stripe). `native` is the view's own scale, device
/// pixels per document point, when it is known: where it accounts for the side asked for (the page's `longest`
/// side, in points, at that scale rounds up to `side`), the picture is rasterised at exactly that scale, one raster
/// pixel per device pixel. Otherwise (another view's request, a fit zoom not settled yet, a part of a page shown
/// reduced) it is rasterised at the side asked for, as before, and is not the screen's own.
pub(super) fn raster_scale(side: u32, step: u32, longest: f32, native: Option<f32>) -> (f32, bool) {
let largest = MAX_TEXTURE as f32;
// `side / longest * longest` can come out a hair over `side`, which rounds up to a pixel too many for a texture.
let mut asked = side as f32 / longest;
if side <= MAX_TEXTURE && (longest * asked).ceil() > largest {
asked = asked.next_down().next_down();
}
let fits = |scale: f32| {
let pixels = longest * scale;
scale.is_finite() && scale > 0.0 && pixels.is_finite() && pixels <= side as f32 + 0.5 && pixels > side as f32 - step as f32 - 0.5
// A pixel over the largest texture and the store halves the whole picture.
&& pixels.ceil() <= largest
};
match native.filter(|scale| longest.is_finite() && longest > 0.0 && step > 0 && fits(*scale)) {
Some(scale) => (scale, true),
None => (asked, false),
}
}
/// The size in device pixels of the place on screen a page's picture is drawn in, when a picture of about
/// `expected` pixels (its size at the view's scale) is that place's own.
///
/// The page view draws a picture as its painter does every picture: the place (`page`, in screen points, or the
/// part `region` of it, in fractions) is rounded to whole pixels, and the picture is fitted inside it by its own
/// proportions. A picture of exactly the rounded place's size is drawn one pixel for one. Any other is scaled:
/// rasterised a whole pixel up each way, as a single scale gives, a 2016 × 2851 pixel place gets a 2017 × 2852
/// picture squeezed by a twentieth of a percent, and the text slides off the pixel grid and back down the page.
/// The rounded size depends on where the place starts, so it comes from where the view last put the page, not
/// from the page's size. `None` where the place is not within a pixel and a half of `expected` each way: a
/// place left over from another zoom, or numbers that aren't.
pub(super) fn picture_pixels(page: egui::Rect, region: Option<egui::Rect>, ppp: f32, expected: (f32, f32)) -> Option<(u32, u32)> {
let place = match region {
Some(part) => {
let at = |f: egui::Pos2| egui::pos2(page.min.x + f.x * page.width(), page.min.y + f.y * page.height());
egui::Rect::from_min_max(at(part.min), at(part.max))
}
None => page,
};
let side = |lo: f32, hi: f32, expected: f32| {
let pixels = (hi * ppp).round() - (lo * ppp).round();
(pixels.is_finite() && expected.is_finite() && pixels >= 1.0 && (pixels - expected).abs() <= 1.5).then_some(pixels as u32)
};
Some((side(place.min.x, place.max.x, expected.0)?, side(place.min.y, place.max.y, expected.1)?))
}
/// Render options for rasters shown on screen other than the pages themselves (style and font previews, a dragged
/// object), so their text looks as it does in the platform's other apps (exports never change): on macOS it is
/// darkened the way the system draws it; on Linux and the BSDs it is hinted lightly, as FreeType's `hintslight`
/// draws it there (not darkened: hinted text already has FreeType's weight, and darkening made it look semi-bold).
/// Baselines sit on whole device pixels (hinting does that; unhinted text is moved there). These are fixed per
/// platform: such rasters are cached without the system's text settings in their keys, so they must not follow
/// them. Pages do ([`page_render_options`]).
pub(crate) fn screen_render_options() -> wordcraft_render::RenderOptions {
let mut opts = wordcraft_render::RenderOptions { baseline_snap: true, ..Default::default() };
crate::screen_text::ScreenText::PLATFORM.apply(&mut opts);
opts
}
/// Render options for the template thumbnails of File › New: the platform's text, as [`screen_render_options`],
/// without the baseline snapping. A thumbnail is a page shrunk to a tile, drawn as it was before pages were
/// sharpened.
pub(crate) fn thumbnail_render_options() -> wordcraft_render::RenderOptions {
let mut opts = wordcraft_render::RenderOptions::default();
crate::screen_text::ScreenText::PLATFORM.apply(&mut opts);
opts
}
+90 -17
View File
@@ -8,12 +8,12 @@ use std::sync::Arc;
use craft::behavior::kurbo::Size;
use craft::pages::ui::PageSource;
use craft::ui::primitives::textures::{LoadedPicture, Revision, ThumbRender, ThumbRequest, ThumbSource};
use craft::ui::primitives::textures::{LoadedPicture, MAX_TEXTURE, Revision, ThumbRender, ThumbRequest, ThumbSource};
use wordcraft_doc::{Document, Pos};
use wordcraft_layout::DocLayout;
use super::WordApp;
use super::pages::{PageKeys, page_render_options, page_shows, view_key};
use super::pages::{PageKeys, lcd_for, page_render_options, page_shows, picture_pixels, raster_scale, view_key};
/// A page dimension (points) safe to lay out: finite, at least 1 pt, at most `cap`.
fn dim(v: f32, cap: f32) -> f64 {
@@ -30,13 +30,38 @@ pub(super) struct WordPages {
options: wordcraft_render::RenderOptions,
/// The page a drag took an object off, and the object: rendered without it.
hidden: Option<(usize, Pos)>,
/// Screen points per document point in the view these pages show in, when it is one whose pages are drawn at
/// that scale (the page view); `None` where the view sizes its pages itself (Read Mode's columns). With the
/// screen's density it gives the scale at which a picture is the screen's own ([`raster_scale`]).
view_scale: Option<f32>,
/// Where the page view put each page (page, its place in screen points) the last time the view was at rest;
/// empty for a view that sizes its pages itself. A picture is made exactly as many pixels each way as its
/// place is ([`picture_pixels`]).
placed: Vec<(usize, egui::Rect)>,
/// File › Options › General › Screen text smoothing, and what the system says of the screen's text.
smoothing: wordcraft_engine::cmd::view::TextSmoothing,
screen_text: crate::screen_text::ScreenText,
}
/// The page view asks for pictures whose longest side is a multiple of this many pixels
/// (`ThumbRequest::side`).
const SIDE_STEP: u32 = 16;
impl WordPages {
/// The source of `layout` for this pass. The page fingerprints move out of the app for the pass; give them back
/// with [`WordPages::into_keys`].
pub(super) fn new(app: &mut WordApp, layout: &Arc<DocLayout>, dim_body: bool, hidden: Option<(usize, Pos)>) -> Self {
let view = view_key(app, dim_body, hidden.as_ref().map(|(_, p)| p));
/// `view_scale` is the view's screen points per document point where its pages are drawn at exactly that scale,
/// so that their pictures can be rasterised one pixel per device pixel.
pub(super) fn new(app: &mut WordApp, layout: &Arc<DocLayout>, dim_body: bool, hidden: Option<(usize, Pos)>, view_scale: Option<f32>) -> Self {
let view_scale = view_scale.filter(|scale| scale.is_finite() && *scale > 0.0);
let placed = if view_scale.is_some() { app.canvas.settled_pages.clone() } else { Vec::new() };
let view = {
// A picture rasterised for another zoom is not this zoom's, even where the side asked for is the same.
let mut h = DefaultHasher::new();
(view_key(app, dim_body, hidden.as_ref().map(|(_, p)| p)), view_scale.map(f32::to_bits)).hash(&mut h);
h.finish()
};
let (smoothing, screen_text) = (app.session.prefs.text_smoothing, crate::screen_text::current());
let options = page_render_options(app, dim_body);
let doc = if let Some((_, preview, _, _)) = &app.canvas.table_preview_layout {
Arc::new(preview.clone())
@@ -51,7 +76,8 @@ impl WordPages {
}
}
};
WordPages { doc, layout: layout.clone(), keys: RefCell::new(std::mem::take(&mut app.canvas.page_keys)), view, options, hidden }
let keys = RefCell::new(std::mem::take(&mut app.canvas.page_keys));
WordPages { doc, layout: layout.clone(), keys, view, options, hidden, view_scale, placed, smoothing, screen_text }
}
/// The pass's document snapshot, shared with the accessibility describer so the pass holds one copy.
@@ -65,16 +91,26 @@ impl WordPages {
}
}
impl ThumbSource<usize> for WordPages {
fn revision(&self, page: &usize, _request: &ThumbRequest) -> Revision {
let mut h = DefaultHasher::new();
page_shows(&mut self.keys.borrow_mut(), &self.layout, *page, self.view).hash(&mut h);
Revision::new(h.finish())
}
/// What a request for a page's picture is rasterised as.
pub(super) struct RasterPlan {
/// The whole page, or only `area` of it.
pub(super) whole: bool,
/// The part of the page to rasterise, in document points.
pub(super) area: wordcraft_geom::Rect,
/// Pixels per document point.
pub(super) scale: f32,
/// The picture's size in pixels where it is made to fill its place on screen exactly; `None` for one made at
/// `scale`, a whole pixel up each way.
pub(super) pixels: Option<(u32, u32)>,
pub(super) options: wordcraft_render::RenderOptions,
}
fn render(&self, page: &usize, request: &ThumbRequest) -> ThumbRender {
let index = *page;
let Some(p) = self.layout.pages.get(index) else { return ThumbRender::Blank };
impl WordPages {
/// What of page `index` a picture for `request` shows and how large it is made: whether it is the whole page,
/// the area in document points, the pixels per point, whether that is the screen's own scale, and the picture's
/// size in pixels where it is made to fill its place exactly. `None` for a page the layout doesn't have.
fn geometry(&self, index: usize, request: &ThumbRequest) -> Option<(bool, wordcraft_geom::Rect, f32, bool, Option<(u32, u32)>)> {
let p = self.layout.pages.get(index)?;
let (pw, ph) = (dim(p.w, 1e5) as f32, dim(p.h, 1e6) as f32);
let whole = request.region.is_none();
let (x0, y0, x1, y1) = match request.region {
@@ -84,14 +120,51 @@ impl ThumbSource<usize> for WordPages {
let area = wordcraft_geom::Rect::new(x0 * pw, y0 * ph, ((x1 - x0) * pw).max(0.01), ((y1 - y0) * ph).max(0.01));
let longest = area.w.max(area.h);
let cap = wordcraft_render::MAX_SIDE as f32 / longest;
let scale = request.side as f32 / longest;
// At the screen's own scale where the view's zoom accounts for the side asked for, so no glyph is resampled
// on its way to the screen; else at the side asked for.
let (scale, own) = raster_scale(request.side, SIDE_STEP, longest, self.view_scale.map(|s| s * request.pixels_per_point));
let own = own && scale <= cap;
let scale = if scale.is_finite() { scale.clamp(0.01, cap.max(0.01)) } else { 1.0 };
let (doc, layout) = (Arc::clone(&self.doc), Arc::clone(&self.layout));
// Exactly as many pixels each way as the picture's place on screen has, where that is known and is this
// scale's: a pixel more and the page view scales the picture into its place.
let place = self.placed.iter().find(|(page, _)| *page == index).map(|(_, rect)| *rect);
let pixels = place
.filter(|_| own)
.and_then(|place| picture_pixels(place, request.region, request.pixels_per_point, (area.w * scale, area.h * scale)))
// A place can round to a pixel more than the largest texture, and a larger picture is halved.
.filter(|(w, h)| *w.max(h) <= MAX_TEXTURE);
Some((whole, area, scale, own, pixels))
}
/// How page `index` is rasterised for `request`; `None` for a page the layout doesn't have.
pub(super) fn plan(&self, index: usize, request: &ThumbRequest) -> Option<RasterPlan> {
let (whole, area, scale, own, pixels) = self.geometry(index, request)?;
let mut options = self.options.clone();
options.display.hide_object = self.hidden.as_ref().filter(|(hidden, _)| *hidden == index).map(|(_, pos)| pos.clone());
// Subpixel text only on a picture that is the screen's own: scaled, each colour's edge would miss its stripe.
options.lcd = lcd_for(self.smoothing, self.screen_text.subpixel, self.screen_text.stripes, request.pixels_per_point).filter(|_| own);
Some(RasterPlan { whole, area, scale, pixels, options })
}
}
impl ThumbSource<usize> for WordPages {
fn revision(&self, page: &usize, request: &ThumbRequest) -> Revision {
let mut h = DefaultHasher::new();
page_shows(&mut self.keys.borrow_mut(), &self.layout, *page, self.view).hash(&mut h);
// A picture made for another place's pixel size is not this place's.
self.geometry(*page, request).and_then(|(.., pixels)| pixels).hash(&mut h);
Revision::new(h.finish())
}
fn render(&self, page: &usize, request: &ThumbRequest) -> ThumbRender {
let index = *page;
let Some(RasterPlan { whole, area, scale, pixels, options }) = self.plan(index, request) else { return ThumbRender::Blank };
let (doc, layout) = (Arc::clone(&self.doc), Arc::clone(&self.layout));
ThumbRender::Later(Box::new(move |_cancel| {
let Some(page) = layout.pages.get(index) else { return Ok(LoadedPicture::Blank) };
let img = if whole {
let img = if let Some((w, h)) = pixels {
wordcraft_render::render_area_to(&doc, page, area, w, h, &options)
} else if whole {
wordcraft_render::render_page(&doc, page, scale, &options)
} else {
wordcraft_render::render_area(&doc, page, area, scale, &options)
+300 -3
View File
@@ -2359,6 +2359,209 @@ fn the_view_key_changes_when_a_drag_takes_an_object_off_the_page() {
assert_eq!(hidden, view_key(&app, false, Some(&object)), "the same drag keeps the key: no re-render every frame");
}
#[test]
fn only_pages_follow_the_systems_text_settings() {
use crate::screen_text::ScreenText;
// Previews and thumbnails are cached without the system's settings in their keys: they are
// drawn the platform's fixed way. Thumbnails are not baseline-snapped either.
let (screen, thumb) = (screen_render_options(), thumbnail_render_options());
for opts in [&screen, &thumb] {
assert_eq!((opts.text_darkening, opts.hinting, opts.lcd), (ScreenText::PLATFORM.darkening, ScreenText::PLATFORM.hinting, None));
}
assert!(screen.baseline_snap && !thumb.baseline_snap);
// A page takes the same until the app has asked the system (tests never do).
let a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
let page = page_render_options(&a, false);
assert_eq!((page.text_darkening, page.hinting, page.baseline_snap), (screen.text_darkening, screen.hinting, true));
}
#[test]
fn subpixel_text_follows_the_choice_the_system_and_the_screen() {
use super::pages::lcd_for;
use crate::screen_text::SubpixelOrder::{Bgr, Rgb};
use wordcraft_engine::cmd::view::TextSmoothing::{Grayscale, Subpixel, System};
use wordcraft_render::LcdOrder;
// Use system setting: where the system asks for it, in its order, below 2x only.
assert_eq!(lcd_for(System, Some(Rgb), Some(Rgb), 1.0), Some(LcdOrder::Rgb));
assert_eq!(lcd_for(System, Some(Bgr), Some(Bgr), 1.5), Some(LcdOrder::Bgr));
assert_eq!(lcd_for(System, Some(Rgb), Some(Rgb), 2.0), None, "a high-density screen");
assert_eq!(lcd_for(System, Some(Rgb), Some(Rgb), f32::NAN), None);
assert_eq!(lcd_for(System, None, None, 1.0), None, "the system asks for greyscale, or says nothing");
assert_eq!(lcd_for(System, None, Some(Bgr), 1.0), None, "a known stripe order is not a request");
// The user's own choice wins on any screen; RGB when the system names no order.
assert_eq!(lcd_for(Subpixel, None, None, 2.0), Some(LcdOrder::Rgb));
assert_eq!(lcd_for(Subpixel, Some(Bgr), Some(Bgr), 3.0), Some(LcdOrder::Bgr));
// A BGR panel whose system has smoothing off (ClearType off on Windows, greyscale on a
// Linux desktop) still gets BGR edges, not RGB ones.
assert_eq!(lcd_for(Subpixel, None, Some(Bgr), 1.0), Some(LcdOrder::Bgr));
let cleartype_off = crate::screen_text::ScreenText::from_windows(Some("0"), Some(2), Some(0));
assert_eq!(lcd_for(Subpixel, cleartype_off.subpixel, cleartype_off.stripes, 1.0), Some(LcdOrder::Bgr));
assert_eq!(lcd_for(System, cleartype_off.subpixel, cleartype_off.stripes, 1.0), None);
for (asked, stripes) in [(None, None), (Some(Rgb), Some(Rgb)), (None, Some(Bgr))] {
assert_eq!(lcd_for(Grayscale, asked, stripes, 1.0), None);
}
}
#[test]
fn a_page_picture_is_rasterised_at_the_screens_own_scale_where_the_view_accounts_for_it() {
use super::pages::raster_scale;
// An A4 page (841.89 pt) at 100 % on a 2x screen: 2245.04 device pixels, asked for as 2256 (the next multiple
// of 16). At 2256 every glyph would be shrunk by half a percent on its way to the screen.
let longest = 841.89_f32;
let native = 96.0 / 72.0 * 2.0;
assert_eq!(raster_scale(2256, 16, longest, Some(native)), (native, true));
assert_eq!(raster_scale(2256, 16, longest, None), (2256.0 / longest, false), "a view with no scale of its own");
// US Letter (792 pt) at the same zoom is 2112 pixels, a multiple of 16: the same either way.
let (scale, own) = raster_scale(2112, 16, 792.0, Some(native));
assert!(own && (scale - 2112.0 / 792.0).abs() < 1e-6);
// A side the view's scale doesn't account for: another zoom's request, a side lowered to the largest texture,
// a part of the page shown reduced. Rasterised as asked for, and not the screen's own.
for side in [2240, 2272, 1024, 16] {
assert_eq!(raster_scale(side, 16, longest, Some(native)), (side as f32 / longest, false), "{side}");
}
// Numbers that aren't: as asked for.
for (longest, native, step) in
[(longest, f32::NAN, 16), (longest, f32::INFINITY, 16), (longest, -1.0, 16), (longest, 0.0, 16), (longest, native, 0)]
{
assert!(!raster_scale(2256, step, longest, Some(native)).1, "{longest} {native} {step}");
}
assert!(!raster_scale(2256, 16, f32::NAN, Some(native)).1 && !raster_scale(2256, 16, 0.0, Some(native)).1);
}
/// A page a fraction of a pixel longer than the largest texture is made no larger than it: a picture one pixel over
/// is halved on upload, and the page stays blurry at rest.
#[test]
fn a_page_picture_never_outgrows_the_largest_texture() {
use super::source::WordPages;
use craft::ui::primitives::textures::{MAX_TEXTURE, ThumbRequest};
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
let layout = a.session.layout();
let (w, h) = (layout.pages[0].w, layout.pages[0].h);
let longest = w.max(h);
for over in [-0.6, -0.1, 0.0, 0.1, 0.3, 0.5] {
for y in [0.0, 0.3, 0.49, 0.6] {
let scale = (MAX_TEXTURE as f32 + over) / longest;
a.canvas.settled_pages = vec![(0, Rect::from_min_size(egui::pos2(10.0, y), egui::vec2(w * scale, h * scale)))];
let pages = WordPages::new(&mut a, &layout, false, None, Some(scale));
let plan = pages.plan(0, &ThumbRequest::for_cell(longest * scale, 1.0)).unwrap();
let side = plan.pixels.map_or((longest * plan.scale).ceil() as u32, |(w, h)| w.max(h));
assert!(side <= MAX_TEXTURE, "{over} at {y}: {side}");
assert!(side + 2 >= MAX_TEXTURE, "not reduced either: {over} at {y}: {side}");
if over < -0.5 {
assert!(plan.pixels.is_some(), "a page below the limit keeps its own pixels: {over} at {y}");
}
}
}
}
#[test]
fn a_page_picture_is_made_as_many_pixels_as_its_place_on_screen() {
use super::pages::picture_pixels;
use egui::{pos2, vec2};
// An A4 page at 110 % on a 2x screen, centred in a window: 1746.155 × 2469.544 pixels starting at 642.923.
// Its place rounds to 643..2389 across and 356..2826 down.
let page = Rect::from_min_size(pos2(321.4615, 178.0), vec2(873.0775, 1234.772));
let expected = (1746.155, 2469.544);
assert_eq!(picture_pixels(page, None, 2.0, expected), Some((1746, 2470)));
// The same page half a pixel further right ends on the next pixel and starts on the same one: 1747 across.
assert_eq!(picture_pixels(page.translate(vec2(0.25, 0.0)), None, 2.0, expected), Some((1747, 2470)));
// The upper half of it, as the page view asks for a part: the part's own place, rounded the same way.
let half = Rect::from_min_max(pos2(0.0, 0.0), pos2(1.0, 0.5));
assert_eq!(picture_pixels(page, Some(half), 2.0, (1746.155, 1234.772)), Some((1746, 1235)));
// A place left from another zoom, or a part shown reduced, is not this picture's: no size.
assert_eq!(picture_pixels(page, None, 2.0, (1587.4, 2245.0)), None);
assert_eq!(picture_pixels(page, Some(half), 2.0, (873.0, 617.0)), None);
// Numbers that aren't.
for (page, ppp, expected) in [
(Rect::from_min_size(pos2(f32::NAN, 0.0), vec2(800.0, 1100.0)), 2.0, expected),
(Rect::from_min_size(pos2(0.0, 0.0), vec2(f32::INFINITY, 1100.0)), 2.0, expected),
(page, f32::NAN, expected),
(page, 0.0, expected),
(page, 2.0, (f32::NAN, 2469.5)),
(Rect::NOTHING, 2.0, expected),
] {
assert_eq!(picture_pixels(page, None, ppp, expected), None, "{page:?} {ppp} {expected:?}");
}
}
#[test]
fn page_pictures_fill_the_place_the_view_last_rested_at() {
use super::source::WordPages;
use craft::ui::primitives::textures::{ThumbRequest, ThumbSource};
use egui::{pos2, vec2};
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
let layout = a.session.layout();
let (pw, ph) = (layout.pages[0].w, layout.pages[0].h);
let view_scale = 96.0 / 72.0 * 1.1;
let request = ThumbRequest::for_cell(pw.max(ph) * view_scale, 2.0);
// Before the view has rested anywhere: one scale, a whole pixel up each way.
let fresh = WordPages::new(&mut a, &layout, false, None, Some(view_scale));
let plan = fresh.plan(0, &request).unwrap();
assert_eq!((plan.pixels, plan.scale), (None, view_scale * 2.0));
let fresh_revision = fresh.revision(&0, &request);
a.canvas.page_keys = fresh.into_keys();
// At rest, a third of a pixel into a pixel: the picture is its place's size, and another picture than before.
let place = Rect::from_min_size(pos2(321.4615, 178.0), vec2(pw * view_scale, ph * view_scale));
a.canvas.settled_pages = vec![(0, place)];
let rested = WordPages::new(&mut a, &layout, false, None, Some(view_scale));
let plan = rested.plan(0, &request).unwrap();
let (w, h) = plan.pixels.expect("a place to fill");
assert_eq!(w as f32, (place.max.x * 2.0).round() - (place.min.x * 2.0).round());
assert_eq!(h as f32, (place.max.y * 2.0).round() - (place.min.y * 2.0).round());
assert_ne!(rested.revision(&0, &request), fresh_revision);
assert!(rested.plan(1, &request).is_none_or(|plan| plan.pixels.is_none()), "a page with no place");
a.canvas.page_keys = rested.into_keys();
// A place from another zoom is not this zoom's; Read Mode's columns use none.
let zoomed = WordPages::new(&mut a, &layout, false, None, Some(view_scale * 1.3));
assert_eq!(zoomed.plan(0, &ThumbRequest::for_cell(pw.max(ph) * view_scale * 1.3, 2.0)).unwrap().pixels, None);
a.canvas.page_keys = zoomed.into_keys();
let reading = WordPages::new(&mut a, &layout, false, None, None);
assert_eq!(reading.plan(0, &request).unwrap().pixels, None);
a.canvas.page_keys = reading.into_keys();
}
#[test]
fn page_pictures_take_subpixel_text_only_at_the_screens_own_scale() {
use super::source::WordPages;
use craft::ui::primitives::textures::{ThumbRequest, ThumbSource};
use wordcraft_render::LcdOrder;
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
let layout = a.session.layout();
let longest = layout.pages[0].w.max(layout.pages[0].h);
let view_scale = 96.0 / 72.0 * 1.1;
let request = |ppp: f32| ThumbRequest::for_cell(longest * view_scale, ppp);
let pages = |a: &mut WordApp, scale: Option<f32>| WordPages::new(a, &layout, false, None, scale);
// Greyscale until chosen (tests never ask the system), at the screen's own scale.
let grey = pages(&mut a, Some(view_scale));
let plan = grey.plan(0, &request(2.0)).unwrap();
assert_eq!((plan.scale, plan.options.lcd), (view_scale * 2.0, None));
assert!(plan.options.baseline_snap);
let grey_revision = grey.revision(&0, &request(2.0));
a.canvas.page_keys = grey.into_keys();
// The user's choice, a command: subpixel text on the picture that is the screen's own...
a.run("view.textSmoothing", json!({"value": "subpixel"})).unwrap();
let sub = pages(&mut a, Some(view_scale));
assert_eq!(sub.plan(0, &request(2.0)).unwrap().options.lcd, Some(LcdOrder::Rgb));
assert_eq!(sub.plan(0, &request(1.0)).unwrap().options.lcd, Some(LcdOrder::Rgb));
assert_ne!(sub.revision(&0, &request(2.0)), grey_revision, "a page drawn the other way is another picture");
let sub_revision = sub.revision(&0, &request(2.0));
// ...and not on one that will be scaled: a request the view's zoom doesn't account for, a part shown reduced.
let other = ThumbRequest::for_cell(longest * view_scale * 1.3, 2.0);
let plan = sub.plan(0, &other).unwrap();
assert_eq!((plan.scale, plan.options.lcd), (other.side as f32 / longest, None));
a.canvas.page_keys = sub.into_keys();
// Read Mode's columns size their pages themselves: as asked for, greyscale.
let reading = pages(&mut a, None);
let plan = reading.plan(0, &request(2.0)).unwrap();
assert_eq!((plan.scale, plan.options.lcd), (request(2.0).side as f32 / longest, None));
a.canvas.page_keys = reading.into_keys();
// Another zoom is another picture, even where the side asked for is the same.
let nudged = pages(&mut a, Some(view_scale * 1.0005));
assert_eq!(ThumbRequest::for_cell(longest * view_scale * 1.0005, 2.0).side, request(2.0).side);
assert_ne!(nudged.revision(&0, &request(2.0)), sub_revision);
assert!(nudged.plan(99, &request(2.0)).is_none());
}
#[test]
fn screen_paper_color_changes_raster_and_cache_without_changing_export_paper() {
use wordcraft_doc::props::Rgb;
@@ -2955,18 +3158,18 @@ fn the_caret_blinks_only_while_the_window_is_active() {
fn word_pages_reuses_doc_snapshot_across_unchanged_frames_and_invalidates_on_edit() {
let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::from_text("hello")), Default::default());
let layout = app.session.layout();
let first = super::source::WordPages::new(&mut app, &layout, false, None);
let first = super::source::WordPages::new(&mut app, &layout, false, None, None);
let doc1 = first.doc();
app.canvas.page_keys = first.into_keys();
let second = super::source::WordPages::new(&mut app, &layout, false, None);
let second = super::source::WordPages::new(&mut app, &layout, false, None, None);
let doc2 = second.doc();
app.canvas.page_keys = second.into_keys();
assert!(std::sync::Arc::ptr_eq(&doc1, &doc2), "unchanged frame reuses cached Arc<Document> snapshot");
app.run("text.insert", json!({"text": " world"})).unwrap();
let layout2 = app.session.layout();
let third = super::source::WordPages::new(&mut app, &layout2, false, None);
let third = super::source::WordPages::new(&mut app, &layout2, false, None, None);
let doc3 = third.doc();
app.canvas.page_keys = third.into_keys();
assert!(!std::sync::Arc::ptr_eq(&doc1, &doc3), "editing document invalidates cached snapshot");
@@ -3085,6 +3288,100 @@ fn shift_clicking_a_picture_does_not_scroll_the_view() {
assert_eq!(h.state().canvas.view.offset, before, "the view stayed where it was");
}
/// The pictures drawn in the last pass that are at least 300 texels wide (a page's, not an icon's or the font
/// atlas's glyphs): how many device pixels each is drawn across and down, and how many texels it shows.
fn drawn_pictures(
shapes: &[egui::epaint::ClippedShape],
sizes: &std::collections::HashMap<egui::TextureId, [usize; 2]>,
ppp: f32,
) -> Vec<([f32; 2], [f32; 2])> {
fn walk(shape: &egui::Shape, found: &mut Vec<(egui::TextureId, Rect, Rect)>) {
match shape {
egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| walk(s, found)),
egui::Shape::Mesh(mesh) if mesh.texture_id != egui::TextureId::default() => {
let (mut at, mut uv) = (Rect::NOTHING, Rect::NOTHING);
for v in &mesh.vertices {
at.extend_with(v.pos);
uv.extend_with(v.uv);
}
found.push((mesh.texture_id, at, uv));
}
egui::Shape::Rect(rect) => {
if let Some(brush) = &rect.brush
&& brush.fill_texture_id != egui::TextureId::default()
{
found.push((brush.fill_texture_id, rect.rect, brush.uv));
}
}
_ => {}
}
}
let mut found = Vec::new();
shapes.iter().for_each(|clipped| walk(&clipped.shape, &mut found));
found
.into_iter()
.filter_map(|(id, at, uv)| {
let size = sizes.get(&id).filter(|size| size[0] >= 300)?;
let texels = [uv.width() * size[0] as f32, uv.height() * size[1] as f32];
(texels[0] >= 300.0).then_some(([at.width() * ppp, at.height() * ppp], texels))
})
.collect()
}
/// The page view scales a picture into its place, so a page's picture has to be exactly as many pixels each way
/// as that place: a pixel more (what one scale and rounding up give) squeezes it by a twentieth of a percent and
/// the text slides off the pixel grid and back down the page, which reads as blur. Run through the real page view
/// and its picture store, at several zooms and screen densities, on the passes a renderer would draw.
#[test]
fn a_page_at_rest_is_drawn_one_texel_per_device_pixel() {
for ppp in [1.0_f32, 2.0] {
let ctx = crate::test_harness::context();
crate::test_harness::cjk_stand_in(&ctx);
ctx.set_pixels_per_point(ppp);
let mut app = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
app.run("document.setText", json!({"text": "The quick brown fox jumps over the lazy dog."})).unwrap();
app.run("layout.size", json!({"name": "A4"})).unwrap();
let mut sizes = std::collections::HashMap::new();
for (step, zoom) in [100, 110, 137].into_iter().enumerate() {
app.run("view.zoom", json!({"value": zoom})).unwrap();
// Until the view has come to rest and the worker has made the picture for where it rests.
let mut seen = Vec::new();
let exact = |pictures: &[([f32; 2], [f32; 2])]| {
!pictures.is_empty()
&& pictures.iter().all(|(drawn, texels)| (drawn[0] - texels[0]).abs() < 0.01 && (drawn[1] - texels[1]).abs() < 0.01)
};
for frame in 0..600 {
let mut input = egui::RawInput {
screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1500.0, 950.0))),
time: Some(step as f64 * 100.0 + frame as f64 * 0.05),
max_texture_side: Some(8192),
..Default::default()
};
if let Some(viewport) = input.viewports.get_mut(&egui::ViewportId::ROOT) {
viewport.native_pixels_per_point = Some(ppp);
}
craft::ui::shell::embed::before_input(&ctx, |out| app.frame_input(out));
let mut out = ctx.run_ui(input, |ui| {
crate::test_harness::logic(ui.ctx(), &mut app);
app.ui(ui);
});
for (id, deltas) in &out.textures_delta.set {
for delta in deltas.iter().filter(|delta| delta.pos.is_none()) {
sizes.insert(*id, delta.image.size());
}
}
seen = drawn_pictures(&out.shapes, &sizes, ppp);
out.textures_delta.clear();
if frame > 3 && exact(&seen) {
break;
}
std::thread::sleep(std::time::Duration::from_millis(10));
}
assert!(exact(&seen), "{zoom} % at {ppp}x: (pixels drawn, texels shown) {seen:?}");
}
}
}
/// Mouse-wheel notches scroll by WordCraft's document line distance (`NOTCH_PX`, 56 pt) rather than the framework's
/// 16 pt default, and rapid flick notches accelerate when animations are enabled (#8840).
#[test]
+80 -2
View File
@@ -390,6 +390,24 @@ fn draft_text(app: &WordApp) -> Option<String> {
app.canvas.comments.editing.as_ref().map(|(_, _, text)| text.clone())
}
/// Whether this frame painted `text` inside `rect`: the balloon's own text. Not an accessible name, which holds the
/// same words while nothing is drawn: the card's name is built from the stored comment (so it reads "Original" even
/// while the card shows a draft), the picture Size dialog's "Original size" and Compare's "Original document" hold the
/// word too (#9218). A text its clip hides (a card scrolled out of the balloon column) is not painted either.
fn paints_inside(h: &H, rect: Rect, text: &str) -> bool {
fn walk(shape: &egui::Shape, visible: Rect, text: &str) -> bool {
match shape {
egui::Shape::Text(t) => t.galley.text().contains(text) && visible.contains_rect(shape.visual_bounding_rect()),
egui::Shape::Vec(children) => children.iter().any(|child| walk(child, visible, text)),
_ => false,
}
}
h.output().shapes.iter().any(|clipped| {
let visible = rect.intersect(clipped.clip_rect);
visible.is_positive() && walk(&clipped.shape, visible, text)
})
}
/// #1348: a comment edit typed, then refused (the document became read-only).
fn refused_draft() -> (H, u32) {
let (mut h, id) = comment_harness();
@@ -469,22 +487,50 @@ fn escape_reverts_a_comment_draft() {
// initial build frame, which populates `balloon_rects` before `click_balloon` clicks). The window stays wide enough
// for the click on the page's centre to land on the page, not on a balloon.
let (mut h, id) = comment_harness_in(egui::vec2(1440.0, 900.0), 0);
let card = |h: &H| h.state().canvas.balloon_rects.iter().find(|(i, _)| *i == id).map(|(_, r)| *r).expect("the comment has a balloon");
click_balloon(&mut h, id);
type_in(&mut h, "Discarded ");
assert!(draft_text(h.state()).is_some_and(|d| d.contains("Discarded")), "the draft was recorded before Escape");
assert!(edit_field(&h).and_then(|n| n.value()).is_some_and(|v| v.contains("Discarded")), "the Edit field showed the typed draft before Escape");
assert!(paints_inside(&h, card(&h), "Discarded"), "and the balloon paints it before Escape");
h.event(egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: Default::default() });
h.app_frame();
assert_eq!(draft_text(h.state()), None, "the draft is gone");
assert_eq!(comment_text(h.state(), id), "Original", "nothing was written");
assert!(edit_field(&h).is_none(), "Escape closes the inline Edit field");
assert!(h.query_by_label_contains("Original").is_some(), "the balloon shows the comment's original text again");
assert!(h.query_by_label_contains("Discarded").is_none(), "no discarded draft remains shown in the balloon");
// The card's painted text, not the window's accessible names: the card's own name comes from the comment, and the
// picture Size dialog's "Original size" and Compare's "Original document" hold the word too, so a name would
// satisfy this even if the balloon painted nothing (#9218).
assert!(paints_inside(&h, card(&h), "Original"), "the balloon paints the comment's original text again");
assert!(!paints_inside(&h, card(&h), "Discarded"), "no discarded draft remains painted in the balloon");
leave_field(&mut h);
assert_eq!(h.state().canvas.selected_balloon(), None, "the click on the page left the balloon");
assert_eq!(comment_text(h.state(), id), "Original", "and nothing is written later");
}
/// #9218: the balloon's check reads the text its card paints, not the window's accessible names. A card scrolled out of
/// the balloon column keeps the name it takes from the stored comment while it paints none of it, so a name search
/// would pass with nothing drawn.
#[test]
fn the_balloon_check_reads_painted_text_not_its_name() {
let (mut h, id) = comment_harness_in(egui::vec2(1440.0, 900.0), 0);
let card = |h: &H| h.state().canvas.balloon_rects.iter().find(|(i, _)| *i == id).map(|(_, r)| *r).expect("the comment has a balloon");
assert!(paints_inside(&h, card(&h), "Original"), "a card in view paints the comment's text");
// Scroll the card up out of the balloon column.
h.event(egui::Event::PointerMoved(card(&h).center()));
h.event(egui::Event::MouseWheel {
unit: egui::MouseWheelUnit::Point,
delta: vec2(0.0, -200.0),
phase: egui::TouchPhase::Move,
source: egui::MouseWheelSource::Unknown,
modifiers: Default::default(),
});
h.app_frame();
let card = card(&h);
assert!(h.query_all_by_label_contains("Original").any(|n| card.contains_rect(n.rect())), "the card's name still holds the comment's text");
assert!(!paints_inside(&h, card, "Original"), "though the card paints none of it: the balloon check reads paint, so it fails");
}
/// #3268: clicking a balloon's Reply button, typing a reply and clicking away posts it as a
/// reply comment under the original, not a draft that silently disappears.
#[test]
@@ -1080,3 +1126,35 @@ fn context_menu_paste_inserts_system_clipboard_text() {
steps(&mut h, 3);
assert_eq!(h.state().session.doc.body[0].as_para().unwrap().plain_text(), "Hello pasted text");
}
/// #9190: resolving a comment while its balloon is being edited keeps what was typed.
#[test]
fn resolving_a_comment_mid_edit_keeps_the_typed_text() {
let (mut h, id) = comment_harness();
click_balloon(&mut h, id);
type_in(&mut h, "Typed ");
let resolve = h.get_by_label("Resolve").rect().center();
click_at(&mut h, resolve);
assert!(h.state().session.doc.comments[&id].resolved);
assert_eq!(draft_text(h.state()), None, "resolving ends the edit");
h.app_frame();
assert!(edit_field(&h).is_none(), "the resolved balloon shows no edit field");
leave_field(&mut h);
let text = comment_text(h.state(), id);
assert!(text.contains("Typed "), "{text:?}");
}
/// #9190: double-clicking a resolved comment balloon must not open it for editing.
#[test]
fn double_clicking_a_resolved_comment_balloon_does_not_open_edit() {
let (mut h, id) = comment_harness();
h.state_mut().run("review.resolveComment", json!({"id": id})).unwrap();
steps(&mut h, 3);
assert!(h.state().session.doc.comments[&id].resolved);
select_balloon_card(&mut h, id);
let card = h.state().canvas.balloon_rects.iter().find(|(i, _)| *i == id).map(|(_, r)| *r).expect("the comment has a balloon");
double_click_at(&mut h, card.left_top() + vec2(30.0, 8.0));
assert!(h.state().canvas.comments.editing.is_none(), "a resolved balloon must not enter edit mode");
assert!(edit_field(&h).is_none(), "no inline edit field should open for a resolved balloon");
}
+5 -2
View File
@@ -51,8 +51,11 @@ pub(crate) fn help_entries(app: &WordApp) -> Vec<HelpEntry> {
.iter()
.filter(|c| !crate::dialogs::NOT_IN_SEARCH.contains(&c.id))
.map(|c| {
let command =
if c.id == "view.paperColor" { CommandRef::with_params("file.options", json!({"pane": "general"})) } else { CommandRef::new(c.id) };
let command = if c.id == "view.paperColor" || c.id == "view.textSmoothing" {
CommandRef::with_params("file.options", json!({"pane": "general"}))
} else {
CommandRef::new(c.id)
};
let entry = HelpEntry::new(command, tl!(c.label).to_string()).with_english(c.label.to_string());
match crate::app::command_board::location_path(c.location) {
Some(path) => entry.with_path(path.into_iter().map(|part| tl!(part).to_string())),
+13 -4
View File
@@ -301,6 +301,11 @@ pub(crate) fn show(app: &mut WordApp, ui: &mut Ui, layout: &DocLayout, body: &Pa
}
let out = ContentControls::new(tl!("Content controls").to_string(), &framed, &check_rects, button.as_ref().map(|(last, _)| *last))
.show_at(ui, body.rect);
// The pointer parts preserve the caret. Give the page focus before a popup opens so closing it
// returns to the page even when another field had the keyboard before the click.
if (out.toggled.is_some() || out.opened) && !app.canvas.focused(ui.ctx()) {
app.canvas.focus_page(ui.ctx());
}
if let Some(at) = out.toggled.and_then(|i| check_at.get(i)) {
let at = serde_json::to_value(at).unwrap_or_default();
let _ = app.run("developer.toggleCheckBox", json!({"at": at}));
@@ -486,15 +491,19 @@ mod tests {
assert!(h.state().session.undo_depth() > depth, "the stroke ran table.draw");
}
/// #7862: a press on the list button leaves the keyboard with the page, so the list gives it
/// back to the page when it closes, by Escape or by a pick.
/// #7862 and #8407: closing the list returns focus to the page even when a ribbon field held it
/// before the list opened. Clicking the list button still leaves the caret in place.
#[test]
fn closing_the_list_gives_the_keyboard_back_to_the_page() {
fn closing_the_list_returns_focus_to_the_page_from_a_ribbon_field() {
let mut h = dropdown_harness();
focus_page(&mut h);
h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Font Size").focus();
crate::test_harness::frames(&mut h, 2);
assert!(h.get_by_role_and_label(egui::accesskit::Role::ComboBox, "Font Size").is_focused(), "the ribbon field has the keyboard");
let caret = h.state().session.sel.focus.clone();
let button = h.get_by_label("Choose item").rect().center();
click_at(&mut h, button);
assert!(popup_open(h.state()), "the list is open");
assert_eq!(h.state().session.sel.focus, caret, "the list button leaves the caret in place");
h.key_press(egui::Key::Escape);
crate::test_harness::frames(&mut h, 2);
assert!(!popup_open(h.state()), "Escape closes the list");
+30
View File
@@ -4,6 +4,8 @@ use serde_json::{Value, json};
use wordcraft_engine::Session;
use craft::automation::control::{ControlRequest, Reply};
use craft::behavior::Selection;
use craft::review::ThreadId;
use super::handle;
use crate::{Services, WordApp};
@@ -87,6 +89,34 @@ fn methods_address_an_open_document_by_id() {
assert_eq!(r["result"]["blocks"][0]["text"], "First more", "{r}");
}
/// A control command resolving a parked thread writes that document's comment and reply drafts first (#9335).
#[test]
fn resolving_an_addressed_comment_saves_its_parked_drafts() {
let mut a = app();
let (first, second) = two_documents(&mut a);
assert_eq!(exec(&mut a, "view.switchWindows", json!({"id": first}))["ok"], true);
let comment = exec(&mut a, "review.newComment", json!({"text": "Original comment"}));
let id = comment["result"]["id"].as_u64().expect("a comment was added");
let thread = ThreadId(id);
a.canvas.comments.editing = Some((thread, 0, "Edited comment".into()));
a.canvas.comments.selected = Selection::single(thread);
a.canvas.comments.reply = "New reply".into();
assert_eq!(exec(&mut a, "view.switchWindows", json!({"id": second}))["ok"], true);
assert!(a.document_has_comment_drafts(first));
let r = send(&mut a, "engine.execute", json!({"command": "review.resolveComment", "params": {"id": id}, "doc": first}));
assert_eq!(r["ok"], true, "{r}");
assert_eq!(a.session.document_id(), second);
assert_eq!(body(&a).trim(), "Second");
let r = send(&mut a, "engine.execute", json!({"command": "review.comments", "doc": first}));
let comments = r["result"].as_array().expect("the parked document's comments");
assert_eq!(comments[0]["text"], "Edited comment");
assert_eq!(comments[1]["text"], "New reply");
assert_eq!(comments[1]["parent"], id);
assert!(comments.iter().all(|c| c["resolved"] == true));
assert!(!a.document_has_comment_drafts(first));
}
/// W1: `file.close` addressed to a document in the background refuses its unsaved changes
/// unless forced (only a boolean true), as it does for the window's document (#1268), and closes
/// only that document.
+7 -1
View File
@@ -232,7 +232,13 @@ fn handle_in(app: &mut WordApp, doc: u64, method: &str, p: &Value) -> Reply {
return err(e);
}
}
let r = app.session.with_document(doc, |s| s.run(id, &params));
let parked = app.parked.get_mut(&doc).filter(|_| id == "review.resolveComment");
let r = app.session.with_document(doc, |s| {
if let Some(parked) = parked {
crate::panes::flush_parked_comment_drafts(s, &mut parked.comments);
}
s.run(id, &params)
});
// UI requests the command made carry `document`, so the window can tell they aren't
// about the document it shows. A command that changes nothing opens the dialog it asks for, as in
// `after_command`.
@@ -61,7 +61,7 @@ fn tab(def: &CommandDef) -> &str {
}
/// Tabs that come up with the selection or a view, besides the engine's contextual ones; they share one Categories entry.
const EXTRA_CONTEXT_TABS: [&str; 3] = ["Header & Footer", "Outlining", "Reading"];
const EXTRA_CONTEXT_TABS: [&str; 4] = ["Header & Footer", "Outlining", "Reading", "Read Mode"];
fn in_tab<const N: usize>(def: &CommandDef) -> bool {
tab(def) == TABS[N]
@@ -356,13 +356,17 @@ mod tests {
let catalog = a.catalog().expect("catalog");
let areas = super::areas();
for (id, tab, group) in [("insert.video", "Insert", "Media"), ("draw.inkToMath", "Draw", "Convert")] {
for (id, tab, group, category) in [
("insert.video", "Insert", "Media", "Insert"),
("draw.inkToMath", "Draw", "Convert", "Draw"),
("view.readLayout", "Read Mode", "View", "Contextual Tabs"),
] {
let command = CommandRef::new(id);
assert!(a.session.registry.get(id).is_none(), "{id} is still unimplemented");
let def = catalog.defs().iter().find(|def| def.command == command).unwrap_or_else(|| panic!("{id} in catalog"));
assert_eq!(def.paths, [vec![tab.to_owned(), group.to_owned()]], "{id} keeps its full ribbon path");
let categories: Vec<_> = areas.iter().filter(|area| (area.rows)(def)).map(|area| area.id).collect();
assert_eq!(categories, [tab, "All Commands"], "{id} is filed under its ribbon tab");
assert_eq!(categories, [category, "All Commands"], "{id} is filed under its ribbon category");
assert!(def.defaults.is_empty(), "{id} has no default chord");
let state = a.command_states.get(&command);
assert!(state.is_some_and(|state| !state.is_enabled()), "{id} publishes an explicit disabled state");
@@ -326,6 +326,10 @@ impl WordForm for NumberingForm {
Vec::new()
}
fn prepare(&mut self, app: &WordApp) {
self.0.prepare(app);
}
fn body(&mut self, ui: &mut Ui, _cx: &mut FormCx<'_, '_>, _asks: &mut Vec<Asks>) -> bool {
let f = &mut self.0;
let format_title = Label::from(tl!("Format:").to_string());
@@ -96,6 +96,32 @@ fn caption_preview_matches_the_inserted_sequence_after_changing_label() {
assert!(a.session.doc.plain_text(StoryRef::Body).contains(&format!("{prefix}: Second chart")));
}
#[test]
fn numbering_form_prepare_computes_real_next_caption_example() {
use super::caption::NumberingForm;
let mut a = app("Results\nA chart\nAnother chart");
a.ui.caption_labels.push("Plate".into());
a.run("select.text", json!({"text": "Results"})).unwrap();
a.run("styles.apply", json!({"style": "Heading 1"})).unwrap();
a.run("select.text", json!({"text": "A chart"})).unwrap();
a.run("references.caption", json!({"label": "Plate", "text": "First chart", "chapter": 1, "separator": ".", "format": "ALPHABETIC"})).unwrap();
a.run("select.text", json!({"text": "Another chart"})).unwrap();
let mut f = CaptionForm::read(&a);
f.label = "Plate".into();
f.format = "ALPHABETIC".into();
f.chapter = true;
f.separator = ".".into();
f.prepare(&a);
assert_eq!(f.preview(), "Plate 1.B");
// Opening Numbering… round-trips CaptionForm through JSON, skipping `preview`.
let mut numbering: NumberingForm = serde_json::from_value(json!(NumberingForm(f))).unwrap();
numbering.prepare(&a);
assert_eq!(numbering.0.preview(), "Plate 1.B");
}
/// #3120: Insert Caption picks the label used last, and saves it with the preferences.
#[test]
fn caption_dialog_remembers_the_last_label() {
+1 -1
View File
@@ -39,7 +39,7 @@ pub(super) fn page_layout_commands(
let cur = sect(&app.session);
let kept = |shown: f32, now: f32| landscape == cur.landscape && now < 0.0 && shown == now;
let (keep_top, keep_bottom) = (kept(m.0, cur.margin_top), kept(m.1, cur.margin_bottom));
let sizes = |(t, b, l, r): (f32, f32, f32, f32)| (t.abs(), b.abs(), l, r);
let sizes = |(t, b, l, r): (f32, f32, f32, f32)| (t.abs(), b.abs(), l.abs(), r.abs());
// `layout.margins` with the sides it sets: all but the exact ones kept.
let set_margins = |(t, b, l, r): (f32, f32, f32, f32)| {
let mut v = json!({"top": t, "bottom": b, "left": l, "right": r});
+21
View File
@@ -1194,6 +1194,27 @@ fn page_setup_keeps_an_exact_margin_it_didnt_change() {
assert_eq!((x.margin_top, x.margin_bottom, x.margin_left), (50.0, -40.0, 80.0), "the changed one set, the other kept");
}
#[test]
fn page_setup_turning_page_keeps_exact_margin_size_on_new_side() {
let mut h = app_harness(app_with("Page"));
h.run_steps(2);
let sect = |h: &egui_kittest::Harness<'_, WordApp>| wordcraft_engine::cmd::page::sect(&h.state().session);
{
let x = &mut h.state_mut().session.doc.last_section;
(x.margin_top, x.margin_bottom, x.margin_left, x.margin_right) = (-60.0, -40.0, 72.0, 54.0);
}
// Turning portrait -> landscape in the dialog rotates the shown margins (top -> right, bottom -> left).
page_setup(&mut h, |f| {
set_landscape(f, true);
let (t, b, l, r) = (f.margins.top, f.margins.bottom, f.margins.left, f.margins.right);
(f.margins.top, f.margins.bottom, f.margins.left, f.margins.right) = (l, r, b, t);
});
assert!(!is_open(h.state(), "pageSetup"));
let x = sect(&h);
assert!(x.landscape);
assert_eq!((x.margin_top, x.margin_bottom, x.margin_left, x.margin_right), (72.0, 54.0, 40.0, 60.0));
}
/// #1433: one OK in Page Setup is one undo step, whichever order its commands run in (the
/// size first; the margins first; margins of 0 in between), and Undo restores the section.
#[test]
+1 -1
View File
@@ -25,7 +25,7 @@ pub(crate) struct Parked {
read_from: Option<std::path::PathBuf>,
/// The comment panel's selection and the comment and reply text typed in this document and not
/// yet written to it.
comments: craft::review::ui::CommentsPanelState,
pub(crate) comments: craft::review::ui::CommentsPanelState,
}
impl WordApp {
+1
View File
@@ -68,6 +68,7 @@ pub mod read_aloud;
mod restrict_pane;
pub mod ribbon;
mod save_types;
pub mod screen_text;
pub mod scroll;
pub use scroll::ScrollSpeed;
pub mod desktop_theme; // owed by ribbon batch 2 (S-L348)
+11
View File
@@ -125,6 +125,8 @@ struct Strings {
region_id: String,
paper: Vec<(String, String)>,
paper_id: String,
smoothing: Vec<(String, String)>,
smoothing_id: String,
numerals: Vec<(String, String)>,
numeral_id: String,
proofing_language: String,
@@ -171,6 +173,8 @@ impl Strings {
let paper = PaperColor::ALL.iter().map(|c| (id_of(c), tl!(c.label()).to_string())).collect();
let paper_id = id_of(&app.session.prefs.paper_color);
let smoothing = wordcraft_engine::cmd::view::TextSmoothing::ALL.iter().map(|c| (id_of(c), tl!(c.label()).to_string())).collect();
let smoothing_id = id_of(&app.session.prefs.text_smoothing);
let numerals = [NumeralMode::Arabic, NumeralMode::Hindi, NumeralMode::Context, NumeralMode::System]
.iter()
.map(|m| (id_of(m), tl!(m.label()).to_string()))
@@ -197,6 +201,8 @@ impl Strings {
region_id,
paper,
paper_id,
smoothing,
smoothing_id,
numerals,
numeral_id,
proofing_language,
@@ -246,6 +252,7 @@ impl<'a> OptionsModel<'a> {
("general.theme", Choice(ui.theme.code().to_string())),
("general.interfaceSize", Choice(size)),
("general.paperColor", Choice(id_of(&prefs.paper_color))),
("general.textSmoothing", Choice(id_of(&prefs.text_smoothing))),
("general.miniToolbar", Bool(ui.mini_toolbar)),
("general.darkPage", Bool(view.dark_mode)),
("general.showCommunity", Bool(ui.show_discord)),
@@ -337,6 +344,9 @@ impl PreferencesModel for OptionsModel<'_> {
RowSpec::new("general.paperColor", tl!("Screen paper color:"), RowKind::choice(&s.paper_id, owned(&s.paper))).help(tl!(
"Screen only. Document backgrounds, printing and exports keep their colours. Dark page and explicit Read Mode colours take precedence."
)),
RowSpec::new("general.textSmoothing", tl!("Screen text smoothing:"), RowKind::choice(&s.smoothing_id, owned(&s.smoothing))).help(tl!(
"Screen only. Subpixel smoothing makes the edges of page text finer sideways, with faint colour in them, and takes longer to draw. Printing and exports are unchanged."
)),
b("general.miniToolbar", tl!("Show the mini toolbar when text is selected"), app.ui.mini_toolbar),
b("general.darkPage", tl!("Dark page (white text on black)"), app.session.view.dark_mode)
.help(tl!("Show documents with their colours inverted, like View › Switch Modes. Saving, printing and PDFs are unchanged.")),
@@ -634,6 +644,7 @@ impl PreferencesModel for OptionsModel<'_> {
Err(_) => self.run("ui.interfaceSize", json!({"value": "auto"})),
},
("general.paperColor", Choice(c)) => self.run("view.paperColor", json!({"value": c})),
("general.textSmoothing", Choice(c)) => self.run("view.textSmoothing", json!({"value": c})),
("general.miniToolbar", Bool(v)) => self.app.ui.mini_toolbar = v,
("general.showCommunity", Bool(v)) => self.app.ui.show_discord = v,
("general.fontDownloadNotice", Bool(v)) => self.app.ui.font_download_notice = v,
+17
View File
@@ -399,6 +399,23 @@ fn length_units_follow_the_interface_language() {
assert_eq!(unit_suffix(Unit::Millimeters), " mm", "English keeps the English names");
}
#[test]
fn screen_text_smoothing_options_round_trip_and_work_without_a_document() {
use wordcraft_engine::cmd::view::TextSmoothing;
let mut a = app();
a.start_screen();
a.run("view.textSmoothing", json!({"value":"grayscale"})).unwrap();
let saved = serde_json::to_vec(&a.prefs()).unwrap();
let mut b = app();
b.apply_prefs(serde_json::from_slice::<Prefs>(&saved).unwrap());
assert_eq!(b.session.prefs.text_smoothing, TextSmoothing::Grayscale);
with_model(&mut b, true, |m| m.set("general.textSmoothing", PrefValue::Choice("subpixel".into())));
assert_eq!(b.session.prefs.text_smoothing, TextSmoothing::Subpixel);
// A value the option doesn't have changes nothing.
with_model(&mut b, true, |m| m.set("general.textSmoothing", PrefValue::Choice("lcd".into())));
assert_eq!(b.session.prefs.text_smoothing, TextSmoothing::Subpixel);
}
#[test]
fn screen_paper_color_options_round_trip_and_work_without_a_document() {
use wordcraft_engine::cmd::view::PaperColor;
+3 -1
View File
@@ -20,7 +20,9 @@ mod side;
mod state;
use comments::comments;
pub(crate) use comments::{commit_comment, commit_reply, flush_comment_drafts, has_comment_drafts, state_has_drafts};
pub(crate) use comments::{
commit_comment, commit_open_comment_edit, commit_reply, flush_comment_drafts, flush_parked_comment_drafts, has_comment_drafts, state_has_drafts,
};
use host::Content;
#[cfg(test)]
pub(crate) use host::apply;
+60 -21
View File
@@ -11,7 +11,8 @@ use craft::ui::sections::GroupBox;
use craft::ui::text::TextField;
use egui::Ui;
use serde_json::{Value, json};
use wordcraft_doc::StoryRef;
use wordcraft_doc::{Document, StoryRef};
use wordcraft_engine::Session;
use super::WordApp;
@@ -79,29 +80,30 @@ fn drafts(app: &mut WordApp) -> &mut CommentsPanelState {
/// The comment thread a message of `id` belongs to, as the panel state names it.
fn thread_of(app: &WordApp, id: u32) -> ThreadId {
ThreadId(u64::from(thread_root(app, id)))
ThreadId(u64::from(thread_root(&app.session.doc, id)))
}
/// The place of comment `id` in its thread: 0 for the comment, then its replies in id order.
fn message_index(app: &WordApp, id: u32) -> usize {
let root = thread_root(app, id);
let doc = &app.session.doc;
let root = thread_root(doc, id);
if root == id {
return 0;
}
replies(app, root).iter().position(|r| *r == id).map_or(0, |at| at + 1)
replies(doc, root).iter().position(|r| *r == id).map_or(0, |at| at + 1)
}
/// The comment at message `index` of the thread rooted at `root`.
fn message_id(app: &WordApp, root: u32, index: usize) -> Option<u32> {
fn message_id(doc: &Document, root: u32, index: usize) -> Option<u32> {
match index {
0 => Some(root),
_ => replies(app, root).get(index - 1).copied(),
_ => replies(doc, root).get(index - 1).copied(),
}
}
/// The ids of the replies to `root`, in id order.
fn replies(app: &WordApp, root: u32) -> Vec<u32> {
let mut replies: Vec<u32> = app.session.doc.comments.iter().filter(|(_, c)| c.parent == Some(root)).map(|(id, _)| *id).collect();
fn replies(doc: &Document, root: u32) -> Vec<u32> {
let mut replies: Vec<u32> = doc.comments.iter().filter(|(_, c)| c.parent == Some(root)).map(|(id, _)| *id).collect();
replies.sort_unstable();
replies
}
@@ -175,19 +177,36 @@ fn comment_field(app: &mut WordApp, ui: &mut Ui, document: u64, id: u32, resolve
/// is dropped once written (or when there is nothing to write); a refused edit keeps it.
pub(crate) fn commit_comment(app: &mut WordApp, id: u32) -> Result<(), String> {
let Some(text) = draft_of(app, id) else { return Ok(()) };
if let Some(part) = app.session.doc.comments.get(&id).map(|c| c.part)
&& text != app.session.doc.plain_text(StoryRef::Part(part))
{
app.run("review.editComment", json!({"id": id, "text": text}))?;
if app.session.doc.comments.get(&id).is_some_and(|c| c.resolved) {
drafts(app).editing = None;
return Ok(());
}
if let Some(params) = edit_params(&app.session.doc, id, &text) {
app.run("review.editComment", params)?;
}
drafts(app).editing = None;
Ok(())
}
/// Write the open comment edit, if any, before `review.resolveComment` runs: a resolved comment takes no edits, so
/// a draft still open then would be lost (#9190). A refused edit keeps its draft.
pub(crate) fn commit_open_comment_edit(app: &mut WordApp) -> Result<(), String> {
let Some((thread, index, _)) = drafts(app).editing.clone() else { return Ok(()) };
match u32::try_from(thread.0).ok().and_then(|root| message_id(&app.session.doc, root, index)) {
Some(id) => commit_comment(app, id),
None => Ok(()),
}
}
fn edit_params(doc: &Document, id: u32, text: &str) -> Option<Value> {
let part = doc.comments.get(&id)?.part;
(text != doc.plain_text(StoryRef::Part(part))).then(|| json!({"id": id, "text": text}))
}
/// The comment a reply to `id` answers: replies to a reply join its thread.
fn thread_root(app: &WordApp, id: u32) -> u32 {
match app.session.doc.comments.get(&id).and_then(|c| c.parent) {
Some(p) if app.session.doc.comments.contains_key(&p) => p,
fn thread_root(doc: &Document, id: u32) -> u32 {
match doc.comments.get(&id).and_then(|c| c.parent) {
Some(p) if doc.comments.contains_key(&p) => p,
_ => id,
}
}
@@ -245,26 +264,28 @@ fn reply_field(app: &mut WordApp, ui: &mut Ui, document: u64, id: u32) -> bool {
/// draft is dropped once posted; a refused reply keeps it.
pub(crate) fn commit_reply(app: &mut WordApp, id: u32) -> Result<(), String> {
let thread = thread_of(app, id);
let d = drafts(app);
let d = &app.canvas.comments;
if !d.selected.lead.as_ref().is_some_and(|t| t.0 == thread.0) {
return Ok(());
}
let text = d.reply.clone();
if !text.trim().is_empty() && app.session.doc.comments.contains_key(&id) {
let root = thread_root(app, id);
app.run("review.reply", json!({"id": root, "text": text.trim_end()}))?;
if let Some(params) = reply_params(&app.session.doc, id, &d.reply) {
app.run("review.reply", params)?;
}
drafts(app).reply.clear();
Ok(())
}
fn reply_params(doc: &Document, id: u32, text: &str) -> Option<Value> {
(!text.trim().is_empty() && doc.comments.contains_key(&id)).then(|| json!({"id": thread_root(doc, id), "text": text.trim_end()}))
}
/// Write every pending comment and reply draft to the document, so a save has them and a close,
/// New or Open sees them as unsaved changes (#1348). Every draft is tried; the first refusal is
/// returned (and is on the status line), and refused drafts stay.
pub(crate) fn flush_comment_drafts(app: &mut WordApp) -> Result<(), String> {
let mut first = Ok(());
if let Some((thread, index, _)) = drafts(app).editing.clone() {
let id = u32::try_from(thread.0).ok().and_then(|root| message_id(app, root, index));
let id = u32::try_from(thread.0).ok().and_then(|root| message_id(&app.session.doc, root, index));
let r = match id {
Some(id) => commit_comment(app, id),
// The comment is gone: its draft has nowhere to go.
@@ -286,3 +307,21 @@ pub(crate) fn flush_comment_drafts(app: &mut WordApp) -> Result<(), String> {
}
first
}
/// Write a parked document's drafts while its session is temporarily addressed by the control
/// channel. Like a resolve in the window, try both drafts and keep any the document refuses.
pub(crate) fn flush_parked_comment_drafts(session: &mut Session, state: &mut CommentsPanelState) {
if let Some((thread, index, text)) = &state.editing {
let params =
u32::try_from(thread.0).ok().and_then(|root| message_id(&session.doc, root, *index)).and_then(|id| edit_params(&session.doc, id, text));
if params.is_none_or(|params| session.run("review.editComment", &params).is_ok()) {
state.editing = None;
}
}
if let Some(id) = state.selected.lead.as_ref().and_then(|t| u32::try_from(t.0).ok()) {
let params = reply_params(&session.doc, id, &state.reply);
if params.is_none_or(|params| session.run("review.reply", &params).is_ok()) {
state.reply.clear();
}
}
}
+48 -19
View File
@@ -54,11 +54,13 @@ impl ThumbSource<usize> for SheetSource<'_> {
fn render(&self, key: &usize, request: &ThumbRequest) -> ThumbRender {
let Some(sheet) = self.sheets.get(*key) else { return ThumbRender::Blank };
let side = request.side.max(1) as usize;
// The 2 px border below is added on top of `side`, so the bordered image stays within the requested side.
let side = (request.side as usize).saturating_sub(2).max(1);
let scale = side as f32 / sheet.width.max(sheet.height).max(1.0);
let w = ((sheet.width * scale).round() as usize).clamp(1, side);
let h = ((sheet.height * scale).round() as usize).clamp(1, side);
let mut image = ColorImage::filled([w, h], Color32::WHITE);
// Reserve a 1 px border around the sheet so `outline_sheet` sits outside the printed content (#9189).
let mut image = ColorImage::filled([w + 2, h + 2], Color32::WHITE);
for slot in &sheet.slots {
let Some(pg) = self.lay.pages.get(slot.page) else { continue };
let k = (slot.width / pg.w).min(slot.height / pg.h);
@@ -70,29 +72,35 @@ impl ThumbSource<usize> for SheetSource<'_> {
let y0 = ((slot.y + (slot.height - pg.h * k) / 2.0) * scale).round() as i64;
let page = wordcraft_render::render_page(&self.app.session.doc, pg, page_scale, &preview_options(self.app));
let straight = page.to_straight();
let row_len = (page.width as usize).max(1) * 4;
for (row, line) in straight.chunks_exact(row_len).enumerate() {
let y = y0 + row as i64;
if y < 0 || y >= h as i64 {
continue;
}
for (col, px) in line.as_chunks::<4>().0.iter().enumerate() {
let x = x0 + col as i64;
if x < 0 || x >= w as i64 {
continue;
}
let Some(dst) = image.pixels.get_mut(y as usize * w + x as usize) else { continue };
let a = u32::from(px[3]);
let mix = |src: u8, under: u8| ((u32::from(src) * a + u32::from(under) * (255 - a) + 127) / 255) as u8;
*dst = Color32::from_rgb(mix(px[0], dst.r()), mix(px[1], dst.g()), mix(px[2], dst.b()));
}
}
composite_page(&mut image, &straight, (page.width as usize).max(1), x0, y0, w, h);
}
outline_sheet(&mut image);
ThumbRender::Ready(image)
}
}
/// Composite straight RGBA page pixels into a `sheet_w` × `sheet_h` sheet with a 1 px outer border.
fn composite_page(image: &mut ColorImage, straight: &[u8], page_w: usize, x0: i64, y0: i64, sheet_w: usize, sheet_h: usize) {
let stride = image.size[0];
let row_len = page_w * 4;
for (row, line) in straight.chunks_exact(row_len).enumerate() {
let y = y0 + row as i64;
if y < 0 || y >= sheet_h as i64 {
continue;
}
for (col, px) in line.as_chunks::<4>().0.iter().enumerate() {
let x = x0 + col as i64;
if x < 0 || x >= sheet_w as i64 {
continue;
}
let Some(dst) = image.pixels.get_mut((y as usize + 1) * stride + (x as usize + 1)) else { continue };
let a = u32::from(px[3]);
let mix = |src: u8, under: u8| ((u32::from(src) * a + u32::from(under) * (255 - a) + 127) / 255) as u8;
*dst = Color32::from_rgb(mix(px[0], dst.r()), mix(px[1], dst.g()), mix(px[2], dst.b()));
}
}
}
/// A one-pixel grey edge on the sheet. The pane's well is as white as the paper, so without it the sheet's
/// own shape is invisible and a portrait page looks like a landscape sheet with the page off to one side (#9111).
const SHEET_EDGE: Color32 = Color32::from_gray(145);
@@ -189,6 +197,27 @@ pub(super) fn show(app: &mut WordApp, ui: &mut Ui, lay: &Arc<DocLayout>) {
mod tests {
use super::*;
#[test]
fn sheet_edge_sits_outside_printed_content() {
let (w, h) = (4, 4);
let mut image = ColorImage::filled([w + 2, h + 2], Color32::WHITE);
let red = [200u8, 10, 20, 255];
let straight = red.repeat(w * h);
composite_page(&mut image, &straight, w, 0, 0, w, h);
outline_sheet(&mut image);
let expected_red = Color32::from_rgb(200, 10, 20);
for y in 0..h {
for x in 0..w {
assert_eq!(image.pixels[(y + 1) * (w + 2) + (x + 1)], expected_red, "content pixel ({x}, {y}) overwritten");
}
}
for x in 0..w + 2 {
assert_ne!(image.pixels[x], expected_red);
assert_ne!(image.pixels[(h + 1) * (w + 2) + x], expected_red);
}
}
#[test]
fn sheet_edge_meets_3_to_1_contrast_against_white() {
let srgb = f64::from(SHEET_EDGE.r()) / 255.0;
+13 -5
View File
@@ -19,6 +19,7 @@ use crate::undo_marks::apply_edits;
/// Fills the Picture Format tab's Adjust, Picture Styles, Accessibility (Alt Text), Arrange and Size groups.
pub(super) fn picture_format(row: &mut RibbonRow<'_>, app: &mut WordApp) {
let primary_picture = super::has_picture_selected(&app.session);
row.group(RibbonGroup::new("picture.adjust", tl!("Adjust"), IconId::new("wordcraft.more").into()), |ui| {
let stacked = |label: &'static str, tip: &'static str| {
Button::new(tl!(label)).icon(IconId::new("picture")).tooltip(tl!(tip)).arrangement(Arrangement::Stacked)
@@ -67,11 +68,13 @@ pub(super) fn picture_format(row: &mut RibbonRow<'_>, app: &mut WordApp) {
});
});
Stack::new().gap(Gap::Tight).show(ui, |ui, _| {
Button::command(CommandRef::new("ui.changePicture"))
.label(tl!("Change"))
.icon(IconId::new("picture"))
.tooltip(tl!("Change Picture"))
.show(ui);
if primary_picture {
Button::command(CommandRef::new("ui.changePicture"))
.label(tl!("Change"))
.icon(IconId::new("picture"))
.tooltip(tl!("Change Picture"))
.show(ui);
}
Button::command(CommandRef::new("picture.reset")).label(tl!("Reset")).icon(IconId::new("picture")).tooltip(tl!("Reset Picture")).show(ui);
});
});
@@ -95,6 +98,11 @@ pub(super) fn picture_format(row: &mut RibbonRow<'_>, app: &mut WordApp) {
}
});
});
if !primary_picture {
// The primary shape has its own Shape Format tab. Only the existing multi-picture
// commands are offered under Picture Format in this case.
return;
}
alt_text_group(row);
row.group(RibbonGroup::new("picture.arrange", tl!("Arrange"), IconId::new("wordcraft.more").into()), |ui| {
Button::command(CommandRef::new("arrange.position")).icon(IconId::new("position")).arrangement(Arrangement::Stacked).show(ui);
+2 -6
View File
@@ -123,9 +123,7 @@ pub(super) fn review(row: &mut RibbonRow<'_>, app: &mut WordApp) {
SplitButton::<u8>::command(
CommandRef::new("review.accept"),
SplitMenu::Body(Box::new(|ui, _| {
MenuItem::command(CommandRef::with_params("review.accept", json!({"next": true})))
.label(tl!("Accept and Move to Next").to_string())
.show(ui);
MenuItem::command(CommandRef::new("review.acceptAndNext")).label(tl!("Accept and Move to Next").to_string()).show(ui);
MenuItem::command(CommandRef::with_params("review.accept", json!({}))).label(tl!("Accept This Change").to_string()).show(ui);
MenuItem::command(CommandRef::new("review.acceptAll")).label(tl!("Accept All Changes").to_string()).show(ui);
MenuItem::command(CommandRef::with_params("review.acceptAll", json!({"stopTracking": true})))
@@ -140,9 +138,7 @@ pub(super) fn review(row: &mut RibbonRow<'_>, app: &mut WordApp) {
SplitButton::<u8>::command(
CommandRef::new("review.reject"),
SplitMenu::Body(Box::new(|ui, _| {
MenuItem::command(CommandRef::with_params("review.reject", json!({"next": true})))
.label(tl!("Reject and Move to Next").to_string())
.show(ui);
MenuItem::command(CommandRef::new("review.rejectAndNext")).label(tl!("Reject and Move to Next").to_string()).show(ui);
MenuItem::command(CommandRef::with_params("review.reject", json!({}))).label(tl!("Reject Change").to_string()).show(ui);
MenuItem::command(CommandRef::new("review.rejectAll")).label(tl!("Reject All Changes").to_string()).show(ui);
MenuItem::command(CommandRef::with_params("review.rejectAll", json!({"stopTracking": true})))
+40 -18
View File
@@ -1,4 +1,4 @@
use craft::behavior::{ColumnWidth, IconId};
use craft::behavior::{ColumnWidth, EditEvent, EditEvents, IconId, Mixed};
use craft::keymap::CommandRef;
use craft::menu::ribbon::{RibbonGroup, RibbonRow};
use craft::theme::ControlSize;
@@ -9,6 +9,7 @@ use craft::ui::display::Text;
use craft::ui::layout::{GridFit, empty_cell};
use craft::ui::layout_components::{Grid, Row, Stack};
use craft::ui::menu::MenuItem;
use craft::ui::runtime::focus;
use craft::ui::style::TypeRole;
use craft::ui::text::NumberField;
@@ -113,21 +114,26 @@ pub(super) fn table_design(row: &mut RibbonRow<'_>, app: &mut WordApp) {
});
}
/// Table Layout › Cell Size: the caret cell's row height and column width. They show the size on the
/// page (a row without a set height shows the height its text gives it) and editing runs
/// `table.rowHeight` / `table.columnWidth`; a drag is one undo step.
/// Table Layout › Cell Size: edit the caret cell's row height and starting grid column width. An
/// automatic row shows the height its text gives it. A drag is one undo step.
fn cell_size_boxes(ui: &mut Ui, app: &mut WordApp) {
let story = app.session.sel.focus.story;
let Some((tp, r, c)) = app.session.sel.focus.path.cell() else { return };
let Some(t) = app.session.doc.table(story, &tp) else { return };
let row = t.rows.get(r).map(|x| x.props.clone()).unwrap_or_default();
let stored_w = t.grid.get(t.grid_col(r, c)).copied();
let laid = app.session.layout().pages.iter().flat_map(|pg| pg.items.iter()).find_map(|it| match it {
wordcraft_layout::Placed::Cell { rect, table, row, cell, story: st, .. } if *table == tp && *row == r && *cell == c && *st == story => {
Some(*rect)
}
_ => None,
});
let column_w = t.grid.get(t.grid_col(r, c)).copied();
let w0 = column_w
.or_else(|| {
app.session.layout().pages.iter().flat_map(|pg| pg.items.iter()).find_map(|it| match it {
wordcraft_layout::Placed::Cell { rect, table, row, cell, story: st, .. }
if *table == tp && *row == r && *cell == c && *st == story =>
{
Some(rect.w)
}
_ => None,
})
})
.unwrap_or(0.0);
// The row's own height: a vertically merged cell's box spans several rows, so take the
// shortest box in this row.
let row_h = app
@@ -142,25 +148,41 @@ fn cell_size_boxes(ui: &mut Ui, app: &mut WordApp) {
})
.reduce(f32::min);
let h0 = row.height.or(row_h).unwrap_or(0.0);
let w0 = laid.map(|x| x.w).or(stored_w).unwrap_or(0.0);
let exact = row.height_rule == wordcraft_doc::props::HeightRule::Exact;
let (height_units, width_units) = (crate::options::lengths(app.session.units()), crate::options::lengths(app.session.units()));
// As the old ribbon and Layout › Paragraph: a visible label beside each field, two decimals ("0.20"). The fields are
// as tall as the small buttons, so their rows line up with Distribute Rows and Distribute Columns beside them.
let caption = |label: &'static str| Text::new(tl!(label)).role(TypeRole::Caption);
let edit_field = |ui: &mut Ui, app: &WordApp, field: NumberField<'_>| -> EditEvents<Option<f64>> {
let out = field
.range(CELL_SIZE_RANGE)
.edit_target((&app.session.sel.anchor, &app.session.sel.focus))
.fixed_decimals(2)
.size(ControlSize::Md)
.show(ui);
// Keep typing in the field until commit, while a scrub updates the table during the drag.
let typing = focus::focused_rec(ui.ctx()).is_some_and(|rec| rec.stop.id == out.edit.response.id && rec.stop.text);
out.edit
.events
.into_iter()
.filter(|event| match event {
EditEvent::Update { .. } => !typing,
EditEvent::Set { before: Mixed::Same(before), after, .. } => before != after,
_ => true,
})
.collect()
};
Grid::new(&[ColumnWidth::Content; 2]).gap(Gap::Tight).show(ui, |ui, _| {
caption("Height:").show(ui);
let field = NumberField::length(tl!("Height:").to_string(), Bind::given(Some(f64::from(h0))), height_units).range(CELL_SIZE_RANGE);
let out = field.fixed_decimals(2).size(ControlSize::Md).show(ui);
apply_edits(app, out.edit.events, |app, v| {
let events = edit_field(ui, app, NumberField::length(tl!("Height:").to_string(), Bind::given(Some(f64::from(h0))), height_units));
apply_edits(app, events, |app, v| {
if let Some(h) = v {
let _ = app.run("table.rowHeight", json!({"height": h, "rule": if exact { "exact" } else { "atLeast" }}));
}
});
caption("Width:").show(ui);
let field = NumberField::length(tl!("Width:").to_string(), Bind::given(Some(f64::from(w0))), width_units).range(CELL_SIZE_RANGE);
let out = field.fixed_decimals(2).size(ControlSize::Md).show(ui);
apply_edits(app, out.edit.events, |app, v| {
let events = edit_field(ui, app, NumberField::length(tl!("Width:").to_string(), Bind::given(Some(f64::from(w0))), width_units));
apply_edits(app, events, |app, v| {
if let Some(w) = v {
let _ = app.run("table.columnWidth", json!({"width": w}));
}
+1 -1
View File
@@ -129,7 +129,7 @@ pub fn contextual_tabs(s: &wordcraft_engine::Session) -> Vec<&'static str> {
tabs.push("Table Design");
tabs.push("Table Layout");
}
if has_picture_selected(s) {
if wordcraft_engine::cmd::objects::has_picture_format_target(s) {
tabs.push("Picture Format");
}
if has_shape_selected(s) {
+158
View File
@@ -535,6 +535,30 @@ fn every_proofing_language_is_picked_from_the_language_menu() {
}
}
#[test]
fn picture_format_offers_multi_picture_commands_for_a_shape_first_selection() {
use egui::accesskit::Role;
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
app.run("insert.picture", json!({"data": png_data()})).unwrap();
app.run("caret.docEnd", json!({})).unwrap();
app.run("insert.shape", json!({"kind": "rectangle"})).unwrap();
app.run("caret.docStart", json!({})).unwrap();
app.run("select.addObject", json!({"index": 1})).unwrap();
assert!(!contextual_tabs(&app.session).contains(&"Picture Format"));
app.run("select.addObject", json!({"index": 0})).unwrap();
let tabs = contextual_tabs(&app.session);
assert!(tabs.contains(&"Picture Format") && tabs.contains(&"Shape Format"));
let mut h = tab_harness(app, "Picture Format");
let border = h.get_by_role_and_label(Role::Button, "Border");
assert!(!border.accesskit_node().is_disabled());
assert!(h.query_by_role_and_label(Role::Button, "Change").is_none());
assert!(h.query_by_label("Crop").is_none());
h.get_by_role_and_label(Role::Button, "Border").click();
crate::test_harness::frames(&mut h, 2);
assert!(h.query_by_label("Thin").is_some(), "the Picture Border menu can be opened");
}
/// #2573, #1901: Picture Format › Size's width shows the interface unit and takes a size typed
/// in pixels, keeping the picture's proportions, as one undo step; Esc throws a typed size away
/// with no undo step.
@@ -1072,6 +1096,140 @@ fn table_cell_size_fields_line_up_with_the_distribute_buttons() {
);
}
#[test]
fn the_width_box_for_a_merged_cell_commits_its_starting_column() {
use egui::accesskit::Role;
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
app.run("file.options", json!({"units": "points"})).unwrap();
app.run("insert.table", json!({"rows": 2, "cols": 3})).unwrap();
let table = |app: &WordApp| app.session.doc.body.iter().position(|block| block.as_table().is_some()).expect("inserted table");
let index = table(&app);
let grid = |app: &WordApp| app.session.doc.body[index].as_table().expect("inserted table").grid.clone();
let cell = |col| json!({"story": "body", "path": [index, 0, col, 0], "off": 0});
app.run("select.range", json!({"anchor": cell(0), "focus": cell(1)})).unwrap();
app.run("table.merge", json!({})).unwrap();
let mut h = tab_harness(app, "Table Layout");
let before = grid(h.state());
let undo = h.state().session.undo_depth();
let displayed = h.get_by_role_and_label(Role::SpinButton, "Width:").accesskit_node().numeric_value().expect("Width value");
assert!((displayed - f64::from(before[0])).abs() < 0.01, "the field shows the column it will edit");
h.get_by_role_and_label(Role::SpinButton, "Width:").click();
crate::test_harness::frames(&mut h, 2);
let focused = h.ctx.memory(|m| m.focused()).expect("Width took keyboard focus");
h.key_press(egui::Key::End);
h.key_press(egui::Key::Delete);
crate::test_harness::frames(&mut h, 2);
assert_eq!((grid(h.state()), h.state().session.undo_depth()), (before.clone(), undo), "Delete at the end changes nothing");
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
crate::test_harness::frames(&mut h, 2);
for digit in ["5", "0"] {
h.event(egui::Event::Text(digit.into()));
crate::test_harness::frames(&mut h, 2);
assert_eq!((grid(h.state()), h.state().session.undo_depth()), (before.clone(), undo), "typing changes only the draft");
assert_eq!(h.ctx.memory(|m| m.focused()), Some(focused), "Width keeps the keyboard while typing");
}
h.key_press(egui::Key::Enter);
crate::test_harness::frames(&mut h, 3);
let mut expected = before.clone();
expected[0] = 50.0;
assert_eq!((grid(h.state()), h.state().session.undo_depth()), (expected, undo + 1), "commit changes the starting column in one step");
h.state_mut().run("edit.undo", json!({})).unwrap();
assert_eq!(grid(h.state()), before, "undo restores the width");
}
/// #9377: Height preserves automatic rows until the user commits a change, and scrubs live as one step.
#[test]
fn the_height_box_commits_typing_and_scrubs_live() {
use egui::accesskit::Role;
use wordcraft_doc::props::HeightRule;
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::new()), crate::Services::default());
app.run("file.options", json!({"units": "points"})).unwrap();
app.run("insert.table", json!({"rows": 3, "cols": 2})).unwrap();
let index = app.session.doc.body.iter().position(|block| block.as_table().is_some()).expect("inserted table");
let cell = |row| json!({"story": "body", "path": [index, row, 0, 0], "off": 0});
let select = |app: &mut WordApp, row| {
app.run("select.range", json!({"anchor": cell(row), "focus": cell(row)})).unwrap();
};
select(&mut app, 2);
app.run("table.rowHeight", json!({"height": 40, "rule": "exact"})).unwrap();
select(&mut app, 1);
app.run("table.rowHeight", json!({"height": 30, "rule": "atLeast"})).unwrap();
let mut h = tab_harness(app, "Table Layout");
let rows = |app: &WordApp| {
app.session.doc.body[index].as_table().unwrap().rows.iter().map(|r| (r.props.height, r.props.height_rule)).collect::<Vec<_>>()
};
let before = rows(h.state());
let undo = h.state().session.undo_depth();
assert_eq!(before, [(None, HeightRule::Auto), (Some(30.0), HeightRule::AtLeast), (Some(40.0), HeightRule::Exact)]);
let at = h.get_by_role_and_label(Role::SpinButton, "Height:").rect().center();
let pointer = |pos, pressed| egui::Event::PointerButton { pos, pressed, button: egui::PointerButton::Primary, modifiers: egui::Modifiers::NONE };
h.event(egui::Event::PointerMoved(at));
h.event(pointer(at, true));
crate::test_harness::frames(&mut h, 2);
let mut last = 30.0;
for distance in [12.0, 24.0] {
h.event(egui::Event::PointerMoved(at + vec2(distance, 0.0)));
crate::test_harness::frames(&mut h, 2);
let after = rows(h.state());
let height = after[1].0.expect("scrubbed height");
assert!(height > last, "each move changes the height before release");
assert_eq!(after[1].1, HeightRule::AtLeast);
assert_eq!([after[0], after[2]], [before[0], before[2]]);
last = height;
}
h.event(pointer(at + vec2(24.0, 0.0), false));
crate::test_harness::frames(&mut h, 3);
assert_eq!(rows(h.state())[1], (Some(last), HeightRule::AtLeast));
assert_eq!(h.state().session.undo_depth(), undo + 1, "one scrub, one undo step");
h.state_mut().run("edit.undo", json!({})).unwrap();
assert_eq!(rows(h.state()), before);
for (row, rule) in [(0, HeightRule::AtLeast), (1, HeightRule::AtLeast), (2, HeightRule::Exact)] {
select(h.state_mut(), row);
h.state_mut().run("table.selectRow", json!({})).unwrap();
crate::test_harness::frames(&mut h, 2);
h.get_by_role_and_label(Role::SpinButton, "Height:").click();
crate::test_harness::frames(&mut h, 2);
h.key_press(egui::Key::End);
h.key_press(egui::Key::Delete);
crate::test_harness::frames(&mut h, 2);
assert_eq!((rows(h.state()), h.state().session.undo_depth()), (before.clone(), undo), "Delete at the end changes nothing");
let type_height = |h: &mut Harness| {
let focused = h.ctx.memory(|m| m.focused()).expect("Height took keyboard focus");
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
crate::test_harness::frames(h, 2);
for digit in ["5", "6"] {
h.event(egui::Event::Text(digit.into()));
crate::test_harness::frames(h, 2);
assert_eq!((rows(h.state()), h.state().session.undo_depth()), (before.clone(), undo), "typing stays in the draft");
assert_eq!(h.ctx.memory(|m| m.focused()), Some(focused), "Height keeps the keyboard while typing");
}
};
type_height(&mut h);
h.key_press(egui::Key::Escape);
crate::test_harness::frames(&mut h, 3);
assert_eq!((rows(h.state()), h.state().session.undo_depth()), (before.clone(), undo), "Escape discards the draft");
h.get_by_role_and_label(Role::SpinButton, "Height:").click();
crate::test_harness::frames(&mut h, 2);
type_height(&mut h);
h.key_press(egui::Key::Enter);
crate::test_harness::frames(&mut h, 3);
let mut expected = before.clone();
expected[row] = (Some(56.0), rule);
assert_eq!((rows(h.state()), h.state().session.undo_depth()), (expected, undo + 1), "only the selected row changes");
h.state_mut().run("edit.undo", json!({})).unwrap();
assert_eq!(rows(h.state()), before, "one Undo restores the original row height and rule");
}
}
/// #4017: Home's small buttons, icon-only or labelled, are at least 24 points square: the least target size the
/// accessibility standard asks for (WCAG 2.5.8).
#[test]
+294
View File
@@ -0,0 +1,294 @@
//! How the desktop draws text, so pages look like the text in the platform's other apps.
//!
//! Each system keeps the user's choice somewhere else, and says different things:
//!
//! - macOS: the `AppleFontSmoothing` default, the strength of its font smoothing (0 to 3).
//! - Windows: `FontSmoothing`, `FontSmoothingType` and `FontSmoothingOrientation` under
//! `HKCU\Control Panel\Desktop`: smoothing on or off, ClearType or greyscale, RGB or BGR stripes.
//! - Linux and the BSDs: the desktop's antialiasing, hinting and subpixel order, as GNOME
//! (`org.gnome.desktop.interface`) or KDE Plasma (`kdeglobals`) keeps them.
//!
//! This module turns those values into one [`ScreenText`] and keeps the latest one for the page rasters to read.
//! It never asks the system itself, and for now nothing does: the app reads the system through craft-libs'
//! `platform::appearance`, which reports theme, contrast and reduced motion and no text settings yet. Until a
//! reader there hands an answer to [`set_system`] (and always in tests and headless screenshots)
//! [`ScreenText::PLATFORM`] stands, so pages are drawn each platform's fixed way. The constructors below are what
//! that reader's values go through.
use std::sync::Mutex;
/// The order of a screen's colour stripes, left to right.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum SubpixelOrder {
Rgb,
Bgr,
}
/// How page text is drawn on screen.
#[derive(Clone, Copy, Debug, PartialEq)]
pub struct ScreenText {
/// The strength of macOS-style font smoothing (glyphs thickened sideways): 0 is none, 1 the
/// system's default. See `wordcraft_render::RenderOptions::text_darkening`.
pub darkening: f32,
/// Light hinting, as FreeType's `hintslight` draws text.
pub hinting: bool,
/// The system asks for subpixel (LCD) antialiasing, in this stripe order; `None` when it asks
/// for greyscale antialiasing or says nothing.
pub subpixel: Option<SubpixelOrder>,
/// The screen's stripe order, where the system names one, whether or not it asks for
/// subpixel antialiasing: a user who chooses subpixel text themselves gets it in the order
/// of their screen. `None` when the system names no side-by-side order.
pub stripes: Option<SubpixelOrder>,
}
impl ScreenText {
/// What each platform's apps do when the user has changed nothing, and what pages are drawn
/// with until the system has been asked: macOS smooths (thickens) text and never hints it;
/// Linux and the BSDs hint lightly; Windows gets neither. All greyscale: a subpixel order is
/// only ever taken from the system.
pub const PLATFORM: ScreenText = ScreenText {
darkening: if cfg!(target_os = "macos") { 1.0 } else { 0.0 },
hinting: cfg!(all(unix, not(target_os = "macos"))),
subpixel: None,
stripes: None,
};
/// macOS, from the `AppleFontSmoothing` default (`None` when it isn't set). 0 turns the
/// smoothing off; 1, 2 and 3 are light, medium and strong, and unset is medium. The three
/// strengths as half, one and one and a half times our darkening are our own choice: Apple
/// publishes no numbers for them. macOS has no hinting and no subpixel antialiasing to ask
/// for (it dropped the latter in 10.14).
pub fn from_macos(font_smoothing: Option<i64>) -> Self {
let darkening = match font_smoothing {
Some(level) if level <= 0 => 0.0,
Some(1) => 0.5,
Some(2) | None => 1.0,
Some(_) => 1.5,
};
ScreenText { darkening, hinting: false, subpixel: None, stripes: None }
}
/// Windows, from the values under `HKCU\Control Panel\Desktop` (`None` for one that isn't
/// there): `FontSmoothing` is the text "2" when edges are smoothed and "0" when not,
/// `FontSmoothingType` is 2 for ClearType (1 is greyscale), `FontSmoothingOrientation` is 1
/// for RGB stripes and 0 for BGR. ClearType gives subpixel edges, RGB unless the system
/// says BGR; the stripe order itself is kept even with ClearType off. Text with smoothing off is still drawn antialiased, in greyscale: this
/// rasteriser has no aliased text.
pub fn from_windows(smoothing: Option<&str>, kind: Option<u32>, orientation: Option<u32>) -> Self {
let smoothed = smoothing.map(str::trim) != Some("0");
// The orientation is the screen's, and is kept whatever the smoothing is set to.
let stripes = match orientation {
Some(0) => Some(SubpixelOrder::Bgr),
Some(1) => Some(SubpixelOrder::Rgb),
_ => None,
};
let subpixel = (smoothed && kind == Some(2)).then_some(stripes.unwrap_or(SubpixelOrder::Rgb));
ScreenText { darkening: 0.0, hinting: false, subpixel, stripes }
}
/// GNOME (and the desktops that keep its settings), from `org.gnome.desktop.interface`:
/// `font-antialiasing` is `none`, `grayscale` or `rgba`; `font-hinting` is `none`, `slight`,
/// `medium` or `full`; `font-rgba-order` is `rgba`, `rgb`, `bgr`, `vrgb` or `vbgr`. `None`
/// when the desktop has none of the three. Any hinting but `none` is our one light hinting.
/// Stripes that run across the screen (`vrgb`, `vbgr`) get greyscale edges: only side by
/// side stripes are drawn.
pub fn from_gnome(antialiasing: Option<&str>, hinting: Option<&str>, rgba_order: Option<&str>) -> Option<Self> {
if antialiasing.is_none() && hinting.is_none() && rgba_order.is_none() {
return None;
}
let order = match rgba_order.map(str::trim) {
Some("bgr") => Some(SubpixelOrder::Bgr),
Some("vrgb" | "vbgr") => None,
// `rgba` is the schema's first value and its default; it and no answer mean RGB.
_ => Some(SubpixelOrder::Rgb),
};
let subpixel = if antialiasing.map(str::trim) == Some("rgba") { order } else { None };
// The order the desktop names, kept when it asks for greyscale.
let stripes = order.filter(|_| rgba_order.is_some());
Some(ScreenText { darkening: 0.0, hinting: hinting.map(str::trim) != Some("none"), subpixel, stripes })
}
/// KDE Plasma, from the `[General]` group of `kdeglobals`: `XftAntialias` is `true` or
/// `false`; `XftHintStyle` is `hintnone`, `hintslight`, `hintmedium` or `hintfull`;
/// `XftSubPixel` is `none`, `rgb`, `bgr`, `vrgb` or `vbgr`. `None` when it has none of the
/// three (Plasma writes them only once the user has changed the font settings).
pub fn from_kde(antialias: Option<&str>, hint_style: Option<&str>, sub_pixel: Option<&str>) -> Option<Self> {
if antialias.is_none() && hint_style.is_none() && sub_pixel.is_none() {
return None;
}
let antialiased = !matches!(antialias.map(|v| v.trim().to_ascii_lowercase()).as_deref(), Some("false" | "0"));
let order = match sub_pixel.map(str::trim) {
Some("rgb") => Some(SubpixelOrder::Rgb),
Some("bgr") => Some(SubpixelOrder::Bgr),
_ => None,
};
Some(ScreenText {
darkening: 0.0,
hinting: hint_style.map(str::trim) != Some("hintnone"),
subpixel: order.filter(|_| antialiased),
stripes: order,
})
}
/// The same settings with numbers a raster can take: a darkening that isn't a number, or is
/// negative, is none, and the strongest is twice the default.
pub fn sanitized(self) -> Self {
let darkening = if self.darkening.is_finite() { self.darkening.clamp(0.0, 2.0) } else { 0.0 };
ScreenText { darkening, ..self }
}
/// Put these settings into a page raster's options.
pub fn apply(self, opts: &mut wordcraft_render::RenderOptions) {
let text = self.sanitized();
opts.text_darkening = text.darkening;
opts.hinting = text.hinting;
}
/// A value to hash into a page's cache key: a page drawn under other settings is another
/// raster.
pub fn key(self) -> (u32, bool, Option<SubpixelOrder>, Option<SubpixelOrder>) {
let text = self.sanitized();
(text.darkening.to_bits(), text.hinting, text.subpixel, text.stripes)
}
}
/// What the system said last; `None` until the app has asked, and when the system said nothing.
static SYSTEM: Mutex<Option<ScreenText>> = Mutex::new(None);
/// How page text is drawn now: the system's settings once they are known ([`set_system`]), else
/// [`ScreenText::PLATFORM`].
pub fn current() -> ScreenText {
SYSTEM.lock().unwrap_or_else(std::sync::PoisonError::into_inner).unwrap_or(ScreenText::PLATFORM)
}
/// Record the system's answer (`None`: it has none, so the platform's own way stands). Returns
/// whether that changes how text is drawn, so the caller can ask for a repaint.
pub fn set_system(answer: Option<ScreenText>) -> bool {
let answer = answer.map(ScreenText::sanitized);
let before = current();
*SYSTEM.lock().unwrap_or_else(std::sync::PoisonError::into_inner) = answer;
current() != before
}
#[cfg(test)]
mod tests {
use super::{ScreenText, SubpixelOrder};
#[test]
fn the_platform_default_is_what_was_built_in() {
let p = ScreenText::PLATFORM;
assert_eq!(p.darkening > 0.0, cfg!(target_os = "macos"));
assert_eq!(p.hinting, cfg!(all(unix, not(target_os = "macos"))));
assert_eq!((p.subpixel, p.stripes), (None, None), "a stripe order only ever comes from the system");
// Tests and headless screenshots never ask the system, so this is what they draw with.
assert_eq!(super::current(), p);
}
#[test]
fn macos_font_smoothing_sets_the_darkening() {
let strength = |level| ScreenText::from_macos(level).darkening;
assert_eq!(strength(None), 1.0, "unset is the system's medium");
assert_eq!((strength(Some(0)), strength(Some(1)), strength(Some(2)), strength(Some(3))), (0.0, 0.5, 1.0, 1.5));
// Values Apple doesn't define: below the range is off, above it the strongest.
assert_eq!((strength(Some(-4)), strength(Some(i64::MIN)), strength(Some(9)), strength(Some(i64::MAX))), (0.0, 0.0, 1.5, 1.5));
let text = ScreenText::from_macos(None);
assert!(!text.hinting && text.subpixel.is_none());
}
#[test]
fn windows_cleartype_gives_subpixel_edges_in_the_screens_order() {
let order = |smoothing, kind, orientation| ScreenText::from_windows(smoothing, kind, orientation).subpixel;
assert_eq!(order(Some("2"), Some(2), Some(1)), Some(SubpixelOrder::Rgb));
assert_eq!(order(Some("2"), Some(2), Some(0)), Some(SubpixelOrder::Bgr));
assert_eq!(order(Some("2"), Some(2), None), Some(SubpixelOrder::Rgb), "no orientation: RGB, as nearly every panel is");
assert_eq!(order(None, Some(2), Some(1)), Some(SubpixelOrder::Rgb), "no on/off value: on, as Windows starts");
// Greyscale smoothing, smoothing off, and a machine that says nothing.
assert_eq!(order(Some("2"), Some(1), Some(1)), None);
assert_eq!(order(Some("0"), Some(2), Some(1)), None);
assert_eq!(order(Some(" 0 "), Some(2), Some(1)), None);
assert_eq!(order(None, None, None), None);
assert_eq!(order(Some("junk"), Some(u32::MAX), Some(u32::MAX)), None);
let text = ScreenText::from_windows(Some("2"), Some(2), Some(1));
assert!(!text.hinting && text.darkening == 0.0);
// The screen's stripe order survives ClearType being off or greyscale, for a user who
// chooses subpixel text themselves; no orientation value is no known order.
let stripes = |smoothing, kind, orientation| ScreenText::from_windows(smoothing, kind, orientation).stripes;
assert_eq!(stripes(Some("0"), Some(2), Some(0)), Some(SubpixelOrder::Bgr));
assert_eq!(stripes(Some("2"), Some(1), Some(0)), Some(SubpixelOrder::Bgr));
assert_eq!(stripes(Some("0"), None, Some(1)), Some(SubpixelOrder::Rgb));
assert_eq!(stripes(Some("2"), Some(2), None), None);
assert_eq!(stripes(Some("2"), Some(2), Some(7)), None);
}
#[test]
fn gnome_settings_set_hinting_and_subpixel_edges() {
assert_eq!(ScreenText::from_gnome(None, None, None), None, "a desktop without these settings says nothing");
let text = |a, h, o| ScreenText::from_gnome(a, h, o).unwrap();
// GNOME's own defaults: greyscale, slight hinting.
assert_eq!(
text(Some("grayscale"), Some("slight"), Some("rgb")),
ScreenText { darkening: 0.0, hinting: true, subpixel: None, stripes: Some(SubpixelOrder::Rgb) }
);
assert_eq!(text(Some("rgba"), Some("slight"), Some("rgb")).subpixel, Some(SubpixelOrder::Rgb));
assert_eq!(text(Some("rgba"), Some("slight"), Some("rgba")).subpixel, Some(SubpixelOrder::Rgb));
assert_eq!(text(Some("rgba"), Some("slight"), Some("bgr")).subpixel, Some(SubpixelOrder::Bgr));
assert_eq!(text(Some("rgba"), None, None).subpixel, Some(SubpixelOrder::Rgb));
// Stripes across the screen, and no antialiasing: greyscale edges.
assert_eq!(text(Some("rgba"), Some("slight"), Some("vrgb")).subpixel, None);
assert_eq!(text(Some("rgba"), Some("slight"), Some("vbgr")).subpixel, None);
assert_eq!(text(Some("none"), Some("slight"), Some("rgb")).subpixel, None);
// Hinting: off only when the desktop says none.
assert!(!text(Some("grayscale"), Some("none"), None).hinting);
for style in ["slight", "medium", "full", "something new"] {
assert!(text(None, Some(style), None).hinting, "{style}");
}
assert!(text(Some("grayscale"), None, None).hinting);
// The stripe order is kept when the desktop asks for greyscale or no antialiasing.
assert_eq!(text(Some("grayscale"), None, Some("bgr")).stripes, Some(SubpixelOrder::Bgr));
assert_eq!(text(Some("none"), None, Some("rgb")).stripes, Some(SubpixelOrder::Rgb));
assert_eq!(text(Some("rgba"), None, None).stripes, None, "no order named");
assert_eq!(text(Some("grayscale"), None, Some("vbgr")).stripes, None);
}
#[test]
fn kde_settings_set_hinting_and_subpixel_edges() {
assert_eq!(ScreenText::from_kde(None, None, None), None, "Plasma writes nothing until the font settings change");
let text = |a, h, s| ScreenText::from_kde(a, h, s).unwrap();
assert_eq!(
text(Some("true"), Some("hintslight"), Some("rgb")),
ScreenText { darkening: 0.0, hinting: true, subpixel: Some(SubpixelOrder::Rgb), stripes: Some(SubpixelOrder::Rgb) }
);
assert_eq!(text(Some("true"), Some("hintslight"), Some("bgr")).subpixel, Some(SubpixelOrder::Bgr));
assert_eq!(text(None, None, Some("rgb")).subpixel, Some(SubpixelOrder::Rgb));
for none in ["none", "vrgb", "vbgr", "junk"] {
assert_eq!(text(Some("true"), None, Some(none)).subpixel, None, "{none}");
}
assert_eq!(text(Some("false"), None, Some("rgb")).subpixel, None, "antialiasing off");
assert_eq!(text(Some(" False "), None, Some("rgb")).subpixel, None);
assert!(!text(None, Some("hintnone"), None).hinting);
assert!(text(None, Some("hintfull"), None).hinting && text(Some("true"), None, None).hinting);
// The stripe order is kept with antialiasing off.
assert_eq!(text(Some("false"), None, Some("bgr")).stripes, Some(SubpixelOrder::Bgr));
assert_eq!(text(Some("true"), None, Some("none")).stripes, None);
}
#[test]
fn settings_go_into_the_page_options_as_numbers_a_raster_can_take() {
let mut opts = wordcraft_render::RenderOptions::default();
ScreenText { darkening: 1.5, hinting: true, subpixel: None, stripes: None }.apply(&mut opts);
assert_eq!((opts.text_darkening, opts.hinting), (1.5, true));
for (given, taken) in [(f32::NAN, 0.0), (f32::INFINITY, 0.0), (-3.0, 0.0), (40.0, 2.0), (0.5, 0.5)] {
let text = ScreenText { darkening: given, hinting: false, subpixel: None, stripes: None };
text.apply(&mut opts);
assert_eq!((opts.text_darkening, opts.hinting), (taken, false), "{given}");
assert_eq!(text.key(), ScreenText { darkening: taken, ..text }.key());
}
// Each setting changes the cache key.
let base = ScreenText { darkening: 1.0, hinting: false, subpixel: None, stripes: None };
assert_ne!(base.key(), ScreenText { darkening: 0.5, ..base }.key());
assert_ne!(base.key(), ScreenText { hinting: true, ..base }.key());
assert_ne!(base.key(), ScreenText { subpixel: Some(SubpixelOrder::Rgb), ..base }.key());
assert_ne!(base.key(), ScreenText { stripes: Some(SubpixelOrder::Bgr), ..base }.key());
assert_ne!(ScreenText { subpixel: Some(SubpixelOrder::Bgr), ..base }.key(), ScreenText { subpixel: Some(SubpixelOrder::Rgb), ..base }.key());
}
}
+2 -1
View File
@@ -474,7 +474,8 @@ fn find_replace_and_go_to_keys_like_word() {
/// #8945: clicking a Navigation pane tab shows that view (the tab strip's selection event, not its overflow pick).
#[test]
fn nav_pane_tabs_switch_on_click() {
let mut h = crate::test_harness::builder().with_size(egui::vec2(800.0, 500.0)).build_eframe(|_| app());
// A page view that comes to rest draws once more at its exact size, so a switch settles in a few more frames.
let mut h = crate::test_harness::builder().with_size(egui::vec2(800.0, 500.0)).with_max_steps(8).build_eframe(|_| app());
h.state_mut().session.view.nav_pane = true;
for _ in 0..2 {
h.step();
+150 -6
View File
@@ -484,10 +484,7 @@ fn unregistered_registry(graph: &PartGraph) -> bool {
mutations.update({
'delta16 destructuring assignment': ('lib.rs', lambda s:s+'\nfn unregistered_read(pkg: Package) -> usize { let items; Package { entries: items, .. } = pkg; items.len() }'),
'delta16 parenthesized destructuring assignment': ('lib.rs', lambda s:s+'\nfn unregistered_read(pkg: Package) -> usize { let items; (Package { entries: items, .. }) = pkg; items.len() }'),
'delta16 macro-produced closure pattern': ('lib.rs', lambda s:s+'''
macro_rules! package_pattern { ($items:ident) => { Package { entries: $items, .. } }; }
fn unregistered_read(pkg: &Package) -> usize { (|package_pattern!(items): &Package| items.len())(pkg) }
'''),
'delta16 macro-produced closure pattern': ('lib.rs', lambda s:s+'\nfn unregistered_read(pkg: &Package) -> usize { (|package_pattern!(items): &Package| items.len())(pkg) }'),
'delta16 raw field read': ('lib.rs', lambda s:s+'\nfn unregistered_read(pkg: &Package) -> usize { pkg.r#entries.len() }'),
'delta16 raw registry method': ('ownership.rs', lambda s:s.replace('impl PackageRegistryContext {', 'impl PackageRegistryContext { fn unregistered_registry(&self) -> usize { self.r#contexts("x").len() }', 1)),
'delta16 module callback body': ('lib.rs', lambda s:s+'\nconst UNREGISTERED_READ: fn(&Package) -> usize = |pkg| pkg.entries.len();'),
@@ -528,7 +525,7 @@ fn unregistered_read(pkg: &Package) -> usize { (|package_pattern!(items): &Packa
'external module without supplied source': ('lib.rs', lambda s:s+'\nmod hidden;'),
'Unicode combining collection field': ('lib.rs', lambda s:s+'\nstruct UnicodeCollection { fresh\u0301: Vec<u8> } fn hidden(p: &UnicodeCollection) -> usize { p.fresh\u0301.len() }'),
'Unicode combining membership receiver': ('lib.rs', lambda s:s+'\nfn hidden(fresh\u0301: &[u8]) -> bool { fresh\u0301.contains(&1) }'),
'Unicode combining parser identifier': ('lib.rs', lambda s:s+'\nfn parse_fresh\u0301() -> usize { 1 } fn hidden() -> usize { parse_fresh\u0301() }'),
'Unicode combining parser identifier': ('lib.rs', lambda s:s+'\nfn hidden() -> usize { parse_fresh\u0301() }'),
'undeclared representation consumer': ('observed.rs', lambda s:s+'\nfn read(pkg: &Package) -> usize { pkg.entries.len() }'),
'representation membership bypass': ('observed.rs', lambda s:s.replace('!self.0.contains(key)', '!self.0.contains(key) || raw.contains(key)', 1)),
})
@@ -580,7 +577,7 @@ fn unregistered_read(pkg: &Package) -> usize { (|package_pattern!(items): &Packa
mutations['R18 qualified consuming macro arguments'] = ('lib.rs', lambda s: s+'\nfn unregistered_read(pkg: &Package) -> String { std::format!("{}", pkg.entries.len()) }')
mutations['R18 standard namespace import shadow'] = ('lib.rs', lambda s: s+'\nuse external as std;')
mutations['R18 derive outside type context'] = ('lib.rs', lambda s: s+'\n#[derive(Debug)] fn unregistered() {}')
mutations['R18 serde field attribute outside policy'] = ('lib.rs', lambda s: s+'\n#[serde(skip)] fn unregistered() {}')
mutations['R18 serde field attribute outside policy'] = ('lib.rs', lambda s: s.replace('pub struct Finding {\n', 'pub struct Finding {\n #[serde(skip)]\n', 1))
mutations['R18 inline outside closed options'] = ('lib.rs', lambda s: s+'\n#[inline(sometimes)] fn unregistered() {}')
getter_contract = 'observation_contract! { rules: "-"; collections: "access.prefix*1"; scope: "prefix presence control"; loss: "incomplete observed map"; fallback: "only presence is established"; package_loss: "independent"; }'
mutations['R18 contracted retained get equality absence'] = ('lib.rs', lambda s: s+'\nimpl Observed<HashMap<String, String>> { fn unregistered_absence(&self, key: &String) -> bool { '+getter_contract+' Self::prefix(self).get(key) == None } }')
@@ -831,6 +828,149 @@ POSITIVE_INVENTORY = (
'declared-presence row',
)
EXPECTED_REJECTIONS = {
'undeclared consumer': "lib.rs::invented_check: bounded consumption has no observation contract: ['access.prefix*1', 'type.Observed*1', 'type.Vec*1']",
'undeclared array consumer': "lib.rs::invented_array: bounded consumption has no observation contract: ['access.prefix*1', 'type.Observed*1', 'type.Vec*1']",
'missing fallback': 'lib.rs: macro argument mismatch',
'accessor bypass': 'lib.rs::invented_bypass: bypasses private observation representation',
'exception leakage': 'lib.rs::invented_registry: undeclared package-registry exception',
'new undeclared accessor': "lib.rs::check_custom_xml: declared collections differ from bounded accesses: declared=['access.into_complete_set*2', 'access.missing*1', 'field.content_types*3', 'field.contexts*2', 'field.entries*3', 'lookup.content_unavailable*1', 'parser.parse_attached_schemas*1', 'parser.parse_custom_xml_schemas*1', 'type.CompleteSet*1', 'type.HashSet*3', 'type.Observed*2', 'type.Vec*3'], used=['access.into_complete_set*2', 'access.missing*1', 'access.retain_budget*1', 'field.content_types*3', 'field.contexts*2', 'field.entries*3', 'lookup.content_unavailable*1', 'parser.parse_attached_schemas*1', 'parser.parse_custom_xml_schemas*1', 'type.CompleteSet*1', 'type.HashSet*3', 'type.Observed*2', 'type.Vec*3']",
'raw membership bypass': 'lib.rs::check_custom_xml: raw membership raw bypasses CompleteSet or undeclared structural scope',
'raw absence difference': 'lib.rs::invented_absence: raw absence difference bypasses CompleteSet',
'destructured package read': 'lib.rs: unrecognized pattern: Package { entries : items , .. }',
'module registry alias and method pointer': 'lib.rs: module-scope package-registry aliases/queries are unsupported',
'destructured parameter read': 'lib.rs: unrecognized pattern: Package { entries : items , .. }',
'destructured match read': 'lib.rs: unrecognized pattern: Package { entries : items , .. }',
'destructured for read': 'lib.rs: unrecognized pattern: Package { entries : items , .. }',
'immediately invoked destructured closure': 'lib.rs: unrecognized pattern: Package { entries : items , .. }',
'let-bound destructured closure': 'lib.rs: unrecognized pattern: Package { entries : items , .. }',
'const fn-pointer destructured closure': 'lib.rs: unrecognized pattern: Package { entries : items , .. }',
'closure argument with nested pattern': 'lib.rs: unrecognized pattern: Package { entries : items , .. }',
'returned closure with later parameter': 'lib.rs: unrecognized pattern: Package { ref entries , .. }',
'static fn-pointer destructured closure': 'lib.rs: unrecognized pattern: crate :: package :: Package { entries : items , .. }',
'array-element destructured closure': 'lib.rs: unrecognized pattern: Package { entries : _ , .. }',
'async destructured closure': 'lib.rs: unrecognized pattern: Package { entries , .. }',
'nested struct closure pattern': 'lib.rs: unrecognized pattern: Wrapper { inner : Package { entries : items , .. } }',
'closure pattern after associated-type constraint': 'lib.rs: unrecognized pattern: Package { entries , .. }',
'closure pattern with attributes and comments': 'lib.rs: unrecognized pattern: Package { entries , .. }',
'destructured closure returning adjacent closure': 'lib.rs: unrecognized pattern: Package { entries , .. }',
'adjacent inner destructured closure': 'lib.rs: unrecognized pattern: Package { entries , .. }',
'closure with parenthesized or-pattern': 'lib.rs: unrecognized pattern: Package { entries , .. }',
'closure with generic struct path': 'lib.rs: unrecognized pattern: Package :: < Vec < u8 > > { entries , .. }',
'closure with qualified struct path': 'lib.rs: unrecognized pattern: < Container as Trait > :: Package { entries , .. }',
'closure with Unicode identifier continuation': 'lib.rs: unrecognized pattern: Packagé { entries , .. }',
'closure with nested block comment': 'lib.rs: unrecognized pattern: Package { entries , .. }',
'module registry type alias': 'lib.rs: module-scope package-registry aliases/queries are unsupported',
'module registry method pointer': 'lib.rs::<initializer QUERY>: undeclared package-registry exception',
'delta16 destructuring assignment': 'lib.rs: unrecognized assignment target: Package { entries : items , .. }',
'delta16 parenthesized destructuring assignment': 'lib.rs: unrecognized assignment target: (Package { entries : items , .. })',
'delta16 macro-produced closure pattern': 'lib.rs: unrecognized pattern: package_pattern ! (items)',
'delta16 raw field read': "lib.rs::unregistered_read: bounded consumption has no observation contract: ['field.entries*1']",
'delta16 raw registry method': 'ownership.rs::unregistered_registry: undeclared package-registry exception',
'delta16 module callback body': "lib.rs::<initializer UNREGISTERED_READ>: bounded consumption has no observation contract: ['field.entries*1']",
'static callback body': "lib.rs::<initializer UNREGISTERED_READ>: bounded consumption has no observation contract: ['field.entries*1']",
'raw private representation': 'lib.rs::invented: bypasses private observation representation',
'raw accessor': "lib.rs::invented: bounded consumption has no observation contract: ['access.prefix*1']",
'raw registry type alias': 'lib.rs: module-scope package-registry aliases/queries are unsupported',
'raw registry function name': 'ownership.rs::unregistered_registry: undeclared package-registry exception',
'registry in representation provider': 'observed.rs::hidden: undeclared package-registry exception',
'unsupported union item': 'lib.rs: unrecognized item: union Unsupported { field : usize }',
'unsupported trait body': 'lib.rs: unrecognized item: trait Hidden { fn read (pkg : & Package) -> usize { pkg . entries . len () } }',
'unsupported foreign item': 'lib.rs: unrecognized item: unsafe extern "C" { fn hidden () ; }',
'unsupported production module': 'lib.rs: unrecognized item: mod hidden { fn read (pkg : & super :: Package) -> usize { pkg . entries . len () } }',
'unsupported attribute macro': 'lib.rs: unrecognized attribute: # [hidden]',
'unsupported pattern macro in binding': 'lib.rs: unrecognized pattern: hidden ! (items)',
'unsupported pattern macro in parameter': 'lib.rs: unrecognized pattern: hidden ! (items)',
'unsupported pattern macro in match': 'lib.rs: unrecognized pattern: hidden ! (items)',
'unsupported pattern macro in assignment': 'lib.rs: unrecognized assignment target: hidden ! (items)',
'unsupported expression macro': 'lib.rs: unrecognized expression/pattern macro: hidden ! (pkg . entries)',
'unsupported macro repetition': 'lib.rs: unsupported macro matcher',
'unsupported async body': 'lib.rs: unrecognized expression: async { pkg . entries . len () }',
'nested closure body': "lib.rs::read: bounded consumption has no observation contract: ['field.entries*1']",
'impl callback initializer': "lib.rs::<initializer READ>: bounded consumption has no observation contract: ['field.entries*1']",
'enum discriminant body': "lib.rs::<structural expression>: bounded consumption has no observation contract: ['field.entries*1']",
'type-level constant body': "lib.rs::<structural expression>: bounded consumption has no observation contract: ['field.entries*1']",
'macro-generated consumer': "lib.rs::AuditPlaceholder: bounded consumption has no observation contract: ['field.entries*1']",
'macro-captured collection field': "lib.rs::read: bounded consumption has no observation contract: ['field.AuditPlaceholder*1']",
'contract macro starts emitting code': 'lib.rs: unsupported item macro expansion: expected one of: `fn`, `extern`, `use`, `static`, `const`, `unsafe`, `mod`, `type`, `struct`, `enum`, `union`, `trait`, `auto`, `impl`, `default`, `macro`, identifier, `self`, `super`, `crate`, `::`',
'contract text in literal is not a declaration': "lib.rs::invented: bounded consumption has no observation contract: ['field.entries*1']",
'standard macro shadow hides consuming expansion': 'lib.rs: standard expression macro shadowing is outside the closed grammar',
'standard macro import shadow': 'lib.rs: unrecognized macro-shadowing import: format',
'standard macro alias shadow': 'lib.rs: unrecognized macro-shadowing import: hidden as matches',
'glob import could hide standard macro shadow': 'lib.rs: unrecognized glob import: *',
'attribute macro on item invocation': 'scan.rs: unrecognized attribute: # [hidden]',
'attribute macro on definition': 'scan.rs: unrecognized attribute: # [hidden]',
'external module without supplied source': 'lib.rs: external module hidden has no supplied audited source or explicit excluded table/test/policy source',
'Unicode combining collection field': "lib.rs::hidden: bounded consumption has no observation contract: ['field.fresh́*1']",
'Unicode combining membership receiver': 'lib.rs::hidden: raw membership fresh́ bypasses CompleteSet or undeclared structural scope',
'Unicode combining parser identifier': "lib.rs::hidden: bounded consumption has no observation contract: ['parser.parse_fresh́*1']",
'undeclared representation consumer': 'observed.rs::read: representation contract differs or is missing',
'representation membership bypass': 'observed.rs::missing: representation contract differs or is missing',
'R18 obsolete Option absence': 'lib.rs::check_rels: unsupported package Resolution operation; match One/Absent/Unknown/Ambiguous explicitly',
'R18 raw iterator absence': 'package.rs::unregistered_absence: raw absence requires completeness-carrying input/result; an observation contract cannot establish raw membership completeness',
'R18 contracted raw iterator absence': 'package.rs::unregistered_absence: raw absence requires completeness-carrying input/result; an observation contract cannot establish raw membership completeness',
'R18 helper-mediated absence': 'lib.rs::unregistered_absence: unsupported package Resolution operation; match One/Absent/Unknown/Ambiguous explicitly',
'R18 raw slice alias': 'package.rs::unregistered_absence: raw absence requires completeness-carrying input/result; an observation contract cannot establish raw membership completeness',
'R18 fabricated absence': 'package.rs::invented: unauthorized literal Resolution::Absent construction; use discovered with package loss evidence',
'R18 fabricated completeness': 'package.rs::canonical_entry: literal true is not package completeness evidence',
'R18 Unknown-or-Absent': 'lib.rs::check_rels: absence polarity: package lookup Unknown must have an explicit separate unguarded arm; catch-all/Absent collapse is forbidden',
'R18 missing Unknown': 'lib.rs::check_rels: package Resolution match must explicitly cover One, Absent, Unknown and Ambiguous',
'R18 direct state deletion': 'lib.rs::has_unique_rels_owner: entry-loss predicate differs from its named conservative/lookup contract',
'R18 direct state negation': 'lib.rs::has_unique_rels_owner: entry-loss predicate differs from its named conservative/lookup contract',
'R18 discovery complete deletion': 'lib.rs::ownership_discovery_complete: entry-loss predicate differs from its named conservative/lookup contract',
'R18 discovery complete negation': 'lib.rs::ownership_discovery_complete: entry-loss predicate differs from its named conservative/lookup contract',
'R18 reader assembly limit inversion': 'package.rs::load: entry-loss predicate differs from its named conservative/lookup contract',
'R18 canonical external call': 'package.rs::invented: raw absence requires completeness-carrying input/result; an observation contract cannot establish raw membership completeness',
'R18 helper alias/value canonical_entry/hidden_lookup': "lib.rs::unregistered_absence: bounded consumption has no observation contract: ['lookup.canonical_entry*1']",
'R18 helper alias/value canonical_entry/package::canonical_entry': "lib.rs::unregistered_absence: bounded consumption has no observation contract: ['lookup.canonical_entry*1']",
'R18 helper alias/value entry_by_name/hidden_lookup': "lib.rs::unregistered_absence: bounded consumption has no observation contract: ['lookup.entry_by_name*1']",
'R18 helper alias/value entry_by_name/package::entry_by_name': "lib.rs::unregistered_absence: bounded consumption has no observation contract: ['lookup.entry_by_name*1']",
'R18 helper alias/value content_unavailable/hidden_lookup': "lib.rs::unregistered_absence: bounded consumption has no observation contract: ['lookup.content_unavailable*1']",
'R18 helper alias/value content_unavailable/package::content_unavailable': "lib.rs::unregistered_absence: bounded consumption has no observation contract: ['lookup.content_unavailable*1']",
'R18 retained prefix !Self::prefix(self).contains(key)': 'lib.rs::unregistered_absence: negative retained-prefix membership requires CompleteSet, regardless of contract or local binding',
'R18 retained prefix Self::prefix(self).contains(key) == false': 'lib.rs::unregistered_absence: negative retained-prefix membership requires CompleteSet, regardless of contract or local binding',
'R18 retained prefix !Self::prefix(self).iter().any(|candidate| candidate == key)': 'lib.rs::unregistered_absence: negative retained-prefix membership requires CompleteSet, regardless of contract or local binding',
'R18 retained prefix matches!(Self::prefix(self).contains(key), false)': 'lib.rs::unregistered_absence: negative retained-prefix membership requires CompleteSet, regardless of contract or local binding',
'R18 retained prefix match Self::prefix(self).contains(key) { false => true, true => false }': 'lib.rs::unregistered_absence: boolean membership match on retained prefix requires CompleteSet',
'R18 retained prefix !<Self>::prefix(self).contains(key)': 'lib.rs::unregistered_absence: negative retained-prefix membership requires CompleteSet, regardless of contract or local binding',
'R18 retained prefix <Self>::prefix(self).contains(key) == false': 'lib.rs::unregistered_absence: negative retained-prefix membership requires CompleteSet, regardless of contract or local binding',
'R18 retained prefix !<Self>::prefix(self).iter().any(|candidate| candidate == key)': 'lib.rs::unregistered_absence: negative retained-prefix membership requires CompleteSet, regardless of contract or local binding',
'R18 retained prefix matches!(<Self>::prefix(self).contains(key), false)': 'lib.rs::unregistered_absence: negative retained-prefix membership requires CompleteSet, regardless of contract or local binding',
'R18 retained prefix match <Self>::prefix(self).contains(key) { false => true, true => false }': 'lib.rs::unregistered_absence: boolean membership match on retained prefix requires CompleteSet',
'R18 retained prefix !<Observed<HashSet<String>>>::prefix(self).contains(key)': 'lib.rs::unregistered_absence: negative retained-prefix membership requires CompleteSet, regardless of contract or local binding',
'R18 retained prefix <Observed<HashSet<String>>>::prefix(self).contains(key) == false': 'lib.rs::unregistered_absence: negative retained-prefix membership requires CompleteSet, regardless of contract or local binding',
'R18 retained prefix !<Observed<HashSet<String>>>::prefix(self).iter().any(|candidate| candidate == key)': 'lib.rs::unregistered_absence: negative retained-prefix membership requires CompleteSet, regardless of contract or local binding',
'R18 retained prefix matches!(<Observed<HashSet<String>>>::prefix(self).contains(key), false)': 'lib.rs::unregistered_absence: negative retained-prefix membership requires CompleteSet, regardless of contract or local binding',
'R18 retained prefix match <Observed<HashSet<String>>>::prefix(self).contains(key) { false => true, true => false }': 'lib.rs::unregistered_absence: boolean membership match on retained prefix requires CompleteSet',
'R18 accessor function binding Self::prefix': 'lib.rs::unregistered_absence: negative retained-prefix membership requires CompleteSet, regardless of contract or local binding',
'R18 accessor function binding HiddenDefinitions::prefix': 'lib.rs::unregistered_absence: negative retained-prefix membership requires CompleteSet, regardless of contract or local binding',
'R18 aliased UFCS': 'lib.rs::unregistered_absence: negative retained-prefix membership requires CompleteSet, regardless of contract or local binding',
'R18 local prefix with exact original contract': 'lib.rs::special_notes: negative retained-prefix membership requires CompleteSet, regardless of contract or local binding',
'R18 retained map get absence': 'lib.rs::unregistered_absence: negative retained-prefix membership requires CompleteSet, regardless of contract or local binding',
'R18 unauthorized ContentTypes reader serde::Serialize': 'package.rs::ContentTypes: unauthorized reader derive serde::Serialize or changed representation/DTO field shape',
'R18 unauthorized ContentTypes reader serde::Deserialize': 'package.rs::ContentTypes: unauthorized reader derive serde::Deserialize or changed representation/DTO field shape',
'R18 unauthorized ContentTypes reader Debug': 'package.rs::ContentTypes: unauthorized reader derive Debug or changed representation/DTO field shape',
'R18 renamed reader derive': 'package.rs::ContentTypes: unauthorized reader derive serde::Serialize or changed representation/DTO field shape',
'R18 unauthorized reader on DTO': 'lib.rs::Finding: unauthorized reader derive serde::Deserialize or changed representation/DTO field shape',
'R18 registry fields added to allowed DTO': 'lib.rs::Finding: unauthorized reader derive Debug or changed representation/DTO field shape',
'R18 reader allowance cannot transfer into a function scope': 'lib.rs::<function unregistered_nested_reader>::Limits: unauthorized reader derive Debug or changed representation/DTO field shape',
'R18 same-named DTO in another module': 'package.rs::Finding: unauthorized reader derive Debug or changed representation/DTO field shape',
'R18 unsupported qualified env macro': 'lib.rs: unrecognized expression/pattern macro: std :: env ! ("X")',
'seam/other-macro-path (R18 argument footprint)': "lib.rs::unregistered_read: bounded consumption has no observation contract: ['field.entries*2']",
'R18 qualified consuming macro arguments': "lib.rs::unregistered_read: bounded consumption has no observation contract: ['field.entries*1']",
'R18 standard namespace import shadow': 'lib.rs: unrecognized macro-shadowing import: external as std',
'R18 derive outside type context': 'lib.rs: derive is permitted only on a recorded struct/enum, never a function, field or other attribute context',
'R18 serde field attribute outside policy': 'lib.rs: unrecognized attribute: # [serde (skip)]',
'R18 inline outside closed options': 'lib.rs: unrecognized inline attribute: # [inline (sometimes)]',
'R18 contracted retained get equality absence': 'lib.rs::unregistered_absence: unmodeled membership boolean comparison requires CompleteSet',
'R18 local Resolution matches else collapse': 'lib.rs::check_rels: absence polarity: package lookup if-let/matches else collapse is unsupported; use explicit Resolution arms',
'R18 Resolution parameter collapse Resolution<String>': 'lib.rs::unregistered_resolution_absence: absence polarity: package lookup Unknown must have an explicit separate unguarded arm; catch-all/Absent collapse is forbidden',
'R18 Resolution parameter collapse HiddenResolution': 'lib.rs::unregistered_resolution_absence: absence polarity: package lookup Unknown must have an explicit separate unguarded arm; catch-all/Absent collapse is forbidden',
'R18 Resolution Self collapse': 'resolution.rs::unregistered_resolution_absence: absence polarity: package lookup Unknown must have an explicit separate unguarded arm; catch-all/Absent collapse is forbidden',
'R18 aliased bool cannot launder raw absence': 'package.rs::unregistered_return_alias: raw absence requires completeness-carrying input/result; an observation contract cannot establish raw membership completeness',
'R18 opaque function cannot collapse package Resolution': 'lib.rs::check_rels: absence polarity: package Resolution must be matched or locally bound; unmodeled callable/argument flow is forbidden',
}
def inventory_check(actual, expected, kind):
counts = Counter(iter(actual))
missing = sorted(set(expected)-counts.keys())
@@ -847,6 +987,7 @@ def inventory_digest():
def checked_mutations():
mutations = mutation_cases()
inventory_check(mutations, MUTATION_INVENTORY, 'mutation')
inventory_check(EXPECTED_REJECTIONS, MUTATION_INVENTORY, 'expected rejection')
if len(MUTATION_INVENTORY) != 140 or inventory_digest() != 'cb823adedb87fc9ba64516406abdf954635f7579ed2e695ae42599fcbd7f51d7':
raise ValueError('pinned round-18 mutation inventory changed')
return mutations
@@ -863,6 +1004,9 @@ def reject_mutation(sources, label, case):
message = str(error).splitlines()[0] if str(error) else ''
if not message.strip():
raise ValueError('mutation has no rejection message: '+label)
expected = EXPECTED_REJECTIONS[label]
if message != expected:
raise ValueError(f'mutation rejected with unexpected diagnostic for {label}: got {message!r}, expected {expected!r}')
return dict(label=label, message=message)
raise ValueError('audit accepted mutation: '+label)
File diff suppressed because one or more lines are too long
+5
View File
@@ -106,6 +106,11 @@ open another one and make it active; later commands and the saves work on the ac
`view.switchWindows={"id": n}` makes one active. A failing command stops the run with `command N (id): …` and exit
status 1, and nothing is saved. Every output is checked (known extension, folder exists) before the first is written. Paths inside command params (a picture to insert, say) are relative to the working folder, not the script's. Scripts are capped at 4 MiB.
With `--print`, successful commands write `id: <JSON>` records to stdout. Successful saves then
write `wrote <path>` confirmations on the same stream, including when `--print` is absent. A script
that consumes command results should parse the JSON only in the result records. Use the MCP server
for framed JSON responses.
## Tracked changes by an agent
Tracked changes and comments are recorded under the session's user name ("WordCraft User" by
+10 -1
View File
@@ -58,7 +58,11 @@ Document title opens Rename Document; the account badge opens Options › Genera
| Vertical scrollbar track paging | ✅ clicking the vertical scrollbar track above the elevator moves one screen up, and below it moves one screen down, as in Word (#5853, `canvas::tests::clicking_vertical_scrollbar_track_advances_one_screen`); it previously jumped to the clicked position | moves one screen | 90% | — |
| Scrollbar drag page tip | ✅ while the vertical scrollbar is dragged, a tip beside the pointer names the page at the top of the window in the status bar's words ("Page 7 of 10"), on one line however long the number (#2551, #3341, `canvas::tests::dragging_the_scrollbar_names_the_page_at_the_top`); its look and wording not yet compared with Word's | not compared | 70% | 0.5 |
| Interface text on screen (Linux, BSD) | Drawn by egui with Inter's ttfautohint hints, which match FreeType's light autohinting: measured against headless Firefox (Inter, 18.1 and 15.2 px at 1.45x), the same rows of pixels and weight (ink within 1 %) in the light theme. The dark theme no longer looks semi-bold: egui's dark default thickened light-on-dark text (about 21 % more ink than Firefox); it now adds a light 7 % (plain coverage, Firefox's weight, looked soft on the dark tab row; chosen side by side on a 145 % desktop). Not yet: subpixel (LCD) edges | sharp interface text | 90% | — |
| Page text on screen (Linux, BSD) | Lightly hinted as FreeType's `hintslight` draws it (Firefox and other apps there): FreeType's autohinter puts baselines, x-heights and cap heights on whole pixels, nothing moves sideways, so lines break as before. Measured against headless Firefox (Arial, 21.27 px): the same rows of pixels and weight. Not yet: subpixel (LCD) edges; the interface text (egui) is hinted separately. macOS keeps its darkened unhinted text; Windows and exports are unchanged | sharp document text | 90% | 4–8 (subpixel edges) |
| Page text on screen (Linux, BSD) | Lightly hinted as FreeType's `hintslight` draws it (Firefox and other apps there): FreeType's autohinter puts baselines, x-heights and cap heights on whole pixels, nothing moves sideways, so lines break as before. Measured against headless Firefox (Arial, 21.27 px): the same rows of pixels and weight. Subpixel (LCD) edges are their own row below; the interface text (egui) is hinted separately. Exports are unchanged | sharp document text | 90% | — |
| Page text on screen (macOS, Windows) | Drawn from the fonts' own outlines, unhinted, as macOS draws text. Every baseline sits on a whole device pixel (upright text only; a glyph moves half a pixel at most, never sideways, so lines break as before), so the feet of the letters fill one pixel row; between two rows they were two grey ones, which read as blur beside Preview and OpenOffice on the same screen. On macOS, text is also thickened as the system's font smoothing does it, sideways only (1.21 % of the pixel size on each side, 0.3 px at most, none past 72 px per em): stems gain weight and no grey is added above or below the letters. The outline itself is widened and filled once. The softness was found by comparing 144 dpi screenshots of one paragraph (Times New Roman) in WordCraft, Preview and OpenOffice; the fix is checked on headless rasters, not yet side by side in the running app, and not measured against CoreText's own output. Subpixel (LCD) edges are their own row below. Not yet: Windows text has no ClearType-style hinting | sharp document text | 80% | 4–8 (hinting on Windows) |
| Page text and the system's text settings | **Not followed yet.** What each system's values mean is in place (`screen_text.rs`: macOS `AppleFontSmoothing` as a darkening strength; Windows ClearType and stripe orientation; GNOME's and KDE Plasma's antialiasing, hinting and stripe order), and pages are drawn with those settings, and redrawn when they change, once one is recorded. Nothing records one: the app reads the system only through craft-libs' `platform::appearance`, which reports theme, contrast and reduced motion and no text settings. So pages are drawn each platform's fixed way (macOS darkened; Linux and BSD lightly hinted) plus the user's own Screen text smoothing choice. Shared-API gap: craft-libs needs to report the font smoothing strength, antialiasing kind, hinting and stripe order; an earlier version of this work read them in the app itself (macOS only run), which the move of system access to craft-libs rules out. Previews, dragged objects and File › New thumbnails keep the fixed defaults in any case (thumbnails without baseline snapping) | follows system settings | 20% | 4–8 (the craft-libs reader, then the wiring) |
| Subpixel (LCD) page text | File › Options › General › Screen text smoothing (`view.textSmoothing`): Use system setting, Grayscale, Subpixel (LCD). A WordCraft extension, saved per user, never in the document. With subpixel smoothing each colour channel of a pixel takes the text's coverage around its own stripe: the page is rasterised three times, its text a third of a pixel to the left, in place and to the right, and red, green and blue are taken from the matching pass (RGB or BGR stripes). That equals text rasterised three times as wide and averaged over three neighbours (the box filter FreeType calls its light LCD filter); there is no sharper filter and no fringe reduction, so edges show more colour than ClearType's or FreeType's default. Everything but text is drawn as without it. "Subpixel (LCD)" draws it on any screen, in the screen's stripe order where the system names one, else RGB. "Use system setting" is greyscale until the system's settings are read (row above); it then draws subpixel text where the system asks for it on screens below 2 device pixels per point. Only on a page picture rasterised at the screen's own scale or size (next row): Read Mode's columns, and a part of a page shown reduced, stay greyscale. Costs up to three rasters per page with text; not timed. Formatting marks, watermarks, previews and thumbnails stay greyscale. Vertical stripe orders are not drawn. **Run on macOS only**, on headless rasters; not yet seen on a 1x LCD or on Windows or Linux | subpixel text | 50% | 6–12 (check on real screens, timing, a 5-tap filter) |
| Page pictures at the screen's own size | The shared page view asks for each page's picture by its longest side in pixels, rounded up to a multiple of 16, and draws what it gets as its painter draws every picture: the page's place is rounded to whole pixels and the picture fitted inside it by its own proportions. Only a picture of exactly the rounded place's size is drawn one pixel for one. Rasterised at the side asked for, a page is up to 16 pixels too large (A4 at 100 % on a 2x screen: 2256 pixels for 2245); rasterised at the view's own scale and rounded up, as a first version of this did, it is still a pixel or two too large (2017 × 2852 for a 2016 × 2851 place), squeezed by a twentieth of a percent, and the text slides off the pixel grid and back down the page, which reads as blur. Now: once the view is at rest (two passes running put the pages in the same places), each picture is made exactly as many pixels each way as its place, scaled across and down by whatever that takes (a pixel in two thousand apart). While the view moves, pictures stay as they were; a page that comes into view is first made at the view's scale and again, exactly, when the view rests. Read Mode's columns, and a part of a page shown reduced, are rasterised as asked for, as before. Checked through the real page view and its picture store, headless: one texel per device pixel at 100, 110 and 137 % on 1x and 2x screens. The reporter's blurry screenshot was of the first version; **the fix has not been seen in the running app yet**. The rounding lives in the shared painter, so this follows it from outside: a shared-API gap remains (the page view could say what size it wants, or draw a screen-scale picture at its own size) | sharp document text | 80% | 2–4 (craft-libs page view) |
| Web and Draft Layout rendering | Very long pages render only visible full-resolution raster tiles instead of shrinking one huge texture to the GPU size limit; nearby tiles are cached for scrolling | sharp document text | 95% | — |
| Reading Mode | Existing Read Mode ribbon button opens a read-only, viewport-column layout with animated horizontal paging, transient width/text/spacing controls, heading navigation (Navigation pane) and resize anchoring; print/export layout unchanged. The arrows, Page Up/Down and Escape work straight after entering it; only whole columns show, centred, at any width, text size or window size; the columns end above the page-turn bar (#1772); Page color: None (white, the document's page color and page picture not shown), Sepia or Inverse (a dark page with light text), as Word's View › Page Color in Read Mode, starting at None and kept between Read Mode entries, documents and runs (`view.readPageColor`); ink, object drag previews and table drag arrows drawn over the pages follow it; Read Mode's View menu: Column Width and Page Color work, Layout is missing ([parity-checklist.md](parity-checklist.md), Read Mode 2/3) | reading-optimized view and navigation | 75% | 1–2 |
| Status bar (page x of y, words, language, view buttons, zoom slider) | ✅ (the page is the caret's while the caret is on screen, else the page at the top of the window, so scrolling updates it (#3880); the language is the caret's, by name; a click sets the proofing language, or opens Set Proofing Language… for any other). The count at the right is what it shows in Word: words (default), characters (with spaces) or characters (no spaces), chosen from a right-click menu on it or File › Options › Display (Status bar count, `ui.statusCount`), kept between runs; a selection shows "selected of total" as the Word Count dialog counts them (#2797) | ✅ | 90% | — |
@@ -127,6 +131,11 @@ Page Setup's margin, paper-size and document-grid number boxes scroll long text
|---|---|---|
| 2026-12-04 | trivial | View › Window › Full Screen fills the screen and a maximized document window stays maximized on Windows again (#8838); v0.20.0 moved the window back to its normal place. |
| 2026-11-27 | trivial | Tracked changes: resting the pointer on an insertion, deletion, move or formatting change shows a tip with its kind (Inserted, Deleted, Moved to, Moved from, Formatted), its author and, when it has one, its time (in local time for a change WordCraft made, which keeps its UTC time; for a file's own change that has only `w:date`, as written when that ends in `Z` or names no offset, and in local time when it names a `±HH:MM` offset); only for the changes Show Markup marks, and a link's tip comes first (#7887, `canvas::tests::markup::hovering_a_tracked_change_shows_its_author_and_time`) |
| 2026-11-21 | minor | Page pictures are made exactly as many pixels each way as their place on screen once the view rests (the row "Page pictures at the screen's own scale" is now "…own size"): the first version, a pixel or two too large, was scaled by the shared painter and looked blurry. Also: stretched hinted text and synthetic bold are darkened correctly |
| 2026-11-20 | minor | Ported onto the shared page view and Options (after #7101): page pictures are rasterised at the screen's own scale where the view's zoom accounts for the side asked for, and subpixel text is drawn only there; the Screen text smoothing row is in the shared Options; the app no longer reads the system's text settings itself, so the row "Page text follows the system's text settings" became "Page text and the system's text settings" (not followed yet: craft-libs gap). New row "Page pictures at the screen's own scale" |
| 2026-11-19 | minor | Subpixel (LCD) page text: three rasters with the text a third of a pixel apart, one per colour stripe; File › Options › General › Screen text smoothing (`view.textSmoothing`). New row "Subpixel (LCD) page text"; run on macOS only |
| 2026-11-19 | minor | Page drawing can take the system's text settings; nothing reads them from the system yet (see the row "Page text and the system's text settings") |
| 2026-11-19 | minor | Page text on macOS and Windows: baselines on whole device pixels; macOS stem darkening widens outlines sideways only, in one fill, instead of stroking them all round. New row "Page text on screen (macOS, Windows)" |
| 2026-11-25 | trivial | Review › Comments › Delete is a split button: Delete, Delete All Comments in Document and Delete All Resolved Comments. The last deletes each resolved comment with its replies and keeps the open ones, in one undo step (#7818) |
| 2026-11-17 | trivial | Format Shape pane adds Line section (No line, Solid line with color, width, dash type, and cap type) and Layout & Properties section (size, rotation, and text box direction and vertical alignment), routes active canvas text-box edits to the member while leaving grouped text boxes disabled, rejects unknown outline `dash`/`cap` values, and applies Line and Layout edits across multi-shape selections (#5896) |
| 2026-11-15 | trivial | Paste: a copied table pasted with the caret in a table cell inserts its rows above (caret in the first column, same width) or overwrites the cells from the caret's, adding rows and columns, as Word's Paste does; `edit.pasteNestedTable` (Paste as Nested Table) nests it (#6739). Pasted cells take the destination's cell formatting (Word keeps the source's: not done). Left as before: copies with merged cells, pictures or ragged rows, merged destinations, a one-column destination, Track Changes, PasteAppendTable. Paste into selected cells overwrites from the top-left for plain grids, even when the copied table is wider than the selection (#6742). |