mirror of
https://github.com/storytold/wordcraft.git
synced 2026-12-05 22:59:18 +00:00
Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
8dbfa312f4 |
@@ -9,6 +9,5 @@ mod mcp_roots;
|
||||
#[cfg(all(unix, not(target_os = "macos")))]
|
||||
mod non_utf8_args;
|
||||
mod picture_then_typing;
|
||||
mod reproducible_pdf;
|
||||
mod strict;
|
||||
mod text_tracked;
|
||||
|
||||
@@ -519,7 +519,6 @@ fn render_label<'a>(level_def: impl Fn(usize) -> Option<&'a Level>, def: &Level,
|
||||
while let Some(c) = chars.next() {
|
||||
if c == '%'
|
||||
&& let Some(d) = chars.peek().and_then(|d| d.to_digit(10))
|
||||
&& (1..=9).contains(&d)
|
||||
{
|
||||
chars.next();
|
||||
let k = (d as usize).saturating_sub(1).min(8);
|
||||
@@ -843,43 +842,6 @@ mod tests {
|
||||
assert_eq!(c.next_label(&n, r, 0).unwrap().0, "Part V");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn start_zero_counters_increment_properly() {
|
||||
let mut n = Numbering::default();
|
||||
let id = n.add_list(ListKind::Numbered);
|
||||
if let Some(a) = n.abstracts.first_mut() {
|
||||
a.levels[0].start = 0;
|
||||
a.levels[0].text = "Item %1.".into();
|
||||
}
|
||||
let mut c = Counters::default();
|
||||
assert_eq!(c.next_label(&n, id, 0).unwrap().0, "Item 0.");
|
||||
assert_eq!(c.next_label(&n, id, 0).unwrap().0, "Item 1.");
|
||||
assert_eq!(c.next_label(&n, id, 0).unwrap().0, "Item 2.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn start_override_of_zero_starts_at_zero() {
|
||||
let mut n = Numbering::default();
|
||||
let id = n.add_list(ListKind::Numbered);
|
||||
if let Some(num) = n.nums.iter_mut().find(|x| x.id == id) {
|
||||
num.start_overrides = vec![(0, 0)];
|
||||
}
|
||||
let mut c = Counters::default();
|
||||
let labels: Vec<String> = (0..3).map(|_| c.next_label(&n, id, 0).unwrap().0).collect();
|
||||
assert_eq!(labels, ["0.", "1.", "2."]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn placeholder_percent_zero_is_preserved_as_literal() {
|
||||
let mut n = Numbering::default();
|
||||
let id = n.add_list(ListKind::Numbered);
|
||||
if let Some(a) = n.abstracts.first_mut() {
|
||||
a.levels[0].text = "%0 %1.".into();
|
||||
}
|
||||
let mut c = Counters::default();
|
||||
assert_eq!(c.next_label(&n, id, 0).unwrap().0, "%0 1.");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn definition_index_keeps_first_ids_overrides_and_missing_definitions() {
|
||||
let override_level = Level { start: 0, text: "own %1".into(), ..Default::default() };
|
||||
|
||||
@@ -122,6 +122,7 @@ fn run_and_style_emphasis_marks_survive_two_saves() {
|
||||
</w:p>
|
||||
"#;
|
||||
let mut doc = wordcraft_docx::read(&docx(body, styles)).unwrap();
|
||||
let p = doc.body.iter().find_map(|b| b.as_para()).unwrap();
|
||||
let expected_styles = [
|
||||
("Dot", Some(EmphasisMark::Dot)),
|
||||
("Comma", Some(EmphasisMark::Comma)),
|
||||
@@ -129,33 +130,21 @@ fn run_and_style_emphasis_marks_survive_two_saves() {
|
||||
("UnderDot", Some(EmphasisMark::UnderDot)),
|
||||
("NoMark", Some(EmphasisMark::None)),
|
||||
];
|
||||
for (id, mark) in expected_styles {
|
||||
assert_eq!(doc.styles.get(id).and_then(|style| style.chr.emphasis), mark);
|
||||
}
|
||||
assert_eq!(p.runs[4].props.emphasis, Some(EmphasisMark::None));
|
||||
let expected_runs = [
|
||||
(Some("Dot"), None, EmphasisMark::Dot),
|
||||
(Some("Comma"), None, EmphasisMark::Comma),
|
||||
(Some("Circle"), None, EmphasisMark::Circle),
|
||||
(Some("UnderDot"), None, EmphasisMark::UnderDot),
|
||||
(Some("Dot"), Some(EmphasisMark::None), EmphasisMark::None),
|
||||
(Some("NoMark"), None, EmphasisMark::None),
|
||||
(None, Some(EmphasisMark::Dot), EmphasisMark::Dot),
|
||||
(None, Some(EmphasisMark::Comma), EmphasisMark::Comma),
|
||||
(None, Some(EmphasisMark::Circle), EmphasisMark::Circle),
|
||||
(None, Some(EmphasisMark::UnderDot), EmphasisMark::UnderDot),
|
||||
(None, Some(EmphasisMark::None), EmphasisMark::None),
|
||||
(None, None, EmphasisMark::None),
|
||||
Some(EmphasisMark::Dot),
|
||||
Some(EmphasisMark::Comma),
|
||||
Some(EmphasisMark::Circle),
|
||||
Some(EmphasisMark::UnderDot),
|
||||
Some(EmphasisMark::None),
|
||||
None,
|
||||
];
|
||||
let assert_state = |doc: &wordcraft_doc::Document, stage: &str| {
|
||||
for (id, mark) in expected_styles {
|
||||
assert_eq!(doc.styles.get(id).and_then(|style| style.chr.emphasis), mark, "{stage}: style {id}");
|
||||
}
|
||||
let p = doc.body.iter().find_map(|b| b.as_para()).unwrap();
|
||||
let actual: Vec<_> = p
|
||||
.runs
|
||||
.iter()
|
||||
.map(|r| (r.props.style.as_deref(), r.props.emphasis, doc.styles.resolve_char(p.props.style.as_deref(), &r.props).emphasis))
|
||||
.collect();
|
||||
assert_eq!(actual, expected_runs, "{stage}");
|
||||
};
|
||||
assert_state(&doc, "initial read");
|
||||
for (run, mark) in p.runs.iter().skip(6).zip(expected_runs) {
|
||||
assert_eq!(run.props.emphasis, mark);
|
||||
}
|
||||
|
||||
for pass in 0..2 {
|
||||
let out = wordcraft_docx::write(&doc).unwrap();
|
||||
@@ -167,7 +156,17 @@ fn run_and_style_emphasis_marks_survive_two_saves() {
|
||||
assert!(document_xml.contains(r#"<w:em w:val="none"/>"#), "pass {pass}: {document_xml}");
|
||||
assert!(document_xml.contains("default dot"));
|
||||
doc = wordcraft_docx::read(&out).unwrap();
|
||||
assert_state(&doc, &format!("pass {pass}"));
|
||||
for (id, mark) in expected_styles {
|
||||
assert_eq!(doc.styles.get(id).and_then(|style| style.chr.emphasis), mark, "pass {pass}");
|
||||
}
|
||||
let p = doc.body.iter().find_map(|b| b.as_para()).unwrap();
|
||||
for index in [0, 1, 2, 3, 5] {
|
||||
assert_eq!(p.runs[index].props.emphasis, None, "pass {pass}: run {index}");
|
||||
}
|
||||
assert_eq!(p.runs[4].props.emphasis, Some(EmphasisMark::None), "pass {pass}: run 4",);
|
||||
for (run, mark) in p.runs.iter().skip(6).zip(expected_runs) {
|
||||
assert_eq!(run.props.emphasis, mark, "pass {pass}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -513,7 +513,6 @@ fn split_para_as(s: &mut Session, at: &Pos, enter: bool) -> Result<Pos, CmdError
|
||||
let para = s.doc.para_mut(at.story, &at.path)?;
|
||||
if n.level > 0 {
|
||||
para.props.numbering = Some(wordcraft_doc::props::NumRef { num: n.num, level: n.level - 1 });
|
||||
para::drop_direct_indents(&mut para.props);
|
||||
para.touch();
|
||||
} else {
|
||||
leave_list(para);
|
||||
|
||||
@@ -128,7 +128,7 @@ fn turn(s: &mut Session) -> Option<TextDirection> {
|
||||
}
|
||||
|
||||
/// Vertical text: to the next (`next`) or previous line, at the same distance along it. With no
|
||||
/// such line in the caret's flow (a table cell's only line, the last column), Left/Right step along
|
||||
/// such line in the caret's flow, Left/Right stop in a table cell or text box and otherwise step along
|
||||
/// the text as they did before (`is_left`: backwards).
|
||||
fn line_step(s: &mut Session, v: &Value, next: bool, is_left: bool) -> CmdResult {
|
||||
let ext = extend(v);
|
||||
@@ -145,6 +145,8 @@ fn line_step(s: &mut Session, v: &Value, next: bool, is_left: bool) -> CmdResult
|
||||
s.goal_x = Some(g);
|
||||
p
|
||||
}
|
||||
// Inside a table cell or text box the caret stops at the edge rather than leaving it.
|
||||
None if from.path.0.len() > 1 => return sel_result(s),
|
||||
None => return lr_along(s, v, is_left),
|
||||
};
|
||||
let gx = s.goal_x;
|
||||
|
||||
@@ -335,66 +335,43 @@ mod tests {
|
||||
#[cfg_attr(coverage, ignore = "coverage instrumentation skews the measured time")]
|
||||
fn rerouting_many_pages_does_not_rescan_all_objects_per_connector() {
|
||||
use wordcraft_doc::{Document, Paragraph, para_block};
|
||||
fn glued_pages(n: u32) -> Session {
|
||||
let mut doc = Document::new();
|
||||
doc.body = (0..n)
|
||||
.map(|i| {
|
||||
let mut p = Paragraph::default();
|
||||
p.props.page_break_before = Some(i > 0);
|
||||
let id = i * 2 + 1;
|
||||
for (kind, x, extra) in [
|
||||
(ShapeKind::Rectangle, 100.0, ShapeExtra { id, ..Default::default() }),
|
||||
(ShapeKind::Ellipse, 300.0, ShapeExtra { id: id + 1, ..Default::default() }),
|
||||
(
|
||||
ShapeKind::ElbowConnector,
|
||||
0.0,
|
||||
ShapeExtra { start: Some(ConnEnd { id, site: 3 }), end: Some(ConnEnd { id: id + 1, site: 2 }), ..Default::default() },
|
||||
),
|
||||
] {
|
||||
let float = Float { wrap: Wrap::InFrontOfText, h_rel: Anchor::Page, v_rel: Anchor::Page, x, y: 200.0, ..Default::default() };
|
||||
p.insert_object(p.len(), shape(kind, extra, float), &Default::default()).unwrap();
|
||||
}
|
||||
para_block(p)
|
||||
})
|
||||
.collect();
|
||||
let mut s = Session::new(doc);
|
||||
s.view.proofing = false;
|
||||
s.page_hint = 0;
|
||||
assert_eq!(s.layout().pages.len(), n as usize);
|
||||
s
|
||||
}
|
||||
// Use the running thread's CPU time on Linux; scheduler pauses are not reroute work.
|
||||
fn cpu_cost(mut f: impl FnMut()) -> f64 {
|
||||
let ran = || std::fs::read_to_string("/proc/thread-self/schedstat").ok()?.split_whitespace().next()?.parse::<u64>().ok();
|
||||
let (wall, before) = (std::time::Instant::now(), ran());
|
||||
f();
|
||||
match (before, ran()) {
|
||||
(Some(a), Some(b)) if b > a => (b - a) as f64 * 1e-9,
|
||||
_ => wall.elapsed().as_secs_f64(),
|
||||
}
|
||||
}
|
||||
const SMALL: u32 = 500;
|
||||
const SCALE: u32 = 8;
|
||||
let (mut small_min, mut big_min) = (f64::INFINITY, f64::INFINITY);
|
||||
let mut last_big = None;
|
||||
for _ in 0..3 {
|
||||
let mut small = glued_pages(SMALL);
|
||||
small_min = small_min.min(cpu_cost(|| assert!(reroute(&mut small))));
|
||||
let mut big = glued_pages(SMALL * SCALE);
|
||||
big_min = big_min.min(cpu_cost(|| assert!(reroute(&mut big))));
|
||||
last_big = Some(big);
|
||||
}
|
||||
let ratio = big_min / small_min.max(1e-9);
|
||||
eprintln!("{SMALL} vs {} pages reroute: {small_min:.4}s vs {big_min:.4}s (ratio {ratio:.2}x)", SMALL * SCALE);
|
||||
assert!(ratio < SCALE as f64 * 3.0, "reroute scaled superlinearly: {small_min:.4}s -> {big_min:.4}s ({ratio:.2}x for {SCALE}x pages)");
|
||||
let mut big = last_big.unwrap();
|
||||
for path in big.doc.para_paths(StoryRef::Body) {
|
||||
let para = big.doc.para(StoryRef::Body, &path).unwrap();
|
||||
let mut doc = Document::new();
|
||||
doc.body = (0..8000u32)
|
||||
.map(|i| {
|
||||
let mut p = Paragraph::default();
|
||||
p.props.page_break_before = Some(i > 0);
|
||||
let id = i * 2 + 1;
|
||||
for (kind, x, extra) in [
|
||||
(ShapeKind::Rectangle, 100.0, ShapeExtra { id, ..Default::default() }),
|
||||
(ShapeKind::Ellipse, 300.0, ShapeExtra { id: id + 1, ..Default::default() }),
|
||||
(
|
||||
ShapeKind::ElbowConnector,
|
||||
0.0,
|
||||
ShapeExtra { start: Some(ConnEnd { id, site: 3 }), end: Some(ConnEnd { id: id + 1, site: 2 }), ..Default::default() },
|
||||
),
|
||||
] {
|
||||
let float = Float { wrap: Wrap::InFrontOfText, h_rel: Anchor::Page, v_rel: Anchor::Page, x, y: 200.0, ..Default::default() };
|
||||
p.insert_object(p.len(), shape(kind, extra, float), &Default::default()).unwrap();
|
||||
}
|
||||
para_block(p)
|
||||
})
|
||||
.collect();
|
||||
let mut s = Session::new(doc);
|
||||
s.view.proofing = false;
|
||||
s.page_hint = 0;
|
||||
assert_eq!(s.layout().pages.len(), 8000);
|
||||
let started = std::time::Instant::now();
|
||||
assert!(reroute(&mut s));
|
||||
let elapsed = started.elapsed();
|
||||
eprintln!("8000-page reroute: {elapsed:?}");
|
||||
assert!(elapsed < std::time::Duration::from_secs(5), "reroute took {elapsed:?}");
|
||||
for path in s.doc.para_paths(StoryRef::Body) {
|
||||
let para = s.doc.para(StoryRef::Body, &path).unwrap();
|
||||
let InlineObject::Shape { w, h, float, .. } = para.object_at(6).unwrap() else { panic!("connector") };
|
||||
assert_eq!((*w, *h, float.x, float.y), (160.0, 0.0, 140.0, 210.0));
|
||||
}
|
||||
big.touch();
|
||||
assert!(!reroute(&mut big), "rerouting must settle after refreshing the layout");
|
||||
s.touch();
|
||||
assert!(!reroute(&mut s), "rerouting must settle after refreshing the layout");
|
||||
}
|
||||
|
||||
/// The per-case shape/geometry of one scaled-group reroute case.
|
||||
|
||||
@@ -161,7 +161,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.params(r#"{"tab"?: "find|replace|goto" (default replace)}"#)
|
||||
.pure(),
|
||||
CommandSpec::new("edit.replaceAll", "Replace All", "Home › Editing › Replace", replace_all)
|
||||
.params(r#"{"text": string, "with": string (^p ^t ^& ^c …; \\1 with wildcards; with regex also $1 ${n} ${name} $0 $$ \\1 \\n (paragraph mark) \\t), …options of edit.find} (with AutoFormat's smart quotes on, a " or ' typed in `with` goes in curly by the character before it, as typing does, except with regex or special: false (taken as written); ^034 and ^039 stay straight; a match that already reads so, curled the same kind, is left and not counted); replaces in the main text, headers, footers, footnotes, endnotes and text boxes, wherever the caret is"#),
|
||||
.params(r#"{"text": string, "with": string (^p ^t ^& ^c …; \\1 with wildcards; with regex also $1 ${n} ${name} $0 $$ \\1 \\n (paragraph mark) \\t), …options of edit.find} (with AutoFormat's smart quotes on, a " or ' typed in `with` goes in curly by the character before it, as typing does, except with regex or special: false (taken as written); ^034 and ^039 stay straight; a match that already reads so, curled the same kind, is left and not counted)"#),
|
||||
CommandSpec::new("edit.goto", "Go To", "Home › Editing › Find", goto)
|
||||
.key("Mod+Alt+G / F5")
|
||||
.params(r#"{"page"?: n, "pageBy"?: int (pages forward, negative back, from the caret's page), "bookmark"?: string (selects its text), "paragraph"?: n}; none opens Find and Replace on its Go To tab"#)
|
||||
@@ -827,46 +827,16 @@ fn replace(s: &mut Session, v: &Value) -> CmdResult {
|
||||
Ok(json!({"replaced": replaced, "remaining": search(s, story)?.len(), "selected": selected}))
|
||||
}
|
||||
|
||||
/// The stories Replace All covers, as in Word: the main text, then the headers, footers,
|
||||
/// footnotes, endnotes and text boxes the document shows. Hidden stories (a removed header, a
|
||||
/// deleted note's text) and comments keep their words.
|
||||
fn replace_stories(s: &Session) -> Vec<StoryRef> {
|
||||
s.doc.shown_stories()
|
||||
}
|
||||
|
||||
/// Every match in every story replaced (wherever the caret is), last first so earlier positions
|
||||
/// stay valid (one undo step). A `\r` in the replacement (`^p`) splits the paragraph. Locked
|
||||
/// content in any story stops it before anything changes.
|
||||
/// Every match replaced, last first so earlier positions stay valid (one undo step). A `\r` in
|
||||
/// the replacement (`^p`) splits the paragraph.
|
||||
fn replace_all(s: &mut Session, v: &Value) -> CmdResult {
|
||||
need_query(s, v)?;
|
||||
read_opts(s, v);
|
||||
let mut found = Vec::new();
|
||||
// A protected document only lets the editable regions change: matches elsewhere (in a header,
|
||||
// say) stay as they are, so they don't make the whole command fail.
|
||||
let editable = super::protect::editable_ranges(s);
|
||||
for story in replace_stories(s) {
|
||||
// Matches already curled as the replacement would curl them are left and not counted (#7307).
|
||||
let mut results: Vec<Found> = search_matches(s, story, true, true)?.into_iter().filter(|f| !f.keep).collect();
|
||||
if let Some(ranges) = &editable {
|
||||
results.retain(|f| ranges.iter().any(|(from, to)| f.a.story == from.story && f.a >= *from && f.b <= *to));
|
||||
}
|
||||
if results.is_empty() {
|
||||
continue;
|
||||
}
|
||||
super::controls::check_deletions(s, story, results.iter().map(|f| (&f.a, &f.b)))?;
|
||||
found.push(results);
|
||||
}
|
||||
let n: usize = found.iter().map(Vec::len).sum();
|
||||
// The main text comes last, so under Track Changes the caret ends where it did before.
|
||||
for results in found.into_iter().rev() {
|
||||
replace_found(s, results)?;
|
||||
}
|
||||
s.status = format!("All done. We made {n} replacements.");
|
||||
Ok(json!({"replaced": n}))
|
||||
}
|
||||
|
||||
/// Replace the matches of one story, last first.
|
||||
fn replace_found(s: &mut Session, results: Vec<Found>) -> Result<(), CmdError> {
|
||||
let story = s.sel.focus.story;
|
||||
// Matches already curled as the replacement would curl them are left and not counted (#7307).
|
||||
let results: Vec<Found> = search_matches(s, story, true, true)?.into_iter().filter(|f| !f.keep).collect();
|
||||
let n = results.len();
|
||||
super::controls::check_deletions(s, story, results.iter().map(|f| (&f.a, &f.b)))?;
|
||||
for Found { a, b, rep, .. } in results.into_iter().rev() {
|
||||
let with = rep.unwrap_or_default();
|
||||
if s.doc.settings.track_changes {
|
||||
@@ -887,7 +857,8 @@ fn replace_found(s: &mut Session, results: Vec<Found>) -> Result<(), CmdError> {
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
s.status = format!("All done. We made {n} replacements.");
|
||||
Ok(json!({"replaced": n}))
|
||||
}
|
||||
|
||||
fn goto(s: &mut Session, v: &Value) -> CmdResult {
|
||||
|
||||
@@ -668,18 +668,6 @@ fn recipient_lists_in_legacy_and_utf16_encodings() {
|
||||
assert_eq!(s.merge.rows, [["José"]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn recipient_list_with_generic_utf32_uses_its_big_endian_bom() {
|
||||
let mut data = vec![0x00, 0x00, 0xFE, 0xFF];
|
||||
for c in "Name,City\nAda,A🌍\n".chars() {
|
||||
data.extend_from_slice(&(c as u32).to_be_bytes());
|
||||
}
|
||||
let mut s = Session::new(Document::new());
|
||||
s.run("mailings.recipients", &json!({"path": "list.csv", "data": b64(&data), "encoding": "utf-32"})).unwrap();
|
||||
assert_eq!(s.merge.headers, ["Name", "City"]);
|
||||
assert_eq!(s.merge.rows, [["Ada", "A🌍"]]);
|
||||
}
|
||||
|
||||
/// #778: legacy Excel 97–2003 workbooks are recipient lists; a CSV named .xls reads as text.
|
||||
#[test]
|
||||
fn recipients_from_an_xls_workbook() {
|
||||
|
||||
@@ -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, is_shape_or_canvas, obj_size, selected, target_objects, with_obj};
|
||||
use super::{CmdError, CmdResult, InlineObject, Pos, Rgb, Session, Value, Wrap, json, p};
|
||||
use wordcraft_doc::picfx::PicFx;
|
||||
|
||||
@@ -186,30 +186,6 @@ pub fn fit_size(w: f32, h: f32, keep: bool) -> (f32, f32) {
|
||||
(side(w), side(h))
|
||||
}
|
||||
|
||||
/// Runs a one-picture command on each selected picture in turn (several selected with Shift or
|
||||
/// 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 {
|
||||
return run(s);
|
||||
}
|
||||
let (sel, also) = (s.sel.clone(), s.also_selected.clone());
|
||||
// The failed command's rollback restores the document but not these maps: put them back too.
|
||||
let (originals, looks) = (s.originals.clone(), s.picture_looks.clone());
|
||||
let mut out = Ok(Value::Null);
|
||||
for (pos, _) in &picks {
|
||||
select_object(s, pos);
|
||||
s.also_selected.clear();
|
||||
out = run(s);
|
||||
if out.is_err() {
|
||||
(s.originals, s.picture_looks) = (originals, looks);
|
||||
break;
|
||||
}
|
||||
}
|
||||
(s.sel, s.also_selected) = (sel, also);
|
||||
out
|
||||
}
|
||||
|
||||
/// Apply an image operation to the selected picture's bitmap (stored as a new PNG).
|
||||
pub(super) fn adjust(s: &mut Session, f: impl Fn(image::DynamicImage) -> Result<image::DynamicImage, CmdError>) -> CmdResult {
|
||||
let (_, o) = selected(s).ok_or_else(|| CmdError::Disabled("no picture".into()))?;
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
use super::arrange::{MAX_OFFSET, bounds, copy_to, move_with_text, unalign};
|
||||
use super::group::{add_object, group, ungroup};
|
||||
use super::picture::{
|
||||
adjust, adjust_media, clear_lum, crop, each_picture, original_media, recolor, relook, remove_background, reset, shape_size, size,
|
||||
};
|
||||
use super::picture::{adjust, adjust_media, clear_lum, crop, 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,
|
||||
@@ -60,112 +58,98 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.params(r#"{"text"?: string, "title"?: string, "decorative"?: bool} (the selected picture, shape, text box, group or chart)"#)
|
||||
.when(has_object),
|
||||
CommandSpec::new("picture.corrections", "Corrections", "Picture Format › Adjust", |s, v| {
|
||||
each_picture(s, |s| {
|
||||
let b = p::f32(v, "brightness").unwrap_or(0.0).clamp(-100.0, 100.0);
|
||||
let c = p::f32(v, "contrast").unwrap_or(0.0).clamp(-100.0, 100.0);
|
||||
let sharpen = p::f32(v, "sharpen").unwrap_or(0.0).clamp(-100.0, 100.0);
|
||||
// Absolute from the original (like transparency): re-setting all three to 0
|
||||
// restores the original pixels instead of stacking on the last pass.
|
||||
// The file's own brightness and contrast (`fx`) are replaced, not stacked on.
|
||||
let base = original_media(s)?;
|
||||
adjust_media(s, &base, clear_lum, move |img| {
|
||||
let mut img = img;
|
||||
if b != 0.0 {
|
||||
img = image::DynamicImage::ImageRgba8(image::imageops::colorops::brighten(&img, (b * 2.55) as i32));
|
||||
}
|
||||
if c != 0.0 {
|
||||
img = image::DynamicImage::ImageRgba8(image::imageops::colorops::contrast(&img, c));
|
||||
}
|
||||
if sharpen > 0.0 {
|
||||
img = img.unsharpen(1.0 + sharpen / 50.0, 2);
|
||||
} else if sharpen < 0.0 && (-sharpen / 25.0).is_normal() {
|
||||
// `blur` asserts on a subnormal width.
|
||||
img = img.blur(-sharpen / 25.0);
|
||||
}
|
||||
Ok(img)
|
||||
})
|
||||
let b = p::f32(v, "brightness").unwrap_or(0.0).clamp(-100.0, 100.0);
|
||||
let c = p::f32(v, "contrast").unwrap_or(0.0).clamp(-100.0, 100.0);
|
||||
let sharpen = p::f32(v, "sharpen").unwrap_or(0.0).clamp(-100.0, 100.0);
|
||||
// Absolute from the original (like transparency): re-setting all three to 0
|
||||
// restores the original pixels instead of stacking on the last pass.
|
||||
// The file's own brightness and contrast (`fx`) are replaced, not stacked on.
|
||||
let base = original_media(s)?;
|
||||
adjust_media(s, &base, clear_lum, move |img| {
|
||||
let mut img = img;
|
||||
if b != 0.0 {
|
||||
img = image::DynamicImage::ImageRgba8(image::imageops::colorops::brighten(&img, (b * 2.55) as i32));
|
||||
}
|
||||
if c != 0.0 {
|
||||
img = image::DynamicImage::ImageRgba8(image::imageops::colorops::contrast(&img, c));
|
||||
}
|
||||
if sharpen > 0.0 {
|
||||
img = img.unsharpen(1.0 + sharpen / 50.0, 2);
|
||||
} else if sharpen < 0.0 && (-sharpen / 25.0).is_normal() {
|
||||
// `blur` asserts on a subnormal width.
|
||||
img = img.blur(-sharpen / 25.0);
|
||||
}
|
||||
Ok(img)
|
||||
})
|
||||
})
|
||||
.params(r#"{"brightness"?: -100..100, "contrast"?: -100..100, "sharpen"?: -100..100}"#)
|
||||
.when(has_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();
|
||||
let sat = p::f32(v, "saturation").unwrap_or(100.0);
|
||||
// Absolute from the original (like transparency): saturation 100 restores it.
|
||||
// Color and Corrections are independent, as in Word: only Washout, which Word stores
|
||||
// as brightness and contrast (`a:lum`), replaces the file's own (`fx`).
|
||||
let base = original_media(s)?;
|
||||
let fx: fn(&mut PicFx) = if mode == "washout" { clear_lum } else { |_| {} };
|
||||
adjust_media(s, &base, fx, move |img| Ok(recolor(img, &mode, sat)))
|
||||
})
|
||||
let mode = p::str(v, "mode").unwrap_or("grayscale").to_string();
|
||||
let sat = p::f32(v, "saturation").unwrap_or(100.0);
|
||||
// Absolute from the original (like transparency): saturation 100 restores it.
|
||||
// Color and Corrections are independent, as in Word: only Washout, which Word stores
|
||||
// as brightness and contrast (`a:lum`), replaces the file's own (`fx`).
|
||||
let base = original_media(s)?;
|
||||
let fx: fn(&mut PicFx) = if mode == "washout" { clear_lum } else { |_| {} };
|
||||
adjust_media(s, &base, fx, move |img| Ok(recolor(img, &mode, sat)))
|
||||
})
|
||||
.params(r#"{"mode": "grayscale|sepia|washout|blackAndWhite|saturation|tint", "saturation"?: 0..400}"#)
|
||||
.when(has_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()))?;
|
||||
// One colour everywhere, transparency kept: recolours an inserted icon or other
|
||||
// one-colour line art without redrawing it.
|
||||
adjust(s, move |img| {
|
||||
let mut rgba = img.to_rgba8();
|
||||
for px in rgba.pixels_mut() {
|
||||
px.0 = [c.0, c.1, c.2, px.0[3]];
|
||||
}
|
||||
Ok(image::DynamicImage::ImageRgba8(rgba))
|
||||
})
|
||||
let c = p::str(v, "color").and_then(Rgb::parse).ok_or_else(|| CmdError::Params("`color` (RRGGBB) is required".into()))?;
|
||||
// One colour everywhere, transparency kept: recolours an inserted icon or other
|
||||
// one-colour line art without redrawing it.
|
||||
adjust(s, move |img| {
|
||||
let mut rgba = img.to_rgba8();
|
||||
for px in rgba.pixels_mut() {
|
||||
px.0 = [c.0, c.1, c.2, px.0[3]];
|
||||
}
|
||||
Ok(image::DynamicImage::ImageRgba8(rgba))
|
||||
})
|
||||
})
|
||||
.params(r#"{"color": "RRGGBB"}"#)
|
||||
.when(has_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).
|
||||
let e = p::str(v, "effect").unwrap_or("blur").to_string();
|
||||
relook(s, move |l| l.effect = (e != "none").then_some(e))
|
||||
})
|
||||
// One effect at a time, as in Word: a second one replaces the first (#2052).
|
||||
let e = p::str(v, "effect").unwrap_or("blur").to_string();
|
||||
relook(s, move |l| l.effect = (e != "none").then_some(e))
|
||||
})
|
||||
.params(r#"{"effect": "blur|sharpen|invert|posterize|pixelate|none"} (replaces the picture's effect)"#)
|
||||
.when(has_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);
|
||||
// Absolute, not compounding: 0% is always the original pixels fully opaque.
|
||||
// The base is the pre-edit original (kept for Reset Picture), so dragging a
|
||||
// slider back and forth never fades what a previous pass already faded.
|
||||
// (Combining with other pixel edits then re-setting transparency drops those
|
||||
// edits; a full live-effect stack is future work.)
|
||||
// The file's own transparency (`fx`, `a:alphaModFix`) is replaced too: it's baked
|
||||
// into the pixels from here on.
|
||||
let base = original_media(s)?;
|
||||
adjust_media(s, &base, |fx: &mut PicFx| fx.transparency = 0, move |img| {
|
||||
let mut rgba = img.to_rgba8();
|
||||
for px in rgba.pixels_mut() {
|
||||
px.0[3] = (px.0[3] as f32 * (1.0 - t / 100.0)) as u8;
|
||||
}
|
||||
Ok(image::DynamicImage::ImageRgba8(rgba))
|
||||
})
|
||||
let t = p::f32(v, "percent").unwrap_or(50.0).clamp(0.0, 100.0);
|
||||
// Absolute, not compounding: 0% is always the original pixels fully opaque.
|
||||
// The base is the pre-edit original (kept for Reset Picture), so dragging a
|
||||
// slider back and forth never fades what a previous pass already faded.
|
||||
// (Combining with other pixel edits then re-setting transparency drops those
|
||||
// edits; a full live-effect stack is future work.)
|
||||
// The file's own transparency (`fx`, `a:alphaModFix`) is replaced too: it's baked
|
||||
// into the pixels from here on.
|
||||
let base = original_media(s)?;
|
||||
adjust_media(s, &base, |fx: &mut PicFx| fx.transparency = 0, move |img| {
|
||||
let mut rgba = img.to_rgba8();
|
||||
for px in rgba.pixels_mut() {
|
||||
px.0[3] = (px.0[3] as f32 * (1.0 - t / 100.0)) as u8;
|
||||
}
|
||||
Ok(image::DynamicImage::ImageRgba8(rgba))
|
||||
})
|
||||
})
|
||||
.params(r#"{"percent": 0..100}"#)
|
||||
.when(has_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);
|
||||
adjust(s, move |img| Ok(remove_background(img, tol)))
|
||||
})
|
||||
let tol = p::f32(v, "tolerance").unwrap_or(30.0).clamp(0.0, 255.0);
|
||||
adjust(s, move |img| Ok(remove_background(img, tol)))
|
||||
})
|
||||
.params(r#"{"tolerance"?: 0..255}"#)
|
||||
.when(has_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;
|
||||
adjust(s, move |img| Ok(if img.width().max(img.height()) > max { img.resize(max, max, image::imageops::FilterType::Lanczos3) } else { img }))
|
||||
})
|
||||
let max = p::u64(v, "maxPixels").unwrap_or(1600).clamp(32, 20000) as u32;
|
||||
adjust(s, move |img| Ok(if img.width().max(img.height()) > max { img.resize(max, max, image::imageops::FilterType::Lanczos3) } else { img }))
|
||||
})
|
||||
.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),
|
||||
CommandSpec::new("picture.reset", "Reset Picture", "Picture Format › Adjust", reset).when(has_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()))?
|
||||
@@ -200,24 +184,20 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.params(r#"{"path"?: string, "data"?: base64}"#)
|
||||
.when(has_picture),
|
||||
CommandSpec::new("picture.style", "Picture Styles", "Picture Format › Picture Styles", |s, v| {
|
||||
each_picture(s, |s| {
|
||||
// A style replaces the picture's style and border, as Word's gallery does (#2052).
|
||||
let style = p::str(v, "style").unwrap_or("simpleFrame").to_string();
|
||||
relook(s, move |l| {
|
||||
l.style = Some(style);
|
||||
l.border = None;
|
||||
})
|
||||
// A style replaces the picture's style and border, as Word's gallery does (#2052).
|
||||
let style = p::str(v, "style").unwrap_or("simpleFrame").to_string();
|
||||
relook(s, move |l| {
|
||||
l.style = Some(style);
|
||||
l.border = None;
|
||||
})
|
||||
})
|
||||
.params(r#"{"style": "simpleFrame|thickFrame|rounded|softEdge|shadow"} (replaces the picture's style and border)"#)
|
||||
.when(has_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);
|
||||
let w = p::u64(v, "width").unwrap_or(4).clamp(1, 200) as u32;
|
||||
// Replaces the picture's border, keeping its style (#2052).
|
||||
relook(s, move |l| l.border = Some((c, w)))
|
||||
})
|
||||
let c = p::str(v, "color").and_then(Rgb::parse).unwrap_or(Rgb::BLACK);
|
||||
let w = p::u64(v, "width").unwrap_or(4).clamp(1, 200) as u32;
|
||||
// Replaces the picture's border, keeping its style (#2052).
|
||||
relook(s, move |l| l.border = Some((c, w)))
|
||||
})
|
||||
.params(r#"{"color"?: "RRGGBB", "width"?: px} (replaces the picture's border)"#)
|
||||
.when(has_picture),
|
||||
|
||||
@@ -432,28 +432,6 @@ 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));
|
||||
}
|
||||
|
||||
/// #8832: a picture command on several selected pictures changes each, in one undo step.
|
||||
#[test]
|
||||
fn picture_border_applies_to_every_selected_picture() {
|
||||
let data = super::super::insert::base64_encode(&png(20, 10));
|
||||
let mut s = Session::new(wordcraft_doc::Document::new());
|
||||
s.run("insert.picture", &json!({"data": data})).unwrap();
|
||||
s.run("insert.picture", &json!({"data": data})).unwrap();
|
||||
s.run("select.addObject", &json!({"index": 0})).unwrap();
|
||||
s.run("select.addObject", &json!({"index": 1})).unwrap();
|
||||
let media = |s: &Session| {
|
||||
all_objects(s)
|
||||
.into_iter()
|
||||
.map(|(_, o)| matches!(o, InlineObject::Image { media, .. } if s.picture_looks.get(&media).is_some_and(|l| l.border.is_some())))
|
||||
.collect::<Vec<_>>()
|
||||
};
|
||||
assert_eq!(media(&s), [false, false]);
|
||||
s.run("picture.border", &json!({"width": 3})).unwrap();
|
||||
assert_eq!(media(&s), [true, true]);
|
||||
s.run("edit.undo", &json!({})).unwrap();
|
||||
assert_eq!(media(&s), [false, false]);
|
||||
}
|
||||
|
||||
/// #2019: Insert › Shapes adds each new shape beside the selected one, as Word draws it, so
|
||||
/// shapes inserted in a row are all kept (the second used to replace the first, which stays
|
||||
/// selected after its insert). Selected text stays too, and the new shape is selected.
|
||||
|
||||
@@ -97,8 +97,8 @@ mod tests {
|
||||
use super::*;
|
||||
use crate::packs::{Backend, FixedBackend};
|
||||
|
||||
/// Tests that set the process-wide backend or packs directory share the dictionary test lock.
|
||||
use crate::custom_dict::DICT_TEST_LOCK as LOCK;
|
||||
/// Tests that set the process-wide backend take turns.
|
||||
static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
|
||||
/// Puts the process back to no backend and no background thread when dropped, even when
|
||||
/// the test panicked.
|
||||
|
||||
@@ -695,27 +695,6 @@ pub(crate) fn typing_pos(s: &Session, p: &Pos) -> Pos {
|
||||
Pos { off, ..p.clone() }
|
||||
}
|
||||
|
||||
/// The ranges, in any story, that a document protected as read only, comments only or forms
|
||||
/// lets this author edit; `None` when the protection doesn't limit where edits may land. A command
|
||||
/// that searches the whole document keeps only its matches inside them, so a match in protected
|
||||
/// content (a header repeating a placeholder) is left alone instead of failing the command.
|
||||
pub(crate) fn editable_ranges(s: &Session) -> Option<Vec<(Pos, Pos)>> {
|
||||
match s.doc.settings.protection.as_deref()? {
|
||||
"forms" => {
|
||||
let stories = std::iter::once(StoryRef::Body).chain(s.doc.parts.keys().map(|k| StoryRef::Part(*k)));
|
||||
Some(
|
||||
stories
|
||||
.flat_map(|story| s.doc.control_ranges(story))
|
||||
.filter(|r| r.control.lock.can_edit())
|
||||
.map(|r| (r.content_start(), r.end))
|
||||
.collect(),
|
||||
)
|
||||
}
|
||||
"readOnly" | "comments" => Some(s.doc.perm_ranges().into_iter().filter(|r| editable_by(r, &s.author)).map(|r| (r.start, r.end)).collect()),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// The first position in an editable range after `from` (wrapping round), for Find Next Region
|
||||
/// I Can Edit; with it, the range's end. Filling in forms: the next fillable control's content.
|
||||
pub fn next_region(s: &Session, from: &Pos) -> Option<(Pos, Pos)> {
|
||||
|
||||
@@ -32,30 +32,6 @@ fn read_only_with_an_exception_allows_edits_only_inside_it() {
|
||||
assert_eq!(s.doc.settings.protection.as_deref(), Some("readOnly"));
|
||||
}
|
||||
|
||||
/// Replace All covers every story, but in a protected document only the editable regions change:
|
||||
/// the same placeholder in a header, a footnote or the locked body text is left as it is, and
|
||||
/// the replacement in the editable region still goes through.
|
||||
#[test]
|
||||
fn replace_all_in_a_protected_document_skips_protected_matches() {
|
||||
let mut s = Session::new(Document::from_text("Locked [NAME].\nFill [NAME] in."));
|
||||
let header = s.run("insert.header", &json!({"text": "Header [NAME]"})).unwrap()["story"].as_u64().unwrap() as u32;
|
||||
s.run("caret.docStart", &json!({})).unwrap();
|
||||
let note = s.run("references.footnote", &json!({"text": "Note [NAME]"})).unwrap()["id"].as_u64().unwrap() as u32;
|
||||
s.sel = Selection::caret(Pos::body(0, 0));
|
||||
select(&mut s, "Fill [NAME] in.");
|
||||
s.run("review.restrict", &json!({"exception": "add"})).unwrap();
|
||||
s.run("review.restrict", &json!({"mode": "readOnly"})).unwrap();
|
||||
let r = s.run("edit.replaceAll", &json!({"text": "[NAME]", "with": "Jane"})).unwrap();
|
||||
assert_eq!(r["replaced"], 1, "{r}");
|
||||
let body = s.doc.plain_text(StoryRef::Body).replace(OBJ, "");
|
||||
assert!(body.contains("Locked [NAME]."), "{body}");
|
||||
assert!(body.contains("Fill Jane in."), "{body}");
|
||||
for id in [header, note] {
|
||||
let first = Pos::new(StoryRef::Part(id), wordcraft_doc::Path::top(0), 0);
|
||||
assert!(s.doc.para_at(&first).unwrap().text.contains("[NAME]"));
|
||||
}
|
||||
}
|
||||
|
||||
/// An exception that starts a line: Home, Left and Down put the caret before its start
|
||||
/// marker, and Enter and typing there go inside the exception. A caret after the end marker at
|
||||
/// the end of the line goes back inside it too.
|
||||
|
||||
@@ -273,7 +273,7 @@ pub fn save_custom_dictionary(path: &Path, removed: &[String]) -> Result<(), Str
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) use tests::{DICT_TEST_LOCK, TestDir, dict_test_lock};
|
||||
pub(crate) use tests::{DICT_TEST_LOCK, TestDir};
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
@@ -282,11 +282,6 @@ mod tests {
|
||||
/// Test lock serializing tests that access the global proofing dictionary.
|
||||
pub(crate) static DICT_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
|
||||
/// Acquire [`DICT_TEST_LOCK`], recovering cleanly if an earlier test panicked while holding it.
|
||||
pub(crate) fn dict_test_lock() -> std::sync::MutexGuard<'static, ()> {
|
||||
DICT_TEST_LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// RAII guard for temporary directories in dictionary tests.
|
||||
pub(crate) struct TestDir(pub(crate) std::path::PathBuf);
|
||||
|
||||
|
||||
@@ -300,7 +300,6 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn layout_drops_stale_revision_slot_but_keeps_same_revision_mode() {
|
||||
let _dict_guard = crate::custom_dict::dict_test_lock();
|
||||
let mut session = Session::new(Document::new());
|
||||
let first = session.layout();
|
||||
let first_weak = Arc::downgrade(&first);
|
||||
|
||||
@@ -465,16 +465,6 @@ impl Session {
|
||||
| "shape.size"
|
||||
| "shape.rotation"
|
||||
| "picture.size"
|
||||
| "picture.reset"
|
||||
| "picture.corrections"
|
||||
| "picture.color"
|
||||
| "picture.iconColor"
|
||||
| "picture.effects"
|
||||
| "picture.transparency"
|
||||
| "picture.removeBackground"
|
||||
| "picture.compress"
|
||||
| "picture.style"
|
||||
| "picture.border"
|
||||
| "arrange.rotate"
|
||||
| "arrange.rotation"
|
||||
| "shape.alignText"
|
||||
|
||||
+33
-122
@@ -3775,14 +3775,14 @@ fn select_all_keeps_the_whole_story_when_it_ends_in_a_table() {
|
||||
run(&mut s, "insert.table", json!({"rows": 2, "cols": 2}));
|
||||
run(&mut s, "text.insert", json!({"text": "A1"}));
|
||||
s.doc.body.pop();
|
||||
run(&mut s, "select.all", json!({"whole": false}));
|
||||
run(&mut s, "select.all", json!({"whole": false}));
|
||||
run(&mut s, "select.all", json!({"whole": false}));
|
||||
run(&mut s, "select.all", json!({"whole": false}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
let whole = (s.doc.start_of(StoryRef::Body), s.doc.end_of(StoryRef::Body));
|
||||
assert!(s.doc.end_of(StoryRef::Body).path.cell().is_some());
|
||||
assert_eq!(s.sel.ordered(), whole);
|
||||
run(&mut s, "select.all", json!({"whole": false}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
assert!(s.column.is_none());
|
||||
assert_eq!(s.sel.ordered(), whole);
|
||||
}
|
||||
@@ -11890,17 +11890,19 @@ fn next_footnote_skips_endnotes() {
|
||||
assert_eq!(s.sel.focus.off, 9);
|
||||
}
|
||||
|
||||
/// Tests that read or mutate process-wide proofing dictionaries take turns through `DICT_TEST_LOCK`.
|
||||
/// Tests that install a test dictionary wait for the dictionaries-folder test, which changes the
|
||||
/// folder and then reads what each language reports: an install in between reports no file.
|
||||
static DICTIONARIES: std::sync::Mutex<()> = std::sync::Mutex::new(());
|
||||
|
||||
fn dictionaries_turn() -> std::sync::MutexGuard<'static, ()> {
|
||||
crate::custom_dict::dict_test_lock()
|
||||
DICTIONARIES.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// A tiny synthetic Polish Hunspell dictionary (written for these tests). Real dictionaries are
|
||||
/// installed on the system, never bundled; every Polish test installs this same one.
|
||||
fn polish_test_dictionary() -> std::sync::MutexGuard<'static, ()> {
|
||||
let turn = dictionaries_turn();
|
||||
fn polish_test_dictionary() {
|
||||
let _turn = dictionaries_turn();
|
||||
wordcraft_proof::pl::install_dictionary(POLISH_TEST_AFF, POLISH_TEST_DIC).unwrap();
|
||||
turn
|
||||
}
|
||||
|
||||
const POLISH_TEST_AFF: &str = "SET UTF-8\nTRY aioeznrwcyszżtkpdmłjlubąęgh\nMAP 2\nMAP oó\nMAP zż\nREP 2\nREP ż rz\nREP rz ż\n";
|
||||
@@ -11908,10 +11910,9 @@ const POLISH_TEST_DIC: &str = "12\npłynie\nrzeka\na\nto\nwiem\nże\ntak\nw\nog
|
||||
|
||||
/// A tiny synthetic Portuguese Hunspell dictionary (written for these tests). Real dictionaries
|
||||
/// are installed on the system, never bundled; every Portuguese test installs this same one.
|
||||
fn portuguese_test_dictionary() -> std::sync::MutexGuard<'static, ()> {
|
||||
let turn = dictionaries_turn();
|
||||
fn portuguese_test_dictionary() {
|
||||
let _turn = dictionaries_turn();
|
||||
wordcraft_proof::pt::install_dictionary(PORTUGUESE_TEST_AFF, PORTUGUESE_TEST_DIC).unwrap();
|
||||
turn
|
||||
}
|
||||
|
||||
const PORTUGUESE_TEST_AFF: &str =
|
||||
@@ -11986,7 +11987,7 @@ fn dictionaries_folder_option_is_saved_searched_and_reported() {
|
||||
/// grammar, suggestions come from it, and a suggestion fixes the text.
|
||||
#[test]
|
||||
fn portuguese_proofing_through_the_review_commands() {
|
||||
let _turn = portuguese_test_dictionary();
|
||||
portuguese_test_dictionary();
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "Saudade coraçao, e ele ele disse."}));
|
||||
// English by default: the Portuguese words are English misspellings.
|
||||
@@ -12017,10 +12018,9 @@ fn portuguese_proofing_through_the_review_commands() {
|
||||
assert_eq!(left.as_array().unwrap().len(), 1, "{left}");
|
||||
}
|
||||
|
||||
fn indonesian_test_dictionary() -> std::sync::MutexGuard<'static, ()> {
|
||||
let turn = dictionaries_turn();
|
||||
fn indonesian_test_dictionary() {
|
||||
let _turn = dictionaries_turn();
|
||||
wordcraft_proof::id::install_dictionary(INDONESIAN_TEST_AFF, INDONESIAN_TEST_DIC).unwrap();
|
||||
turn
|
||||
}
|
||||
|
||||
// Hand-written synthetic fixture (no system dictionary data).
|
||||
@@ -12031,7 +12031,7 @@ const INDONESIAN_TEST_DIC: &str = "8\nrumah\nsekolah\nanak\nbermain\ndi\nmakan/A
|
||||
/// Dictionary.
|
||||
#[test]
|
||||
fn indonesian_proofing_through_the_review_commands() {
|
||||
let _turn = indonesian_test_dictionary();
|
||||
indonesian_test_dictionary();
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "Saya di sekolha, anak anak bermain."}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
@@ -12086,7 +12086,6 @@ fn english_dialects_through_the_review_commands() {
|
||||
if no_language_data("english_dialects_through_the_review_commands") {
|
||||
return;
|
||||
}
|
||||
let _turn = dictionaries_turn();
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "The colour of the center."}));
|
||||
// US English by default: the British spelling is flagged, the American one isn't.
|
||||
@@ -12194,20 +12193,19 @@ const SPANISH_TEST_AFF: &str =
|
||||
const SPANISH_TEST_DIC: &str = "10\nesto\nes\nuna\nprueba/S\ndel\ncorrector\ntambién\nhabéis\nvenido\ndecir\n";
|
||||
const URUGUAYAN_TEST_DIC: &str = "10\nesto\nes\nuna\nprueba/S\ndel\ncorrector\ntambién\ntener\nvenir\ndecir\n";
|
||||
|
||||
fn spanish_test_dictionaries() -> std::sync::MutexGuard<'static, ()> {
|
||||
fn spanish_test_dictionaries() {
|
||||
use wordcraft_proof::ProofLang;
|
||||
let turn = dictionaries_turn();
|
||||
let _turn = dictionaries_turn();
|
||||
for (lang, dic) in [(ProofLang::Es, SPANISH_TEST_DIC), (ProofLang::EsUy, URUGUAYAN_TEST_DIC)] {
|
||||
wordcraft_proof::es::install_dictionary(lang, SPANISH_TEST_AFF, dic).unwrap();
|
||||
}
|
||||
turn
|
||||
}
|
||||
|
||||
/// #3553: Spanish proofing through the same commands as Review, F7, Change and Add to
|
||||
/// Dictionary: `prueva` and `corector` are flagged with `prueba` and `corrector` offered.
|
||||
#[test]
|
||||
fn spanish_proofing_through_the_review_commands() {
|
||||
let _turn = spanish_test_dictionaries();
|
||||
spanish_test_dictionaries();
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "esto es una prueva del corector. Habéis venido?"}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
@@ -12238,7 +12236,7 @@ fn spanish_proofing_through_the_review_commands() {
|
||||
/// bytes.
|
||||
#[test]
|
||||
fn add_and_ignore_all_accept_both_normalization_forms() {
|
||||
let _turn = spanish_test_dictionaries();
|
||||
spanish_test_dictionaries();
|
||||
let mut s = s();
|
||||
let text = "esto zqanade\u{301}do y zqignora\u{301}do";
|
||||
run(&mut s, "document.setText", json!({"text": text}));
|
||||
@@ -12267,7 +12265,7 @@ fn add_and_ignore_all_accept_both_normalization_forms() {
|
||||
/// Uruguayan Spanish accepts the `vos` forms, imperatives included, that Spain's flags.
|
||||
#[test]
|
||||
fn uruguayan_spanish_accepts_vos_forms() {
|
||||
let _turn = spanish_test_dictionaries();
|
||||
spanish_test_dictionaries();
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "Vení, decime qué tenés."}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
@@ -12286,7 +12284,7 @@ fn uruguayan_spanish_accepts_vos_forms() {
|
||||
/// Czech proofing through the same commands as Review, F7, Change and Add to Dictionary.
|
||||
#[test]
|
||||
fn czech_proofing_through_the_review_commands() {
|
||||
let _turn = czech_test_dict::install();
|
||||
czech_test_dict::install();
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "Město pocitac, škola škola."}));
|
||||
assert!(run(&mut s, "review.issues", json!({})).as_array().unwrap().len() >= 3);
|
||||
@@ -12325,10 +12323,9 @@ fn czech_proofing_through_the_review_commands() {
|
||||
const ITALIAN_TEST_AFF: &str = "SET UTF-8\nTRY aeiortnsclcaffèéè\nMAP 2\nMAP aà\nMAP eéè\nREP 1\nREP caffe caffè\n";
|
||||
const ITALIAN_TEST_DIC: &str = "6\ncasa\ncaffè\nroma\ndisse\ne\nper\n";
|
||||
|
||||
fn italian_test_dictionary() -> std::sync::MutexGuard<'static, ()> {
|
||||
let turn = dictionaries_turn();
|
||||
fn italian_test_dictionary() {
|
||||
let _turn = dictionaries_turn();
|
||||
wordcraft_proof::it::install_dictionary(ITALIAN_TEST_AFF, ITALIAN_TEST_DIC).unwrap();
|
||||
turn
|
||||
}
|
||||
|
||||
/// Review › Language and the proofing commands work in Italian end to end: the language makes
|
||||
@@ -12336,7 +12333,7 @@ fn italian_test_dictionary() -> std::sync::MutexGuard<'static, ()> {
|
||||
/// suggestions come from it, and a suggestion fixes the text.
|
||||
#[test]
|
||||
fn italian_proofing_through_the_review_commands() {
|
||||
let _turn = italian_test_dictionary();
|
||||
italian_test_dictionary();
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "Casa caffe, e roma roma disse."}));
|
||||
// English by default: the Italian words are English misspellings.
|
||||
@@ -12369,7 +12366,7 @@ fn italian_proofing_through_the_review_commands() {
|
||||
|
||||
#[test]
|
||||
fn polish_proofing_through_the_review_commands() {
|
||||
let _turn = polish_test_dictionary();
|
||||
polish_test_dictionary();
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "Płynie żeka, a wogóle to wiem że tak."}));
|
||||
// English by default: the Polish words are English misspellings.
|
||||
@@ -12409,7 +12406,6 @@ fn turkish_proofing_through_the_review_commands() {
|
||||
if !crate::proof::tr::has_dictionary() {
|
||||
return;
|
||||
}
|
||||
let _turn = dictionaries_turn();
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "Bana bazen gelenler oldu ise de. Sana olacaklardan sonra sorna"}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
@@ -12437,7 +12433,7 @@ fn turkish_proofing_through_the_review_commands() {
|
||||
/// no parameters keep the old meaning (US English), and `default` needs a language.
|
||||
#[test]
|
||||
fn review_language_validates_tags_and_marks_text_unchecked() {
|
||||
let _turn = polish_test_dictionary();
|
||||
polish_test_dictionary();
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "Hello wrold"}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
@@ -12465,7 +12461,7 @@ fn review_language_validates_tags_and_marks_text_unchecked() {
|
||||
/// the caret, not the document's default, so what is typed in them is proofed in that language.
|
||||
#[test]
|
||||
fn a_new_table_is_in_the_language_at_the_caret() {
|
||||
let _turn = polish_test_dictionary();
|
||||
polish_test_dictionary();
|
||||
let cell_langs = |s: &Session| -> Vec<Option<String>> {
|
||||
let t = s.doc.body.iter().find_map(|b| b.as_table()).unwrap();
|
||||
t.rows.iter().flat_map(|r| &r.cells).flat_map(|c| &c.blocks).filter_map(|b| b.as_para()).map(|p| p.mark.lang.clone()).collect()
|
||||
@@ -12509,7 +12505,7 @@ fn a_new_table_is_in_the_language_at_the_caret() {
|
||||
/// a document with changes never does, and templates stay English.
|
||||
#[test]
|
||||
fn new_documents_follow_the_editing_language() {
|
||||
let _turn = polish_test_dictionary();
|
||||
polish_test_dictionary();
|
||||
let mut s = s();
|
||||
s.set_editing_language(Some("pl-PL"));
|
||||
assert_eq!(s.doc.styles.default_chr.lang.as_deref(), Some("pl-PL"), "the untouched blank document switches");
|
||||
@@ -12615,7 +12611,7 @@ fn rejected_default_proofing_language_does_not_survive_a_restart() {
|
||||
/// English run (`w:lang`) come back, and so does the proofing.
|
||||
#[test]
|
||||
fn proofing_languages_survive_a_docx_round_trip() {
|
||||
let _turn = polish_test_dictionary();
|
||||
polish_test_dictionary();
|
||||
let mut s = s();
|
||||
run(&mut s, "document.setText", json!({"text": "Płynie żeka. Hello wrold."}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
@@ -15860,7 +15856,7 @@ fn page_down_and_up_never_stay_on_a_line_in_the_continuous_views() {
|
||||
for view in ["view.draft", "view.outline", "view.webLayout"] {
|
||||
let mut s = s();
|
||||
run(&mut s, "layout.margins", json!({"top": 370, "bottom": 370}));
|
||||
let long = "Lorem ipsum dolor sit amet ".repeat(2);
|
||||
let long = "Lorem ipsum dolor sit amet ".repeat(4);
|
||||
run(&mut s, "text.insert", json!({"text": long}));
|
||||
run(&mut s, "text.newParagraph", json!({}));
|
||||
run(&mut s, "para.indents", json!({"right": 700}));
|
||||
@@ -15920,91 +15916,6 @@ fn page_down_extends_a_selection_that_ends_in_collapsed_outline_text() {
|
||||
assert!(s.layout().caret(&s.sel.focus).is_some(), "to a place the outline shows");
|
||||
}
|
||||
|
||||
/// #3300: Replace All, as in Word, replaces in the main text, headers, footers, footnotes,
|
||||
/// endnotes and text boxes, wherever the caret is. Comments keep their words.
|
||||
#[test]
|
||||
fn replace_all_replaces_in_every_story() {
|
||||
use wordcraft_doc::{CharProps, Paragraph, PartKind, StoryRef, para_block};
|
||||
let story_text = |t: &Session, story: StoryRef| {
|
||||
let first = wordcraft_doc::Pos::new(story, wordcraft_doc::Path::top(0), 0);
|
||||
if story == StoryRef::Body { t.doc.plain_text(story) } else { t.doc.para_at(&first).map(|p| p.text.clone()).unwrap_or_default() }
|
||||
};
|
||||
let build = || {
|
||||
let mut t = s();
|
||||
run(&mut t, "document.setText", json!({"text": "Body: [NAME] and [NAME]."}));
|
||||
// A text box the body shows (one nothing shows is pruned with the next command).
|
||||
let boxed = run(&mut t, "insert.textBox", json!({"text": "Text box: [NAME]"}))["story"].as_u64().unwrap() as u32;
|
||||
run(&mut t, "caret.docStart", json!({}));
|
||||
let header = run(&mut t, "insert.header", json!({"text": "Header: [NAME]"}))["story"].as_u64().unwrap() as u32;
|
||||
let footer = run(&mut t, "insert.footer", json!({"text": "Footer: [NAME]"}))["story"].as_u64().unwrap() as u32;
|
||||
run(&mut t, "caret.docStart", json!({}));
|
||||
let footnote = run(&mut t, "references.footnote", json!({"text": "Footnote: [NAME]"}))["id"].as_u64().unwrap() as u32;
|
||||
run(&mut t, "caret.docStart", json!({}));
|
||||
let endnote = run(&mut t, "references.endnote", json!({"text": "Endnote: [NAME]"}))["id"].as_u64().unwrap() as u32;
|
||||
run(&mut t, "caret.docStart", json!({}));
|
||||
let comment = t.doc.add_part(PartKind::Comment, vec![para_block(Paragraph::with_text("Comment: [NAME]", CharProps::default()))]);
|
||||
let ids = [header, footer, footnote, endnote, boxed, comment];
|
||||
(t, ids)
|
||||
};
|
||||
let (mut t, ids) = build();
|
||||
let r = run(&mut t, "edit.replaceAll", json!({"text": "[NAME]", "with": "Jane"}));
|
||||
assert_eq!(r["replaced"], 7, "{r}");
|
||||
assert_eq!(story_text(&t, StoryRef::Body).replace(wordcraft_doc::para::OBJ, ""), "Body: Jane and Jane.");
|
||||
let texts: Vec<String> = ids.iter().map(|id| story_text(&t, StoryRef::Part(*id)).replace(wordcraft_doc::para::OBJ, "")).collect();
|
||||
assert_eq!(texts, ["Header: Jane", "Footer: Jane", " Footnote: Jane", " Endnote: Jane", "Text box: Jane", "Comment: [NAME]"]);
|
||||
// One undo step brings every story back.
|
||||
run(&mut t, "edit.undo", json!({}));
|
||||
assert_eq!(story_text(&t, StoryRef::Body).replace(wordcraft_doc::para::OBJ, ""), "Body: [NAME] and [NAME].");
|
||||
assert_eq!(story_text(&t, StoryRef::Part(ids[0])), "Header: [NAME]");
|
||||
assert_eq!(story_text(&t, StoryRef::Part(ids[2])).replace(wordcraft_doc::para::OBJ, ""), " Footnote: [NAME]");
|
||||
// From the caret in a footnote the body is replaced too.
|
||||
let (mut t, ids) = build();
|
||||
t.sel = crate::session::Selection::caret(wordcraft_doc::Pos::new(StoryRef::Part(ids[2]), wordcraft_doc::Path::top(0), 0));
|
||||
let r = run(&mut t, "edit.replaceAll", json!({"text": "[NAME]", "with": "Jane"}));
|
||||
assert_eq!(r["replaced"], 7, "{r}");
|
||||
assert_eq!(story_text(&t, StoryRef::Body).replace(wordcraft_doc::para::OBJ, ""), "Body: Jane and Jane.");
|
||||
// Under Track Changes the replacements are revisions in every story, and nothing breaks.
|
||||
let (mut t, ids) = build();
|
||||
run(&mut t, "review.trackChanges", json!({"enabled": true}));
|
||||
let r = run(&mut t, "edit.replaceAll", json!({"text": "[NAME]", "with": "Jane"}));
|
||||
assert_eq!(r["replaced"], 7, "{r}");
|
||||
assert!(story_text(&t, StoryRef::Part(ids[0])).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]
|
||||
fn replace_all_skips_removed_header_and_deleted_footnote_stories() {
|
||||
use wordcraft_doc::StoryRef;
|
||||
let mut t = s();
|
||||
run(&mut t, "document.setText", json!({"text": "Body."}));
|
||||
let header = run(&mut t, "insert.header", json!({"text": "Header [NAME]"}))["story"].as_u64().unwrap() as u32;
|
||||
run(&mut t, "insert.removeHeader", json!({}));
|
||||
run(&mut t, "caret.docStart", json!({}));
|
||||
let footnote = run(&mut t, "references.footnote", json!({"text": "Footnote [NAME]"}))["id"].as_u64().unwrap() as u32;
|
||||
// Delete the footnote reference from the body without Track Changes, leaving the part behind.
|
||||
t.doc.delete_range(&Pos::body(0, 0), &Pos::body(0, 1)).unwrap();
|
||||
t.sel = crate::session::Selection::caret(Pos::body(0, 0));
|
||||
|
||||
let r = run(&mut t, "edit.replaceAll", json!({"text": "[NAME]", "with": "Jane"}));
|
||||
assert_eq!(r["replaced"], 0, "{r}");
|
||||
assert_eq!(t.status, "All done. We made 0 replacements.");
|
||||
for id in [header, footnote] {
|
||||
let first = Pos::new(StoryRef::Part(id), wordcraft_doc::Path::top(0), 0);
|
||||
assert!(t.doc.para_at(&first).unwrap().text.contains("[NAME]"));
|
||||
}
|
||||
|
||||
// A match in a shown story still replaces, without touching or counting the hidden ones.
|
||||
run(&mut t, "document.setText", json!({"text": "Body [NAME]."}));
|
||||
let r = run(&mut t, "edit.replaceAll", json!({"text": "[NAME]", "with": "Jane"}));
|
||||
assert_eq!(r["replaced"], 1, "{r}");
|
||||
assert_eq!(t.doc.plain_text(StoryRef::Body), "Body Jane.");
|
||||
for id in [header, footnote] {
|
||||
let first = Pos::new(StoryRef::Part(id), wordcraft_doc::Path::top(0), 0);
|
||||
assert!(t.doc.para_at(&first).unwrap().text.contains("[NAME]"));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn page_down_and_up_reach_the_ends_on_first_and_last_page() {
|
||||
let mut s = s();
|
||||
|
||||
@@ -54,8 +54,6 @@ to
|
||||
zqzakázané/F
|
||||
";
|
||||
|
||||
pub fn install() -> std::sync::MutexGuard<'static, ()> {
|
||||
let turn = super::dictionaries_turn();
|
||||
pub fn install() {
|
||||
super::install_dictionary(AFF, DIC).unwrap();
|
||||
turn
|
||||
}
|
||||
|
||||
@@ -195,68 +195,6 @@ fn enter_on_an_empty_nested_item_moves_it_up_a_level_first() {
|
||||
assert_eq!(paras(&s), vec![para("A", Some(0)), para("B", Some(1)), para("text", None)]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn enter_outdents_an_empty_list_item_and_drops_direct_indents() {
|
||||
use wordcraft_doc::props::{NumRef, ParaProps};
|
||||
use wordcraft_doc::styles::Style;
|
||||
|
||||
let fixture = typed("* One\n\tTwo\n");
|
||||
let at = fixture.sel.focus.clone();
|
||||
let item = fixture.doc.para_at(&at).unwrap();
|
||||
assert!(item.is_empty());
|
||||
let nested = item.props.numbering.unwrap();
|
||||
assert_eq!(nested.level, 1);
|
||||
let promoted = NumRef { level: 0, ..nested };
|
||||
|
||||
let mut doc = fixture.doc.clone();
|
||||
Arc::make_mut(&mut doc.styles).upsert(Style {
|
||||
id: "NestedFixture".into(),
|
||||
name: "Nested Fixture".into(),
|
||||
para: ParaProps { numbering: Some(nested), ..Default::default() },
|
||||
..Default::default()
|
||||
});
|
||||
let caret_x = |s: &mut Session| s.layout().caret(&at).expect("the empty list item's caret").x;
|
||||
for inherited in [false, true] {
|
||||
let mut doc = doc.clone();
|
||||
let props = &mut doc.para_mut(at.story, &at.path).unwrap().props;
|
||||
props.style = Some("NestedFixture".into());
|
||||
props.numbering = (!inherited).then_some(nested);
|
||||
props.indent_right = Some(12.0);
|
||||
props.space_after = Some(9.0);
|
||||
let mut expected = props.clone();
|
||||
expected.numbering = Some(promoted);
|
||||
|
||||
let mut control = Session::new(doc.clone());
|
||||
control.sel = crate::Selection::caret(at.clone());
|
||||
typ(&mut control, "\n");
|
||||
assert_eq!(control.doc.para_at(&at).unwrap().props, expected);
|
||||
let promoted_x = caret_x(&mut control);
|
||||
|
||||
for chars in [false, true] {
|
||||
let mut s = Session::new(doc.clone());
|
||||
s.sel = crate::Selection::caret(at.clone());
|
||||
let props = &mut s.doc.para_mut(at.story, &at.path).unwrap().props;
|
||||
if chars {
|
||||
props.indent_left_chars = Some(8.0);
|
||||
props.indent_first_chars = Some(-2.0);
|
||||
} else {
|
||||
props.indent_left = Some(144.0);
|
||||
props.indent_first = Some(-18.0);
|
||||
}
|
||||
let before = props.clone();
|
||||
let depth = s.undo_depth();
|
||||
typ(&mut s, "\n");
|
||||
|
||||
assert_eq!(s.doc.para_at(&at).unwrap().props, expected, "inherited={inherited}, chars={chars}");
|
||||
assert_eq!(caret_x(&mut s), promoted_x, "indent matches the new level without an override");
|
||||
assert_eq!(s.sel.focus, at);
|
||||
assert_eq!(s.undo_depth(), depth + 1);
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert_eq!(s.doc.para_at(&at).unwrap().props, before, "Undo restores both numbering and indentation");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// #2143: in a Word file whose list comes from the paragraph styles (List Number, List Number 2
|
||||
/// with `w:numPr` in styles.xml, none on the paragraphs), Enter on an empty nested item moves it
|
||||
/// up a level and then ends the list, as with direct numbering.
|
||||
@@ -2896,12 +2834,23 @@ fn typing_rtl_letters_into_an_empty_paragraph_makes_it_rtl() {
|
||||
#[test]
|
||||
fn select_all_then_delete_removes_tables() {
|
||||
let tables = |s: &Session| s.doc.body.iter().filter(|b| b.as_table().is_some()).count();
|
||||
// With the caret in a table, Select All grows the selection a step at a time (cell, row,
|
||||
// table, document; #1478): press it until the whole document is selected.
|
||||
let select_whole_document = |s: &mut Session| {
|
||||
for _ in 0..6 {
|
||||
let before = s.sel.clone();
|
||||
run(s, "select.all", json!({}));
|
||||
if s.sel == before {
|
||||
break;
|
||||
}
|
||||
}
|
||||
};
|
||||
for key in ["text.delete", "text.backspace"] {
|
||||
let mut s = typed("");
|
||||
run(&mut s, "insert.table", json!({"rows": 2, "cols": 2}));
|
||||
typ(&mut s, "cell");
|
||||
assert_eq!(tables(&s), 1);
|
||||
run(&mut s, "select.all", json!({}));
|
||||
select_whole_document(&mut s);
|
||||
run(&mut s, key, json!({}));
|
||||
assert_eq!(tables(&s), 0, "{key}: a table at the start of the document goes");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "", "{key}");
|
||||
@@ -2910,7 +2859,7 @@ fn select_all_then_delete_removes_tables() {
|
||||
run(&mut s, "insert.table", json!({"rows": 2, "cols": 2}));
|
||||
typ(&mut s, "cell");
|
||||
assert_eq!(tables(&s), 1);
|
||||
run(&mut s, "select.all", json!({}));
|
||||
select_whole_document(&mut s);
|
||||
run(&mut s, key, json!({}));
|
||||
assert_eq!(tables(&s), 0, "{key}: a table after text goes");
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "", "{key}");
|
||||
@@ -3649,7 +3598,6 @@ fn change_case_follows_turkic_case_mapping() {
|
||||
}
|
||||
// Other languages keep the Unicode default.
|
||||
let mut s = self::s();
|
||||
run(&mut s, "review.language", json!({"lang": "en-US", "default": true}));
|
||||
run(&mut s, "text.insert", json!({"text": "istanbul", "raw": true}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "title"}));
|
||||
@@ -3669,18 +3617,6 @@ fn change_case_follows_turkic_case_mapping() {
|
||||
run(&mut s, "format.changeCase", json!({"mode": mode}));
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), want, "mixed runs {mode}");
|
||||
}
|
||||
// Mixed runs tagged on selections within existing text: each run's own language decides.
|
||||
let mut s = self::s();
|
||||
run(&mut s, "text.insert", json!({"text": "IŞIK IŞIK", "raw": true}));
|
||||
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 0)}));
|
||||
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 5), "extend": true}));
|
||||
run(&mut s, "review.language", json!({"lang": "tr-TR"}));
|
||||
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 6)}));
|
||||
run(&mut s, "caret.set", json!({"pos": Pos::body(0, 11), "extend": true}));
|
||||
run(&mut s, "review.language", json!({"lang": "en-US"}));
|
||||
run(&mut s, "select.all", json!({}));
|
||||
run(&mut s, "format.changeCase", json!({"mode": "lower"}));
|
||||
assert_eq!(s.doc.plain_text(StoryRef::Body), "ışık işik", "mixed runs on selection");
|
||||
}
|
||||
|
||||
// Spelling as you type (#1552): the word being typed gets no red squiggle until the caret leaves
|
||||
@@ -4876,3 +4812,19 @@ fn enter_in_a_drop_cap_paragraph_makes_a_normal_paragraph() {
|
||||
assert_eq!(second.drop_cap_font, None, "{position}");
|
||||
}
|
||||
}
|
||||
|
||||
/// #8986: in top-to-bottom text Left/Right change line (lines stack leftwards), keeping the
|
||||
/// distance along the line, and stop at the first/last line of a table cell.
|
||||
#[test]
|
||||
fn arrows_in_vertical_text_change_line_and_stop_in_a_cell() {
|
||||
let mut d = wordcraft_doc::Document::from_text("abc\ndef");
|
||||
d.last_section.text_direction = wordcraft_doc::props::TextDirection::Down;
|
||||
let mut s = Session::new(d);
|
||||
s.sel = crate::Selection::caret(Pos::body(0, 1));
|
||||
run(&mut s, "caret.left", json!({}));
|
||||
assert_eq!(s.sel.focus, Pos::body(1, 1), "Left goes to the next, leftward line");
|
||||
run(&mut s, "caret.right", json!({}));
|
||||
assert_eq!(s.sel.focus, Pos::body(0, 1));
|
||||
run(&mut s, "caret.left", json!({"extend": true}));
|
||||
assert!(!s.sel.is_collapsed(), "Shift+Left extends over the line change");
|
||||
}
|
||||
|
||||
+12
-135
@@ -13,56 +13,14 @@ use crate::model::{FBlock, ListCounter, from_doc};
|
||||
#[cfg(test)]
|
||||
mod legacy_oracle_tests;
|
||||
|
||||
const UTF32_LE_BOM: &[u8] = &[0xFF, 0xFE, 0x00, 0x00];
|
||||
const UTF32_BE_BOM: &[u8] = &[0x00, 0x00, 0xFE, 0xFF];
|
||||
|
||||
fn utf32(b: &[u8], le: bool) -> String {
|
||||
let units: Vec<char> = b
|
||||
.as_chunks::<4>()
|
||||
.0
|
||||
.iter()
|
||||
.map(|c| {
|
||||
let u = if le { u32::from_le_bytes(*c) } else { u32::from_be_bytes(*c) };
|
||||
char::from_u32(u).unwrap_or('\u{FFFD}')
|
||||
})
|
||||
.collect();
|
||||
units.into_iter().collect()
|
||||
}
|
||||
|
||||
fn decode_utf32_bom(b: &[u8]) -> Option<String> {
|
||||
if let Some(rest) = b.strip_prefix(UTF32_LE_BOM) {
|
||||
return Some(utf32(rest, true));
|
||||
}
|
||||
b.strip_prefix(UTF32_BE_BOM).map(|rest| utf32(rest, false))
|
||||
}
|
||||
|
||||
// Detection is shared with the other Craft apps. WordCraft's `cp1252` and encoding_rs agree on
|
||||
// every byte (pinned by `legacy_oracle_tests`), so a Windows-1252 guess needs no local mapping.
|
||||
pub use craft_mime::detect::legacy;
|
||||
|
||||
/// Does `b` look like plain text ([`craft_mime::detect::is_text`])? A UTF-32 BOM counts as text.
|
||||
pub fn is_text(b: &[u8]) -> bool {
|
||||
b.starts_with(UTF32_LE_BOM) || b.starts_with(UTF32_BE_BOM) || craft_mime::detect::is_text(b)
|
||||
}
|
||||
|
||||
/// Decode text bytes: a UTF-32 BOM first, then [`craft_mime::detect::decode`] (other BOMs, UTF-16
|
||||
/// without BOM, UTF-8, the legacy encoding the bytes look like).
|
||||
pub fn decode(b: &[u8]) -> String {
|
||||
decode_utf32_bom(b).unwrap_or_else(|| craft_mime::detect::decode(b))
|
||||
}
|
||||
pub use craft_mime::detect::{decode, is_text, legacy};
|
||||
|
||||
/// Decode bytes in a named encoding (a WHATWG label such as `gbk`, `gb18030`, `big5`,
|
||||
/// `shift_jis`, `euc-kr`, `utf-16le`, `windows-1251`); `None` when the label isn't known.
|
||||
/// The generic `utf-32` label honors either BOM and defaults to little-endian without one.
|
||||
pub fn decode_as(b: &[u8], label: &str) -> Option<String> {
|
||||
let clean = label.trim().to_ascii_lowercase();
|
||||
match clean.as_str() {
|
||||
"utf-32" => return Some(decode_utf32_bom(b).unwrap_or_else(|| utf32(b, true))),
|
||||
"utf-32le" => return Some(utf32(b.strip_prefix(UTF32_LE_BOM).unwrap_or(b), true)),
|
||||
"utf-32be" => return Some(utf32(b.strip_prefix(UTF32_BE_BOM).unwrap_or(b), false)),
|
||||
_ => {}
|
||||
}
|
||||
let enc = encoding_rs::Encoding::for_label(clean.as_bytes())?;
|
||||
let enc = encoding_rs::Encoding::for_label(label.trim().as_bytes())?;
|
||||
Some(enc.decode(b).0.into_owned())
|
||||
}
|
||||
|
||||
@@ -70,7 +28,7 @@ pub fn decode_as(b: &[u8], label: &str) -> Option<String> {
|
||||
pub fn import(bytes: &[u8]) -> Document {
|
||||
let text = decode(bytes);
|
||||
let text = text.replace("\r\n", "\n").replace('\r', "\n");
|
||||
let clean: String = text.chars().filter(|c| !c.is_control() || matches!(c, '\n' | '\t' | '\u{000B}' | '\u{000C}' | '\u{000E}')).collect();
|
||||
let clean: String = text.chars().filter(|c| !c.is_control() || matches!(c, '\n' | '\t' | '\u{000C}')).collect();
|
||||
Document::from_text(&clean)
|
||||
}
|
||||
|
||||
@@ -99,23 +57,18 @@ fn blocks_text(blocks: &[FBlock], out: &mut Vec<String>, lists: &mut ListCounter
|
||||
}
|
||||
FBlock::Table(t) => {
|
||||
lists.reset();
|
||||
let cols = t.cols();
|
||||
for row in &t.rows {
|
||||
let mut cells: Vec<String> = Vec::new();
|
||||
for c in row {
|
||||
if c.covered || depth > 8 {
|
||||
cells.push(String::new());
|
||||
} else {
|
||||
let cells: Vec<String> = row
|
||||
.iter()
|
||||
.map(|c| {
|
||||
if depth > 8 {
|
||||
return String::new();
|
||||
}
|
||||
let mut v = Vec::new();
|
||||
blocks_text(&c.blocks, &mut v, &mut ListCounter::default(), depth + 1);
|
||||
let text = v.join(" ").split_whitespace().collect::<Vec<_>>().join(" ");
|
||||
cells.push(text);
|
||||
}
|
||||
for _ in 1..c.colspan.clamp(1, 63) {
|
||||
cells.push(String::new());
|
||||
}
|
||||
}
|
||||
cells.resize(cols, String::new());
|
||||
v.join(" ")
|
||||
})
|
||||
.collect();
|
||||
out.push(cells.join("\t"));
|
||||
}
|
||||
}
|
||||
@@ -133,79 +86,3 @@ pub fn export(doc: &Document) -> Vec<u8> {
|
||||
blocks_text(&flow.blocks, &mut lines, &mut ListCounter::default(), 0);
|
||||
lines.join("\r\n").into_bytes()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::model::{Cell, Fmt, Para};
|
||||
use wordcraft_doc::StoryRef;
|
||||
|
||||
#[test]
|
||||
fn test_utf32_bom_decode_and_sniffing() {
|
||||
let mut u32le = vec![0xFF, 0xFE, 0x00, 0x00];
|
||||
for c in "Hello 🦀".chars() {
|
||||
u32le.extend((c as u32).to_le_bytes());
|
||||
}
|
||||
assert!(is_text(&u32le));
|
||||
assert_eq!(decode(&u32le), "Hello 🦀");
|
||||
assert_eq!(decode_as(&u32le, "utf-32"), Some("Hello 🦀".into()));
|
||||
assert_eq!(decode_as(&u32le, "utf-32le"), Some("Hello 🦀".into()));
|
||||
assert_eq!(decode_as(&u32le[4..], "utf-32"), Some("Hello 🦀".into()));
|
||||
|
||||
let mut u32be = vec![0x00, 0x00, 0xFE, 0xFF];
|
||||
for c in "World 🌍".chars() {
|
||||
u32be.extend((c as u32).to_be_bytes());
|
||||
}
|
||||
assert!(is_text(&u32be));
|
||||
assert_eq!(decode(&u32be), "World 🌍");
|
||||
assert_eq!(decode_as(&u32be, "utf-32"), Some("World 🌍".into()));
|
||||
assert_eq!(decode_as(&u32be, "utf-32be"), Some("World 🌍".into()));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_import_preserves_soft_breaks() {
|
||||
let raw = b"Line 1\x0BSoft break\x0ECol break";
|
||||
let doc = import(raw);
|
||||
let text = doc.plain_text(StoryRef::Body);
|
||||
assert_eq!(text, "Line 1\u{000B}Soft break\u{000E}Col break");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_table_export_colspan_covered_and_newline_cleaning() {
|
||||
let mut t = crate::model::FTable::default();
|
||||
let mut c1 = Cell { colspan: 2, ..Default::default() };
|
||||
let mut p1 = Para::default();
|
||||
p1.push_text("Merged\nHeader\tItem", &Fmt::default());
|
||||
c1.blocks.push(FBlock::Para(p1));
|
||||
|
||||
let mut c2 = Cell::default();
|
||||
let mut p2 = Para::default();
|
||||
p2.push_text("Col 3", &Fmt::default());
|
||||
c2.blocks.push(FBlock::Para(p2));
|
||||
|
||||
let c3 = Cell { covered: true, ..Default::default() };
|
||||
|
||||
let mut c4 = Cell::default();
|
||||
let mut p4 = Para::default();
|
||||
p4.push_text("Row 2 Col 2", &Fmt::default());
|
||||
c4.blocks.push(FBlock::Para(p4));
|
||||
|
||||
let mut c5 = Cell::default();
|
||||
let mut p5 = Para::default();
|
||||
p5.push_text("Row 2 Col 3", &Fmt::default());
|
||||
c5.blocks.push(FBlock::Para(p5));
|
||||
|
||||
t.rows.push(vec![c1, c2]);
|
||||
t.rows.push(vec![c3, c4, c5]);
|
||||
|
||||
let mut out = Vec::new();
|
||||
let blocks = vec![FBlock::Table(t)];
|
||||
blocks_text(&blocks, &mut out, &mut ListCounter::default(), 0);
|
||||
|
||||
assert_eq!(out.len(), 2);
|
||||
// Row 1: Merged Header Item (colspan 2) -> "Merged Header Item\t\tCol 3"
|
||||
assert_eq!(out[0], "Merged Header Item\t\tCol 3");
|
||||
// Row 2: Covered cell is empty -> "\tRow 2 Col 2\tRow 2 Col 3"
|
||||
assert_eq!(out[1], "\tRow 2 Col 2\tRow 2 Col 3");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
use super::ctx::{Ctx, Joining, page_anchored};
|
||||
use super::floats::{
|
||||
AnchoredFloat, AreaKind, ObjFrame, ObjectPlacement, WrapArea, align_in, float_rect, floating, left_out_objects, place_objects, rel_exclusions,
|
||||
wrap_area,
|
||||
AnchoredFloat, ObjFrame, ObjectPlacement, WrapArea, align_in, float_rect, floating, left_out_objects, place_objects, rel_exclusions, wrap_area,
|
||||
};
|
||||
use super::flow::again;
|
||||
use super::page::PageFrame;
|
||||
@@ -163,11 +162,11 @@ fn layout_table_block(input: TableBlockContext<'_, '_, '_>) -> bool {
|
||||
Some(float) => {
|
||||
let place = FloatPlace { shift: table::float_offset_shift(ctx, t), modern: ctx.doc.settings.compat_mode >= 15 };
|
||||
let (rect, area) = box_float_table_rect(frame, width, *y, &layout, &float, place, float_tables);
|
||||
exclusions.push((area, false, None, WrapText::BothSides, AreaKind::Table));
|
||||
exclusions.push((area, false, None, WrapText::BothSides, true));
|
||||
float_tables.push(area);
|
||||
table_areas.push(area);
|
||||
if float.v_rel == Anchor::Page {
|
||||
page_table_wraps.push((area, false, None, WrapText::BothSides, AreaKind::Table));
|
||||
page_table_wraps.push((area, false, None, WrapText::BothSides, true));
|
||||
}
|
||||
(rect.x, rect.y)
|
||||
}
|
||||
@@ -813,7 +812,7 @@ impl Joint {
|
||||
let probe = again(ctx, eq, |ctx| ctx.para_labelled(q, width, table, &[], 0.0, None));
|
||||
let (gap, height) = probe.lines.first().map_or((0.0, self.height), |l| ((self.baseline - (l.baseline - l.top)).max(0.0), l.height));
|
||||
let rect = Rect::new(self.left, self.top, (self.end - self.left).max(0.0), (gap + height - 0.01).max(0.01));
|
||||
let mut areas = vec![(rect, false, None, WrapText::Right, AreaKind::Object)];
|
||||
let mut areas = vec![(rect, false, None, WrapText::Right, false)];
|
||||
// Just below the first row as the line breaker tests it: the breaker tests every row at
|
||||
// its estimate (`row_est`), not at the line's height, so the first row never meets this
|
||||
// area and every later row, starting lower, does and moves below it. The probe's own first
|
||||
@@ -821,7 +820,7 @@ impl Joint {
|
||||
// line), so its height can't be used here.
|
||||
let below = self.top + gap + probe.row_est + 0.01;
|
||||
if self.bottom() > below {
|
||||
areas.push((Rect::new(self.left, below, width.max(0.01), self.bottom() - below), true, None, WrapText::BothSides, AreaKind::Object));
|
||||
areas.push((Rect::new(self.left, below, width.max(0.01), self.bottom() - below), true, None, WrapText::BothSides, false));
|
||||
}
|
||||
(gap, areas)
|
||||
}
|
||||
|
||||
@@ -117,20 +117,8 @@ pub(crate) fn align_in((start, extent): (f32, f32), offset: f32, size: f32, alig
|
||||
|
||||
/// An area text keeps clear of: its bounds, whether text may only go above and below it, and
|
||||
/// (Tight and Through wrapping) the outline text follows inside it, the sides text may go on,
|
||||
/// and what it comes from (a floating table: inclusive line-bottom contact, #3977; Tight and
|
||||
/// Through wrapping: a narrower gap beside it before Word 2013 layout, #6316).
|
||||
pub(crate) type WrapArea = (Rect, bool, Option<Arc<contour::Contour>>, WrapText, AreaKind);
|
||||
|
||||
/// What a [`WrapArea`] keeps text clear of.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum AreaKind {
|
||||
/// A floating picture, shape, text box or chart wrapped Square or Top and Bottom.
|
||||
Object,
|
||||
/// A floating object wrapped Tight or Through, with or without an outline.
|
||||
Tight,
|
||||
/// A floating table.
|
||||
Table,
|
||||
}
|
||||
/// and whether it comes from a floating table (inclusive line-bottom contact, #3977).
|
||||
pub(crate) type WrapArea = (Rect, bool, Option<Arc<contour::Contour>>, WrapText, bool);
|
||||
|
||||
/// Wrap areas a page starts with (#2048): by page index, the floating objects (block, object
|
||||
/// index) placed above the top of their anchor paragraph, with text before it on the page, and
|
||||
@@ -222,14 +210,13 @@ pub(crate) fn wrap_area(r: Rect, float: &Float, outline: Option<&[(f32, f32)]>)
|
||||
if matches!(float.wrap, Wrap::Tight | Wrap::Through)
|
||||
&& let Some((area, c)) = outline.and_then(|o| contour::contour_area(r, float, o))
|
||||
{
|
||||
return Some((area, false, Some(Arc::new(c)), float.wrap_text, AreaKind::Tight));
|
||||
return Some((area, false, Some(Arc::new(c)), float.wrap_text, false));
|
||||
}
|
||||
let d = |v: f32| if v.is_finite() { v.clamp(0.0, 1584.0) } else { 0.0 };
|
||||
let (side, top, bottom) = (d(float.dist), d(float.dist_top), d(float.dist_bottom));
|
||||
// A rotated object keeps text clear of its rotated bounds.
|
||||
let r = float.spin().bounds(r);
|
||||
let kind = if matches!(float.wrap, Wrap::Tight | Wrap::Through) { AreaKind::Tight } else { AreaKind::Object };
|
||||
Some((Rect::new(r.x - side, r.y - top, r.w + side * 2.0, r.h + top + bottom), float.wrap == Wrap::TopAndBottom, None, float.wrap_text, kind))
|
||||
Some((Rect::new(r.x - side, r.y - top, r.w + side * 2.0, r.h + top + bottom), float.wrap == Wrap::TopAndBottom, None, float.wrap_text, false))
|
||||
}
|
||||
|
||||
/// Wrap areas relative to a paragraph whose column starts at `x0` and whose top is `y0`, with
|
||||
@@ -237,7 +224,7 @@ pub(crate) fn wrap_area(r: Rect, float: &Float, outline: Option<&[(f32, f32)]>)
|
||||
pub(crate) fn rel_exclusions(excl: &[WrapArea], x0: f32, y0: f32, space_before: f32) -> Vec<para::Exclusion> {
|
||||
let before = if space_before > 0.0 { space_before } else { 0.0 };
|
||||
excl.iter()
|
||||
.map(|(r, tb, c, side, kind)| para::Exclusion {
|
||||
.map(|(r, tb, c, side, table)| para::Exclusion {
|
||||
top: r.y - y0,
|
||||
bottom: r.bottom() - y0,
|
||||
left: r.x - x0,
|
||||
@@ -245,8 +232,7 @@ pub(crate) fn rel_exclusions(excl: &[WrapArea], x0: f32, y0: f32, space_before:
|
||||
top_bottom: *tb,
|
||||
contour: c.clone(),
|
||||
side: *side,
|
||||
table: *kind == AreaKind::Table,
|
||||
tight: *kind == AreaKind::Tight,
|
||||
table: *table,
|
||||
})
|
||||
// Top-and-Bottom areas ending within the paragraph's applied space before can still take
|
||||
// room, with that space laid out again below them (#7143). Any ending at or above it
|
||||
|
||||
@@ -1332,7 +1332,7 @@ mod tests {
|
||||
pb.cap_columns();
|
||||
// A preceding floating object leaves a narrow strip of the first column, but does
|
||||
// not occupy the second column. The same kept paragraph fits there in one line.
|
||||
pb.excl.push((Rect::new(pb.col_x(), top, pb.col_w() - 26.0, 100.0), false, None, WrapText::BothSides, crate::floats::AreaKind::Object));
|
||||
pb.excl.push((Rect::new(pb.col_x(), top, pb.col_w() - 26.0, 100.0), false, None, WrapText::BothSides, false));
|
||||
place_para_in_flow(ctx, pb, p, 0, top);
|
||||
|
||||
assert_eq!(pb.pages.len(), 1, "a fitting candidate kept the balance attempt on its page");
|
||||
|
||||
+28
-15
@@ -801,25 +801,38 @@ impl DocLayout {
|
||||
/// caret's flow on the page.
|
||||
pub fn turned_line(&self, pos: &Pos, goal: Option<f32>, next: bool, page_hint: usize) -> Option<(Pos, f32)> {
|
||||
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 flow = |pi: usize| -> Option<Vec<(&Path, &std::sync::Arc<ParaLayout>, usize)>> {
|
||||
Some(
|
||||
items_of(self.pages.get(pi)?, 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 = flow(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)? })?;
|
||||
// Past the page's first/last line, the flow goes on at the adjacent page's last/first.
|
||||
let target = if next { lines.get(here + 1).copied() } else { here.checked_sub(1).and_then(|i| lines.get(i).copied()) }.or_else(|| {
|
||||
let other = flow(if next { c.page + 1 } else { c.page.checked_sub(1)? })?;
|
||||
if next { other.first().copied() } else { other.last().copied() }
|
||||
});
|
||||
let (path, para, li) = target?;
|
||||
let gx = match goal {
|
||||
Some(g) => g,
|
||||
None => lines[here].1.x_of(lines[here].2, pos.off)?,
|
||||
None => {
|
||||
let x = lines[here].1.x_of(lines[here].2, pos.off)?;
|
||||
lines[here].1.caret_limit(lines[here].2).map_or(x, |m| x.min(m))
|
||||
}
|
||||
};
|
||||
let off = para.off_at_x(*li, gx);
|
||||
Some((Pos { story: pos.story, path: (*path).clone(), off }, gx))
|
||||
let off = para.off_at_x(li, gx);
|
||||
Some((Pos { story: pos.story, path: path.clone(), off }, gx))
|
||||
}
|
||||
|
||||
/// The position one line up (`dir < 0`) or down from `pos`, keeping `goal_x` (page x).
|
||||
|
||||
@@ -173,9 +173,6 @@ pub struct Exclusion {
|
||||
pub side: WrapText,
|
||||
/// A floating table counts a line touching its top as overlapping; shapes do not (#3977).
|
||||
pub table: bool,
|
||||
/// Tight and Through wrapping: before Word 2013 layout text goes in a narrower gap beside
|
||||
/// it (#6316).
|
||||
pub tight: bool,
|
||||
}
|
||||
|
||||
impl Exclusion {
|
||||
|
||||
+18
-118
@@ -30,9 +30,6 @@ struct Breaker<'e> {
|
||||
/// Word 2013+ (compatibility mode 15) fits more text on a justified line by shrinking its
|
||||
/// spaces (`space_room`); on a line with tabs, only the spaces after a final left/default tab.
|
||||
shrink_spaces: bool,
|
||||
/// Word 2013+ layout (compatibility mode 15): the narrowest span beside a Tight or Through
|
||||
/// object is the same as beside any other ([`min_span`]).
|
||||
layout_2013: bool,
|
||||
/// Word 2003's indent rules (`w:doNotSuppressIndentation`) before Word 2013's layout, for an
|
||||
/// unnumbered paragraph: a row starts right after a floating object before the indent.
|
||||
tight_indent: bool,
|
||||
@@ -211,7 +208,6 @@ impl<'e> Breaker<'e> {
|
||||
hanging_at: if rp.indent_first < 0.0 { Some(rp.indent_left) } else { None },
|
||||
tab_origin: if settings.odf.is_some_and(|o| o.tabs_from_indent) { rp.indent_left } else { 0.0 },
|
||||
shrink_spaces: rp.align == Align::Justify && settings.compat_mode >= wordcraft_doc::COMPAT_MODE_CURRENT,
|
||||
layout_2013: settings.compat_mode >= wordcraft_doc::COMPAT_MODE_CURRENT,
|
||||
tight_indent: settings.do_not_suppress_indentation
|
||||
&& settings.compat_mode < wordcraft_doc::COMPAT_MODE_CURRENT
|
||||
&& level.is_none()
|
||||
@@ -299,9 +295,7 @@ impl<'e> Breaker<'e> {
|
||||
}
|
||||
}
|
||||
let row = (self.top, self.est_h, self.table_h);
|
||||
match row_spans(self.exclusions, row, (lo, self.base_right), self.tight_indent, self.layout_2013)
|
||||
.map(|mut spans| (spans.pop_front(), spans))
|
||||
{
|
||||
match row_spans(self.exclusions, row, (lo, self.base_right), self.tight_indent).map(|mut spans| (spans.pop_front(), spans)) {
|
||||
Ok((Some((a, b)), rest)) => {
|
||||
// Under Word 2003's indent rules a row can start left of the indent too.
|
||||
let moved = if self.tight_indent { (a - lo).abs() > 0.01 } else { a > lo };
|
||||
@@ -1196,28 +1190,10 @@ fn line_end_kern(pl: &ParaLayout, j: usize) -> f32 {
|
||||
}
|
||||
}
|
||||
|
||||
/// Narrowest span text flows into beside a floating table, points. Word puts an empty
|
||||
/// Narrowest span text flows into beside a floating object, points. Word puts an empty
|
||||
/// paragraph beside a floating table in a 21.3pt gap but not in an 18.6pt one.
|
||||
const MIN_SPAN: f32 = 20.0;
|
||||
|
||||
/// Narrowest span text flows into beside a floating picture or shape, points: Word puts a line
|
||||
/// in an 18pt gap to its wrap area but not in a 17.95pt one, for square, tight and through
|
||||
/// wrapping alike, whatever the text (#6316).
|
||||
const MIN_SPAN_OBJECT: f32 = 18.0;
|
||||
|
||||
/// Tight and Through wrapping before Word 2013 layout (compatibility mode 14 and below) need
|
||||
/// only half that: 9pt fits, 8.95pt doesn't.
|
||||
const MIN_SPAN_CONTOUR_OLD: f32 = 9.0;
|
||||
|
||||
/// The narrowest span text goes into beside `e`, with Word 2013 layout or later (`current`).
|
||||
fn min_span(e: &Exclusion, current: bool) -> f32 {
|
||||
match (e.table, e.tight) {
|
||||
(true, _) => MIN_SPAN,
|
||||
(false, true) if !current => MIN_SPAN_CONTOUR_OLD,
|
||||
_ => MIN_SPAN_OBJECT,
|
||||
}
|
||||
}
|
||||
|
||||
/// Where a row starts under Word 2003's indent rules: right after the floating objects that end
|
||||
/// at or before the indent `lo` on this row and let text past their right side (their outline's
|
||||
/// right edge for Tight and Through wrapping), never left of the paragraph's own left edge (0) or
|
||||
@@ -1248,18 +1224,16 @@ fn baseline_offset(spacing: LineSpacing, asc: f32, height: f32, desc: f32) -> f3
|
||||
}
|
||||
|
||||
/// The spans of a row at `top` (about `h` tall) between `lo` and `hi` that text can use around
|
||||
/// the exclusions, left to right (Square wrapping uses both sides of an object); a span must be
|
||||
/// as wide as the minimum of each object it borders (`current`: Word 2013 layout or later).
|
||||
/// `Err(y)`: none here, try again at `y` (below what's in the way). With `tight_indent` (Word
|
||||
/// 2003's indent rules, `w:doNotSuppressIndentation`) a row starts right after a floating object
|
||||
/// that ends before `lo`, the indent ignored (ECMA-376 Part 4 §14.8.3.12: a paragraph indented
|
||||
/// 1" tightly wraps an object at 0.25").
|
||||
/// the exclusions, left to right (Square wrapping uses both sides of an object). `Err(y)`: none
|
||||
/// here, try again at `y` (below what's in the way). With `tight_indent` (Word 2003's indent
|
||||
/// rules, `w:doNotSuppressIndentation`) a row starts right after a floating object that ends
|
||||
/// before `lo`, the indent ignored (ECMA-376 Part 4 §14.8.3.12: a paragraph indented 1" tightly
|
||||
/// wraps an object at 0.25").
|
||||
fn row_spans(
|
||||
exclusions: &[Exclusion],
|
||||
(top, h, table_h): (f32, f32, f32),
|
||||
(lo, hi): (f32, f32),
|
||||
tight_indent: bool,
|
||||
current: bool,
|
||||
) -> Result<VecDeque<(f32, f32)>, f32> {
|
||||
let lo = if tight_indent { tight_row_start(exclusions, (top, h, table_h), lo) } else { lo };
|
||||
let here: Vec<&Exclusion> = exclusions.iter().filter(|e| e.intersects_row(top, h, table_h, lo, hi)).collect();
|
||||
@@ -1267,14 +1241,13 @@ fn row_spans(
|
||||
return Err(below);
|
||||
}
|
||||
// What each object takes of the row: its whole area, or (Tight, Through) the stretches its
|
||||
// outline takes, as (left, right, bottom of the object's area, the narrowest span beside it).
|
||||
let mut taken: Vec<(f32, f32, f32, f32)> = Vec::new();
|
||||
// outline takes, as (left, right, bottom of the object's area).
|
||||
let mut taken: Vec<(f32, f32, f32)> = Vec::new();
|
||||
for e in &here {
|
||||
let first = taken.len();
|
||||
let min = min_span(e, current);
|
||||
match &e.contour {
|
||||
None => taken.push((e.left, e.right, e.bottom, min)),
|
||||
Some(c) => taken.extend(c.occupied(top - e.top, top + h - e.top).into_iter().map(|(a, b)| (a + e.left, b + e.left, e.bottom, min))),
|
||||
None => taken.push((e.left, e.right, e.bottom)),
|
||||
Some(c) => taken.extend(c.occupied(top - e.top, top + h - e.top).into_iter().map(|(a, b)| (a + e.left, b + e.left, e.bottom))),
|
||||
}
|
||||
// Text on one side only: the object's other side of the row is taken too.
|
||||
let Some(mine) = taken.get(first..).filter(|t| !t.is_empty() && !e.side.is_both()) else { continue };
|
||||
@@ -1287,96 +1260,23 @@ fn row_spans(
|
||||
_ => left - lo >= hi - right,
|
||||
};
|
||||
taken.truncate(first);
|
||||
taken.push(if text_left { (left, hi.max(right), e.bottom, min) } else { (lo.min(left), right, e.bottom, min) });
|
||||
taken.push(if text_left { (left, hi.max(right), e.bottom) } else { (lo.min(left), right, e.bottom) });
|
||||
}
|
||||
taken.retain(|(l, r, _, _)| *r > lo && *l < hi);
|
||||
taken.retain(|(l, r, _)| *r > lo && *l < hi);
|
||||
if taken.is_empty() {
|
||||
return Ok(VecDeque::from([(lo, hi)]));
|
||||
}
|
||||
// Each span with the minimum of what borders it on the left and on the right (nothing at the
|
||||
// row's ends): an object cutting a span becomes the new edge of both pieces, and an object
|
||||
// ending right at a span's edge borders it too, the larger minimum winning (a picture and a
|
||||
// table both ending at 70: the span after them needs the table's).
|
||||
let mut spans = vec![(lo, hi, 0.0_f32, 0.0_f32)];
|
||||
for &(left, right, _, min) in &taken {
|
||||
let mut spans = vec![(lo, hi)];
|
||||
for &(left, right, _) in &taken {
|
||||
spans = spans
|
||||
.into_iter()
|
||||
.flat_map(|(a, b, ml, mr)| {
|
||||
if right <= a || left >= b {
|
||||
let ml = if (right - a).abs() < 0.01 { ml.max(min) } else { ml };
|
||||
let mr = if (left - b).abs() < 0.01 { mr.max(min) } else { mr };
|
||||
vec![(a, b, ml, mr)]
|
||||
} else {
|
||||
vec![(a, left.min(b), ml, min), (right.max(a), b, min, mr)]
|
||||
}
|
||||
})
|
||||
.flat_map(|(a, b)| if right <= a || left >= b { vec![(a, b)] } else { vec![(a, left.min(b)), (right.max(a), b)] })
|
||||
.collect();
|
||||
}
|
||||
let spans: VecDeque<(f32, f32)> = spans.into_iter().filter(|(a, b, ml, mr)| b - a >= ml.max(*mr)).map(|(a, b, ..)| (a, b)).collect();
|
||||
spans.retain(|(a, b)| b - a >= MIN_SPAN);
|
||||
if spans.is_empty() {
|
||||
// Nothing wide enough: the line goes below the first object that ends.
|
||||
return Err(taken.iter().map(|t| t.2).reduce(f32::min).unwrap_or(top));
|
||||
}
|
||||
Ok(spans)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// An exclusion from the row's left edge to `right`, 100pt tall.
|
||||
fn area(right: f32, table: bool, tight: bool) -> Exclusion {
|
||||
Exclusion { top: 0.0, bottom: 100.0, left: 0.0, right, top_bottom: false, contour: None, side: WrapText::BothSides, table, tight }
|
||||
}
|
||||
|
||||
/// Whether a line at the top of a 100pt row finds a span `gap` points wide beside `e`.
|
||||
fn fits(e: Exclusion, gap: f32, current: bool) -> bool {
|
||||
let hi = e.right + gap;
|
||||
row_spans(&[e], (0.0, 12.0, 12.0), (0.0, hi), false, current).is_ok()
|
||||
}
|
||||
|
||||
/// #6316: 18pt beside pictures and shapes; Tight and Through 9pt before Word 2013 layout;
|
||||
/// floating tables keep 20.
|
||||
#[test]
|
||||
fn the_narrowest_span_depends_on_the_object() {
|
||||
for current in [true, false] {
|
||||
assert!(fits(area(50.0, false, false), 18.0, current) && !fits(area(50.0, false, false), 17.9, current));
|
||||
assert!(fits(area(50.0, true, false), 20.0, current) && !fits(area(50.0, true, false), 19.9, current));
|
||||
}
|
||||
assert!(fits(area(50.0, false, true), 18.0, true) && !fits(area(50.0, false, true), 17.9, true));
|
||||
assert!(fits(area(50.0, false, true), 9.0, false) && !fits(area(50.0, false, true), 8.9, false));
|
||||
// A span between a picture and a table needs the table's 20.
|
||||
let both = |gap: f32| {
|
||||
let table = Exclusion { left: 50.0 + gap, right: 300.0, ..area(0.0, true, false) };
|
||||
row_spans(&[area(50.0, false, false), table], (0.0, 12.0, 12.0), (0.0, 300.0), false, true).is_ok()
|
||||
};
|
||||
assert!(both(20.0) && !both(19.9));
|
||||
// A span bordered only by a picture needs 18, whichever order the objects come in, also
|
||||
// when a table cut the span first (a table at 0..70, a picture at 80..100, a 19pt span
|
||||
// right of the picture).
|
||||
let table = area(70.0, true, false);
|
||||
let picture = Exclusion { left: 80.0, right: 100.0, ..area(0.0, false, false) };
|
||||
for order in [[table.clone(), picture.clone()], [picture.clone(), table.clone()]] {
|
||||
let spans = row_spans(&order, (0.0, 12.0, 12.0), (0.0, 119.0), false, true);
|
||||
assert_eq!(spans, Ok(VecDeque::from([(100.0, 119.0)])), "{order:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A picture and a table ending at the same edge: the span after them needs the table's 20,
|
||||
/// whichever comes first, and on the other side too.
|
||||
#[test]
|
||||
fn objects_sharing_an_edge_need_the_larger_minimum() {
|
||||
let row = (0.0, 12.0, 12.0);
|
||||
let (picture, table) = (area(70.0, false, false), area(70.0, true, false));
|
||||
for order in [[picture.clone(), table.clone()], [table.clone(), picture.clone()]] {
|
||||
assert!(row_spans(&order, row, (0.0, 89.0), false, true).is_err(), "19pt: {order:?}");
|
||||
assert_eq!(row_spans(&order, row, (0.0, 90.0), false, true), Ok(VecDeque::from([(70.0, 90.0)])), "20pt: {order:?}");
|
||||
}
|
||||
let picture = Exclusion { left: 30.0, right: 100.0, ..picture };
|
||||
let table = Exclusion { left: 30.0, right: 100.0, ..table };
|
||||
for order in [[picture.clone(), table.clone()], [table.clone(), picture.clone()]] {
|
||||
assert!(row_spans(&order, row, (11.0, 100.0), false, true).is_err(), "19pt: {order:?}");
|
||||
assert_eq!(row_spans(&order, row, (10.0, 100.0), false, true), Ok(VecDeque::from([(10.0, 30.0)])), "20pt: {order:?}");
|
||||
}
|
||||
}
|
||||
Ok(spans.into())
|
||||
}
|
||||
|
||||
@@ -1775,10 +1775,7 @@ fn apply_cell_widths(t: &Table, grid: &mut [f32]) {
|
||||
grid.copy_from_slice(&widths);
|
||||
}
|
||||
|
||||
/// An autofit table whose width matches its complete point-width rows but not its grid takes the
|
||||
/// rows. Because `preferred_grid` fills in equal shares of `avail` when `tblGrid` is missing or
|
||||
/// has the wrong column count, this also covers tables with no usable grid whose width differs
|
||||
/// from `avail`: they take their column widths from the cells instead of equal shares.
|
||||
// An autofit table whose width matches its complete point-width rows but not its grid takes the rows.
|
||||
fn stale_grid_widths(t: &Table, grid: &[f32]) -> Option<Vec<f32>> {
|
||||
const WIDTH_EPSILON: f32 = 0.5;
|
||||
const EDGE_EPSILON: f32 = 0.01;
|
||||
@@ -2038,57 +2035,6 @@ mod width_tests {
|
||||
assert_eq!(grid, [100.0, 200.0, 250.0, 100.0], "a fixed table keeps its grid");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grid_before_row_keeps_grid() {
|
||||
let mut table = Table::new(2, 3, 300.0);
|
||||
for row in &mut table.rows {
|
||||
for cell in &mut row.cells {
|
||||
cell.props.width = Some(100.0);
|
||||
}
|
||||
}
|
||||
table.rows[1].props.grid_before = 1;
|
||||
table.grid = vec![150.0, 150.0, 150.0];
|
||||
table.props.width = Some(300.0);
|
||||
let mut grid = table.grid.clone();
|
||||
|
||||
apply_cell_widths(&table, &mut grid);
|
||||
assert_eq!(grid, [150.0, 150.0, 150.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn grid_after_row_keeps_grid() {
|
||||
let mut table = Table::new(2, 3, 300.0);
|
||||
for row in &mut table.rows {
|
||||
for cell in &mut row.cells {
|
||||
cell.props.width = Some(100.0);
|
||||
}
|
||||
}
|
||||
table.rows[1].props.grid_after = 1;
|
||||
table.grid = vec![150.0, 150.0, 150.0];
|
||||
table.props.width = Some(300.0);
|
||||
let mut grid = table.grid.clone();
|
||||
|
||||
apply_cell_widths(&table, &mut grid);
|
||||
assert_eq!(grid, [150.0, 150.0, 150.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn disagreeing_row_edges_keep_grid() {
|
||||
let mut table = Table::new(2, 3, 300.0);
|
||||
for (cell, width) in table.rows[0].cells.iter_mut().zip([100.0, 100.0, 100.0]) {
|
||||
cell.props.width = Some(width);
|
||||
}
|
||||
for (cell, width) in table.rows[1].cells.iter_mut().zip([120.0, 80.0, 100.0]) {
|
||||
cell.props.width = Some(width);
|
||||
}
|
||||
table.grid = vec![150.0, 150.0, 150.0];
|
||||
table.props.width = Some(300.0);
|
||||
let mut grid = table.grid.clone();
|
||||
|
||||
apply_cell_widths(&table, &mut grid);
|
||||
assert_eq!(grid, [150.0, 150.0, 150.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn autofit_keeps_fitting_widths() {
|
||||
crate::test_fonts();
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
use super::boxes::{BoxInput, clear_of_float_tables, layout_box};
|
||||
use super::ctx::{Ctx, with_pct_base};
|
||||
use super::floats::{AreaKind, WrapArea, align_in, body_wraps};
|
||||
use super::floats::{WrapArea, align_in, body_wraps};
|
||||
use super::flow::again;
|
||||
use super::headers::{begins_section, header_items_cap, header_table_areas, placed_cost};
|
||||
use super::notes::table_notes;
|
||||
@@ -435,7 +435,7 @@ fn place_floating_table(ctx: &mut Ctx, pb: &mut PageBuilder, tl: &table::TableLa
|
||||
pg.float_tables.push(Path::top(block));
|
||||
}
|
||||
let area = r.inset(-dl, -dt, -dr, -db);
|
||||
pb.excl.push((area, false, None, WrapText::BothSides, AreaKind::Table));
|
||||
pb.excl.push((area, false, None, WrapText::BothSides, true));
|
||||
pb.float_tables.push(area);
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -12574,68 +12574,6 @@ fn tight_wrap_follows_an_ellipse() {
|
||||
assert_eq!(through, tight);
|
||||
}
|
||||
|
||||
/// #6316: how many of seven empty paragraphs (the first anchoring a 200pt-tall rectangle at the
|
||||
/// column's left with `wrap`) go in the `free` points it leaves on its right (column edge to its
|
||||
/// wrap area, 9pt from text included), in compatibility mode `mode`.
|
||||
fn empty_lines_beside(wrap: wordcraft_doc::para::Wrap, free: f32, mode: u32) -> usize {
|
||||
use wordcraft_doc::para::{Anchor, Float, ShapeKind};
|
||||
let w = 468.0 - 9.0 - free;
|
||||
let mut d = Document::from_text("");
|
||||
d.settings.compat_mode = mode;
|
||||
let float = Float { wrap, h_rel: Anchor::Column, v_rel: Anchor::Paragraph, dist: 9.0, ..Default::default() };
|
||||
let shape = InlineObject::Shape {
|
||||
kind: ShapeKind::Rectangle,
|
||||
w,
|
||||
h: 200.0,
|
||||
fill: None,
|
||||
stroke: None,
|
||||
stroke_width: 1.0,
|
||||
float,
|
||||
story: None,
|
||||
effects: Default::default(),
|
||||
freeform: None,
|
||||
extra: Default::default(),
|
||||
};
|
||||
d.insert_object(&Pos::body(0, 0), shape, &Default::default()).unwrap();
|
||||
for i in 1..7 {
|
||||
d.insert_block(StoryRef::Body, &Path::top(i), wordcraft_doc::Block::Para(Default::default())).unwrap();
|
||||
}
|
||||
let l = lay(&d);
|
||||
let lines: Vec<(f32, f32)> =
|
||||
l.pages[0].items.iter().filter_map(|i| if let Placed::Lines { y, para, .. } = i { Some((para.lines[0].left, *y)) } else { None }).collect();
|
||||
let Some(top) = lines.iter().map(|l| l.1).reduce(f32::min) else { return 0 };
|
||||
lines.iter().filter(|(left, y)| *left >= w + 9.0 - 0.01 && *y < top + 200.0).count()
|
||||
}
|
||||
|
||||
/// #6316: Word puts a line beside a floating picture or shape when the gap between the column
|
||||
/// edge and the object's wrap area is at least 18pt, for square, tight and through wrapping; a
|
||||
/// tight-wrapped cover with 17.55 and 19.15pt gaps was pushed onto three pages by a 20pt minimum.
|
||||
#[test]
|
||||
fn text_goes_beside_a_float_in_an_18pt_gap() {
|
||||
crate::test_fonts();
|
||||
use wordcraft_doc::para::Wrap;
|
||||
let current = wordcraft_doc::COMPAT_MODE_CURRENT;
|
||||
for wrap in [Wrap::Square, Wrap::Tight, Wrap::Through] {
|
||||
assert_eq!(empty_lines_beside(wrap, 18.1, current), 7, "{wrap:?} 18.1");
|
||||
assert_eq!(empty_lines_beside(wrap, 17.9, current), 0, "{wrap:?} 17.9");
|
||||
}
|
||||
}
|
||||
|
||||
/// Before Word 2013 layout (mode 14 and below) a line goes beside a tight or through object in
|
||||
/// a 9pt gap; square wrapping still needs 18.
|
||||
#[test]
|
||||
fn tight_wrap_needs_only_9pt_beside_it_before_word_2013_layout() {
|
||||
crate::test_fonts();
|
||||
use wordcraft_doc::para::Wrap;
|
||||
for wrap in [Wrap::Tight, Wrap::Through] {
|
||||
assert_eq!(empty_lines_beside(wrap, 9.1, 14), 7, "{wrap:?} 9.1");
|
||||
assert_eq!(empty_lines_beside(wrap, 8.9, 14), 0, "{wrap:?} 8.9");
|
||||
assert_eq!(empty_lines_beside(wrap, 9.1, wordcraft_doc::COMPAT_MODE_CURRENT), 0, "{wrap:?} 9.1 in mode 15");
|
||||
}
|
||||
assert_eq!(empty_lines_beside(Wrap::Square, 17.9, 14), 0);
|
||||
assert_eq!(empty_lines_beside(Wrap::Square, 18.1, 14), 7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn contour_wrap_turns_with_the_object() {
|
||||
crate::test_fonts();
|
||||
|
||||
@@ -126,7 +126,6 @@ impl WordApp {
|
||||
applied_editing: None,
|
||||
frame_ms: 0.0,
|
||||
quit_requested: false,
|
||||
quit_recheck: false,
|
||||
autosave: true,
|
||||
zotero: zotero::ZoteroLink::default(),
|
||||
ctx: None,
|
||||
@@ -265,12 +264,8 @@ impl WordApp {
|
||||
if let Some(ctx) = self.ctx.clone() {
|
||||
self.run_fired(&ctx, &out);
|
||||
self.canvas.take_focus_after_pass(&ctx);
|
||||
// The zoom is context-wide but the display scale is per window: read it from the active
|
||||
// document window. The windowless root has no window, so it reports none (#8853).
|
||||
let active = self.active_viewport();
|
||||
let native_now = ctx.input_for(active, |i| i.viewport().native_pixels_per_point).or_else(|| ctx.native_pixels_per_point());
|
||||
self.native_scale = theme::usable_scale(native_now.unwrap_or(1.0));
|
||||
if let Some(native) = native_now
|
||||
self.native_scale = theme::usable_scale(ctx.native_pixels_per_point().unwrap_or(1.0));
|
||||
if let Some(native) = ctx.native_pixels_per_point()
|
||||
&& let Some(old) = self.legacy_interface_size.take()
|
||||
{
|
||||
self.ui.interface_size = theme::migrate_legacy_interface_size(old, native);
|
||||
|
||||
@@ -519,12 +519,7 @@ impl WordApp {
|
||||
return false;
|
||||
}
|
||||
if self.quit_requested {
|
||||
// A quit that found nothing unsaved: the close that ends it has committed the focused field's typed text,
|
||||
// which is asked about like any other change (#8790). Once only, so an answered prompt is not asked again.
|
||||
if !(std::mem::take(&mut self.quit_recheck) && self.has_unsaved_documents()) {
|
||||
return true;
|
||||
}
|
||||
self.quit_requested = false;
|
||||
return true;
|
||||
}
|
||||
// Nothing to save, also with no document open in this window (#1129) and none elsewhere.
|
||||
if !self.has_unsaved_documents() {
|
||||
|
||||
@@ -653,17 +653,13 @@ fn mark_areas(app: &mut WordApp, layout: &DocLayout, selected: &[(usize, wordcra
|
||||
areas
|
||||
}
|
||||
|
||||
/// The navigation options of WordCraft's canvas: the document wheel scheme, the document wheel notch
|
||||
/// ([`crate::scroll::NOTCH_PX`]), eased wheel scrolling when animations are enabled, and middle-click autoscroll
|
||||
/// where the platform has the gesture (not macOS, iOS or the web, whose middle button has its own meaning).
|
||||
fn navigation_options(animations: bool) -> NavigationOptions {
|
||||
/// The navigation options of WordCraft's canvas: the document wheel scheme, and middle-click autoscroll where the
|
||||
/// platform has the gesture (not macOS, iOS or the web, whose middle button has its own meaning).
|
||||
fn navigation_options() -> NavigationOptions {
|
||||
let mut options = NavigationOptions::default();
|
||||
options.middle_button =
|
||||
if cfg!(any(target_os = "macos", target_os = "ios", target_arch = "wasm32")) { MiddleButton::Pan } else { MiddleButton::AutoScroll };
|
||||
options.wheel = WheelScheme::Document;
|
||||
// Browsers report three lines per notch where native platforms report one.
|
||||
options.wheel_line = if cfg!(target_arch = "wasm32") { crate::scroll::NOTCH_PX / 3.0 } else { crate::scroll::NOTCH_PX };
|
||||
options.eased_wheel = animations;
|
||||
options
|
||||
}
|
||||
|
||||
@@ -866,12 +862,11 @@ fn show_pages(app: &mut WordApp, ui: &mut Ui, layout: &Arc<DocLayout>, full: Rec
|
||||
.into_iter()
|
||||
.filter(|(_, id)| !crate::app::command_board::command_enabled(app, id))
|
||||
.fold(EditSet::NONE, |set, (command, _)| set.with(command));
|
||||
let animations = app.animations_on();
|
||||
let out = PageView::new(tl!("Document"), &source, &mut state, paper)
|
||||
.options(options)
|
||||
// Hide White Space cuts each page to its text area: without the bodies the pages show whole.
|
||||
.bodies(&bodies)
|
||||
.navigation(navigation_options(animations))
|
||||
.navigation(navigation_options())
|
||||
.editor(craft::ui::primitives::EditorPurpose::Text)
|
||||
.inactive_edits(inactive_edits)
|
||||
.rulers(show_rulers)
|
||||
@@ -1059,12 +1054,7 @@ fn show_pages(app: &mut WordApp, ui: &mut Ui, layout: &Arc<DocLayout>, full: Rec
|
||||
app.canvas.mini_dismissed = None;
|
||||
}
|
||||
balloons::balloons(app, ui, &out, layout);
|
||||
if show_rulers {
|
||||
rulers::page_rulers(app, ui, &out, layout);
|
||||
} else if app.canvas.table_resize.as_ref().is_some_and(crate::table_resize::ResizeDrag::on_ruler) {
|
||||
// Hidden rulers can't finish a border drag they started: drop it with its preview.
|
||||
app.canvas.table_resize = None;
|
||||
}
|
||||
rulers::page_rulers(app, ui, &out, layout);
|
||||
// The one context-menu ask of the pass: Shift+F10 or `ui.contextMenu` (below the caret), a click on the equation
|
||||
// frame's options strip, then the tool host's own request by how it was asked for.
|
||||
let ask = app.canvas.context_request.take().or_else(|| strip_click.map(ContextAsk::AtPointer));
|
||||
|
||||
@@ -66,8 +66,6 @@ pub(crate) struct EquationFrameStyle {
|
||||
line: StyleColor,
|
||||
accent: StyleColor,
|
||||
soft: StyleColor,
|
||||
/// Behind the equation's text, so translucent: the argument the caret is in.
|
||||
shade: StyleColor,
|
||||
handle_fill: StyleColor,
|
||||
handle_stroke: StyleColor,
|
||||
}
|
||||
@@ -123,7 +121,6 @@ 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)),
|
||||
handle_fill: cx.color(t.color.overlay.handle_fill),
|
||||
handle_stroke: cx.color(t.color.overlay.handle_stroke),
|
||||
}
|
||||
@@ -163,7 +160,7 @@ impl Component for EquationFrameControl<'_> {
|
||||
let EquationFrame { outline, grip, strip } = equation_frame(self.page, self.bx, &style.sizes);
|
||||
let corner = CornerRadius::from(style.radius);
|
||||
if let Some(arg) = self.argument {
|
||||
draw.fill(&PaintShape::Rect(arg, CornerRadius::ZERO), style.shade);
|
||||
draw.fill(&PaintShape::Rect(arg, CornerRadius::ZERO), style.soft);
|
||||
}
|
||||
draw.fill(&PaintShape::Rect(strip, CornerRadius::ZERO), style.soft);
|
||||
let (c, w) = (strip.center(), style.chevron / 2.0);
|
||||
|
||||
@@ -300,10 +300,6 @@ impl CanvasTool for PageTextTool<'_> {
|
||||
if self.app.session.painter.is_some() {
|
||||
return Cursor::System(CursorIcon::Copy);
|
||||
}
|
||||
// Word: Ctrl/⌘ held over a link shows the hand, as a click there follows it.
|
||||
if pointer.mods.cmd && self.link_tip(pointer.pos).is_some() {
|
||||
return Cursor::System(CursorIcon::PointingHand);
|
||||
}
|
||||
text()
|
||||
}
|
||||
|
||||
|
||||
@@ -8,11 +8,9 @@ use crate::test_harness::AppFrames as _;
|
||||
use std::collections::HashSet;
|
||||
|
||||
/// Rests the pointer for as long as the framework's tooltip waits before it shows a tool's tip
|
||||
/// (`tooltip::DELAY`, the framework's look), at the harness's configured step time (`predicted_dt`).
|
||||
/// (`tooltip::DELAY`, the framework's look), at the harness's default step of a quarter second.
|
||||
fn rest_for_tip(h: &mut H) {
|
||||
let step_dt = f64::from(h.ctx.input(|i| i.predicted_dt));
|
||||
assert!(step_dt > 0.0, "harness step_dt must be positive, got {step_dt}");
|
||||
let frames = (craft::ui::contract::tooltip::DELAY / step_dt).ceil() as usize + 3;
|
||||
let frames = (craft::ui::contract::tooltip::DELAY / 0.25).ceil() as usize + 3;
|
||||
steps(h, frames);
|
||||
}
|
||||
|
||||
@@ -2901,67 +2899,3 @@ fn shift_clicking_a_picture_does_not_scroll_the_view() {
|
||||
assert!(picked.contains(&first) && picked.contains(&second), "both pictures are selected: {picked:?} {:?} at {at:?}", h.state().session.sel);
|
||||
assert_eq!(h.state().canvas.view.offset, before, "the view stayed where it was");
|
||||
}
|
||||
|
||||
/// 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]
|
||||
fn mouse_wheel_notch_scrolls_document_line_distance_and_accelerates_on_flick() {
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
a.run("text.insert", json!({"text": "lorem ipsum dolor sit amet consectetur ".repeat(2000)})).unwrap();
|
||||
a.run("caret.docStart", json!({})).unwrap();
|
||||
a.ui.animations = crate::theme::Animations::Off;
|
||||
let mut h = crate::test_harness::builder().with_size(egui::vec2(1280.0, 800.0)).with_step_dt(1.0 / 60.0).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
a,
|
||||
);
|
||||
steps(&mut h, 4);
|
||||
let center = h.state().canvas.view_rect().expect("the canvas laid out").center();
|
||||
let wheel = || egui::Event::MouseWheel {
|
||||
unit: egui::MouseWheelUnit::Line,
|
||||
delta: egui::vec2(0.0, -1.0),
|
||||
phase: egui::TouchPhase::Move,
|
||||
modifiers: egui::Modifiers::NONE,
|
||||
source: egui::MouseWheelSource::Wheel,
|
||||
};
|
||||
|
||||
// With animations off, one notch jumps the full document line distance in a single frame.
|
||||
let start_y = h.state().canvas.view.offset.1;
|
||||
h.event(egui::Event::PointerMoved(center));
|
||||
h.event(wheel());
|
||||
h.app_frame();
|
||||
let one_notch = h.state().canvas.view.offset.1 - start_y;
|
||||
assert!(
|
||||
(one_notch - f64::from(crate::scroll::NOTCH_PX)).abs() < 2.0,
|
||||
"one mouse-wheel notch should scroll ~{} pt, got {one_notch}",
|
||||
crate::scroll::NOTCH_PX
|
||||
);
|
||||
|
||||
// With animations on, a single notch eases to the same distance, and a rapid flick accelerates past it.
|
||||
h.state_mut().ui.animations = crate::theme::Animations::On;
|
||||
h.state_mut().canvas.view.offset.1 = 0.0;
|
||||
steps(&mut h, 4);
|
||||
let eased_start = h.state().canvas.view.offset.1;
|
||||
h.event(wheel());
|
||||
steps(&mut h, 30);
|
||||
let eased_notch = h.state().canvas.view.offset.1 - eased_start;
|
||||
assert!(
|
||||
(eased_notch - f64::from(crate::scroll::NOTCH_PX)).abs() < 2.0,
|
||||
"an eased notch should settle at ~{} pt, got {eased_notch}",
|
||||
crate::scroll::NOTCH_PX
|
||||
);
|
||||
|
||||
h.state_mut().canvas.view.offset.1 = 0.0;
|
||||
steps(&mut h, 30);
|
||||
let flick_start = h.state().canvas.view.offset.1;
|
||||
for _ in 0..5 {
|
||||
h.event(wheel());
|
||||
h.app_frame();
|
||||
}
|
||||
steps(&mut h, 40);
|
||||
let flicked = h.state().canvas.view.offset.1 - flick_start;
|
||||
assert!(flicked > 5.0 * eased_notch, "a rapid 5-notch flick ({flicked}) should accelerate past 5 single notches ({})", 5.0 * eased_notch);
|
||||
}
|
||||
|
||||
@@ -14,14 +14,7 @@ fn window(a: WordApp) -> H {
|
||||
/// [`window`] with a chosen step time (the time one frame adds), for gestures whose outcome
|
||||
/// depends on how long frames last.
|
||||
fn window_dt(a: WordApp, dt: Option<f32>) -> H {
|
||||
sized_window(a, egui::vec2(1440.0, 900.0), dt, 6)
|
||||
}
|
||||
|
||||
/// A harness around `a` in a window of `size`, with step time `dt` (the default when `None`),
|
||||
/// after `settle` frames: a smaller window and fewer frames keep a test that needs little of
|
||||
/// the window fast.
|
||||
fn sized_window(a: WordApp, size: egui::Vec2, dt: Option<f32>, settle: usize) -> H {
|
||||
let mut b = crate::test_harness::builder().with_size(size);
|
||||
let mut b = crate::test_harness::builder().with_size(egui::vec2(1440.0, 900.0));
|
||||
if let Some(dt) = dt {
|
||||
b = b.with_step_dt(dt);
|
||||
}
|
||||
@@ -33,7 +26,9 @@ fn sized_window(a: WordApp, size: egui::Vec2, dt: Option<f32>, settle: usize) ->
|
||||
},
|
||||
a,
|
||||
);
|
||||
steps(&mut h, settle);
|
||||
for _ in 0..6 {
|
||||
h.app_frame();
|
||||
}
|
||||
h
|
||||
}
|
||||
|
||||
@@ -267,17 +262,12 @@ fn ruler_tab_stops_are_set_moved_and_cleared_with_the_pointer() {
|
||||
|
||||
/// #1348: an app with one comment ("Original") on some text, its balloon on screen.
|
||||
fn comment_harness() -> (H, u32) {
|
||||
comment_harness_in(egui::vec2(1440.0, 900.0), 6)
|
||||
}
|
||||
|
||||
/// [`comment_harness`] in a window of `size`, after `settle` frames.
|
||||
fn comment_harness_in(size: egui::Vec2, settle: usize) -> (H, u32) {
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
a.run("text.insert", json!({"text": "Some text here"})).unwrap();
|
||||
a.run("select.text", json!({"text": "text"})).unwrap();
|
||||
let id = a.run("review.newComment", json!({"text": "Original"})).unwrap()["id"].as_u64().unwrap() as u32;
|
||||
a.run("view.commentsPane", json!({"value": false})).unwrap();
|
||||
(sized_window(a, size, Some(1.0 / 60.0), settle), id)
|
||||
(window_dt(a, Some(1.0 / 60.0)), id)
|
||||
}
|
||||
|
||||
/// Click comment `id`'s balloon (from no selected balloon): the card is selected with no edit open (as in Word), then
|
||||
@@ -418,24 +408,6 @@ fn a_refused_comment_edit_keeps_the_draft() {
|
||||
assert!(text.contains("Edited"), "the typed text survived the refusal: {text:?}");
|
||||
}
|
||||
|
||||
/// #1348: Escape in a balloon throws the draft away and shows the comment's text again, and leaving the field writes nothing.
|
||||
#[test]
|
||||
fn escape_reverts_a_comment_draft() {
|
||||
// No settle frames of its own (`click_balloon` settles before it clicks) keep the test fast. 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);
|
||||
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");
|
||||
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");
|
||||
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");
|
||||
}
|
||||
|
||||
/// #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]
|
||||
|
||||
@@ -252,14 +252,10 @@ fn cell_shading(table: &wordcraft_doc::Table, cells: impl IntoIterator<Item = (u
|
||||
agree(cells.into_iter().filter_map(|(r, c)| table.rows.get(r)?.cells.get(c).map(|cell| cell.props.shading)))
|
||||
}
|
||||
|
||||
/// The colour a target has now (the dialog's Current swatch).
|
||||
///
|
||||
/// Returns the colour already stored in `params` at the JSON pointer `at` first (used for targets
|
||||
/// such as gradient stops, so a non-null colour at `at` overrides reading the document). Otherwise
|
||||
/// reads from what its command changes: `para.shading` reads the selected text's shading when the
|
||||
/// selection is text within one paragraph, else the paragraphs'; `shape.effects` reads shapes only.
|
||||
/// `None` when it has none, is Automatic, differs across the selection, or cannot be read (a
|
||||
/// picture's icon colour is not stored).
|
||||
/// The colour a target has now (the dialog's Current swatch), read from what its command changes:
|
||||
/// `para.shading` reads the selected text's shading when the selection is text within one paragraph,
|
||||
/// else the paragraphs'; `shape.effects` reads shapes only. `None` when it has none, is Automatic,
|
||||
/// differs across the selection, or cannot be read (a picture's icon colour is not stored).
|
||||
fn current_of(app: &mut WordApp, target: &Target) -> Option<Rgb> {
|
||||
use wordcraft_doc::InlineObject;
|
||||
let Target::Run { cmd, params, at, .. } = target else { return None };
|
||||
|
||||
@@ -425,61 +425,3 @@ fn inspect_lists_recent_documents_as_full_paths() {
|
||||
let Reply::Done(r) = control::handle(&mut a, &installed(), &req) else { panic!("ui.inspect answers at once") };
|
||||
assert_eq!(r["result"]["ui"]["recent"], json!([full]), "{r}");
|
||||
}
|
||||
|
||||
/// Quit with a table title still typed in the focused Alt Text field: the root window's close (the built-in Quit)
|
||||
/// commits the draft and asks Save Changes; `ui.quit` (the app menu's Quit, ⌘Q, the Dock) must do the same (#8790),
|
||||
/// and asks only once: Don't Save quits.
|
||||
#[test]
|
||||
fn quit_commits_the_focused_fields_draft_before_asking() {
|
||||
use egui::accesskit::Role;
|
||||
use egui_kittest::kittest::Queryable;
|
||||
fn caption(a: &WordApp) -> Option<String> {
|
||||
let focus = &a.session.sel.focus;
|
||||
let (path, _, _) = focus.path.cell()?;
|
||||
a.session.doc.table(focus.story, &path)?.props.caption.clone()
|
||||
}
|
||||
fn typed_title() -> egui_kittest::Harness<'static, WordApp> {
|
||||
let mut a = app();
|
||||
a.run("insert.table", json!({"rows": 1, "cols": 1})).unwrap();
|
||||
a.session.dirty = false;
|
||||
a.session.view.alt_text_pane = true;
|
||||
let mut h = harness(a);
|
||||
h.get_by_role_and_label(Role::TextInput, "Title:").click();
|
||||
frames(&mut h, 2);
|
||||
h.get_by_role_and_label(Role::TextInput, "Title:").type_text("Prices");
|
||||
frames(&mut h, 2);
|
||||
assert!(!h.state().session.dirty && caption(h.state()).is_none(), "the title is still a draft in the focused field");
|
||||
h
|
||||
}
|
||||
fn host_close(h: &mut egui_kittest::Harness<'static, WordApp>) {
|
||||
h.input_mut().viewports.entry(egui::ViewportId::ROOT).or_default().events.push(egui::ViewportEvent::Close);
|
||||
frames(h, 6);
|
||||
}
|
||||
|
||||
// The root window's close, as the built-in Quit sent it.
|
||||
let mut h = typed_title();
|
||||
host_close(&mut h);
|
||||
let a = h.state();
|
||||
assert_eq!(prompt(a), Some("saveChanges"), "root close asks about the committed title");
|
||||
|
||||
// The app menu's Quit (⌘Q), then the close the host sends once `quit_requested` is set.
|
||||
let mut h = typed_title();
|
||||
h.state_mut().run("ui.quit", json!({})).unwrap();
|
||||
frames(&mut h, 2);
|
||||
host_close(&mut h);
|
||||
let a = h.state();
|
||||
assert!(
|
||||
prompt(a) == Some("saveChanges") && !a.quit_requested,
|
||||
"ui.quit lost the typed title: caption={:?} dirty={} quit_requested={}",
|
||||
caption(a),
|
||||
a.session.dirty,
|
||||
a.quit_requested
|
||||
);
|
||||
assert_eq!(caption(a).as_deref(), Some("Prices"), "the prompt is about the committed title");
|
||||
|
||||
// Don't Save answers the quit: it is not asked again, though the last document stays open and modified.
|
||||
h.state_mut().run("ui.saveChanges", json!({"answer": "dontSave"})).unwrap();
|
||||
assert!(h.state().quit_requested, "Don't Save quits");
|
||||
host_close(&mut h);
|
||||
assert!(h.state().quit_requested && prompt(h.state()).is_none(), "the answered quit is not asked about again");
|
||||
}
|
||||
|
||||
@@ -167,7 +167,7 @@ pub fn field_kind(name: &str) -> FieldKind {
|
||||
pub struct FieldForm {
|
||||
pub category: String,
|
||||
pub name: String,
|
||||
/// `\@` picture for date fields. Empty uses the field language's default.
|
||||
/// `\@` picture for date fields.
|
||||
pub date_format: String,
|
||||
/// `\*` value for number fields (empty = none).
|
||||
pub number_format: String,
|
||||
@@ -206,7 +206,7 @@ impl FieldForm {
|
||||
let mut f = FieldForm {
|
||||
category: FIELD_CATEGORIES.first().copied().unwrap_or("(All)").to_string(),
|
||||
name: "DATE".into(),
|
||||
date_format: String::new(),
|
||||
date_format: DATE_FORMATS.first().copied().unwrap_or("M/d/yyyy").to_string(),
|
||||
number_format: String::new(),
|
||||
text_format: String::new(),
|
||||
typed_text_formats: Vec::new(),
|
||||
@@ -257,7 +257,7 @@ impl FieldForm {
|
||||
};
|
||||
self.style_switches.clear();
|
||||
if field_kind(name) == FieldKind::Date {
|
||||
self.date_format.clear();
|
||||
self.date_format = if name == "TIME" { "h:mm am/pm" } else { "M/d/yyyy" }.into();
|
||||
}
|
||||
self.code = self.instruction();
|
||||
}
|
||||
@@ -377,14 +377,10 @@ impl FieldForm {
|
||||
match field_kind(&self.name) {
|
||||
FieldKind::Date => {
|
||||
text_field(ui, "field_date", &word("Date formats:"), &mut self.date_format);
|
||||
let formats: Vec<_> = std::iter::once("").chain(DATE_FORMATS.iter().copied()).collect();
|
||||
let samples = formats
|
||||
.iter()
|
||||
.map(|p| if p.is_empty() { tl!("Default (field language)").to_string() } else { wordcraft_engine::cmd::insert::format_date(p) })
|
||||
.collect::<Vec<_>>();
|
||||
let current = formats.iter().position(|p| *p == self.date_format.trim());
|
||||
let samples: Vec<String> = DATE_FORMATS.iter().map(|p| wordcraft_engine::cmd::insert::format_date(p)).collect();
|
||||
let current = DATE_FORMATS.iter().position(|p| *p == self.date_format);
|
||||
if let Some(at) = list_index(ui, &word("Date formats:"), &samples, current).selected
|
||||
&& let Some(p) = formats.get(at)
|
||||
&& let Some(p) = DATE_FORMATS.get(at)
|
||||
{
|
||||
self.date_format = (*p).to_string();
|
||||
}
|
||||
|
||||
@@ -247,7 +247,7 @@ fn cross_font_recent_symbol_inserts_clicked_character() {
|
||||
fn field_dialog_builds_the_instruction() {
|
||||
let a = app();
|
||||
let mut f = FieldForm::new(&a);
|
||||
assert_eq!(f.instruction(), r"DATE \* MERGEFORMAT");
|
||||
assert_eq!(f.instruction(), r#"DATE \@ "M/d/yyyy" \* MERGEFORMAT"#);
|
||||
f.date_format = "yyyy-MM-dd".into();
|
||||
f.preserve = false;
|
||||
assert_eq!(f.instruction(), r#"DATE \@ "yyyy-MM-dd""#);
|
||||
@@ -275,73 +275,6 @@ fn field_dialog_builds_the_instruction() {
|
||||
assert!(f.params().is_none());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn field_dialog_date_and_time_defaults_follow_the_field_language_on_update() {
|
||||
use crate::dialogs::host::WordForm;
|
||||
use wordcraft_doc::InlineObject;
|
||||
use wordcraft_engine::cmd::{insert::format_date_at_in, local_offset_secs, now_unix};
|
||||
|
||||
let locales = [("de-DE", "HH:mm", "dd.MM.yyyy", "04.12.2026"), ("en-US", "h:mm am/pm", "M/d/yyyy", "12/4/2026")];
|
||||
for (lang, time, date, created) in locales {
|
||||
let mut a = app();
|
||||
a.session.doc.core.created = "2026-12-04".into();
|
||||
a.session.run("review.language", &json!({"lang": lang, "default": true})).unwrap();
|
||||
let mut form = FieldForm::new(&a);
|
||||
let mut expected = Vec::new();
|
||||
let start = now_unix();
|
||||
for name in ["TIME", "DATE", "CREATEDATE", "SAVEDATE", "PRINTDATE"] {
|
||||
let picture = if name == "TIME" { time } else { date };
|
||||
a.run("insert.field", json!({"instr": name})).unwrap();
|
||||
expected.push((name.to_string(), picture));
|
||||
|
||||
form.select(name);
|
||||
assert!(form.date_format.is_empty(), "{name} starts from the field-language default");
|
||||
let instruction = format!(r"{name} \* MERGEFORMAT");
|
||||
assert_eq!(form.final_code(), instruction);
|
||||
let (command, params) = form.commands().pop().expect("the dialog inserts a field");
|
||||
a.run(&command, params).unwrap();
|
||||
expected.push((instruction, picture));
|
||||
}
|
||||
|
||||
for (name, picture) in [("TIME", "HH:mm:ss"), ("DATE", "yyyy-MM-dd")] {
|
||||
form.select(name);
|
||||
form.date_format = picture.into();
|
||||
let (command, params) = form.commands().pop().unwrap();
|
||||
a.run(&command, params).unwrap();
|
||||
expected.push((format!(r#"{name} \@ "{picture}" \* MERGEFORMAT"#), picture));
|
||||
}
|
||||
|
||||
let check = |a: &WordApp, from, to| {
|
||||
let p = a.session.doc.body.first().and_then(|b| b.as_para()).unwrap();
|
||||
assert_eq!(p.objects.len(), expected.len());
|
||||
for (object, (instruction, picture)) in p.objects.iter().zip(&expected) {
|
||||
let InlineObject::Field { instr, result, .. } = object else { panic!("expected {instruction}") };
|
||||
assert_eq!(instr, instruction);
|
||||
if instr.starts_with("CREATEDATE") {
|
||||
assert_eq!(result, created);
|
||||
} else {
|
||||
// The clock can roll over while the command is running.
|
||||
assert!(
|
||||
(from..=to).any(|t| *result == format_date_at_in(picture, Some(lang), t, local_offset_secs(t))),
|
||||
"{lang}: {instr} showed {result:?}, expected {picture}"
|
||||
);
|
||||
}
|
||||
}
|
||||
};
|
||||
check(&a, start, now_unix());
|
||||
|
||||
let p = a.session.doc.para_mut(wordcraft_doc::StoryRef::Body, &wordcraft_doc::Path::top(0)).unwrap();
|
||||
for o in &mut p.objects {
|
||||
if let InlineObject::Field { result, .. } = o {
|
||||
*result = "stale".into();
|
||||
}
|
||||
}
|
||||
let start = now_unix();
|
||||
a.run("references.updateFields", json!({"all": true})).unwrap();
|
||||
check(&a, start, now_unix());
|
||||
}
|
||||
}
|
||||
|
||||
/// Text fields take a capitalization Format: each choice writes its `\*` switch before
|
||||
/// `\* MERGEFORMAT`, after the field's own arguments and switches, and (none) writes none.
|
||||
#[test]
|
||||
|
||||
@@ -481,9 +481,6 @@ pub struct WordApp {
|
||||
/// Escape may leave full screen. Read before anything handles the frame's keys.
|
||||
escape_free: bool,
|
||||
pub quit_requested: bool,
|
||||
/// A quit ([`WordApp::quit`]) went ahead with nothing unsaved. The root close that ends it checks once more,
|
||||
/// because a focused field's typed text commits to its document only on that close (#8790).
|
||||
pub(crate) quit_recheck: bool,
|
||||
pub autosave: bool,
|
||||
/// The document's fonts that aren't installed, for the status bar and the font box, and the
|
||||
/// layout they were read from.
|
||||
|
||||
@@ -50,39 +50,6 @@ fn anchor_skips_rects_scrolled_offscreen_and_clips_partial_ones() {
|
||||
assert_eq!(visible_anchor([nan], clip, false), None);
|
||||
}
|
||||
|
||||
/// #7317: a viewport narrower than the bar still places the mini toolbar inside the canvas and viewport on all four sides.
|
||||
#[test]
|
||||
fn a_viewport_narrower_than_the_bar_still_yields_a_rect() {
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
a.run("text.insert", json!({"text": "The quick brown fox"})).unwrap();
|
||||
a.run("select.text", json!({"text": "quick"})).unwrap();
|
||||
let viewport = Rect::from_min_size(pos2(0.0, 0.0), Vec2::new(220.0, 480.0));
|
||||
let mut h = crate::test_harness::builder().with_size(viewport.size()).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
app.logic(&ctx);
|
||||
app.ui(ui);
|
||||
},
|
||||
a,
|
||||
);
|
||||
steps(&mut h);
|
||||
let bold = member(&h, "Bold").expect("mini toolbar Bold inside canvas");
|
||||
// The framework's selection task bar is the group named "Formatting" that holds the bar's Bold.
|
||||
let bar = h
|
||||
.query_all_by_role(Role::Group)
|
||||
.filter(|n| n.accesskit_node().label().as_deref() == Some("Formatting"))
|
||||
.map(|n| n.rect())
|
||||
.find(|r| r.contains_rect(bold))
|
||||
.expect("the selection bar is shown around its Bold");
|
||||
assert!(bar.is_finite() && bar.is_positive(), "bar placed at {bar:?}");
|
||||
for (area, name) in [(canvas(&h), "canvas"), (viewport, "narrow viewport")] {
|
||||
assert!(bar.left() >= area.left(), "bar's left edge stays inside the {name}: {bar:?} vs {area:?}");
|
||||
assert!(bar.top() >= area.top(), "bar's top edge stays inside the {name}: {bar:?} vs {area:?}");
|
||||
assert!(bar.right() <= area.right(), "bar's right edge stays inside the {name}: {bar:?} vs {area:?}");
|
||||
assert!(bar.bottom() <= area.bottom(), "bar's bottom edge stays inside the {name}: {bar:?} vs {area:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// The whole window over a document with `pick` selected, run until the bar is up.
|
||||
fn bar_over(pick: &str) -> H {
|
||||
let mut a = WordApp::new(wordcraft_engine::Session::new(wordcraft_doc::Document::new()), Default::default());
|
||||
@@ -92,8 +59,7 @@ fn bar_over(pick: &str) -> H {
|
||||
}
|
||||
|
||||
/// `bar_over` for an app whose document and selection are already set up.
|
||||
fn bar_over_app(mut a: WordApp) -> H {
|
||||
a.font_catalog.get_or_insert_with(crate::test_harness::fixed_catalog);
|
||||
fn bar_over_app(a: WordApp) -> H {
|
||||
let mut h = crate::test_harness::builder().with_size(Vec2::new(1440.0, 900.0)).build_ui_state(
|
||||
|ui, app: &mut WordApp| {
|
||||
let ctx = ui.ctx().clone();
|
||||
@@ -386,6 +352,16 @@ fn hovering_a_bar_member_previews_its_command() {
|
||||
h.get_by_label("20").rect().center()
|
||||
}
|
||||
Member::Font => {
|
||||
// `FontPicker` scans `Catalog::global()` on a background thread; wait until ready so the
|
||||
// chevron click isn't ignored while the picker is still disabled in a fresh test process.
|
||||
let catalog = craft::font_manager::Catalog::global();
|
||||
catalog.scan_in_background();
|
||||
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(10);
|
||||
while !catalog.is_ready() && std::time::Instant::now() < deadline {
|
||||
std::thread::sleep(std::time::Duration::from_millis(10));
|
||||
}
|
||||
assert!(catalog.is_ready(), "font catalog finished scanning");
|
||||
steps(&mut h);
|
||||
let b = font_box(&h);
|
||||
let c = canvas(&h);
|
||||
// A click on a Plain picker's name only selects it (craft-libs #3103); the chevron opens the list.
|
||||
|
||||
@@ -86,12 +86,7 @@ fn tabs(app: &mut WordApp, ui: &mut Ui) {
|
||||
.shown(shown)
|
||||
.show_items(ui, &places(&labels), &mut |key, _| Tab::new(labels.get(*key).map(|label| label.1.clone()).unwrap_or_default()));
|
||||
|
||||
// A click or the keyboard arrives as a selection event; `out.picked` is only the overflow menu's pick.
|
||||
let clicked = out.response.events.iter().rev().find_map(|event| match event {
|
||||
CollectionEvent::Selection { change: SelectionChange::Set(keys), .. } => keys.last().copied(),
|
||||
_ => None,
|
||||
});
|
||||
if let Some((key, _)) = out.picked.or(clicked).and_then(|k| TABS.get(k)) {
|
||||
if let Some((key, _)) = out.picked.and_then(|k| TABS.get(k)) {
|
||||
app.ui.nav_tab = (*key).into();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -220,7 +220,6 @@ mod tests {
|
||||
let html = format!(r#"<meta http-equiv="content-type" content="text/html; charset=utf-8"><img src="{url}" alt="A & B">"#);
|
||||
let url_and_alt = format!("{url}\r\nA & B");
|
||||
let title = "Picture title";
|
||||
let first_srcset_url = "https://example.test/picture-1x.png";
|
||||
let srcset_url = "https://example.test/picture-2x.png";
|
||||
let comma_srcset_url = "https://example.test/a,b.png";
|
||||
let offers = [
|
||||
@@ -229,10 +228,7 @@ mod tests {
|
||||
(&url_and_alt, html.clone()),
|
||||
(title, format!(r#"<img src="{url}" title="{title}">"#)),
|
||||
(srcset_url, format!(r#"<img src="{url}" srcset="{srcset_url} 2x">"#)),
|
||||
(srcset_url, format!(r#"<img src="{url}" srcset="{first_srcset_url} 1x, {srcset_url} 2x">"#)),
|
||||
(srcset_url, format!(r#"<img src="{url}" srcset="{first_srcset_url}, {srcset_url} 2x">"#)),
|
||||
(srcset_url, format!(r#"<img src="{url}" srcset="{comma_srcset_url} 1x, {srcset_url} 2x">"#)),
|
||||
(comma_srcset_url, format!(r#"<img src="{url}" srcset="{comma_srcset_url} 1x, {srcset_url} 2x">"#)),
|
||||
(comma_srcset_url, format!(r#"<img src="{url}" srcset="{comma_srcset_url} 2x">"#)),
|
||||
];
|
||||
for (text, html) in offers {
|
||||
let mut app = app_holding(&[Flavor::text(text), Flavor::new(HTML, html.as_bytes().to_vec()), rgba8(4, 4, 200)]);
|
||||
@@ -243,17 +239,12 @@ mod tests {
|
||||
assert_eq!(pictures(&mut app), 0);
|
||||
}
|
||||
|
||||
let false_matches = [
|
||||
("b.png", format!(r#"<img src="{url}" srcset="{comma_srcset_url} 2x">"#)),
|
||||
("1x", format!(r#"<img src="{url}" srcset="{first_srcset_url} 1x, {srcset_url} 2x">"#)),
|
||||
("2x", format!(r#"<img src="{url}" srcset="{first_srcset_url} 1x, {srcset_url} 2x">"#)),
|
||||
];
|
||||
for (false_match, html) in false_matches {
|
||||
let mut app = app_holding(&[Flavor::text(false_match), Flavor::new(HTML, html.into_bytes()), rgba8(4, 4, 200)]);
|
||||
app.run("edit.paste", json!({})).unwrap();
|
||||
assert_eq!(pictures(&mut app), 0, "clipboard text {false_match:?}");
|
||||
assert_eq!(app.session.doc.plain_text(wordcraft_doc::StoryRef::Body), false_match);
|
||||
}
|
||||
let false_match = "b.png";
|
||||
let html = format!(r#"<img src="{url}" srcset="{comma_srcset_url} 2x">"#);
|
||||
let mut app = app_holding(&[Flavor::text(false_match), Flavor::new(HTML, html.into_bytes()), rgba8(4, 4, 200)]);
|
||||
app.run("edit.paste", json!({})).unwrap();
|
||||
assert_eq!(pictures(&mut app), 0);
|
||||
assert_eq!(app.session.doc.plain_text(wordcraft_doc::StoryRef::Body), false_match);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -204,9 +204,8 @@ pub(super) fn home(row: &mut RibbonRow<'_>, app: &mut WordApp) {
|
||||
if let Some(f) = out.picked {
|
||||
let _ = app.run("format.font", json!({"name": f}));
|
||||
}
|
||||
// Given, not bound: a bound local rebuilt from the engine each frame cancels the typed draft (#8921).
|
||||
let size = st.get("size").and_then(Value::as_f64).map(format_font_size).unwrap_or_default();
|
||||
let out = craft::ui::pickers::ComboBox::new(tl!("Font Size").to_string(), Bind::given(size), font_size_entries())
|
||||
let mut size = st.get("size").and_then(Value::as_f64).map(format_font_size).unwrap_or_default();
|
||||
let out = craft::ui::pickers::ComboBox::new(tl!("Font Size").to_string(), Bind::bound(&mut size), font_size_entries())
|
||||
.tooltip(tl!("Font Size").to_string())
|
||||
.show(ui);
|
||||
painted_ibeam_over(ui, &out.edit.response);
|
||||
@@ -555,9 +554,7 @@ mod tests {
|
||||
h.app_frame();
|
||||
assert!(!tooltip_visible(&h), "just focused: hint should not show before tooltip delay");
|
||||
|
||||
let step_dt = f64::from(h.ctx.input(|i| i.predicted_dt));
|
||||
assert!(step_dt > 0.0, "harness step_dt must be positive, got {step_dt}");
|
||||
let delay_frames = (craft::ui::contract::tooltip::DELAY / step_dt).ceil() as usize + 3;
|
||||
let delay_frames = (craft::ui::contract::tooltip::DELAY / 0.25).ceil() as usize + 3;
|
||||
for _ in 0..delay_frames {
|
||||
h.step();
|
||||
}
|
||||
|
||||
@@ -413,11 +413,6 @@ fn smart_art_design_layouts_are_one_strip_and_size_is_labelled() {
|
||||
/// control lies inside its group's access node.
|
||||
#[test]
|
||||
fn ribbon_groups_fit_above_their_labels() {
|
||||
if crate::i18n::Lang::all().any(|l| l.code() == "ar")
|
||||
&& crate::test_harness::skip_without_embedded_script("ribbon::tests::ribbon_groups_fit_above_their_labels", "Arab")
|
||||
{
|
||||
return;
|
||||
}
|
||||
fn rects(node: &egui_kittest::Node<'_>, out: &mut Vec<egui::Rect>) {
|
||||
for child in node.children() {
|
||||
// The framework's parts (a split button's arrow, a field's adornments) can be nodes with no
|
||||
@@ -476,11 +471,6 @@ fn ribbon_groups_fit_above_their_labels() {
|
||||
/// Language Preferences… opens Options › Language, and French text shows by name, checked.
|
||||
#[test]
|
||||
fn language_menu_reaches_every_language() {
|
||||
if crate::i18n::Lang::all().any(|l| l.code() == "ar")
|
||||
&& crate::test_harness::skip_without_embedded_script("ribbon::tests::language_menu_reaches_every_language", "Arab")
|
||||
{
|
||||
return;
|
||||
}
|
||||
let app = WordApp::new(Session::new(wordcraft_doc::Document::from_text("Bonjour")), crate::Services::default());
|
||||
let mut h = tab_harness(app, "Review");
|
||||
click_button(&mut h, "Language");
|
||||
@@ -1634,23 +1624,3 @@ fn the_numbering_menu_offers_a_dot_b_dot_c_dot() {
|
||||
crate::test_harness::frames(&mut h, 3);
|
||||
assert_eq!(label(&mut h).as_deref(), Some("A."), "another preset changes the list");
|
||||
}
|
||||
|
||||
/// #8921: a size typed in the Font Size box and committed with Enter formats the selection.
|
||||
#[test]
|
||||
fn a_size_typed_in_the_font_size_box_formats_the_selection() {
|
||||
use egui::accesskit::Role;
|
||||
|
||||
let mut app = WordApp::new(Session::new(wordcraft_doc::Document::from_text("Sample\n\nafter")), crate::Services::default());
|
||||
app.run("select.all", json!({})).unwrap();
|
||||
let mut h = tab_harness(app, "Home");
|
||||
h.get_all_by_role(Role::TextInput).find(|n| n.value().is_some_and(|v| v.trim().parse::<f64>().is_ok())).expect("the font size box").focus();
|
||||
crate::test_harness::frames(&mut h, 2);
|
||||
h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A);
|
||||
crate::test_harness::frames(&mut h, 2);
|
||||
h.event(egui::Event::Text("15".into()));
|
||||
crate::test_harness::frames(&mut h, 2);
|
||||
h.key_press(egui::Key::Enter);
|
||||
crate::test_harness::frames(&mut h, 3);
|
||||
let st = wordcraft_engine::cmd::format::cached_state(&h.state().session);
|
||||
assert_eq!(st.get("size").and_then(Value::as_f64), Some(15.0));
|
||||
}
|
||||
|
||||
@@ -1,9 +1,5 @@
|
||||
//! The user's scrolling-speed choice (issue #6146). The wheel and touchpad themselves are scrolled by the
|
||||
//! framework's canvas navigation; this module keeps the setting, the document wheel notch, and its multipliers.
|
||||
|
||||
/// Screen points one mouse-wheel notch scrolls at 100% zoom: about three lines of body text,
|
||||
/// like other desktop apps (the framework's default canvas line is 16).
|
||||
pub const NOTCH_PX: f32 = 56.0;
|
||||
//! framework's canvas navigation; this module keeps the setting and its multipliers.
|
||||
|
||||
/// The user's choice for scrolling speed, relative to the platform's normal speed (#6146).
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
|
||||
|
||||
@@ -50,11 +50,6 @@ pub(crate) struct ResizeDrag {
|
||||
}
|
||||
|
||||
impl ResizeDrag {
|
||||
/// Started on a ruler marker.
|
||||
pub(crate) fn on_ruler(&self) -> bool {
|
||||
self.ruler
|
||||
}
|
||||
|
||||
/// Who makes up a column border's move, by the keys held: Ctrl the columns on the
|
||||
/// right; Shift nobody on the page but the neighbour on a ruler marker, which works the other
|
||||
/// way round; else the neighbour on the page and nobody on the ruler. The one place the key rule lives.
|
||||
|
||||
@@ -169,60 +169,3 @@ pub(crate) fn frames(h: &mut egui_kittest::Harness<'_, crate::WordApp>, n: usize
|
||||
frame(h);
|
||||
}
|
||||
}
|
||||
|
||||
/// A font catalog scanned synchronously from the bundled `assets/fonts/` directory, with no
|
||||
/// host system fonts or background font service.
|
||||
pub(crate) fn fixed_catalog() -> std::sync::Arc<craft::font_manager::Catalog> {
|
||||
use craft::font_manager::Catalog;
|
||||
use craft::font_manager::craft_font_catalog::{FontEnv, Os};
|
||||
let env = FontEnv { os: Os::None, ..Default::default() };
|
||||
let catalog = std::sync::Arc::new(Catalog::new(env).with_font_service(false));
|
||||
catalog.set_app_dirs(vec![std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts")]);
|
||||
catalog.rescan();
|
||||
assert!(catalog.is_ready(), "fixed font catalog scanned synchronously");
|
||||
assert!(catalog.families().iter().any(|f| f == "Inter"), "fixed catalog loaded assets/fonts");
|
||||
catalog
|
||||
}
|
||||
|
||||
/// Evaluate whether a test missing an embedded `script` face should skip under
|
||||
/// `CRAFT_FONTS_REQUIRED` (`None` / `""` skips, `"1"` fails, any other value fails naming the
|
||||
/// variable and accepted values).
|
||||
fn should_skip_missing_script(test: &str, script: &str, required: Option<&str>) -> bool {
|
||||
match required {
|
||||
None | Some("") => {
|
||||
eprintln!("SKIPPED ({test}): no embedded {script} face in CRAFT_FONTS (set CRAFT_FONTS_DIR)");
|
||||
true
|
||||
}
|
||||
Some("1") => panic!("{test}: missing embedded {script} face in CRAFT_FONTS (CRAFT_FONTS_REQUIRED=1)"),
|
||||
Some(other) => panic!("{test}: invalid CRAFT_FONTS_REQUIRED={other:?}; accepted values are empty/unset (skip) or \"1\" (require)"),
|
||||
}
|
||||
}
|
||||
|
||||
/// Skip `test` when no embedded `craft-fonts` face covers `script`, unless `CRAFT_FONTS_REQUIRED`
|
||||
/// requires or rejects the value.
|
||||
pub(crate) fn skip_without_embedded_script(test: &str, script: &str) -> bool {
|
||||
if crate::app::fonts::CRAFT_FONTS.iter().any(|f| f.has_script(script)) {
|
||||
return false;
|
||||
}
|
||||
let required = std::env::var("CRAFT_FONTS_REQUIRED").ok();
|
||||
should_skip_missing_script(test, script, required.as_deref())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::should_skip_missing_script;
|
||||
|
||||
#[test]
|
||||
fn craft_fonts_required_controls_skip_and_rejects_unknown_values() {
|
||||
assert!(should_skip_missing_script("t", "Arab", None));
|
||||
assert!(should_skip_missing_script("t", "Arab", Some("")));
|
||||
|
||||
let required_err = std::panic::catch_unwind(|| should_skip_missing_script("t", "Arab", Some("1"))).unwrap_err();
|
||||
let required_msg = required_err.downcast_ref::<String>().map(String::as_str).unwrap_or("");
|
||||
assert!(required_msg.contains("CRAFT_FONTS_REQUIRED=1"), "{required_msg}");
|
||||
|
||||
let invalid_err = std::panic::catch_unwind(|| should_skip_missing_script("t", "Arab", Some("yes"))).unwrap_err();
|
||||
let invalid_msg = invalid_err.downcast_ref::<String>().map(String::as_str).unwrap_or("");
|
||||
assert!(invalid_msg.contains("CRAFT_FONTS_REQUIRED") && invalid_msg.contains("\"1\""), "{invalid_msg}");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -814,8 +814,8 @@ fn ctrl_wheel_zoom_keeps_the_place_under_the_pointer() {
|
||||
modifiers,
|
||||
source: egui::MouseWheelSource::Unknown,
|
||||
};
|
||||
// Away from the caret, several pages down.
|
||||
for _ in 0..40 {
|
||||
// Away from the caret, several pages down (a wheel line scrolls less under the framework's page view).
|
||||
for _ in 0..240 {
|
||||
frame(&mut a, vec![wheel(-1.0, egui::Modifiers::NONE)]);
|
||||
}
|
||||
for _ in 0..60 {
|
||||
|
||||
@@ -470,18 +470,3 @@ fn find_replace_and_go_to_keys_like_word() {
|
||||
assert_eq!(h.state().ui.nav_tab, "results", "Find leaves Pages to show the selected-text matches");
|
||||
assert_eq!(h.state().session.find.results.len(), 2);
|
||||
}
|
||||
|
||||
/// #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());
|
||||
h.state_mut().session.view.nav_pane = true;
|
||||
for _ in 0..2 {
|
||||
h.step();
|
||||
}
|
||||
for (label, key) in [("Pages", "pages"), ("Results", "results"), ("Headings", "headings")] {
|
||||
h.get_by_role_and_label(egui::accesskit::Role::Tab, label).click();
|
||||
h.run();
|
||||
assert_eq!(h.state().ui.nav_tab, key);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,8 @@
|
||||
use std::path::Path;
|
||||
use std::sync::Arc;
|
||||
|
||||
use craft::font_manager::Catalog;
|
||||
use craft::font_manager::craft_font_catalog::{FontEnv, Os};
|
||||
use craft::font_manager::missing::MissingFontsWords;
|
||||
use craft::host::{Host, PickKind, ScriptedFiles};
|
||||
use craft::ui::buttons::IconButton;
|
||||
@@ -10,9 +13,18 @@ use egui_kittest::kittest::{By, NodeT, Queryable};
|
||||
use serde_json::{Value, json};
|
||||
use wordcraft_engine::Session;
|
||||
|
||||
use crate::test_harness::fixed_catalog;
|
||||
use crate::{Services, WordApp};
|
||||
|
||||
fn fixed_catalog() -> Arc<Catalog> {
|
||||
let env = FontEnv { os: Os::None, ..Default::default() };
|
||||
let catalog = Arc::new(Catalog::new(env).with_font_service(false));
|
||||
catalog.set_app_dirs(vec![Path::new(env!("CARGO_MANIFEST_DIR")).join("../../assets/fonts")]);
|
||||
catalog.rescan();
|
||||
assert!(catalog.is_ready(), "fixed font catalog scanned synchronously");
|
||||
assert!(catalog.families().iter().any(|f| f == "Inter"), "fixed catalog loaded assets/fonts");
|
||||
catalog
|
||||
}
|
||||
|
||||
fn open_ribbon_font_box(h: &mut egui_kittest::Harness<'static, WordApp>) {
|
||||
h.get_by_role_and_label(Role::ComboBox, "Font").click();
|
||||
h.run_steps(1);
|
||||
|
||||
@@ -176,7 +176,6 @@ impl WordApp {
|
||||
applied_editing: _,
|
||||
frame_ms: _,
|
||||
quit_requested: _,
|
||||
quit_recheck: _,
|
||||
autosave: _,
|
||||
zotero: _,
|
||||
ctx: _,
|
||||
|
||||
@@ -254,18 +254,11 @@ impl WordApp {
|
||||
|
||||
/// Quit the app (the app menu's Quit): ask about every document with unsaved work, each in
|
||||
/// its window, as [`WordApp::close_requested`] does. True when the app may quit now; the
|
||||
/// host closes it once `quit_requested` is set. The text typed in a focused field commits
|
||||
/// only on that close, so a quit that found nothing unsaved checks once more there and asks
|
||||
/// then if the text left something unsaved: a true answer can still turn into a prompt.
|
||||
/// host closes it once `quit_requested` is set.
|
||||
pub fn quit(&mut self) -> bool {
|
||||
// A quit already pending: leave `quit_recheck` for the host's close, which a second quit must not use up.
|
||||
if self.quit_requested && !self.printing.busy() {
|
||||
return true;
|
||||
}
|
||||
let go = self.close_requested();
|
||||
if go {
|
||||
self.quit_requested = true;
|
||||
self.quit_recheck = true;
|
||||
}
|
||||
go
|
||||
}
|
||||
|
||||
@@ -67,11 +67,11 @@ impl Rig {
|
||||
/// One frame of every window with explicit root and child input events.
|
||||
fn frame_events(&mut self, a: &mut WordApp, root: Vec<egui::Event>, child: Vec<egui::Event>) {
|
||||
self.kit.root_info(self.info(false));
|
||||
self.kit.child_info(self.info(true));
|
||||
self.frame_with_reported_info(a, root, child);
|
||||
self.frame_after_root_report(a, root, child);
|
||||
}
|
||||
|
||||
fn frame_with_reported_info(&mut self, a: &mut WordApp, root: Vec<egui::Event>, child: Vec<egui::Event>) {
|
||||
fn frame_after_root_report(&mut self, a: &mut WordApp, root: Vec<egui::Event>, child: Vec<egui::Event>) {
|
||||
self.kit.child_info(self.info(true));
|
||||
if let Some(focused) = self.focused {
|
||||
self.kit.focus(focused);
|
||||
}
|
||||
@@ -1035,15 +1035,14 @@ fn new_document_builder(inner_rect: Option<egui::Rect>, outer_rect: Option<egui:
|
||||
let mut rig = Rig::new();
|
||||
let mut a = app("First draft");
|
||||
rig.kit.root_info(ViewportInfo { inner_rect, outer_rect, focused: Some(true), ..Default::default() });
|
||||
rig.kit.child_info(rig.info(true));
|
||||
for _ in 0..3 {
|
||||
rig.frame_with_reported_info(&mut a, Vec::new(), Vec::new());
|
||||
rig.frame_after_root_report(&mut a, Vec::new(), Vec::new());
|
||||
}
|
||||
let step = super::StyleCx::with_root(&rig.ctx(), |cx| cx.tokens.size.window.cascade);
|
||||
a.run("file.new", json!({})).unwrap();
|
||||
assert_eq!(a.window_count(), 2);
|
||||
let title = a.window_title();
|
||||
rig.frame_with_reported_info(&mut a, Vec::new(), Vec::new());
|
||||
rig.frame_after_root_report(&mut a, Vec::new(), Vec::new());
|
||||
let builder = rig.builders.into_iter().find(|b| b.title.as_ref() == Some(&title)).expect("the new document opened a native window");
|
||||
(builder, step)
|
||||
}
|
||||
@@ -1064,68 +1063,9 @@ fn new_document_cascade_keeps_the_predecessors_client_size_and_outer_origin() {
|
||||
#[test]
|
||||
fn new_document_cascade_without_predecessor_geometry_uses_default_placement() {
|
||||
let rect = egui::Rect::from_min_size(egui::pos2(50.0, 70.0), egui::vec2(800.0, 600.0));
|
||||
let zero = egui::Rect::from_min_size(egui::pos2(50.0, 70.0), egui::Vec2::ZERO);
|
||||
let infinite_size = egui::Rect::from_min_size(egui::pos2(50.0, 70.0), egui::vec2(f32::INFINITY, 600.0));
|
||||
let nan_origin = egui::Rect::from_min_size(egui::pos2(f32::NAN, 70.0), egui::vec2(800.0, 600.0));
|
||||
for (label, inner, outer) in [
|
||||
("missing outer", Some(rect), None),
|
||||
("missing inner", None, Some(rect)),
|
||||
("zero outer", Some(rect), Some(zero)),
|
||||
("zero inner", Some(zero), Some(rect)),
|
||||
("infinite outer size", Some(rect), Some(infinite_size)),
|
||||
("infinite inner size", Some(infinite_size), Some(rect)),
|
||||
("nan outer origin", Some(rect), Some(nan_origin)),
|
||||
("nan inner origin", Some(nan_origin), Some(rect)),
|
||||
] {
|
||||
for (inner, outer) in [(Some(rect), None), (None, Some(rect))] {
|
||||
let (builder, _) = new_document_builder(inner, outer);
|
||||
assert_eq!(builder.position, None, "{label}: the platform picks the initial position without a usable predecessor");
|
||||
assert_eq!(builder.inner_size, None, "{label}: no predecessor client size is carried over");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn new_document_cascade_skips_ineligible_recent_window_to_earlier_predecessor() {
|
||||
let root_origin = egui::pos2(50.0, 70.0);
|
||||
let root_client = egui::vec2(800.0, 600.0);
|
||||
let root_outer = egui::Rect::from_min_size(root_origin, root_client + egui::vec2(16.0, 38.0));
|
||||
let root_inner = egui::Rect::from_min_size(root_origin + egui::vec2(8.0, 30.0), root_client);
|
||||
let child_origin = egui::pos2(200.0, 220.0);
|
||||
let child_client = egui::vec2(700.0, 520.0);
|
||||
let child_outer = egui::Rect::from_min_size(child_origin, child_client + egui::vec2(12.0, 34.0));
|
||||
let child_inner = egui::Rect::from_min_size(child_origin + egui::vec2(6.0, 28.0), child_client);
|
||||
let zero = egui::Rect::from_min_size(child_origin, egui::Vec2::ZERO);
|
||||
let infinite_size = egui::Rect::from_min_size(child_origin, egui::vec2(f32::INFINITY, 400.0));
|
||||
|
||||
for (label, inner, outer, expected_client, expected_origin) in [
|
||||
("valid child", Some(child_inner), Some(child_outer), child_client, child_origin),
|
||||
("zero outer", Some(child_inner), Some(zero), root_client, root_origin),
|
||||
("zero inner", Some(zero), Some(child_outer), root_client, root_origin),
|
||||
("infinite outer size", Some(child_inner), Some(infinite_size), root_client, root_origin),
|
||||
] {
|
||||
let mut rig = Rig::new();
|
||||
let mut a = app("First draft");
|
||||
rig.kit.root_info(ViewportInfo { inner_rect: Some(root_inner), outer_rect: Some(root_outer), focused: Some(true), ..Default::default() });
|
||||
rig.kit.child_info(rig.info(true));
|
||||
for _ in 0..3 {
|
||||
rig.frame_with_reported_info(&mut a, Vec::new(), Vec::new());
|
||||
}
|
||||
let step = super::StyleCx::with_root(&rig.ctx(), |cx| cx.tokens.size.window.cascade);
|
||||
|
||||
a.run("file.new", json!({})).unwrap();
|
||||
assert_eq!(a.window_count(), 2);
|
||||
rig.kit.root_info(ViewportInfo { inner_rect: Some(root_inner), outer_rect: Some(root_outer), focused: Some(false), ..Default::default() });
|
||||
rig.kit.child_info(ViewportInfo { inner_rect: inner, outer_rect: outer, focused: Some(true), ..Default::default() });
|
||||
for _ in 0..3 {
|
||||
rig.frame_with_reported_info(&mut a, Vec::new(), Vec::new());
|
||||
}
|
||||
|
||||
a.run("file.new", json!({})).unwrap();
|
||||
assert_eq!(a.window_count(), 3);
|
||||
let third_title = a.window_title();
|
||||
rig.frame_with_reported_info(&mut a, Vec::new(), Vec::new());
|
||||
let builder = rig.builders.into_iter().find(|b| b.title.as_ref() == Some(&third_title)).expect("the third document opened a native window");
|
||||
assert_eq!(builder.inner_size, Some(expected_client), "{label}: third window client size");
|
||||
assert_eq!(builder.position, Some(expected_origin + egui::Vec2::splat(step)), "{label}: third window origin");
|
||||
assert_eq!(builder.position, None, "the platform picks the initial position without a usable predecessor");
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
File diff suppressed because one or more lines are too long
@@ -86,11 +86,11 @@ Bullets and Numbering decide whether to toggle off from the selected paragraphs'
|
||||
|---|---|---|
|
||||
| `* item` Enter Enter `text` | the second Enter ends the list; `text` is a **Normal** paragraph (no list indent left behind) | `enter_twice_after_a_list_item_ends_the_list`, `the_paragraph_after_a_list_is_normal_text` |
|
||||
| … Enter ×3, ×4 | each further Enter adds a blank Normal paragraph (never swallowed) | `more_enters_after_a_list_make_blank_paragraphs` |
|
||||
| Enter on an empty **nested** item | moves it up one level and uses that level's indentation, dropping direct leading and first-line indents (#8929). Only a top-level empty item leaves the list. The same applies when numbering comes from the paragraph style (#2143). | `enter_on_an_empty_nested_item_moves_it_up_a_level_first`, `enter_on_an_empty_item_numbered_by_its_style_moves_it_up_a_level`, `enter_outdents_an_empty_list_item_and_drops_direct_indents` |
|
||||
| Enter on an empty **nested** item | moves it up one level; only a top-level empty item leaves the list. The same when the list comes from the paragraph style (List Number 2 in a Word file, #2143) | `enter_on_an_empty_nested_item_moves_it_up_a_level_first`, `enter_on_an_empty_item_numbered_by_its_style_moves_it_up_a_level` |
|
||||
| Enter (Return) on a selected picture or shape, inline or floating | nothing: the object stays, still selected, and no paragraph is added, however many times it is pressed (Word for Mac, observed 2026-10-24; #4126). On a selected text box, Enter puts the caret in its text | `enter_on_a_selected_picture_does_nothing` |
|
||||
| Shift+Enter (⇧Return), Insert › Page Break (⌘Return) on a selected picture or shape | the break goes in front of it (in front of a content control around it) and the object stays selected: each Shift+Enter moves an inline picture down a line (with a floating picture, the text after its anchor), and a page break moves it to the next page (Word for Mac, observed 2026-10-24; #4126). A column break does the same (not observed) | `a_break_on_a_selected_picture_goes_in_front_of_it`, `a_break_on_a_picture_in_a_picture_control_keeps_the_picture_selected` |
|
||||
| `* ` Enter (nothing typed) | list cancelled, Normal paragraph | `enter_right_after_starting_a_list_cancels_it` |
|
||||
| Tab / Shift+Tab at the start of an item | demote / promote; when the level changes, the item takes the new level's indents and drops any direct indent (#4287) | `shift_tab_and_tab_change_list_levels`, `changing_a_list_level_drops_a_direct_indent` |
|
||||
| Tab / Shift+Tab at the start of an item | demote / promote | `shift_tab_and_tab_change_list_levels` |
|
||||
| Tab with a whole paragraph (or several paragraphs) selected | indents the paragraph(s) by one default tab stop; the text stays. A partial selection inside one paragraph is replaced by a tab character | `tab_with_a_whole_paragraph_selected_indents_it`, `tab_with_a_partial_selection_still_inserts_a_tab` |
|
||||
| Backspace at the start of an item | 1st: number removed, indent kept; 2nd: Normal paragraph — **not** joined to the one above | `backspace_at_the_start_of_an_item_removes_the_number_then_the_indent` |
|
||||
| Enter mid-item / at item start | splits the item / inserts an empty item above | `enter_in_the_middle_or_at_the_start_of_an_item` |
|
||||
|
||||
+3
-17
@@ -337,23 +337,9 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn wasm_summary_lists_only_crates_with_checked_test_targets() {
|
||||
let included = "wordcraft-geom".to_string();
|
||||
let excluded: Vec<String> = WASM_TEST_EXCLUDED.iter().map(|s| format!("wordcraft-{s}")).collect();
|
||||
let mut set = vec![included.clone()];
|
||||
set.extend(excluded.iter().cloned());
|
||||
|
||||
let set = vec!["wordcraft-geom".to_string(), "wordcraft-doc".to_string(), "wordcraft-layout".to_string(), "wordcraft-ui-egui".to_string()];
|
||||
let test_set = wasm_test_set(&set);
|
||||
assert!(test_set.contains(&included));
|
||||
for pkg in &excluded {
|
||||
assert!(!test_set.contains(pkg), "{pkg} should be excluded from wasm_test_set");
|
||||
}
|
||||
|
||||
let summary = wasm_summary(&set, &test_set);
|
||||
for pkg in &test_set {
|
||||
assert!(summary.contains(pkg), "summary should include {pkg}: {summary}");
|
||||
}
|
||||
for pkg in &excluded {
|
||||
assert!(!summary.contains(pkg), "summary should omit excluded {pkg}: {summary}");
|
||||
}
|
||||
assert_eq!(test_set, vec!["wordcraft-geom", "wordcraft-layout"]);
|
||||
assert_eq!(wasm_summary(&set, &test_set), "wasm32-unknown-unknown check: ok (4 crates, 2 test crates: wordcraft-geom, wordcraft-layout)");
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user